pgstyle (empty) → 0.1.2.0
raw patch · 26 files changed
+12586/−0 lines, 26 filesdep +aesondep +basedep +bytestring
Dependencies added: aeson, base, bytestring, containers, libpg-query, microlens, mtl, optparse-applicative, pgstyle, postgresql-syntax, prettyprinter, proto-lens, string-interpolate, syb, text, text-builder
Files
- CHANGELOG.md +172/−0
- LICENSE +21/−0
- README.md +578/−0
- app/Main.hs +165/−0
- cbits/pgstyle.c +153/−0
- pgstyle.cabal +160/−0
- src/PgStyle.hs +19/−0
- src/PgStyle/File.hs +501/−0
- src/PgStyle/Haskell.hs +271/−0
- src/PgStyle/Layout.hs +147/−0
- src/PgStyle/Layout/Comments.hs +169/−0
- src/PgStyle/Layout/Ddl.hs +1333/−0
- src/PgStyle/Layout/Dml.hs +1599/−0
- src/PgStyle/Layout/Dml.hs-boot +12/−0
- src/PgStyle/Layout/Expr.hs +1639/−0
- src/PgStyle/Layout/Locations.hs +103/−0
- src/PgStyle/Layout/Monad.hs +397/−0
- src/PgStyle/Layout/Names.hs +294/−0
- src/PgStyle/Layout/Parens.hs +152/−0
- src/PgStyle/LibPgQuery.hs +252/−0
- src/PgStyle/Plpgsql.hs +340/−0
- src/PgStyle/Render.hs +2072/−0
- test/FileSpec.hs +262/−0
- test/HaskellSpec.hs +187/−0
- test/LayoutSpec.hs +232/−0
- test/RenderSpec.hs +1356/−0
+ CHANGELOG.md view
@@ -0,0 +1,172 @@+# Changelog++## 0.1.2.0++* pgfmt is now pgstyle, since another project is called pgfmt: the package,+ the command, the library's modules (`PgStyle.*`), the flake's outputs+ (`pgstyle`, `pgstyle-kronor`), the release tarballs, and the repository,+ github.com/kronor-io/pgstyle. Nothing else about the command changes;+ replace `pgfmt` with `pgstyle` where you run it. Versions up to 0.1.1.0+ were released as pgfmt.++* Each release also pushes an image, `ghcr.io/kronor-io/pgstyle`, for+ `linux/amd64` and `linux/arm64`, tagged with the version and `latest`. It+ holds the release's static binary and nothing else:++ docker run --rm -v "$PWD:/work" -u "$(id -u):$(id -g)" ghcr.io/kronor-io/pgstyle --check migrations/*.sql++* The `syntax` backend no longer writes `select` twice for a subquery with+ an explicit `all` (`a in (select all b from u)`), which the parse-tree check+ caught as an error.++* `PgStyle.Layout` is split into modules along its sections: `Monad`,+ `Comments`, `Locations`, `Parens`, `Names`, `Expr`, `Dml` and `Ddl`.+ `docs/readability.md` says how the code is meant to read, and+ `scripts/check` checks what a tool can: fourmolu, and pgstyle's hopinion rules+ in `lint/`. CI runs it. The output is unchanged.++* The `syntax` backend lays out more of the tables, indexes and `alter+ table`s it used to leave to `libpg-query`: an index's `include (...)` and+ `with (...)`, on its `on` line; `alter constraint ... deferrable`; `primary+ key using index` and `unique using index`, which break before `using` if+ long; and `create table ... partition of ... for values ...`, each clause+ on a line of its own. On Kronor's migrations this lays out 25 more+ statements, changing 13 files (24 in upper case).++* The `syntax` backend lays out `create trigger`, `grant` and `revoke`. A+ trigger has each clause on a line of its own, at the statement's column,+ its `when` condition broken like a `check`'s if long. A `grant` or `revoke`+ stays on one line if it fits in 80 characters; otherwise `on` and `to` (or+ `from`) go on lines of their own, indented. On Kronor's migrations this+ lays out 882 more statements, all their triggers and grants, changing 151+ files (390 in upper case); none fails the parse-tree check, and formatting+ again changes nothing.++* The `syntax` backend lays out `create function` and `create procedure`:+ the arguments on the first line, or one per line with the comma at the end+ if they do not fit or have comments; each clause before the body on a line+ of its own, `as` ending the last; the body on the next line, as written (or+ as the PL/pgSQL pass formats it), its opening quote lined up with its+ closing one; the clauses after the body on its last line. Clauses keep their source order and words (`default`+ rather than `libpg-query`'s `=`). A SQL-standard body (`begin atomic ...+ end`, `return ...`) has its statements laid out. On Kronor's migrations this+ lays out 2,184 more statements, changing 1,586 files; none fails the+ parse-tree check, and formatting again changes nothing.++* The `syntax` backend lays out `create index` and `alter table` too, in the+ style they are usually written: an index's `on` and `where` on lines of+ their own (`using` only if written, which `libpg-query` adds), an `alter+ table`'s actions one per line with the comma at the end (keeping `drop+ column`'s `column`, which `libpg-query` drops). A long condition, in an+ index's `where` or a table's `check`, breaks at its top-level `and`s or+ `or`s, a long group in parentheses inside it on lines of its own. Names+ longer than PostgreSQL's 63 bytes, which its parse tree cuts short, are+ written as the source has them. On Kronor's migrations this lays out+ 3,015 more statements, changing 746 files; none fails the parse-tree+ check, and formatting again changes nothing.++* The `syntax` backend lays out `create table`, `create view`, `create+ materialized view` and `create table ... as`, which went to `libpg-query`+ before. A table has one column or constraint per line with the comma at+ the end; it keeps the source's keywords, blank lines and comments between+ columns, writes types as `numeric(12, 2)` and references as `t(id)`, and+ breaks long checks at their top-level `and`s or `or`s and long foreign keys+ before `references`. A view's query is laid out like any `select`. Tables+ with `exclude`, storage options, `partition of` and the like still go to+ `libpg-query`. On Kronor's migrations this lays out 1,274 more statements,+ changing about 1,070 files; none fails the parse-tree check, and+ formatting again changes nothing.++* `values` rows go on one line each, `(1, 'a'),`, when every row of the list+ fits in 100 characters and none has a comment inside it; otherwise each+ row's values still go one per line. Lookup-table inserts now read as a+ table. On Kronor's migrations this changes 267 files, only in line breaks+ and spacing.+* A blank line between two `values` rows is kept, so groups of rows stay+ apart, as in `i18n.invoice_page`, the one file on Kronor's migrations it+ changes.++* The `syntax` backend lays out plain SQL statements with comments inside+ them, instead of leaving them as they are (or, with `--backend auto`, to+ `libpg-query`). Each comment goes where the layout breaks a line at its+ place in the source: one sharing a line with code ends the line before the+ break, one on a line of its own stays on one. A list with a comment in it+ (select targets, `set` assignments, call arguments, `in (...)`, `array[...]`,+ `values` rows and their items, insert columns, `group by`, `and`ed+ conditions) puts one item per line. A comment with no break at its place+ (inside an expression, or between the parts of a string continued over+ lines) still leaves the statement as it is. On Kronor's migrations, 177 of+ the 179 DML statements with comments inside are now laid out, along with+ statements with comments in PL/pgSQL bodies; statements without comments+ come out byte for byte the same. The hasql-th dialect still leaves+ statements with comments alone.+* A blank line before a comment on a line of its own is kept, so separate+ comments stay apart.+* Dollar-quoted strings (`$$...$$`, `$body$...$body$`) are kept as written+ instead of being rewritten as `'...'`, which doubled every quote in a+ multi-line job body. On Kronor's migrations these two changes touch 120+ files (mostly `timetable.add_job(...)` calls); nothing else changes.++## 0.1.1.0++* The `syntax` backend lays out plain SQL from libpg_query's parse tree+ (PostgreSQL 18's own parser) instead of postgresql-syntax's, in the same+ layout. On Kronor's migrations, every one of the 2,020 statements it formatted+ before (PL/pgSQL bodies included) comes out byte for byte the same, with+ `--keyword-case lower` and `upper`. It now also lays out DML that+ postgresql-syntax could not parse (`E'...'` strings, `varchar(n)` casts,+ column definition lists, `tablesample`, ...): 96 more statements there.+ Multi-line string literals are no longer re-indented, and numbers are kept+ as written (`1.50`), so statements the old renderer refused as changed now+ format. Statements it does not handle are still left to `libpg-query`. The+ hasql-th dialect still uses postgresql-syntax.+* The safety check compares each statement's parse tree, source positions+ aside, instead of SQL deparsed from it: two different trees the deparser+ prints alike no longer pass. On Kronor's 4,414 migrations the output is+ byte for byte the same as before. Error messages now quote the statement as+ written and as formatted, rather than the deparser's rendering of each.+* Formats the SQL in Haskell files' hasql-th quasiquotes: files ending in+ `.hs`, or stdin with `--haskell`. Comments, strings and character literals+ are skipped as GHC does; each quasiquote's SQL is replaced only if it parses+ back to the same postgresql-syntax AST, and the file must keep the same+ quasiquotes and the same text around them. `--quoter NAME` adds a quoter to+ hasql-th's. On Kronor's code it matches `hasql-th-format`, and also formats+ qualified quoters (`[TH.singletonStatement|`), which that tool skips.+* Builds against Hackage's postgresql-syntax. The hasql-th dialect is upstream+ hasql-th's; the `kronor-syntax` flag (`cabal.project.kronor`, or the flake's+ `pgfmt-kronor`) adds the Haskell targets and param fields of Kronor's fork.+* Builds with the same haskell.nix and nixpkgs as sqiff and sqint, so they+ share one GHC 9.12.4 in the kronor-open cache.++## 0.1.0.1++* Static Linux binaries for x86_64 and aarch64 on each GitHub release, with+ bash, zsh and fish completions. They are built against musl and run on any+ Linux distribution:++ curl -fsSL "https://github.com/kronor-io/pgfmt/releases/latest/download/pgfmt-$(uname -m)-linux.tar.xz" | tar -xJ -C ~/.local++## 0.1.0.0++First release.++* Formats PostgreSQL files statement by statement, and rewrites a statement+ only when libpg_query parses the new text to the same statement, with the+ same number of comments. Text between statements is copied byte for byte.+* Two backends: pgfmt's own renderer for DML, with leading commas, and+ libpg_query's pretty-printer for everything PostgreSQL parses, including all+ DDL. `--backend auto`, the default, uses the first where it can.+* `--check` for CI and pre-commit: names the files that are not formatted and+ exits 1, changing nothing.+* `--keyword-case lower|upper`, applied to every statement in the file,+ whichever backend laid it out. Identifiers are never changed.+* Formats the SQL statements inside PL/pgSQL function bodies, and keeps the new+ body only if it parses to the same PL/pgSQL.+* `SET` values keep their single quotes: `set lock_timeout to '50ms'` stays as+ it is. libpg_query 18.0.0 writes such values as quoted identifiers+ (`"50ms"`); the flake builds it with+ `nix/libpg_query-set-values-as-strings.patch`.+* `--dialect hasql-th` lets the `syntax` backend read hasql-th's quasiquote+ extensions, and the library exposes `PgFmt.Render.formatSql` for them.+* Builds with Nix for `x86_64-linux`, `aarch64-linux` and `aarch64-darwin`;+ binaries come from the kronor-open cache.
+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kronor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,578 @@+# pgstyle++A formatter for PostgreSQL files that does not change what any statement does.+Up to 0.1.1.0 it was called pgfmt.++It turns this:++```sql+-- Orders placed this week, with their customer.+select o.id, o.total, c.name as customer from orders o join customers c on c.id = o.customer_id where o.placed_at >= now() - interval '7 days' and o.status in ('paid', 'shipped') order by o.placed_at desc limit 50;+```++into this:++```sql+-- Orders placed this week, with their customer.+select+ o.id+ , o.total+ , c.name as customer+from orders o+join customers c+ on c.id = o.customer_id+where o.placed_at >= now() - interval '7 days'+ and o.status in ('paid', 'shipped')+order by o.placed_at desc+limit 50;+```++It reads files with PostgreSQL's own parser+([libpg_query](https://github.com/pganalyze/libpg_query)), so anything+PostgreSQL accepts, pgstyle accepts: DDL, DML, `create function` and PL/pgSQL+bodies. Before it rewrites a statement, it parses the new text again and checks+that PostgreSQL sees the same statement. If the check fails, the statement is+left as it was.++It also formats the SQL in a Haskell file's+[hasql-th quasiquotes](#haskell-hasql-th-quasiquotes).++pgstyle is one of the tools Kronor uses to keep a PostgreSQL schema in sqitch, with [sqiff](https://github.com/kronor-io/sqiff), [sqint](https://github.com/kronor-io/sqint), [create-migration](https://github.com/kronor-io/sqitch-with-templates) and [psql-retry](https://github.com/kronor-io/psql-retry). [sqitchcraft](https://kronor-io.github.io/sqitchcraft/) shows how they fit together: the repository layout they assume, one change from an edited file to a deploy, and instructions for coding agents.++## Install++pgstyle is a single binary.++On Linux, each [release](https://github.com/kronor-io/pgstyle/releases) has a+static binary for `x86_64` and `aarch64` that runs on any distribution. Unpack+it into `~/.local` (or `/usr/local`) to get `bin/pgstyle` and its bash, zsh and+fish completions:++```bash+curl -fsSL "https://github.com/kronor-io/pgstyle/releases/latest/download/pgstyle-$(uname -m)-linux.tar.xz" \+ | tar -xJ -C ~/.local+```++`SHA256SUMS` on the release has the tarballs' checksums.++The same binary is an image, `ghcr.io/kronor-io/pgstyle`, for `linux/amd64` and+`linux/arm64`, tagged with each version and `latest`. It holds pgstyle alone, no+shell, and runs it in `/work`. Mount your files there and run it as yourself,+so the files it rewrites stay yours:++```bash+docker run --rm -v "$PWD:/work" -u "$(id -u):$(id -g)" ghcr.io/kronor-io/pgstyle --check migrations/*.sql+```++Elsewhere, and for development, the easiest way to get it is+[Nix](https://nixos.org/download) with flakes enabled. CI pushes every build to+the `kronor-open.cachix.org` binary cache, and the flake offers to use it:+answer yes, or pass `--accept-flake-config`, and Nix downloads pgstyle instead+of compiling it and its Haskell dependencies.++Try it without installing:++```bash+nix run --accept-flake-config github:kronor-io/pgstyle -- --help+```++Install it into your profile:++```bash+nix profile install --accept-flake-config github:kronor-io/pgstyle+```++Or add it to a flake's dev shell:++```nix+{+ inputs.pgstyle.url = "github:kronor-io/pgstyle";++ outputs = { nixpkgs, pgstyle, ... }: {+ devShells.x86_64-linux.default = nixpkgs.legacyPackages.x86_64-linux.mkShell {+ packages = [ pgstyle.packages.x86_64-linux.default ];+ };+ };+}+```++It builds for `x86_64-linux`, `aarch64-linux` and `aarch64-darwin`. To build+without Nix, see [Building from source](#building-from-source).++## Usage++### Format files++Name the files. They are rewritten in place, and files that are already+formatted are not touched:++```bash+pgstyle migrations/*.sql+```++With no files, or `-`, pgstyle reads stdin and writes stdout, which is what+editors want:++```bash+pgstyle < query.sql+```++Each statement is formatted on its own. Comments, blank lines and anything else+between statements stay byte for byte, so a file keeps its shape:++```sql+-- Orders placed this week, with their customer.+select o.id, o.total from orders o where o.status = 'paid';++-- Refunds need a positive amount.+CREATE TABLE refunds (id bigint generated always as identity primary key, order_id bigint not null references orders(id), amount numeric(12,2) not null check (amount > 0), created_at timestamptz not null default now());+```++```sql+-- Orders placed this week, with their customer.+select+ o.id+ , o.total+from orders o+where o.status = 'paid';++-- Refunds need a positive amount.+create table refunds (+ id bigint generated always as identity primary key,+ order_id bigint not null references orders(id),+ amount numeric(12, 2) not null check (amount > 0),+ created_at timestamptz not null default now()+);+```++### Check in CI++`--check` changes nothing. It names the files that are not formatted and+exits 1:++```console+$ pgstyle --check migrations/*.sql+migrations/0042-refunds.sql: not formatted+$ echo $?+1+```++In GitHub Actions:++```yaml+- uses: cachix/install-nix-action@v31+- run: nix run --accept-flake-config github:kronor-io/pgstyle -- --check $(git ls-files '*.sql')+```++As a [pre-commit](https://pre-commit.com) hook, with pgstyle on your `PATH`:++```yaml+repos:+ - repo: local+ hooks:+ - id: pgstyle+ name: pgstyle+ entry: pgstyle+ language: system+ files: \.sql$+```++### Exit codes++| Code | Meaning |+| ---- | ------- |+| 0 | Done; with `--check`, every file is formatted. |+| 1 | `--check` only: at least one file is not formatted. |+| 2 | A file is not valid SQL, or a statement failed verification (a formatter bug; that statement is left as it was). |++A file pgstyle cannot parse is never rewritten:++```console+$ echo 'selec 1;' | pgstyle+<stdin>: not valid SQL at byte 1: syntax error at or near "selec"+```++### See what was skipped++Some statements are left as they were on purpose, for example when the+renderer has no place for a comment inside them. `-v` says which ones, and+why:++```console+$ pgstyle -v --backend syntax queries.sql+queries.sql:2: kept: pgstyle does not lay it out: a comment pgstyle cannot place+```++## Choosing a style++### Keyword case++`--keyword-case lower` (the default) or `--keyword-case upper`. Every+statement pgstyle formats is spelled one way. Identifiers are never changed,+including the ones that look like keywords:++```console+$ echo "SELECT name, type FROM users WHERE value > 3;" | pgstyle --keyword-case upper+SELECT+ name+ , type+FROM users+WHERE value > 3;+```++### Backends++Two backends lay statements out, and they have different styles:++- `syntax`: pgstyle's own renderer. It handles `select`, `insert`, `update`,+ `delete` and `values`, with commas at the start of lines, and `create+ table`, `create view`, `create index`, `alter table` (see below) and+ `create function` (see [PL/pgSQL](#plpgsql)). It lays+ statements out from PostgreSQL's own parse tree (libpg_query's), keeping+ what the tree forgets from the source: redundant parentheses, `!=`, `as`+ before an alias, `inner join`, how a type is spelled, and comments. A+ comment goes where the layout breaks a line at its place: one that shares a+ line with code ends the line before the break, one on a line of its own+ stays on a line of its own. A list with a comment in it (select targets,+ arguments, `in (...)`, `values` rows, ...) puts one item per line:++ ```sql+ select+ id -- the key+ -- what the customer sees+ , display_name+ from customers+ where status in (+ 'active' -- paying+ , 'trial'+ );+ ```++ A statement with something it does not handle, such as a comment with no+ line break at its place (`a + -- note` and `b` on the next line), is left to+ `libpg-query` (or, with `--backend syntax`, as it is), never guessed at.+ (The SQL of Haskell quasiquotes, which libpg_query cannot parse, is laid out+ the same way from postgresql-syntax's tree, but not with comments inside.)+- `libpg-query`: libpg_query's pretty-printer. It puts commas at the end of+ lines, and it handles anything PostgreSQL parses, keeping the comments.++The default, `--backend auto`, uses `syntax` where it can and `libpg-query`+for the rest. Pick one backend to get a single style across the whole file:++```console+$ echo "select o.id, o.total, c.name from orders o join customers c on c.id = o.customer_id where o.status = 'paid';" | pgstyle --backend libpg-query+select o.id, o.total, c.name+from+ orders o+ join customers c on c.id = o.customer_id+where o.status = 'paid';+```++The `libpg-query` backend also takes `--indent N` (spaces per level,+default 4) and `--width N` (the line length it wraps lists at, default 80).++`create table` goes to `syntax` too, one column or constraint per line with+the comma at the end, as tables are usually written. It keeps the source's+own words (`temp` or `temporary`, an explicit `on delete no action`), blank+lines and comments between columns, and breaks a long `check` at its+top-level `and`s and a long foreign key before `references`:++```sql+create table refunds (+ id bigint generated always as identity primary key,+ order_id bigint not null references orders(id),++ -- Never more than the order's total.+ amount numeric(12, 2) not null,+ constraint fk_refund_order_line foreign key (order_id, line_id)+ references order_lines(order_id, id) on delete cascade,+ constraint amount_positive check (amount > 0)+);+```++`create view`, `create materialized view` and `create table ... as` put the+query on the lines after their head, laid out as a statement of its own:++```sql+create view paid_orders as+select+ o.id+ , o.total+from orders o+where o.status = 'paid';+```++`create index` puts `on` and `where` on lines of their own, and+`alter table` one action per line with the comma at the end. A long+condition, in an index's `where` or a `check`, breaks at its top-level+`and`s or `or`s:++```sql+alter table orders+ add column note text,+ add constraint note_len check (length(note) < 500);+create index concurrently orders_status_idx+ on orders (status)+ where status <> 'paid';+```++`create trigger` puts each clause on a line of its own, at the statement's+column. `grant` and `revoke` stay on one line if it fits in 80 characters;+otherwise `on` and `to` (or `from`) go on lines of their own, indented:++```sql+create trigger orders_touch+before update+on orders+for each row+when (new.status <> old.status)+execute function touch_updated_at();+grant select on orders to reporting;+grant select, insert, update+ on table orders, order_lines, refunds+ to order_service, reporting;+```++Any other DDL goes to `libpg-query`, as does a statement with something+`syntax` does not handle (`exclude`, `tablespace`, `attach partition`, ...):++```sql+create sequence order_numbers start 1000 cache 10;+comment on table orders is 'One row per checkout.';+```++## PL/pgSQL++To PostgreSQL, a function body is just a string. pgstyle also parses+PL/pgSQL bodies, and it formats the SQL statements inside them, indented to+where each one starts:++```sql+create function expire_pending_orders(cutoff interval) returns integer+language plpgsql as $$+declare+ expired integer;+begin+ update orders set status = 'expired', updated_at = now() where status = 'pending' and placed_at < now() - cutoff;+ get diagnostics expired = row_count;+ return expired;+end;+$$;+```++```sql+create function expire_pending_orders(cutoff interval)+ returns integer+ language plpgsql as+$$+declare+ expired integer;+begin+ update orders+ set+ status = 'expired'+ , updated_at = now()+ where status = 'pending'+ and placed_at < now() - cutoff;+ get diagnostics expired = row_count;+ return expired;+end;+$$;+```++The function's head is laid out too: its arguments on the first line, or+one per line if they do not fit, each clause before the body on a line of+its own with `as` ending the last, and the body on the next line, its+opening quote lined up with its closing one. The clauses after the body stay+on its last line. A SQL-standard body+(`begin atomic ... end`) has its statements laid out like any others.++The statements it formats are `insert`, `update`, `delete` and `select` run+for their effect, and `return query`. Everything else is left as written: the+PL/pgSQL around them (`declare`, `if`, loops, assignments) and statements with+`into`. The new body is only used if it parses to the same PL/pgSQL as the old+one.++pgstyle skips functions that libpg_query cannot compile. It does not look up+types outside `pg_catalog` and `public`, so a function that declares a+variable of type `myschema.thing` is left alone.++## How it stays safe++1. **Split.** libpg_query parses the whole file and gives each statement's+ byte range. Everything between statements is copied through unchanged.+2. **Format.** A backend lays out each statement.+3. **Verify.** libpg_query parses the new text. It must be one statement with+ the same parse tree, source positions aside, and the same number of+ comments as the original. The trees themselves are compared, not SQL+ printed from them, so two trees that print alike still count as different.+ This check does not depend on either backend. Finally, the whole new file+ must parse to the same statements as the old one.++ It does catch backend bugs. On Kronor's migrations, libpg_query's+ pretty-printer drops the quotes from function parameter names+ (`"startDate" date` comes out as `startDate date`, which PostgreSQL reads as+ `startdate`); pgstyle refuses those statements, leaves them as they are, and+ exits 2. One limit: libpg_query 18 leaves empty strings out of its trees, so+ `comment on t is ''` and `comment on t is null` look the same to it.+ PostgreSQL treats them the same too.++The check compares meaning, not spelling. libpg_query's backend writes some+things differently, and those changes pass: `integer` becomes `int`, an index+gets `using btree`, and `interval '7 days'` can become `'7 days'::interval`.++## Limits++- Files with psql meta-commands (`\set`, `\i`, `\gexec`) are not SQL, and+ pgstyle rejects them.+- Files that set `standard_conforming_strings = off` are left alone.+- `--backend auto` can mix the two styles in one file. Choose a backend if+ that matters to you.+- libpg_query moves a comment that it cannot attach to a node to the end of+ the statement: `select a -- x` followed by `from t` comes out as `select a`,+ `from t`, `-- x`.+- In Haskell quasiquotes, the `syntax` renderer fails its own check on some+ statements with `$$`-quoted strings that contain comments. Those statements+ are left as they are and pgstyle exits 2.++## Haskell: hasql-th quasiquotes++For `.hs` files, pgstyle formats the SQL in+[hasql-th](https://github.com/nikita-volkov/hasql-th) quasiquotes and leaves+the Haskell alone, so it sits next to fourmolu or ormolu, which leave+quasiquotes alone:++```bash+pgstyle src/**/*.hs+```++```haskell+userEmails :: Statement Int64 (Vector (Text, Maybe Text))+userEmails =+ [vectorStatement|+ select u.name :: text, e.address :: text? from users u left join emails e on e.user_id = u.id where u.org_id = $1 :: int8 order by u.name+ |]+```++```haskell+userEmails :: Statement Int64 (Vector (Text, Maybe Text))+userEmails =+ [vectorStatement|+ select+ u.name::text+ , e.address::text?+ from users u+ left join emails e+ on e.user_id = u.id+ where u.org_id = $1::int8+ order by u.name+ |]+```++The SQL goes one indent past the opening `[`, and the closing `|]` lines up+under it. The `syntax` backend lays it out, in lower case, with hasql-th's+extensions such as nullability markers (`text?`); `--backend` and+`--keyword-case` apply to SQL files only. A quasiquote's SQL is only replaced+if it parses back to the same postgresql-syntax AST, and the file must still+have the same quasiquotes and the same text around them.++- **Which quasiquotes:** hasql-th's `singletonStatement`, `maybeStatement`,+ `vectorStatement`, `foldStatement`, `resultlessStatement`,+ `rowsAffectedStatement`, and `uncheckedSql`, qualified or not+ (`[TH.singletonStatement|`). `--quoter NAME` adds another one, for your own+ aliases.+- **What is left alone:** single-line quasiquotes, and SQL postgresql-syntax+ does not parse (`-v` lists them), such as DDL in `uncheckedSql`.+- **Finding them:** pgstyle skips comments, string and character literals as GHC+ does, so a `[singletonStatement|` in a string is not a quasiquote. As in GHC+ with `QuasiQuotes` on, `[name|` with no space before the bar opens one.+- **stdin:** `--haskell` reads it as Haskell: `pgstyle --haskell < Foo.hs`.++`--dialect hasql-th` lets the `syntax` backend read the same extensions in a+SQL file, but libpg_query cannot read them, so such a file is not valid SQL to+pgstyle. The library's `PgStyle.Render.formatSql` formats one quasiquote's SQL.++### Kronor's extensions++Kronor's [fork of hasql-th](https://github.com/kronor-io/hasql-th) adds+Haskell targets (`$Record {field = a :: int8}`, `$f (a :: int8, b :: text)`)+and param fields (`$1.$field`). They need Kronor's fork of+postgresql-syntax, so they are behind the `kronor-syntax` cabal flag, off by+default. The flake builds that variant as `pgstyle-kronor`:++```bash+nix run --accept-flake-config github:kronor-io/pgstyle#pgstyle-kronor -- --help+```++With cabal, `cabal.project.kronor` adds Kronor's package repository and turns+the flag on:++```bash+cabal build --project-file=cabal.project.kronor exe:pgstyle+```++## Library++pgstyle is also a Haskell library:++- `PgStyle.File.formatFile`: a whole file, with a report on each statement.+- `PgStyle.Haskell.formatHaskell`: the hasql-th quasiquotes of a Haskell file,+ with a report on each.+- `PgStyle.Render.formatStatement`: one DML statement with the `syntax` layout.+- `PgStyle.Render.formatSql`: the SQL of one hasql-th quasiquote.++## Building from source++pgstyle links libpg_query 18, the major version that the `libpg-query`+package's protobuf definitions were generated from.++With Nix:++```bash+nix build # result/bin/pgstyle+nix build .#pgstyle-kronor # with the kronor-syntax flag+nix flake check # the test suites, both variants+```++The flake applies one patch to libpg_query,+[`nix/libpg_query-set-values-as-strings.patch`](nix/libpg_query-set-values-as-strings.patch).+Without it, libpg_query writes a `set` value that is not a plain lowercase+word as a quoted identifier: `set lock_timeout to '50ms'` comes out as+`set lock_timeout to "50ms"`. PostgreSQL reads both the same way, but the+patched library keeps the string.++The release binaries come from `scripts/build-static`, which builds the+patched libpg_query and pgstyle in a ghc-musl container with Docker and writes+`dist-static/pgstyle-<arch>-linux.tar.xz`. The image is the `Dockerfile` around+those binaries.++With cabal (GHC 9.12), everything else comes from Hackage. Build libpg_query+18 with that patch+(`patch -p1 < /path/to/pgstyle/nix/libpg_query-set-values-as-strings.patch` in+its source tree) and point cabal at it in `cabal.project.local` (for+`cabal.project.kronor`, `cabal.project.kronor.local`):++```cabal+package libpg-query+ extra-include-dirs: /path/to/libpg_query/include+ extra-lib-dirs: /path/to/libpg_query/lib+package pgstyle+ extra-include-dirs: /path/to/libpg_query/include+ extra-lib-dirs: /path/to/libpg_query/lib+```++```bash+cabal build exe:pgstyle+cabal test+```++## Contributing++`docs/readability.md` says how pgstyle's code is meant to read. Inside+`nix develop`, `scripts/check` runs the checks that CI runs:++```bash+scripts/check fast # fourmolu+scripts/check lint # pgstyle's hopinion rules, in lint/+scripts/check full # both, then every test+```
+ app/Main.hs view
@@ -0,0 +1,165 @@+{-# LANGUAGE ApplicativeDo #-}++module Main (main) where++import Control.Monad (forM, when)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import Options.Applicative+import PgStyle+import PgStyle.Haskell (Quoters, defaultQuoters, formatHaskell)+import PgStyle.LibPgQuery (LibPgQueryError (..), PrettyOptions (..), defaultPrettyOptions)+import System.Exit (ExitCode (..), exitWith)+import System.IO (stderr)+++data Cli = Cli+ { check :: Bool+ , verbose :: Bool+ , options :: Options+ , haskell :: Bool+ , quoters :: Quoters+ , files :: [FilePath]+ }+++cli :: Parser Cli+cli = do+ check <- switch (long "check" <> help "Change nothing; exit 1 if any file is not formatted")+ verbose <- switch (long "verbose" <> short 'v' <> help "Say which statements were left as they were, and why")+ backend <-+ option+ (eitherReader parseBackend)+ ( long "backend"+ <> metavar "auto|syntax|libpg-query"+ <> value Auto+ <> showDefaultWith (const "auto")+ <> help "What lays out statements: pgstyle's own renderer (DML), libpg_query's pretty-printer (anything), or the first where it applies and the second for the rest"+ )+ dialect <-+ option+ (eitherReader parseDialect)+ ( long "dialect"+ <> metavar "plain|hasql-th"+ <> value PlainSql+ <> showDefaultWith (const "plain")+ <> help "Accept hasql-th's extensions ($1 :: int8?, $Record {..}) in the syntax backend"+ )+ keywordCase <-+ option+ (eitherReader parseKeywordCase)+ ( long "keyword-case"+ <> metavar "lower|upper"+ <> value Lower+ <> showDefaultWith (const "lower")+ <> help "How to spell keywords in every formatted statement, whichever backend laid it out"+ )+ indentSize <- option auto (long "indent" <> metavar "N" <> value defaultPrettyOptions.indentSize <> showDefault <> help "libpg_query backend: spaces per indent level")+ maxLineLength <- option auto (long "width" <> metavar "N" <> value defaultPrettyOptions.maxLineLength <> showDefault <> help "libpg_query backend: line length to wrap lists at")+ haskell <- switch (long "haskell" <> help "Read stdin as Haskell, and format the SQL in its hasql-th quasiquotes (files ending in .hs always are)")+ extraQuoters <-+ many+ ( strOption+ ( long "quoter"+ <> metavar "NAME"+ <> help ("Haskell: also format quasiquotes of this quoter, besides " <> T.unpack (T.intercalate ", " defaultQuoters))+ )+ )+ files <- many (strArgument (metavar "FILE..." <> help "Files to format in place; none, or -, reads stdin and writes stdout"))+ pure+ Cli+ { check+ , verbose+ , options = Options{backend, dialect, keywordCase, pretty = PrettyOptions{indentSize, maxLineLength}}+ , haskell+ , quoters = defaultQuoters <> extraQuoters+ , files+ }+++parseBackend :: String -> Either String Backend+parseBackend = \case+ "auto" -> Right Auto+ "syntax" -> Right Syntax+ "libpg-query" -> Right LibPgQuery+ other -> Left ("unknown backend " <> other)+++parseKeywordCase :: String -> Either String KeywordCase+parseKeywordCase = \case+ "lower" -> Right Lower+ "upper" -> Right Upper+ other -> Left ("unknown keyword case " <> other)+++parseDialect :: String -> Either String Dialect+parseDialect = \case+ "plain" -> Right PlainSql+ "hasql-th" -> Right HasqlTh+ other -> Left ("unknown dialect " <> other)+++-- | How a file went, worst last.+data Status = Clean | Changed | Broken+ deriving stock (Eq, Ord)+++main :: IO ()+main = do+ args <- execParser (info (cli <**> helper) (fullDesc <> progDesc "Format PostgreSQL files, and the SQL in Haskell files' hasql-th quasiquotes"))+ statuses <- case args.files of+ [] -> pure <$> run args "-"+ fs -> forM fs (run args)+ let worst = maximum (Clean : statuses)+ exitWith case worst of+ Clean -> ExitSuccess+ Changed | args.check -> ExitFailure 1+ Changed -> ExitSuccess+ Broken -> ExitFailure 2+++run :: Cli -> FilePath -> IO Status+run args path = do+ input <- if path == "-" then TIO.getContents else TIO.readFile path+ result <-+ if isHaskell+ then pure (Right (formatHaskell args.quoters input))+ else formatFile args.options input+ case result of+ Left err -> do+ say (label <> ": not valid SQL" <> position err <> ": " <> err.message)+ pure Broken+ Right r -> do+ let failures = [rep | rep@StatementReport{outcome = Failed _} <- r.reports]+ mapM_ (report "error") failures+ when args.verbose $+ mapM_ (report "kept") [rep | rep@StatementReport{outcome = Kept _} <- r.reports]+ let changed = r.output /= input+ -- A file with a failed statement is still written: that statement+ -- is left as it was, and the others are fine.+ if+ | path == "-" && not args.check -> TIO.putStr r.output+ | changed && args.check -> say (label <> ": not formatted")+ | changed -> TIO.writeFile path r.output+ | otherwise -> pure ()+ pure+ if+ | not (null failures) -> Broken+ | changed -> Changed+ | otherwise -> Clean+ where+ isHaskell = if path == "-" then args.haskell else ".hs" `T.isSuffixOf` T.pack path+ label = T.pack (if path == "-" then "<stdin>" else path)+ position err = if err.cursor > 0 then " at byte " <> T.pack (show err.cursor) else ""+ report :: Text -> StatementReport -> IO ()+ report kind rep =+ say (label <> ":" <> T.pack (show rep.line) <> ": " <> kind <> ": " <> describe rep.outcome)+ describe = \case+ Failed reason -> reason+ Kept reason -> reason+ FormattedBy b -> T.pack (show b)+++say :: Text -> IO ()+say = TIO.hPutStrLn stderr
+ cbits/pgstyle.c view
@@ -0,0 +1,153 @@+/*+ * The libpg_query calls pgstyle makes, reshaped for Haskell's FFI, which cannot+ * take or return C structs by value. Every function returns 0 on success and+ * hands back a malloc'd buffer in *out / *out_len, which the caller frees with+ * free(). On failure it returns 1, *out holds the error message (also malloc'd,+ * NUL-terminated) and *cursor the 1-based byte position libpg_query reported,+ * or 0.+ */+#include <pg_query.h>+#include <stdlib.h>+#include <string.h>++static char *copy_bytes(const char *src, size_t len)+{+ char *dst = malloc(len + 1);+ if (dst == NULL)+ return NULL;+ if (len > 0)+ memcpy(dst, src, len);+ dst[len] = '\0';+ return dst;+}++static int fail(const PgQueryError *error, char **out, size_t *out_len, int *cursor)+{+ const char *message = error->message ? error->message : "unknown libpg_query error";+ *out_len = strlen(message);+ *out = copy_bytes(message, *out_len);+ *cursor = error->cursorpos;+ return 1;+}++/* The protobuf parse tree of sql. */+int pgstyle_parse(const char *sql, char **out, size_t *out_len, int *cursor)+{+ PgQueryProtobufParseResult result = pg_query_parse_protobuf(sql);+ int rc;+ if (result.error) {+ rc = fail(result.error, out, out_len, cursor);+ } else {+ *out_len = result.parse_tree.len;+ *out = copy_bytes(result.parse_tree.data, result.parse_tree.len);+ *cursor = 0;+ rc = 0;+ }+ pg_query_free_protobuf_parse_result(result);+ return rc;+}++/*+ * The JSON parse tree of sql. Unlike the protobuf, it tells an empty string+ * from a missing one (comment on t is '' from comment on t is null).+ */+int pgstyle_parse_json(const char *sql, char **out, size_t *out_len, int *cursor)+{+ PgQueryParseResult result = pg_query_parse(sql);+ int rc;+ if (result.error) {+ rc = fail(result.error, out, out_len, cursor);+ } else {+ *out_len = strlen(result.parse_tree);+ *out = copy_bytes(result.parse_tree, *out_len);+ *cursor = 0;+ rc = 0;+ }+ pg_query_free_parse_result(result);+ return rc;+}++/* The protobuf token stream of sql, comments included. */+int pgstyle_scan(const char *sql, char **out, size_t *out_len, int *cursor)+{+ PgQueryScanResult result = pg_query_scan(sql);+ int rc;+ if (result.error) {+ rc = fail(result.error, out, out_len, cursor);+ } else {+ *out_len = result.pbuf.len;+ *out = copy_bytes(result.pbuf.data, result.pbuf.len);+ *cursor = 0;+ rc = 0;+ }+ pg_query_free_scan_result(result);+ return rc;+}++/* libpg_query's JSON for the PL/pgSQL functions sql creates. */+int pgstyle_parse_plpgsql(const char *sql, char **out, size_t *out_len, int *cursor)+{+ PgQueryPlpgsqlParseResult result = pg_query_parse_plpgsql(sql);+ int rc;+ if (result.error) {+ rc = fail(result.error, out, out_len, cursor);+ } else {+ const char *json = result.plpgsql_funcs ? result.plpgsql_funcs : "[]";+ *out_len = strlen(json);+ *out = copy_bytes(json, *out_len);+ *cursor = 0;+ rc = 0;+ }+ pg_query_free_plpgsql_parse_result(result);+ return rc;+}++/*+ * SQL for a protobuf parse tree. With pretty set, libpg_query's pretty printer+ * lays it out, and the comments of comment_source (the text the tree was parsed+ * from, so their locations line up) are put back; comment_source may be NULL.+ */+int pgstyle_deparse(const char *tree, size_t tree_len, int pretty, int indent_size,+ int max_line_length, const char *comment_source,+ char **out, size_t *out_len, int *cursor)+{+ PgQueryProtobuf protobuf = {tree_len, (char *)tree};+ PostgresDeparseOpts opts;+ memset(&opts, 0, sizeof opts);++ PgQueryDeparseCommentsResult comments = {0};+ int have_comments = 0;+ if (pretty) {+ opts.pretty_print = true;+ opts.indent_size = indent_size;+ opts.max_line_length = max_line_length;+ if (comment_source != NULL) {+ comments = pg_query_deparse_comments_for_query(comment_source);+ have_comments = 1;+ if (comments.error) {+ int rc = fail(comments.error, out, out_len, cursor);+ pg_query_free_deparse_comments_result(comments);+ return rc;+ }+ opts.comments = comments.comments;+ opts.comment_count = comments.comment_count;+ }+ }++ PgQueryDeparseResult result = pretty+ ? pg_query_deparse_protobuf_opts(protobuf, opts)+ : pg_query_deparse_protobuf(protobuf);+ int rc;+ if (result.error) {+ rc = fail(result.error, out, out_len, cursor);+ } else {+ *out_len = strlen(result.query);+ *out = copy_bytes(result.query, *out_len);+ *cursor = 0;+ rc = 0;+ }+ pg_query_free_deparse_result(result);+ if (have_comments)+ pg_query_free_deparse_comments_result(comments);+ return rc;+}
+ pgstyle.cabal view
@@ -0,0 +1,160 @@+cabal-version: 3.0+name: pgstyle+version: 0.1.2.0+synopsis: Format PostgreSQL, checked against PostgreSQL's own parser+description:+ pgstyle formats SQL files statement by statement. Each statement is laid out+ either by pgstyle's own renderer (DML, over libpg_query's parse tree) or by+ libpg_query's pretty-printer (anything PostgreSQL parses), and is only+ rewritten if libpg_query reads the result as the same statement.++category: Database+homepage: https://github.com/kronor-io/pgstyle+bug-reports: https://github.com/kronor-io/pgstyle/issues+license: MIT+license-file: LICENSE+copyright: 2026 Kronor+author: Kronor+maintainer: dev@kronor.io+build-type: Simple+extra-doc-files:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/kronor-io/pgstyle++flag kronor-syntax+ description:+ Accept the hasql-th extensions of Kronor's forks (Haskell targets and+ Haskell param fields) in the hasql-th dialect. Needs Kronor's fork of+ postgresql-syntax.++ manual: True+ default: False++common shared+ default-language: GHC2021+ default-extensions:+ BlockArguments+ DerivingStrategies+ DuplicateRecordFields+ LambdaCase+ MultiWayIf+ NamedFieldPuns+ OverloadedRecordDot+ OverloadedStrings+ StrictData++ ghc-options:+ -Wall -Wcompat -Werror=missing-signatures -Werror=missing-fields+ -Werror=incomplete-patterns -Werror=incomplete-uni-patterns+ -Werror=incomplete-record-updates++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ PgStyle+ PgStyle.File+ PgStyle.Haskell+ PgStyle.Layout+ PgStyle.LibPgQuery+ PgStyle.Plpgsql+ PgStyle.Render++ other-modules:+ PgStyle.Layout.Comments+ PgStyle.Layout.Ddl+ PgStyle.Layout.Dml+ PgStyle.Layout.Expr+ PgStyle.Layout.Locations+ PgStyle.Layout.Monad+ PgStyle.Layout.Names+ PgStyle.Layout.Parens++ c-sources: cbits/pgstyle.c+ extra-libraries: pg_query+ build-depends:+ , aeson+ , base >=4.18 && <5+ , bytestring+ , containers+ , libpg-query ^>=0.1+ , microlens+ , postgresql-syntax >=0.5.0.3 && <0.6+ , mtl+ , prettyprinter+ , proto-lens+ , syb+ , text >=2.0+ , text-builder++ -- The fork versions itself 0.5.0.3.0.*, under upstream's 0.5.0.4; without+ -- the flag, keep the solver off it even where its repository is configured.+ if flag(kronor-syntax)+ cpp-options: -DKRONOR_SYNTAX+ build-depends: postgresql-syntax ==0.5.0.3.0.*++ else+ build-depends: postgresql-syntax ==0.5.0.3 || >=0.5.0.4 && <0.6++executable pgstyle+ import: shared+ hs-source-dirs: app+ main-is: Main.hs+ build-depends:+ , base+ , optparse-applicative+ , pgstyle+ , text++-- The renderer's fixtures, carried over from Kronor's hasql-th-format.+test-suite render+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: RenderSpec.hs+ default-extensions: QuasiQuotes+ build-depends:+ , base+ , pgstyle+ , postgresql-syntax+ , string-interpolate+ , text++ if flag(kronor-syntax)+ cpp-options: -DKRONOR_SYNTAX++test-suite file+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: FileSpec.hs+ build-depends:+ , base+ , pgstyle+ , text++test-suite haskell+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: HaskellSpec.hs+ build-depends:+ , base+ , pgstyle+ , text++-- pgstyle's layout over libpg_query's tree: the same as the renderer's over+-- postgresql-syntax's, and what only it lays out.+test-suite layout+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: LayoutSpec.hs+ build-depends:+ , base+ , pgstyle+ , text
+ src/PgStyle.hs view
@@ -0,0 +1,19 @@+-- | Format PostgreSQL.+--+-- * "PgStyle.File" formats whole files, statement by statement.+-- * "PgStyle.Haskell" formats the SQL in a Haskell file's hasql-th+-- quasiquotes.+-- * "PgStyle.Render" formats one DML statement with pgstyle's own layout, and+-- the SQL of hasql-th quasiquotes.+-- * "PgStyle.LibPgQuery" holds the libpg_query calls both rely on.+module PgStyle (+ module PgStyle.File,+ Dialect (..),+ FormatError (..),+ formatStatement,+ formatSql,+) where++import PgStyle.File+import PgStyle.Render (Dialect (..), FormatError (..), formatSql, formatStatement)+
+ src/PgStyle/File.hs view
@@ -0,0 +1,501 @@+-- | Formatting a whole SQL file: libpg_query splits it into statements, each+-- statement is formatted on its own by the chosen backend, and everything+-- between statements (whitespace, comments, semicolons) is kept byte for byte.+--+-- No statement is rewritten unless libpg_query, PostgreSQL's own parser, reads+-- the result as the same statement: its parse tree, positions aside+-- ('canonical'), before and after must match. That check is independent of either backend's own.+module PgStyle.File (+ Backend (..),+ KeywordCase (..),+ Options (..),+ defaultOptions,+ Outcome (..),+ StatementReport (..),+ FileResult (..),+ formatFile,+) where++import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.List (dropWhileEnd)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout qualified as Layout+import PgStyle.LibPgQuery (LibPgQueryError (..), PrettyOptions, Statement (..), Token (..))+import PgStyle.LibPgQuery qualified as LibPgQuery+import PgStyle.Plpgsql qualified as Plpgsql+import PgStyle.Render (Dialect (..), FormatError (..))+import PgStyle.Render qualified as Render+++-- | What lays out a statement.+data Backend+ = -- | pgstyle's own layout. DML only; statements it does not lay out+ -- are left as they are. Plain SQL is laid out from libpg_query's parse+ -- tree ("PgStyle.Layout"), comments and all; the hasql-th dialect from+ -- postgresql-syntax's ("PgStyle.Render"), which leaves statements with+ -- comments inside them as they are.+ Syntax+ | -- | libpg_query's pretty-printer. Any statement PostgreSQL parses,+ -- comments included.+ LibPgQuery+ | -- | 'Syntax' where it applies, 'LibPgQuery' for the rest.+ Auto+ deriving stock (Eq, Show)+++-- | How every formatted statement spells its keywords, whichever backend+-- laid it out. Identifiers are never touched.+data KeywordCase = Lower | Upper+ deriving stock (Eq, Show)+++data Options = Options+ { backend :: Backend+ , dialect :: Dialect+ , keywordCase :: KeywordCase+ , pretty :: PrettyOptions+ }+ deriving stock (Eq, Show)+++defaultOptions :: Options+defaultOptions =+ Options+ { backend = Auto+ , dialect = PlainSql+ , keywordCase = Lower+ , pretty = LibPgQuery.defaultPrettyOptions+ }+++-- | What happened to one statement.+data Outcome+ = -- | Rewritten by this backend (unchanged text counts too).+ FormattedBy Backend+ | -- | Left as it was, for this reason. Not an error.+ Kept Text+ | -- | A backend produced SQL that PostgreSQL reads as a different+ -- statement, or not at all. The statement is left as it was, but this is+ -- a formatter bug and the caller should fail.+ Failed Text+ deriving stock (Eq, Show)+++data StatementReport = StatementReport+ { line :: Int+ -- ^ 1-based line the statement starts on.+ , outcome :: Outcome+ }+ deriving stock (Eq, Show)+++data FileResult = FileResult+ { output :: Text+ , reports :: [StatementReport]+ }+ deriving stock (Eq, Show)+++-- | Format every statement of a file. 'Left' when PostgreSQL cannot parse the+-- file at all (it is invalid SQL, or holds psql meta-commands).+formatFile :: Options -> Text -> IO (Either LibPgQueryError FileResult)+formatFile opts text+ -- libpg_query parses strings as with standard_conforming_strings on, the+ -- default since PostgreSQL 9.1. A file that turns it off reads+ -- backslashes in '...' strings differently from how pgstyle would verify+ -- them, so it is left alone.+ | "standard_conforming_strings" `T.isInfixOf` T.toLower text =+ pure . Right $+ FileResult+ { output = text+ , reports = [StatementReport{line = 1, outcome = Kept "the file sets standard_conforming_strings"}]+ }+ | otherwise = do+ let source = TE.encodeUtf8 text+ parsed <- LibPgQuery.parse source+ scanned <- LibPgQuery.scan source+ case (,) <$> parsed <*> scanned of+ Left err -> pure (Left err)+ Right (tree, scanResult) -> do+ let toks = LibPgQuery.tokens scanResult+ let stmts = LibPgQuery.statements source tree+ results <- traverse (formatOne opts source toks) stmts+ let r = assemble source results+ -- Each statement was checked on its own; check the file as a+ -- whole too, which also catches text between statements that a+ -- rewrite changed the meaning of (a semicolon commented out).+ same <- sameStatements (map (.expected) results) r.output+ pure . Right $ case same of+ Nothing -> r+ Just reason ->+ FileResult+ { output = text+ , reports = r.reports <> [StatementReport{line = 1, outcome = Failed ("the formatted file " <> reason)}]+ }+++-- | 'Nothing' when the file parses to the statements of these SQL texts, by+-- normal form.+sameStatements :: [ByteString] -> Text -> IO (Maybe Text)+sameStatements expected output = do+ before <- traverse LibPgQuery.canonical expected+ after <- LibPgQuery.canonical (TE.encodeUtf8 output)+ pure case (concat <$> sequence before, after) of+ (_, Left err) -> Just ("does not parse: " <> err.message)+ (Left err, _) -> Just ("has a statement that no longer parses on its own: " <> err.message)+ (Right b, Right a)+ | a == b -> Nothing+ | otherwise -> Just "holds different statements than the original"+++-- | A statement's new text for the byte range it replaces.+data Replacement = Replacement+ { from :: Int+ , to :: Int+ , text :: Maybe Text+ , report :: StatementReport+ , expected :: ByteString+ -- ^ The statement the new text must parse to: the original, or the+ -- original with its PL/pgSQL body formatted.+ }+++assemble :: ByteString -> [Replacement] -> FileResult+assemble source replacements =+ FileResult+ { output = T.concat (go 0 replacements)+ , reports = map (.report) replacements+ }+ where+ slice a b = decode (BS.take (b - a) (BS.drop a source))+ go pos [] = [slice pos (BS.length source)]+ go pos (r : rs) = case r.text of+ Nothing -> go pos rs+ Just new -> slice pos r.from : new : go r.to rs+++formatOne :: Options -> ByteString -> [Token] -> Statement -> IO Replacement+formatOne opts source toks stmt =+ case statementCode source toks stmt of+ Nothing -> pure (keep stmt.start stmt.end "empty statement")+ Just code+ | code.start == code.end -> pure (done code (Kept "only comments") Nothing original)+ | otherwise -> do+ prepared <- formatBody opts code.text stmt.raw+ case prepared of+ Left reason -> pure (done code (Failed reason) Nothing original)+ Right p -> do+ laid <- layOut opts code.column p.sql+ pure case laid of+ Right (used, formatted) -> done code (FormattedBy used) (Just formatted) p.sql+ Left outcome@(Kept _)+ | p.bodyChanged -> done code outcome (Just (decode p.sql)) p.sql+ Left outcome -> done code outcome Nothing original+ where+ -- The statement as written, which an unchanged one must still parse to.+ original = BS.take (stmt.end - stmt.start) (BS.drop stmt.start source)+ keep a b reason =+ Replacement+ { from = a+ , to = b+ , text = Nothing+ , report = StatementReport{line = lineAt source a, outcome = Kept reason}+ , expected = original+ }+ done code outcome new expected =+ Replacement+ { from = code.start+ , to = code.end+ , text = new+ , report = StatementReport{line = lineAt source code.start, outcome}+ , expected+ }+++-- | A statement proper: from its first token that is not a comment to its+-- last. Comments and whitespace on either side stay where they are.+data StatementCode = StatementCode+ { start :: Int+ , end :: Int+ -- ^ Equal to 'start' when the statement is only comments.+ , text :: ByteString+ , column :: Int+ -- ^ The column the statement starts at, when only whitespace precedes it+ -- on its line, which its other lines line up with; else 0.+ }+++-- | Where a statement's code is; 'Nothing' when it has no tokens at all.+statementCode :: ByteString -> [Token] -> Statement -> Maybe StatementCode+statementCode source toks stmt = case [t | t <- toks, t.start >= stmt.start, t.end <= stmt.end] of+ [] -> Nothing+ inside ->+ let code = dropWhileEnd (.isComment) (dropWhile (.isComment) inside)+ start = case code of+ t : _ -> t.start+ [] -> stmt.end+ end = maximum (start : map (.end) code)+ lineBefore = decode (snd (BS.breakEnd (== 10) (BS.take start source)))+ in Just+ StatementCode+ { start+ , end+ , text = BS.take (end - start) (BS.drop start source)+ , column = if T.all (== ' ') lineBefore then T.length lineBefore else 0+ }+++-- | The 1-based line of a byte offset.+lineAt :: ByteString -> Int -> Int+lineAt source offset = 1 + BS.count 10 (BS.take offset source)+++-- | A statement ready to lay out: with its PL/pgSQL body formatted, if it has+-- one pgstyle formats.+data Prepared = Prepared+ { sql :: ByteString+ , bodyChanged :: Bool+ }+++-- | Format a statement's PL/pgSQL body, and check the statement still parses+-- with it.+formatBody :: Options -> ByteString -> Pg.RawStmt -> IO (Either Text Prepared)+formatBody opts code raw = do+ bodies <- Plpgsql.formatBodies (formatEmbedded opts) code raw+ case bodies of+ Left reason -> pure (Left reason)+ Right Nothing -> pure (Right Prepared{sql = code, bodyChanged = False})+ Right (Just code') -> do+ reparsed <- LibPgQuery.parse code'+ pure case reparsed of+ Right tree | [_] <- tree ^. Pg.stmts -> Right Prepared{sql = code', bodyChanged = True}+ _ -> Left "the statement with its formatted PL/pgSQL body does not parse"+++-- | Lay out one statement (no comments before or after it), starting at+-- @column@, and check the result still parses to the same statement.+layOut :: Options -> Int -> ByteString -> IO (Either Outcome (Backend, Text))+layOut opts column code = do+ scanned <- LibPgQuery.scan code+ let comments = either (const 0) (length . filter (.isComment) . LibPgQuery.tokens) scanned+ attempt <- runBackend opts column code (comments > 0)+ case attempt of+ Left outcome -> pure (Left outcome)+ Right laid -> do+ let used = laid.backend+ cased <- if laid.keywordsCased then pure (Right laid.text) else applyKeywordCase opts used code laid.text+ case cased of+ Left reason -> pure (Left (Failed reason))+ Right formatted1 -> do+ formatted <- endLineComment =<< indentContinuation column formatted1+ verdict <- verify code (TE.encodeUtf8 formatted) comments+ pure case verdict of+ Nothing -> Right (used, formatted)+ Just reason -> Left (Failed reason)+++-- | Lay out a SQL statement embedded in a PL/pgSQL body.+formatEmbedded :: Options -> Int -> ByteString -> IO (Either Text (Maybe Text))+formatEmbedded opts column query = do+ parsed <- LibPgQuery.parse query+ case parsed of+ Right tree | [_] <- tree ^. Pg.stmts -> do+ laid <- layOut opts column query+ pure case laid of+ Right (_, formatted) -> Right (Just formatted)+ Left (Failed reason) -> Left reason+ Left _ -> Right Nothing+ _ -> pure (Right Nothing)+++-- | A statement as a backend laid it out.+data Laid = Laid+ { backend :: Backend+ , keywordsCased :: Bool+ -- ^ Whether its keywords are already in the requested case.+ , text :: Text+ }+++-- | Lay out one statement, or say why not.+runBackend :: Options -> Int -> ByteString -> Bool -> IO (Either Outcome Laid)+runBackend opts column body interiorComments = case opts.backend of+ Syntax -> syntax body+ LibPgQuery -> libpgQuery body+ Auto -> do+ laid <- syntax body+ case laid of+ Right ok -> pure (Right ok)+ Left (Failed reason) -> pure (Left (Failed reason))+ Left (Kept _) -> libpgQuery body+ Left other -> pure (Left other)+ where+ syntax sql = case opts.dialect of+ PlainSql -> do+ laid <- Layout.formatStatementAt (opts.keywordCase == Upper) column sql+ pure case laid of+ Right formatted -> Right Laid{backend = Syntax, keywordsCased = True, text = formatted}+ Left reason -> Left (Kept ("pgstyle does not lay it out: " <> reason))+ HasqlTh+ -- postgresql-syntax's tree has no comments to place.+ | interiorComments -> pure (Left (Kept "comments inside the statement"))+ | otherwise -> pure case Render.formatStatement opts.dialect (decode sql) of+ Right formatted -> Right Laid{backend = Syntax, keywordsCased = False, text = formatted}+ Left (Unsupported _) -> Left (Kept "postgresql-syntax does not parse it")+ Left (RendererBug reason) -> Left (Failed reason)+ libpgQuery sql = do+ parsed <- LibPgQuery.parse sql+ case parsed of+ Left err -> pure (Left (Failed ("libpg_query could not re-parse the statement: " <> err.message)))+ Right tree -> do+ printed <- LibPgQuery.deparsePretty opts.pretty (Just sql) tree+ pure case printed of+ Left err -> Left (Kept ("libpg_query could not deparse it: " <> err.message))+ Right formatted -> Right Laid{backend = LibPgQuery, keywordsCased = False, text = T.strip formatted}+++-- | Spell the keywords of a backend's output in the chosen case.+--+-- Telling keywords from identifiers spelled like keywords (@name@, @type@):+-- libpg_query writes keywords in upper case and unquoted identifiers in lower+-- case, so its upper-case keyword tokens are keywords. For the syntax backend+-- on the hasql-th dialect, the statement is rendered again with its+-- identifiers masked ('Render.renderIdentifiersMasked'); the tokens that+-- differ between the two renderings are identifiers. ("PgStyle.Layout", for+-- plain SQL, writes keywords in the right case itself.)+applyKeywordCase :: Options -> Backend -> ByteString -> Text -> IO (Either Text Text)+applyKeywordCase opts used body formatted = do+ let bytes = TE.encodeUtf8 formatted+ scanned <- LibPgQuery.scan bytes+ case scanned of+ Left err -> pure (Left ("formatted SQL does not scan: " <> err.message))+ Right result -> do+ let toks = LibPgQuery.tokens result+ keywords <- case used of+ Syntax -> case Render.renderIdentifiersMasked opts.dialect (decode body) of+ Left _ -> pure (Left "could not render the statement's identifiers")+ Right marked -> do+ let markedBytes = TE.encodeUtf8 marked+ markedScan <- LibPgQuery.scan markedBytes+ pure case markedScan of+ Right m+ | Just ks <- unmaskedKeywords bytes toks markedBytes (LibPgQuery.tokens m) -> Right ks+ _ -> Left "could not tell keywords from identifiers"+ _ -> pure (Right (upperCaseKeywords bytes toks))+ pure (recaseTokens opts.keywordCase bytes <$> keywords)+++-- | The keyword tokens of a rendering that its rendering with identifiers+-- masked spells the same; 'Nothing' when the two do not have the same+-- tokens.+unmaskedKeywords :: ByteString -> [Token] -> ByteString -> [Token] -> Maybe [Token]+unmaskedKeywords bytes toks markedBytes markedToks+ | length markedToks /= length toks = Nothing+ | otherwise =+ Just+ [ t+ | (t, t') <- zip toks markedToks+ , t.isKeyword+ , tokenText bytes t == tokenText markedBytes t'+ ]+++-- | The keyword tokens libpg_query wrote in upper case: its keywords, as it+-- writes unquoted identifiers in lower case.+upperCaseKeywords :: ByteString -> [Token] -> [Token]+upperCaseKeywords bytes toks =+ [ t+ | t <- toks+ , t.isKeyword+ , let word = tokenText bytes t+ , T.toUpper word == word+ ]+++-- | The text with these tokens, in order, in the keyword case.+recaseTokens :: KeywordCase -> ByteString -> [Token] -> Text+recaseTokens keywordCase bytes keywords = T.concat (go 0 keywords)+ where+ recase = case keywordCase of+ Lower -> T.toLower+ Upper -> T.toUpper+ go pos [] = [decode (BS.drop pos bytes)]+ go pos (t : ts) =+ decode (BS.take (t.start - pos) (BS.drop pos bytes)) : recase (tokenText bytes t) : go t.end ts+++tokenText :: ByteString -> Token -> Text+tokenText src t = decode (BS.take (t.end - t.start) (BS.drop t.start src))+++-- | Indent every line but the first by this many spaces, except lines that+-- start inside a token (a multi-line string or function body), whose text+-- that would change.+indentContinuation :: Int -> Text -> IO Text+indentContinuation 0 formatted = pure formatted+indentContinuation column formatted = do+ let bytes = TE.encodeUtf8 formatted+ scanned <- LibPgQuery.scan bytes+ let toks = either (const []) LibPgQuery.tokens scanned+ insideToken p = any (\t -> t.start < p && p < t.end) toks+ -- Byte offset at which each line starts.+ starts = scanl (\acc l -> acc + BS.length l + 1) 0 (BS.split 10 bytes)+ pad (start, l)+ | start == 0 || BS.null l || insideToken start = l+ | otherwise = BS.replicate column 32 <> l+ pure case scanned of+ -- Not scannable: the verification after this rejects it anyway.+ Left _ -> formatted+ Right _ -> decode (BS.intercalate "\n" (map pad (zip starts (BS.split 10 bytes))))+++-- | A line comment at the end of a statement would swallow whatever follows+-- it on the line, the semicolon first. libpg_query moves comments it cannot+-- place to the end, so end the line after one.+endLineComment :: Text -> IO Text+endLineComment formatted = do+ scanned <- LibPgQuery.scan (TE.encodeUtf8 formatted)+ pure case scanned of+ Right result+ | t : _ <- reverse (LibPgQuery.tokens result)+ , t.isComment+ , "--" `T.isPrefixOf` decode (BS.drop t.start (TE.encodeUtf8 formatted)) ->+ formatted <> "\n"+ _ -> formatted+++-- | 'Nothing' when the formatted SQL is one statement with the original's+-- normal form and as many comments; otherwise why not.+verify :: ByteString -> ByteString -> Int -> IO (Maybe Text)+verify original formatted commentCount = do+ before <- LibPgQuery.canonical original+ after <- LibPgQuery.canonical formatted+ rescanned <- LibPgQuery.scan formatted+ case (before, after, rescanned) of+ (Left err, _, _) -> pure (Just ("the original does not parse on its own: " <> err.message))+ (_, Left err, _) -> pure (Just ("formatted SQL does not parse: " <> err.message))+ (_, _, Left err) -> pure (Just ("formatted SQL does not scan: " <> err.message))+ (Right b, Right a, Right scanResult)+ | length a /= 1 -> pure (Just ("formatted SQL is " <> T.pack (show (length a)) <> " statements"))+ | a /= b ->+ pure . Just $+ "formatted SQL is a different statement:\n before: "+ <> oneLine original+ <> "\n after: "+ <> oneLine formatted+ | comments scanResult /= commentCount ->+ pure (Just ("formatting lost comments: " <> T.pack (show commentCount) <> " before, " <> T.pack (show (comments scanResult)) <> " after"))+ | otherwise -> pure Nothing+ where+ comments scanResult = length (filter (.isComment) (LibPgQuery.tokens scanResult))+ oneLine = T.unwords . T.words . decode+++decode :: ByteString -> Text+decode = TE.decodeUtf8Lenient
+ src/PgStyle/Haskell.hs view
@@ -0,0 +1,271 @@+-- | Formatting the SQL in a Haskell file's hasql-th quasiquotes.+--+-- A small scanner finds the quasiquotes, skipping comments, string and+-- character literals the way GHC's lexer does, so a @[singletonStatement|@+-- inside a string or a comment is not mistaken for one. Each quasiquote whose+-- quoter is in 'Quoters' has its SQL laid out by "PgStyle.Render", which only+-- returns SQL that parses back to the same postgresql-syntax AST. Everything+-- else in the file is kept as it is, and the result is scanned again to check+-- that it holds the same quasiquotes and the same text around them.+module PgStyle.Haskell (+ Quoters,+ defaultQuoters,+ QuasiQuote (..),+ quasiQuotes,+ formatHaskell,+) where++import Data.Char (isAlphaNum, isLower, isSpace, isUpper)+import Data.List (sortOn)+import Data.Text (Text)+import Data.Text qualified as T+import PgStyle.File (FileResult (..), Outcome (..), StatementReport (..))+import PgStyle.File qualified as File+import PgStyle.Render (FormatError (..))+import PgStyle.Render qualified as Render+++-- | The quoters whose quasiquotes hold SQL to format, by unqualified name: a+-- qualified @[TH.singletonStatement|@ counts as @singletonStatement@.+type Quoters = [Text]+++-- | hasql-th's statement quoters, and 'uncheckedSql'.+defaultQuoters :: Quoters+defaultQuoters =+ [ "singletonStatement"+ , "maybeStatement"+ , "vectorStatement"+ , "foldStatement"+ , "resultlessStatement"+ , "rowsAffectedStatement"+ , "uncheckedSql"+ ]+++-- | One quasiquote, @[quoter|body|]@. Offsets count characters from the start+-- of the file.+data QuasiQuote = QuasiQuote+ { quoter :: Text+ -- ^ As written, qualified or not.+ , bodyStart :: Int+ -- ^ Offset of the body's first character, just after the opening @|@.+ , bodyEnd :: Int+ -- ^ Offset of the closing @|]@.+ , line :: Int+ -- ^ 1-based line of the opening @[@.+ , column :: Int+ -- ^ 0-based column of the opening @[@.+ }+ deriving stock (Eq, Show)+++-- | Every quasiquote in a Haskell source file, in order.+--+-- As in GHC with QuasiQuotes on, @[name|@ with no space before the bar opens+-- one, and the first @|]@ closes it; @[e|@, @[d|@, @[t|@ and @[p|@ are+-- Template Haskell brackets, whose contents are Haskell. A @[name|@ with no+-- @|]@ after it is taken for a list comprehension.+quasiQuotes :: Text -> [QuasiQuote]+quasiQuotes source = code Cursor{offset = 0, line = 1, column = 0} Nothing (T.unpack source)+ where+ -- Where the scan is, the character before, and the rest.+ code :: Cursor -> Maybe Char -> String -> [QuasiQuote]+ code _ _ [] = []+ code at prev s@(x : rest)+ | x == '{', '-' : _ <- rest = blockComment (forward 2 at) (1 :: Int) (drop 1 rest)+ | x == '-', lineComment prev s = skipLine at s+ | x == '"' = string (forward 1 at) rest+ | x == '\'' = charLiteral+ | x == '['+ , Just (name, afterBar) <- opening rest =+ let open = at.offset + 1 + T.length name + 1+ in case closing open afterBar of+ Just (end, afterClose)+ | name `notElem` ["e", "d", "t", "p"] ->+ let body = take (end - open) afterBar+ in QuasiQuote{quoter = name, bodyStart = open, bodyEnd = end, line = at.line, column = at.column}+ : code (past ('[' : T.unpack name <> "|" <> body <> "|]") at) (Just ']') afterClose+ _ -> step+ | otherwise = step+ where+ step = code (past [x] at) (Just x) rest+ -- A prime after an identifier character is part of the name (x', f'');+ -- ''T quotes a type name; otherwise a character literal is 'x' or an+ -- escape, '\n', and anything else is a quoted name, 'f.+ charLiteral+ | Just p <- prev, isIdentChar p = step+ | '\'' : more <- rest = code (forward 2 at) (Just '\'') more+ -- The character after the backslash is part of the escape even+ -- when it is a quote, '\''.+ | '\\' : _ : more <- rest =+ let (escape, after) = break (== '\'') more+ in code (forward (3 + length escape + 1) at) (Just '\'') (drop 1 after)+ | _ : '\'' : more <- rest = code (forward 3 at) (Just '\'') more+ | otherwise = step++ skipLine at s =+ let (comment, after) = break (== '\n') s+ in case after of+ [] -> []+ _ : more -> code (past (comment <> "\n") at) (Just '\n') more++ blockComment at depth s = case s of+ [] -> []+ '-' : '}' : more+ | depth == 1 -> code (forward 2 at) (Just '}') more+ | otherwise -> blockComment (forward 2 at) (depth - 1) more+ '{' : '-' : more -> blockComment (forward 2 at) (depth + 1) more+ x : more -> blockComment (past [x] at) depth more++ string at s = case s of+ [] -> []+ '"' : more -> code (forward 1 at) (Just '"') more+ -- A string gap, \ \, spans whitespace (newlines too) between two+ -- backslashes.+ '\\' : w : more+ | isSpace w ->+ let (gap, after) = break (== '\\') (w : more)+ in string (past ('\\' : gap <> "\\") at) (drop 1 after)+ '\\' : e : more -> string (past ['\\', e] at) more+ -- An unterminated string ends at the line; GHC would reject the file.+ '\n' : more -> code (past "\n" at) (Just '\n') more+ x : more -> string (past [x] at) more+++-- | Where a scan is: an offset in characters, a 1-based line and a 0-based+-- column.+data Cursor = Cursor+ { offset :: Int+ , line :: Int+ , column :: Int+ }+++-- | The cursor after these characters.+past :: String -> Cursor -> Cursor+past s at = foldl step at s+ where+ step c x+ | x == '\n' = c{offset = c.offset + 1, line = c.line + 1, column = 0}+ | otherwise = c{offset = c.offset + 1, column = c.column + 1}+++-- | The cursor after this many characters, none of them a line break.+forward :: Int -> Cursor -> Cursor+forward n at = at{offset = at.offset + n, column = at.column + n}+++-- | Whether a @-@ at this point starts a line comment: two or more dashes+-- that are not part of an operator such as @-->@ or @|--@.+lineComment :: Maybe Char -> String -> Bool+lineComment prev s =+ let (dashes, after) = span (== '-') s+ in length dashes >= 2+ && maybe True (not . isSymbol) prev+ && case after of+ [] -> True+ y : _ -> not (isSymbol y)+++isSymbol :: Char -> Bool+isSymbol x = x `elem` ("!#$%&*+./<=>?@\\^|-~:" :: String)+++isIdentChar :: Char -> Bool+isIdentChar x = isAlphaNum x || x == '_' || x == '\''+++-- | @name|@ after a @[@, the name possibly qualified, with no space before+-- the bar: the name and what follows the bar.+opening :: String -> Maybe (Text, String)+opening s =+ let (name, after) = span (\x -> isIdentChar x || x == '.') s+ in case after of+ '|' : rest | validQuoter name -> Just (T.pack name, rest)+ _ -> Nothing+ where+ validQuoter name = case splitDots name of+ [] -> False+ parts ->+ all qualifier (init parts) && variable (last parts)+ qualifier p = case p of+ x : _ -> isUpper x+ [] -> False+ variable p = case p of+ x : _ -> isLower x || x == '_'+ [] -> False+ splitDots = map T.unpack . T.splitOn "." . T.pack+++-- | The offset of the first @|]@ at or after this one, and what follows it.+closing :: Int -> String -> Maybe (Int, String)+closing i = \case+ [] -> Nothing+ '|' : ']' : more -> Just (i, more)+ _ : more -> closing (i + 1) more+++-- | The unqualified name of a quoter.+baseName :: Text -> Text+baseName = snd . T.breakOnEnd "."+++-- | Format the SQL of every quasiquote of these quoters. Each gets a report,+-- at the line of its opening bracket. A quasiquote whose SQL would come out+-- meaning something else is left as it was and reported as 'Failed'.+formatHaskell :: Quoters -> Text -> FileResult+formatHaskell quoters source =+ let found = zip [0 :: Int ..] (quasiQuotes source)+ results = [(n, q, one q) | (n, q) <- found, baseName q.quoter `elem` quoters]+ edits = [(q, new) | (_, q, (Just new, _)) <- results]+ rewritten = [n | (n, _, (Just _, _)) <- results]+ output = splice source edits+ reports = [StatementReport{line = q.line, outcome = o} | (_, q, (_, o)) <- results]+ in case sameOutside source output rewritten of+ Nothing -> FileResult{output, reports}+ Just reason ->+ FileResult+ { output = source+ , reports = reports <> [StatementReport{line = 1, outcome = Failed ("the formatted file " <> reason)}]+ }+ where+ one q =+ let body = T.take (q.bodyEnd - q.bodyStart) (T.drop q.bodyStart source)+ in if+ | "\r" `T.isInfixOf` body -> (Nothing, Kept "CRLF line endings")+ | otherwise -> case Render.formatQuasiQuote q.column body of+ Right Nothing -> (Nothing, Kept "single-line quasiquotes are left as they are")+ Right (Just new) -> (Just new, FormattedBy File.Syntax)+ Left (Unsupported _) -> (Nothing, Kept "postgresql-syntax does not parse it")+ Left (RendererBug reason) -> (Nothing, Failed reason)+++-- | Replace the bodies of these quasiquotes.+splice :: Text -> [(QuasiQuote, Text)] -> Text+splice source edits = go 0 (sortOn (\(q, _) -> q.bodyStart) edits)+ where+ go from = \case+ [] -> T.drop from source+ (q, new) : more ->+ T.take (q.bodyStart - from) (T.drop from source) <> new <> go q.bodyEnd more+++-- | 'Nothing' when the output has the same quasiquotes as the source, with+-- the same text outside the bodies of the rewritten ones (these indices into+-- 'quasiQuotes').+sameOutside :: Text -> Text -> [Int] -> Maybe Text+sameOutside source output rewritten =+ let before = quasiQuotes source+ after = quasiQuotes output+ in if+ | map (.quoter) before /= map (.quoter) after -> Just "has different quasiquotes"+ | outside source before /= outside output after -> Just "changed text outside the quasiquotes"+ | otherwise -> Nothing+ where+ -- The text with the rewritten quasiquotes' bodies cut out.+ outside text qqs = go 0 [q | (n, q) <- zip [0 ..] qqs, n `elem` rewritten]+ where+ go from = \case+ [] -> [T.drop from text]+ q : more -> T.take (q.bodyStart - from) (T.drop from text) : go q.bodyEnd more
+ src/PgStyle/Layout.hs view
@@ -0,0 +1,147 @@+-- | pgstyle's own layout for DML statements (SELECT, INSERT, UPDATE, DELETE,+-- VALUES), rendered from libpg_query's parse tree; and for CREATE TABLE,+-- CREATE VIEW, CREATE ... AS, CREATE INDEX, ALTER TABLE and CREATE FUNCTION,+-- in a style of its own ("PgStyle.Layout.Ddl").+--+-- This is the layout "PgStyle.Render" gives over postgresql-syntax's AST, and+-- it has to stay byte for byte the same: the rules (leading commas, one select+-- target per line when there are several, @join@ on its own line with @on@+-- under it, the first @where@ condition inline with hanging @and@s, ...) and+-- the thresholds are "PgStyle.Render"'s, function for function. Where+-- "PgStyle.Render" hands a node to postgresql-syntax's own renderer (and+-- lower-cases the result), this module writes that renderer's spelling too+-- (the 'MP' mode). It departs from "PgStyle.Render" to keep what the+-- source wrote (dollar-quoted strings, multi-line strings and numbers stay as+-- they are, comments are laid out rather than refused, and a blank line+-- between @values@ rows is kept), and in one rule:+-- @values@ rows that all fit go on one line each.+--+-- PostgreSQL's parse tree forgets some of what the source said that+-- postgresql-syntax's AST keeps: redundant parentheses, @!=@ for @<>@,+-- whether an alias had @as@, @inner join@ for @join@, how a type was spelled+-- (@int@, @integer@ and @int4@ are all @pg_catalog.int4@). Those come from+-- the source tokens, found through the tree's locations. Every parenthesis in+-- the source must be accounted for, as part of a construct's syntax or as+-- parentheses around one node; a statement with one that is not is refused,+-- as is any node this module does not know. Refused statements are left to+-- the caller (libpg_query's own printer, or as they are), never guessed at.+--+-- Comments are written at the line breaks the layout makes where they are+-- in the source (see 'brk'); a construct with a comment inside takes its+-- multi-line form, and a statement with a comment at no line break is+-- refused.+--+-- Keywords are written in the requested case as they are rendered;+-- identifiers, quoted or not, are never changed.+--+-- The parts: "PgStyle.Layout.Monad" holds the statement's tokens and what is+-- placed so far; "PgStyle.Layout.Comments", "PgStyle.Layout.Locations" and+-- "PgStyle.Layout.Parens" find comments, locations and parentheses in the+-- source; "PgStyle.Layout.Names" writes identifiers, constants and types;+-- "PgStyle.Layout.Expr" expressions, "PgStyle.Layout.Dml" selects and the other+-- DML statements, and "PgStyle.Layout.Ddl" the DDL ones. This module says+-- which statement goes where.+module PgStyle.Layout (+ formatStatement,+ formatStatementAt,+) where++import Control.Monad (unless)+import Control.Monad.Reader (local, runReaderT)+import Control.Monad.State.Strict (runStateT)+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Map.Strict qualified as Map+import Data.ProtoLens.Message (Message (..))+import Data.Text (Text)+import Data.Text.Encoding qualified as TE+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Ddl+import PgStyle.Layout.Dml+import PgStyle.Layout.Expr+import PgStyle.Layout.Monad+import PgStyle.Layout.Names+import PgStyle.Layout.Parens+import PgStyle.LibPgQuery qualified as L+import Prettyprinter (layoutPretty, (<+>))+import Prettyprinter.Render.Text (renderStrict)+++-- | Lay out one DML statement or one of the DDL statements it knows (no comments+-- before or after it, no semicolon), keywords in upper case if asked,+-- starting at column 0 without a trailing newline. 'Left' says why not: the+-- statement is none of those, or has+-- something this renderer does not handle (a comment it cannot place among+-- them).+formatStatement :: Bool -> ByteString -> IO (Either Text Text)+formatStatement upperKeywords = formatStatementAt upperKeywords 0+++-- | 'formatStatement' for a statement that starts at this column of its+-- line, where the caller indents its other lines to: what lines up with+-- text the layout cannot move (a function body's closing quote) needs it.+formatStatementAt :: Bool -> Int -> ByteString -> IO (Either Text Text)+formatStatementAt upperKeywords column sql = do+ parsed <- L.parse sql+ scanned <- L.scan sql+ let laid = render parsed scanned+ case laid of+ Right out+ | Right scan <- scanned+ , hasComments scan -> do+ -- Every comment must come out once, in its order: each is+ -- written where the layout breaks a line at its place in the+ -- source, and one with no such break is not written at all.+ again <- L.scan (TE.encodeUtf8 out)+ pure case again of+ Right scan' | commentTexts (TE.encodeUtf8 out) scan' == commentTexts sql scan -> laid+ _ -> Left "a comment pgstyle cannot place"+ _ -> pure laid+ where+ render parsed scanned = case (parsed, scanned) of+ (Left err, _) -> Left err.message+ (_, Left err) -> Left err.message+ (Right tree, Right scan) -> case tree ^. Pg.stmts of+ [rawStmt] | Just stmt <- rawStmt ^. Pg.maybe'stmt -> do+ let env = (mkEnv upperKeywords sql scan stmt){column}+ (doc, st) <- runStateT (runReaderT (statement stmt) env) St{consumed = IS.empty, parenCounts = Map.empty, boolGroups = IS.empty}+ let unplaced = [i | (i, t) <- IM.toList env.toks, t.text == "(", not (IS.member i st.consumed)]+ unless (null unplaced) (Left "a parenthesis pgstyle cannot place")+ Right (renderStrict (layoutPretty layoutOpts doc))+ _ -> Left "not a single statement"+ hasComments scan = any isComment (scan ^. Pg.tokens)+ commentTexts src scan =+ [ BS.take (fromIntegral (t ^. Pg.end) - fromIntegral (t ^. Pg.start)) (BS.drop (fromIntegral (t ^. Pg.start)) src)+ | t <- scan ^. Pg.tokens+ , isComment t+ ]+++-- | A statement, by its kind.+statement :: Pg.Node -> R D+statement n = case node n of+ Just (Pg.Node'SelectStmt s) -> do+ k <- selectParens 0 s+ selStmt s k+ Just (Pg.Node'InsertStmt s) -> insertStmt s+ Just (Pg.Node'UpdateStmt s) -> updateStmt s+ Just (Pg.Node'DeleteStmt s) -> deleteStmt s+ Just (Pg.Node'CreateStmt c) -> local (\env -> env{tightTypes = True}) (createTable c)+ Just (Pg.Node'ViewStmt v) -> createView v+ Just (Pg.Node'IndexStmt ix) -> createIndex ix+ Just (Pg.Node'CreateFunctionStmt f) -> local (\env -> env{tightTypes = True}) (createFunction statement f)+ Just (Pg.Node'AlterTableStmt a) -> local (\env -> env{tightTypes = True}) (alterTable a)+ Just (Pg.Node'CreateTableAsStmt c) -> createTableAs c+ Just (Pg.Node'CreateTrigStmt t) -> createTrigger t+ Just (Pg.Node'GrantStmt g) -> grantStmt GrantClauses{onObjects = True, grantees = granteesWord (g ^. Pg.isGrant)}+ Just (Pg.Node'GrantRoleStmt g) -> grantStmt GrantClauses{onObjects = False, grantees = granteesWord (g ^. Pg.isGrant)}+ Just (Pg.Node'CallStmt c) -> do+ f <- req "a call" (c ^. Pg.maybe'funccall)+ e <- top (defMessage `withFuncCall` f)+ k <- kw "call"+ d <- funcApplication MP e f+ pure (k <+> d)+ _ -> unsupported "not DML or DDL pgstyle lays out"
+ src/PgStyle/Layout/Comments.hs view
@@ -0,0 +1,169 @@+-- | Comments: each is written at the line break the layout makes where it+-- is in the source. One on a line with code ends the line before the break;+-- one on a line of its own gets a line of its own after it. A construct+-- with a comment inside it takes its multi-line form. A comment with no+-- break at its place is not written, and the statement is refused.+--+-- Also the token spans and lists comments are looked for in.+module PgStyle.Layout.Comments where++import Control.Monad (forM)+import Control.Monad.Reader (asks)+import Data.IntMap.Strict qualified as IM+import Data.Text (Text)+import PgQuery qualified as Pg+import PgStyle.Layout.Locations+import PgStyle.Layout.Monad+import Prettyprinter (hardline)+++-- | The comments in the gap before a token: after the token before it, and+-- before that the comma before it if any (a list's separator, which the+-- source may have before or after a comment).+gapBefore :: Int -> R [Cmt]+gapBefore q = do+ m <- asks (.cmts)+ sep <- tokIs (q - 1) ","+ let at p = IM.findWithDefault [] p m+ pure ((if sep then at (q - 2) else []) ++ at (q - 1))+++-- | A line break before the token at @q@, with the comments before it;+-- @lead@ starts each comment line, aligning it with what follows. A blank+-- line before a comment on a line of its own is kept, as it separates+-- comments about different things.+brk :: D -> Int -> R D+brk lead q = do+ cs <- gapBefore q+ let (trailing, rest) = span (not . (.ownLine)) cs+ pure (mconcat [" " <> raw c.ctext | c <- trailing] <> hardline <> mconcat [(if c.blankBefore then hardline else mempty) <> lead <> raw c.ctext <> hardline | c <- rest])+++-- | 'brk' where the token is known, a plain line break where not.+brkAt :: D -> Maybe Int -> R D+brkAt lead = maybe (pure hardline) (brk lead)+++-- | Lines, each with the token it starts at: the comments between them go+-- at the breaks.+linesAt :: D -> [(Maybe Int, D)] -> R D+linesAt _ [] = pure mempty+linesAt lead ((_, d) : rest) = do+ ds <- forM rest \(q, x) -> (<> x) <$> brkAt lead q+ pure (d <> mconcat ds)+++-- | Whether any comment lies between two tokens.+commentsBetween :: Int -> Int -> R Bool+commentsBetween a b = do+ m <- asks (.cmts)+ pure case IM.lookupGE a m of+ Just (p, _) -> p < b+ Nothing -> False+++-- | Whether the statement has comments at all.+anyComments :: R Bool+anyComments = asks (not . IM.null . (.cmts))+++-- | The tokens an expression spans: from its first located token to its+-- last, and on past any parenthesis opened in between.+spanOf :: Pg.Node -> R (Maybe (Int, Int))+spanOf n = case locsNode n of+ [] -> pure Nothing+ ls -> do+ s <- tokAt (minimum ls)+ e <- tokAt (maximum ls)+ texts <- traverse tokL [s .. e]+ let depth = length (filter (`elem` ["(", "["]) texts) - length (filter (`elem` [")", "]"]) texts)+ close i d+ | d <= 0 = pure (i - 1)+ | otherwise = do+ t <- tokM i+ case (.text) <$> t of+ Nothing -> pure (i - 1)+ Just w+ | w `elem` ["(", "["] -> close (i + 1) (d + 1)+ | w `elem` [")", "]"] -> close (i + 1) (d - 1)+ | otherwise -> close (i + 1) d+ end <- close (e + 1) depth+ pure (Just (s, end))+++-- | Whether an expression has a comment inside it.+hasCmts :: Pg.Node -> R Bool+hasCmts n = do+ any' <- anyComments+ if not any'+ then pure False+ else do+ sp <- spanOf n+ maybe (pure False) (uncurry commentsBetween) sp+++-- | The first token of each item of a comma-separated list between two+-- tokens (a parenthesis pair), if the commas there are the list's.+listFirsts :: Int -> Int -> Int -> R (Maybe [Int])+listFirsts open close n = do+ texts <- traverse tokL [open + 1 .. close - 1]+ let commas = go (0 :: Int) (zip [open + 1 ..] texts)+ go _ [] = []+ go d ((i, w) : rest)+ | w `elem` ["(", "["] = go (d + 1) rest+ | w `elem` [")", "]"] = go (d - 1) rest+ | w == "," && d == 0 = i : go d rest+ | otherwise = go d rest+ pure (if length commas == n - 1 then Just ((open + 1) : map (+ 1) commas) else Nothing)+++-- | The bracket that closes the one at a token.+closeOf :: Int -> R (Maybe Int)+closeOf open = go (open + 1) (0 :: Int)+ where+ go i d = do+ t <- tokM i+ case (.text) <$> t of+ Nothing -> pure Nothing+ Just w+ | w `elem` ["(", "["] -> go (i + 1) (d + 1)+ | w `elem` [")", "]"] -> if d == 0 then pure (Just i) else go (i + 1) (d - 1)+ | otherwise -> go (i + 1) d+++-- | The first token of each item of a bracketed list, and its closing+-- bracket, when it has comments in it.+commentedList :: Int -> Int -> R (Maybe ([Int], Int))+commentedList open n = do+ mclose <- closeOf open+ case mclose of+ Nothing -> pure Nothing+ Just close -> do+ commented <- commentsBetween open close+ if not commented+ then pure Nothing+ else fmap (,close) <$> listFirsts open close n+++-- | The words before a token, back over opening parentheses: where the+-- first of them is, if they are these.+wordsBefore :: [Text] -> Int -> R (Maybe Int)+wordsBefore ws i = do+ j <- back (i - 1)+ let from = j - length ws + 1+ actual <- traverse tokL [from .. j]+ pure (if from >= 0 && actual == ws then Just from else Nothing)+ where+ back j = do+ p <- tokIs j "("+ if p then back (j - 1) else pure j+++-- | A clause's first token, from the keywords that start it and the node+-- that follows them.+clauseAt :: [[Text]] -> Pg.Node -> R (Maybe Int)+clauseAt alternatives n = case locsNode n of+ [] -> pure Nothing+ ls -> do+ i <- tokAt (minimum ls)+ firstJustM (`wordsBefore` i) alternatives
+ src/PgStyle/Layout/Ddl.hs view
@@ -0,0 +1,1333 @@+-- | DDL, in a style of its own: create table, view, index, function and+-- trigger, alter table, grant and revoke.+--+-- The keywords of a clause are the source's own words (@temp@ or+-- @temporary@, an explicit @on delete no action@), in the keyword case;+-- names, types and expressions come from the tree, as in DML. Anything+-- else (storage options pgstyle does not know, @exclude@, ...) is not laid+-- out.+module PgStyle.Layout.Ddl where++import Control.Monad (forM, forM_, unless, when, zipWithM)+import Control.Monad.Reader (asks)+import Data.ByteString qualified as BS+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Lens.Micro ((&), (.~), (^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Comments+import PgStyle.Layout.Dml+import PgStyle.Layout.Expr+import PgStyle.Layout.Monad+import PgStyle.Layout.Names+import PgStyle.Layout.Parens+import Prettyprinter (hardline, nest, pretty, vsep, (<+>))+++-- | The statement's last token, before any semicolon.+lastTok :: R Int+lastTok = do+ ts <- asks (.toks)+ case IM.lookupMax ts of+ Just (i, t) | t.text == ";" -> pure (i - 1)+ Just (i, _) -> pure i+ Nothing -> unsupported "an empty statement"+++data Piece = Word | Open | Call | Glue | Close | Dot+++-- | The tokens from @a@ to before @b@, which must be keywords, numbers, and+-- parentheses and commas between them, as words in the keyword case:+-- @not null@, @on delete set null@, @identity (start with 1 cache 10)@.+wordsRun :: Int -> Int -> R D+wordsRun a b = do+ pieces <- forM [a .. b - 1] \j -> do+ t <- tokM j+ case t of+ Just tk+ | tk.text == "(" -> do+ _ <- expectParen j+ pure (Open, "(")+ | tk.text `elem` [")", ","] -> pure (Close, pretty tk.text)+ | tk.text == "-" -> pure (Glue, "-")+ | tk.kind `elem` [Pg.ICONST, Pg.FCONST] -> pure (Word, pretty (T.toLower tk.text))+ | tk.isKeyword && tk.kind /= Pg.IDENT -> (Word,) <$> kw (T.toLower tk.text)+ _ -> unsupported "a clause pgstyle cannot read"+ pure (joined pieces)+ where+ joined = \case+ [] -> mempty+ (k, d) : rest -> d <> go k rest+ go _ [] = mempty+ go prev ((k, d) : rest) = sep prev k <> d <> go k rest+ -- No space after an opening parenthesis or a minus, or before a+ -- closing parenthesis or a comma.+ sep Open _ = mempty+ sep Glue _ = mempty+ sep _ Close = mempty+ sep _ _ = " "+++-- | 'wordsRun', with a space before it, if there are any tokens.+tailRun :: Int -> Int -> R D+tailRun a b+ | a >= b = pure mempty+ | otherwise = (" " <>) <$> wordsRun a b+++-- | A parenthesized list of names, @(a, b)@, at this token: the list and+-- the token after it.+nameList :: Int -> [Text] -> R (D, Int)+nameList open names = do+ close <- expectParen open+ unless (not (null names) && close == open + 2 * length names) (unsupported "a list of names pgstyle cannot read")+ ds <- zipWithM (\k n -> identAt (open + 1 + 2 * k) n) [0 ..] names+ pure ("(" <> commaJoin ds <> ")", close + 1)+++-- | How many tokens a relation's dotted name has, less its dots.+nameParts :: Pg.RangeVar -> Int+nameParts rv = length (filter (not . T.null) [rv ^. Pg.catalogname, rv ^. Pg.schemaname, rv ^. Pg.relname])+++-- | A relation's name as written, where it starts, and the token after it.+data Relation = Relation+ { name :: D+ , at :: Int+ , after :: Int+ }+++relationAt :: Pg.RangeVar -> R Relation+relationAt rv = do+ at <- tokAt (fromIntegral (rv ^. Pg.location))+ name <- relationName rv+ pure Relation{name, at, after = at + 2 * nameParts rv - 1}+++-- | @create table@: one column or constraint per line, each but the last+-- followed by its comma.+createTable :: Pg.CreateStmt -> R D+createTable c = do+ rv <- req "a create table" (c ^. Pg.maybe'relation)+ when+ (isJust (c ^. Pg.maybe'ofTypename) || (not (null (c ^. Pg.inhRelations)) && isNothing (c ^. Pg.maybe'partbound)))+ (unsupported "a create table pgstyle does not lay out")+ Relation{name, at = relAt, after = open} <- relationAt rv+ header <- wordsRun 0 relAt+ if isJust (c ^. Pg.maybe'partbound)+ then partitionOf c (header <+> name) open+ else tableBody c (header <+> name) open+++-- | @create table t partition of p for values ...@: each clause on a line+-- of its own, at the statement's column.+partitionOf :: Pg.CreateStmt -> D -> Int -> R D+partitionOf c head' at = do+ when+ (not (null (c ^. Pg.tableElts)) || isJust (c ^. Pg.maybe'partspec))+ (unsupported "a create table pgstyle does not lay out")+ parent <- case c ^. Pg.inhRelations of+ [p] | Just (Pg.Node'RangeVar rv) <- node p -> pure rv+ _ -> unsupported "a create table pgstyle cannot read"+ isPartition <- (&&) <$> tokIs at "partition" <*> tokIs (at + 1) "of"+ Relation{name = pname, at = pAt, after = pAfter} <- relationAt parent+ unless (isPartition && pAt == at + 2) (unsupported "a create table pgstyle cannot read")+ w <- wordsRun at pAt+ end <- (+ 1) <$> lastTok+ unless (pAfter < end) (unsupported "a create table pgstyle cannot read")+ bound <- looseRun pAfter end+ b1 <- brk mempty at+ b2 <- brk mempty pAfter+ pure (head' <> b1 <> w <+> pname <> b2 <> bound)+++-- | A table's columns and constraints, in the parentheses at @open@, and+-- what follows them.+tableBody :: Pg.CreateStmt -> D -> Int -> R D+tableBody c head' open = do+ close <- expectParen open+ let elts = c ^. Pg.tableElts+ starts <- traverse elementStart elts+ case starts of+ [] -> unless (close == open + 1) (unsupported "a create table pgstyle cannot read")+ s0 : rest -> do+ unless (s0 == open + 1) (unsupported "a create table pgstyle cannot read")+ forM_ rest \s -> do+ comma <- tokIs (s - 1) ","+ unless comma (unsupported "a create table pgstyle cannot read")+ let ends = map (subtract 1) (drop 1 starts) ++ [close]+ ds <- forM (zip3 elts starts ends) \(el, s, e) -> tableElement el s e+ -- A blank line between two elements is kept, as between values rows.+ rows <- commaRows KeepBlankLines (zip starts ds)+ endComments <- closingComments close+ commented <- not . null <$> gapBefore close+ let body+ | null elts && not commented = "()"+ | otherwise = "(" <> nest indentSize (rows <> endComments) <> hardline <> ")"+ tl <- tableTail c (close + 1)+ pure (head' <+> body <> tl)+++-- | Where a table element starts.+elementStart :: Pg.Node -> R Int+elementStart el = case node el of+ Just (Pg.Node'ColumnDef cd) -> tokAt (fromIntegral (cd ^. Pg.location))+ Just (Pg.Node'Constraint k) -> tokAt (fromIntegral (k ^. Pg.location))+ Just (Pg.Node'TableLikeClause l) -> do+ rv <- req "a like clause" (l ^. Pg.maybe'relation)+ at <- tokAt (fromIntegral (rv ^. Pg.location))+ isLike <- tokIs (at - 1) "like"+ unless isLike (unsupported "a like clause pgstyle cannot read")+ pure (at - 1)+ _ -> unsupported "a table element pgstyle cannot read"+++-- | A column, constraint or @like@ clause, from token @s@ to before @e@.+tableElement :: Pg.Node -> Int -> Int -> R D+tableElement el s e = case node el of+ Just (Pg.Node'ColumnDef cd) -> columnDef cd s e+ Just (Pg.Node'Constraint k) -> constraint k s e+ Just (Pg.Node'TableLikeClause l) -> do+ rv <- req "a like clause" (l ^. Pg.maybe'relation)+ k <- kw "like"+ Relation{name, after} <- relationAt rv+ opts <- tailRun after e+ pure (k <+> name <> opts)+ _ -> unsupported "a table element pgstyle cannot read"+++columnDef :: Pg.ColumnDef -> Int -> Int -> R D+columnDef cd s e = do+ when+ ( not (T.null (cd ^. Pg.compression))+ || not (T.null (cd ^. Pg.storageName))+ || isJust (cd ^. Pg.maybe'collClause)+ || not (null (cd ^. Pg.fdwoptions))+ || isJust (cd ^. Pg.maybe'rawDefault)+ )+ (unsupported "a column pgstyle does not lay out")+ name <- identAt s (cd ^. Pg.colname)+ tn <- req "a column" (cd ^. Pg.maybe'typeName)+ tyAt <- tokAt (fromIntegral (tn ^. Pg.location))+ unless (tyAt == s + 1) (unsupported "a column pgstyle cannot read")+ ty <- typeName tn+ ks <- forM (cd ^. Pg.constraints) \k -> case node k of+ Just (Pg.Node'Constraint x) -> (x,) <$> tokAt (fromIntegral (x ^. Pg.location))+ _ -> unsupported "a column constraint pgstyle cannot read"+ let kends = map snd (drop 1 ks) ++ [e]+ kds <- forM (zip ks kends) \((x, a), b) -> constraint x a b+ pure (spaceJoin (name : ty : kds))+++-- | A constraint, from token @a@ to before @b@, with its name if it has one.+constraint :: Pg.Constraint -> Int -> Int -> R D+constraint x a b+ | T.null (x ^. Pg.conname) = constraintBody 0 x a b+ | otherwise = do+ isCon <- tokIs a "constraint"+ unless isCon (unsupported "a constraint pgstyle cannot read")+ k <- kw "constraint"+ n <- identAt (a + 1) (x ^. Pg.conname)+ -- Comments between the name and the body: the body goes on the+ -- line after them, indented.+ cs <- gapBefore (a + 2)+ d <- constraintBody (if null cs then len (k <+> n) + 1 else 0) x (a + 2) b+ if null cs+ then pure (k <+> n <+> d)+ else do+ br <- brk mempty (a + 2)+ pure (k <+> n <> nest indentSize (br <> d))+++-- | A constraint without its name, which takes @before@ characters of its+-- line.+constraintBody :: Int -> Pg.Constraint -> Int -> Int -> R D+constraintBody before x a b = case x ^. Pg.contype of+ Pg.CONSTR_NULL -> wordsRun a b+ Pg.CONSTR_NOTNULL | null (x ^. Pg.keys) -> wordsRun a b+ Pg.CONSTR_IDENTITY -> wordsRun a b+ k | k `elem` [Pg.CONSTR_ATTR_DEFERRABLE, Pg.CONSTR_ATTR_NOT_DEFERRABLE, Pg.CONSTR_ATTR_DEFERRED, Pg.CONSTR_ATTR_IMMEDIATE] -> wordsRun a b+ Pg.CONSTR_DEFAULT -> do+ isDefault <- tokIs a "default"+ unless isDefault (unsupported "a default pgstyle cannot read")+ k <- kw "default"+ ex <- req "a default" (x ^. Pg.maybe'rawExpr)+ d <- ddlExpr ex+ pure (k <+> d)+ Pg.CONSTR_GENERATED -> do+ open <- parenWithin+ w <- wordsRun a open+ close <- expectParen open+ ex <- req "a generated column" (x ^. Pg.maybe'rawExpr)+ d <- ddlExpr ex+ t <- tailRun (close + 1) b+ pure (w <+> "(" <> d <> ")" <> t)+ Pg.CONSTR_CHECK -> do+ open <- parenWithin+ w <- wordsRun a open+ close <- expectParen open+ ex <- req "a check" (x ^. Pg.maybe'rawExpr)+ d <- checkCondition ex+ t <- tailRun (close + 1) b+ pure (w <+> d <> t)+ k | k `elem` [Pg.CONSTR_PRIMARY, Pg.CONSTR_UNIQUE] -> do+ when+ ( not (null (x ^. Pg.including))+ || not (null (x ^. Pg.options))+ || (not (T.null (x ^. Pg.indexname)) && not (null (x ^. Pg.keys)))+ || not (T.null (x ^. Pg.indexspace))+ || isJust (x ^. Pg.maybe'whereClause)+ || x ^. Pg.withoutOverlaps+ )+ (unsupported "a key pgstyle does not lay out")+ if+ | not (T.null (x ^. Pg.indexname)) -> do+ -- @primary key using index i@: a long one breaks before+ -- @using@.+ usingAt <- findUsing a+ w <- wordsRun a usingAt+ u <- wordsRun usingAt (usingAt + 2)+ nm <- identAt (usingAt + 2) (x ^. Pg.indexname)+ t <- tailRun (usingAt + 3) b+ let rest = u <+> nm <> t+ pure+ if before + len (w <+> rest) <= foreignKeyInlineThreshold+ then w <+> rest+ else nest indentSize (w <> hardline <> rest)+ | null (x ^. Pg.keys) -> wordsRun a b+ | otherwise -> do+ open <- parenWithin+ w <- wordsRun a open+ names <- strsOf (x ^. Pg.keys)+ (l, after) <- nameList open names+ t <- tailRun after b+ pure (w <+> l <> t)+ Pg.CONSTR_FOREIGN -> do+ when+ (not (null (x ^. Pg.fkDelSetCols)) || x ^. Pg.fkWithPeriod || x ^. Pg.pkWithPeriod)+ (unsupported "a foreign key pgstyle does not lay out")+ (lead, refAt) <-+ if null (x ^. Pg.fkAttrs)+ then pure (mempty, a)+ else do+ open <- parenWithin+ w <- wordsRun a open+ names <- strsOf (x ^. Pg.fkAttrs)+ (l, after) <- nameList open names+ pure (w <+> l, after)+ isRef <- tokIs refAt "references"+ unless isRef (unsupported "a foreign key pgstyle cannot read")+ k <- kw "references"+ pk <- req "a foreign key" (x ^. Pg.maybe'pktable)+ Relation{name, at = pkAt, after} <- relationAt pk+ unless (pkAt == refAt + 1) (unsupported "a foreign key pgstyle cannot read")+ (cols, rest) <-+ if null (x ^. Pg.pkAttrs)+ then pure (mempty, after)+ else strsOf (x ^. Pg.pkAttrs) >>= nameList after+ t <- tailRun rest b+ let refs = k <+> name <> cols <> t+ -- A long one breaks before @references@.+ pure+ if+ | null (x ^. Pg.fkAttrs) -> refs+ | before + len (lead <+> refs) <= foreignKeyInlineThreshold -> lead <+> refs+ | otherwise -> nest indentSize (lead <> hardline <> refs)+ _ -> unsupported "a constraint pgstyle does not lay out"+ where+ parenWithin = do+ open <- nextParen a+ unless (open < b) (unsupported "a constraint pgstyle cannot read")+ pure open+ findUsing j+ | j >= b = unsupported "a key pgstyle cannot read"+ | otherwise = do+ u <- tokIs j "using"+ i <- tokIs (j + 1) "index"+ if u && i then pure j else findUsing (j + 1)+++-- | A check constraint's condition, in its parentheses: on one line if+-- short, otherwise broken as 'boolBlock' breaks it.+checkCondition :: Pg.Node -> R D+checkCondition n = do+ e <- top n+ inline <- expr MR e+ if e.lv == 0 && isAndOr n && len inline > checkInlineThreshold+ then do+ b <- boolBlock e+ pure ("(" <> nest indentSize (hardline <> b) <> hardline <> ")")+ else do+ d <- ddlExpr n+ pure ("(" <> d <> ")")+++-- | Whether a node is an @and@ or @or@.+isAndOr :: Pg.Node -> Bool+isAndOr n = case node n of+ Just (Pg.Node'BoolExpr be) -> be ^. Pg.boolop `elem` [Pg.AND_EXPR, Pg.OR_EXPR]+ _ -> False+++-- | A long condition in DDL: each operand of its top-level @and@ (or @or@)+-- on a line of its own, the operator first; an operand in parentheses that+-- is long itself broken the same way inside them.+boolBlock :: E -> R D+boolBlock e = case node e.en of+ Just (Pg.Node'BoolExpr be)+ | Just op <- lookup (be ^. Pg.boolop) [(Pg.AND_EXPR, "and"), (Pg.OR_EXPR, "or")]+ , first : rest <- be ^. Pg.args -> do+ opK <- kw op+ fd <- child e.en first >>= boolPart+ rds <- traverse (child e.en >=> boolPart) rest+ pure (vsep (fd : map (opK <+>) rds))+ _ -> expr MR e+++-- | An operand of 'boolBlock'.+boolPart :: E -> R D+boolPart c = do+ inline <- expr MR c+ if c.lv == 1 && isAndOr c.en && len inline > checkInlineThreshold+ then do+ inner <- boolBlock c{lv = 0}+ pure ("(" <> nest indentSize (hardline <> inner) <> hardline <> ")")+ else pure inline+++-- | An index's @where@: on one line if short, otherwise broken as+-- 'boolBlock' breaks it.+indexWhere :: Pg.Node -> R D+indexWhere n = do+ k <- kw "where"+ e <- top n+ inline <- expr MR e+ if+ | len inline <= checkInlineThreshold || not (isAndOr n) -> pure (k <+> inline)+ | e.lv == 0 -> do+ b <- boolBlock e+ pure (k <> nest indentSize (hardline <> b))+ | otherwise -> (k <+>) <$> boolPart e+++-- | An expression in a column or constraint: on one line if short,+-- otherwise wrapped as a long select target is.+ddlExpr :: Pg.Node -> R D+ddlExpr n = do+ e <- top n+ inline <- expr MR e+ eligible <- isWrapEligible e+ if len inline > checkInlineThreshold && eligible+ then exprWrapped e+ else pure inline+++-- | The longest table foreign key, with its name, that stays on one line.+foreignKeyInlineThreshold :: Int+foreignKeyInlineThreshold = 90+++-- | The longest check condition that stays on one line.+checkInlineThreshold :: Int+checkInlineThreshold = 80+++-- | What follows a table's columns: @partition by range (a)@, @on commit+-- drop@.+tableTail :: Pg.CreateStmt -> Int -> R D+tableTail c from = do+ end <- (+ 1) <$> lastTok+ case c ^. Pg.maybe'partspec of+ Nothing -> tailRun from end+ Just ps -> do+ pAt <- tokAt (fromIntegral (ps ^. Pg.location))+ pre <- tailRun from pAt+ open <- nextParen pAt+ w <- wordsRun pAt open+ names <- forM (ps ^. Pg.partParams) \p -> case node p of+ Just (Pg.Node'PartitionElem pe)+ | not (T.null (pe ^. Pg.name))+ , isNothing (pe ^. Pg.maybe'expr)+ , null (pe ^. Pg.collation)+ , null (pe ^. Pg.opclass) ->+ pure (pe ^. Pg.name)+ _ -> unsupported "a partition key pgstyle does not lay out"+ (l, after) <- nameList open names+ post <- tailRun after end+ pure (pre <> " " <> w <+> l <> post)+++-- | @create view@: its query laid out as a statement of its own, under+-- the line that names the view.+createView :: Pg.ViewStmt -> R D+createView v = do+ rv <- req "a view" (v ^. Pg.maybe'view)+ unless (null (v ^. Pg.options)) (unsupported "a view with options")+ aliases <- strsOf (v ^. Pg.aliases)+ q <- req "a view" (v ^. Pg.maybe'query)+ checkOption <- case v ^. Pg.withCheckOption of+ o | o `elem` [Pg.LOCAL_CHECK_OPTION, Pg.CASCADED_CHECK_OPTION] -> do+ end <- lastTok+ ws <- traverse tokL [end - 3 .. end]+ from <- case ws of+ ["with", m, "check", "option"] | m `elem` ["local", "cascaded"] -> pure (end - 3)+ [_, "with", "check", "option"] -> pure (end - 2)+ _ -> unsupported "a check option pgstyle cannot read"+ Just <$> wordsRun from (end + 1)+ _ -> pure Nothing+ asQuery rv aliases q checkOption+++-- | @create table ... as@ and @create materialized view ... as@.+createTableAs :: Pg.CreateTableAsStmt -> R D+createTableAs c = do+ unless (c ^. Pg.objtype `elem` [Pg.OBJECT_TABLE, Pg.OBJECT_MATVIEW]) (unsupported "a create as pgstyle does not lay out")+ when (c ^. Pg.isSelectInto) (unsupported "select into")+ into <- req "a create as" (c ^. Pg.maybe'into)+ when+ ( not (null (into ^. Pg.options))+ || not (T.null (into ^. Pg.accessMethod))+ || not (T.null (into ^. Pg.tableSpaceName))+ )+ (unsupported "a create as pgstyle does not lay out")+ rv <- req "a create as" (into ^. Pg.maybe'rel)+ cols <- strsOf (into ^. Pg.colNames)+ q <- req "a create as" (c ^. Pg.maybe'query)+ end <- lastTok+ ws <- traverse tokL [end - 2 .. end]+ withData <- case ws of+ ["with", "no", "data"] -> Just <$> wordsRun (end - 2) (end + 1)+ [_, "with", "data"] -> Just <$> wordsRun (end - 1) (end + 1)+ _ -> pure Nothing+ asQuery rv cols q withData+++-- | The head of a @create ... as@ (its words, the name, the column names),+-- its query on the lines after it, and what follows the query on a line of+-- its own.+asQuery :: Pg.RangeVar -> [Text] -> Pg.Node -> Maybe D -> R D+asQuery rv cols q after = do+ Relation{name, at = relAt, after = next} <- relationAt rv+ recursive <- anyM (`tokIs` "recursive") [0 .. relAt - 1]+ when recursive (unsupported "a recursive view")+ header <- wordsRun 0 relAt+ (colsD, asAt) <-+ if null cols+ then pure (mempty, next)+ else do+ (l, nx) <- nameList next cols+ pure (" " <> l, nx)+ -- Words before @as@: @on commit drop@.+ asAt' <- findAs asAt+ between <- tailRun asAt asAt'+ asK <- kw "as"+ s <- case node q of+ Just (Pg.Node'SelectStmt s) -> pure s+ _ -> unsupported "a query pgstyle does not lay out"+ k <- selectParens 0 s+ body <- selStmt s k+ first <- selectFirst s+ b <- brk mempty first+ pure (header <+> name <> colsD <> between <+> asK <> b <> body <> maybe mempty (hardline <>) after)+ where+ findAs j = do+ t <- tokM j+ case t of+ Just tk | T.toLower tk.text == "as" -> pure j+ Just tk | tk.isKeyword && tk.kind /= Pg.IDENT -> findAs (j + 1)+ _ -> unsupported "a create as pgstyle cannot read"+++-- | The top-level commas from token @a@ to before @b@: where each of the+-- parts they separate starts.+partsBetween :: Int -> Int -> R [Int]+partsBetween a b = go a [a]+ where+ go j acc+ | j >= b = pure (reverse acc)+ | otherwise = do+ t <- tokL j+ case t of+ "(" -> do+ m <- matchOf j+ maybe (unsupported "an unclosed parenthesis") (\c -> go (c + 1) acc) m+ "," -> go (j + 1) (j + 1 : acc)+ _ -> go (j + 1) acc+++-- | @create index@: the index's name on its first line, then @on@ the+-- table and its columns, and the @where@ condition, each on a line of its+-- own.+createIndex :: Pg.IndexStmt -> R D+createIndex ix = do+ when+ ( not (T.null (ix ^. Pg.tableSpace))+ || not (null (ix ^. Pg.excludeOpNames))+ )+ (unsupported "an index pgstyle does not lay out")+ rv <- req "an index" (ix ^. Pg.maybe'relation)+ Relation{name = rel, at = relAt, after = afterRel} <- relationAt rv+ isOn <- tokIs (relAt - 1) "on"+ unless isOn (unsupported "an index pgstyle cannot read")+ let named = not (T.null (ix ^. Pg.idxname))+ nameAt = relAt - 2+ header <- wordsRun 0 (if named then nameAt else relAt - 1)+ nameD <- if named then (" " <>) <$> identAt nameAt (ix ^. Pg.idxname) else pure mempty+ onK <- kw "on"+ -- @using gin@, if written.+ usingWritten <- tokIs afterRel "using"+ (usingD, open) <-+ if usingWritten+ then do+ u <- kw "using"+ m <- identAt (afterRel + 1) (ix ^. Pg.accessMethod)+ pure (" " <> u <+> m, afterRel + 2)+ else pure (mempty, afterRel)+ close <- expectParen open+ starts <- partsBetween (open + 1) close+ unless (length starts == length (ix ^. Pg.indexParams)) (unsupported "an index pgstyle cannot read")+ let ends = map (subtract 1) (drop 1 starts) ++ [close]+ cols <- forM (zip3 (ix ^. Pg.indexParams) starts ends) \(p, s, e) -> case node p of+ Just (Pg.Node'IndexElem el) -> indexElem el s e+ _ -> unsupported "an index column pgstyle cannot read"+ whereAt <- maybe (pure Nothing) (clauseAt [["where"]]) (ix ^. Pg.maybe'whereClause)+ end <- (+ 1) <$> lastTok+ between <- indexTail ix (close + 1) (fromMaybe end whereAt)+ wh <- traverse indexWhere (ix ^. Pg.maybe'whereClause)+ let onLine = onK <+> rel <> usingD <+> "(" <> commaJoin cols <> ")" <> between+ onBreak <- brk mempty (relAt - 1)+ whBreak <- brkAt mempty whereAt+ pure (header <> nameD <> nest indentSize (onBreak <> onLine <> maybe mempty (whBreak <>) wh))+++-- | What follows an index's columns, before its @where@: @include (a,+-- b)@, @nulls not distinct@, @with (fastupdate = off)@; with a space+-- before it, if there is any.+indexTail :: Pg.IndexStmt -> Int -> Int -> R D+indexTail ix from to = do+ included <- forM (ix ^. Pg.indexIncludingParams) \p -> case node p of+ Just (Pg.Node'IndexElem el) | isNothing (el ^. Pg.maybe'expr) -> pure (el ^. Pg.name)+ _ -> unsupported "an index pgstyle does not lay out"+ let go j+ | j >= to = pure []+ | otherwise = do+ w <- tokL j+ case w of+ "include" | not (null included) -> do+ k <- kw "include"+ (l, after) <- nameList (j + 1) included+ ((k <+> l) :) <$> go after+ "with" | not (null (ix ^. Pg.options)) -> do+ k <- kw "with"+ close <- expectParen (j + 1)+ o <- relOptions (ix ^. Pg.options)+ ((k <+> o) :) <$> go (close + 1)+ _ -> do+ d <- wordsRun j (j + 1)+ (d :) <$> go (j + 1)+ ds <- go from+ pure (mconcat [" " <> d | d <- ds])+++-- | An index column, from token @s@ to before @e@: a column or an+-- expression, its operator class, its order.+indexElem :: Pg.IndexElem -> Int -> Int -> R D+indexElem el s e = do+ unless (null (el ^. Pg.collation) && null (el ^. Pg.opclassopts) && T.null (el ^. Pg.indexcolname)) (unsupported "an index column pgstyle does not lay out")+ (d, next) <- case el ^. Pg.maybe'expr of+ Nothing -> do+ n <- identAt s (el ^. Pg.name)+ pure (n, s + 1)+ Just ex -> do+ -- An expression in parentheses, or a function call: it ends at+ -- the first parenthesis's match.+ open <- nextParen s+ close <- matchOf open >>= req "an index expression"+ d <- top ex >>= expr MR+ pure (d, close + 1)+ opclass <- strsOf (el ^. Pg.opclass)+ (opD, after) <-+ if null opclass+ then pure (mempty, next)+ else do+ q <- qualNameAt next opclass+ pure (" " <> q, next + 2 * length opclass - 1)+ t <- tailRun after e+ pure (d <> opD <> t)+++-- | @alter table@: each action on a line of its own, each but the last+-- followed by its comma.+alterTable :: Pg.AlterTableStmt -> R D+alterTable a = do+ unless (a ^. Pg.objtype == Pg.OBJECT_TABLE) (unsupported "an alter pgstyle does not lay out")+ rv <- req "an alter table" (a ^. Pg.maybe'relation)+ Relation{name = rel, at = relAt, after = afterRel} <- relationAt rv+ header <- wordsRun 0 relAt+ end <- (+ 1) <$> lastTok+ starts <- partsBetween afterRel end+ let cmds = a ^. Pg.cmds+ ends = map (subtract 1) (drop 1 starts) ++ [end]+ unless (length starts == length cmds) (unsupported "an alter table pgstyle cannot read")+ ds <- forM (zip3 cmds starts ends) \(c, s, e) -> do+ cmd <- case node c of+ Just (Pg.Node'AlterTableCmd x) -> pure x+ _ -> unsupported "an alter table pgstyle cannot read"+ alterCmd cmd s e+ rows <- commaRows KeepBlankLines (zip starts ds)+ pure (header <+> rel <> nest indentSize rows)+++-- | One action of an @alter table@, from token @s@ to before @e@.+alterCmd :: Pg.AlterTableCmd -> Int -> Int -> R D+alterCmd c s e = case c ^. Pg.subtype of+ Pg.AT_AddColumn -> case def of+ Just (Pg.Node'ColumnDef cd) -> do+ at <- tokAt (fromIntegral (cd ^. Pg.location))+ w <- wordsRun s at+ d <- columnDef cd at e+ pure (w <+> d)+ _ -> cannot+ Pg.AT_AddConstraint -> case def of+ Just (Pg.Node'Constraint x) -> do+ at <- tokAt (fromIntegral (x ^. Pg.location))+ w <- wordsRun s at+ d <- constraint x at e+ pure (w <+> d)+ _ -> cannot+ t | t `elem` [Pg.AT_DropColumn, Pg.AT_DropConstraint, Pg.AT_ValidateConstraint, Pg.AT_DropNotNull, Pg.AT_SetNotNull, Pg.AT_DropIdentity, Pg.AT_EnableTrig, Pg.AT_DisableTrig, Pg.AT_EnableAlwaysTrig, Pg.AT_EnableReplicaTrig] -> withName Nothing+ -- @alter constraint c deferrable@: the name is the constraint's.+ Pg.AT_AlterConstraint -> case def of+ Just (Pg.Node'AtalterConstraint x) -> do+ nameAt <- nameToken+ unless (nameAt < e) cannot+ w <- wordsRun s nameAt+ nm <- identAt nameAt (x ^. Pg.conname)+ t <- tailRun (nameAt + 1) e+ pure (w <+> nm <> t)+ _ -> cannot+ Pg.AT_ColumnDefault -> withName (c ^. Pg.maybe'def)+ t | t `elem` [Pg.AT_EnableRowSecurity, Pg.AT_DisableRowSecurity, Pg.AT_ForceRowSecurity, Pg.AT_NoForceRowSecurity, Pg.AT_SetLogged, Pg.AT_SetUnLogged, Pg.AT_EnableTrigAll, Pg.AT_DisableTrigAll, Pg.AT_EnableTrigUser, Pg.AT_DisableTrigUser] -> wordsRun s e+ Pg.AT_AlterColumnType -> case def of+ Just (Pg.Node'ColumnDef cd) | isNothing (cd ^. Pg.maybe'collClause) -> do+ nameAt <- nameToken+ w <- wordsRun s nameAt+ nm <- identAt nameAt (c ^. Pg.name)+ tn <- req "an alter column" (cd ^. Pg.maybe'typeName)+ tyAt <- tokAt (fromIntegral (tn ^. Pg.location))+ w2 <- wordsRun (nameAt + 1) tyAt+ ty <- typeName tn+ using <- case cd ^. Pg.maybe'rawDefault of+ Nothing -> pure mempty+ Just ex -> do+ u <- kw "using"+ d <- ddlExpr ex+ pure (" " <> u <+> d)+ pure (w <+> nm <+> w2 <+> ty <> using)+ _ -> cannot+ t | t `elem` [Pg.AT_SetRelOptions, Pg.AT_ResetRelOptions] -> do+ open <- nextParen s+ w <- wordsRun s open+ close <- expectParen open+ opts <- case def of+ Just (Pg.Node'List l) -> relOptions (l ^. Pg.items)+ _ -> cannot+ t' <- tailRun (close + 1) e+ pure (w <+> opts <> t')+ _ -> unsupported "an alter table action pgstyle does not lay out"+ where+ def = c ^. Pg.maybe'def >>= node+ cannot :: R a+ cannot = unsupported "an alter table action pgstyle cannot read"+ -- The named column, constraint or trigger: after the keywords that+ -- start the action.+ nameToken = go (s + 1)+ where+ go j = do+ w <- tokL j+ if w `elem` ["column", "constraint", "trigger", "if", "exists"] then go (j + 1) else pure j+ withName mexpr = do+ nameAt <- nameToken+ unless (nameAt < e) cannot+ w <- wordsRun s nameAt+ nm <- identAt nameAt (c ^. Pg.name)+ case mexpr of+ Nothing -> do+ t <- tailRun (nameAt + 1) e+ pure (w <+> nm <> t)+ Just ex -> do+ -- @set default@, then the expression.+ defaultAt <- findDefault (nameAt + 1)+ w2 <- wordsRun (nameAt + 1) (defaultAt + 1)+ d <- ddlExpr ex+ pure (w <+> nm <+> w2 <+> d)+ findDefault j+ | j >= e = cannot+ | otherwise = do+ w <- tokL j+ if w == "default" then pure j else findDefault (j + 1)+++-- | The tokens from @a@ to before @b@, as written but for keywords, in the+-- keyword case: a function's clauses (@language plpgsql@, @set search_path+-- = public@, @as 'obj', 'sym'@).+looseRun :: Int -> Int -> R D+looseRun a b = do+ pieces <- forM [a .. b - 1] \j -> do+ t <- tokM j+ case t of+ Just tk+ | tk.text == "(" -> do+ _ <- expectParen j+ -- Right after a name, as in @f(bigint)@, if the source+ -- has it there.+ prev <- if j > a then tokM (j - 1) else pure Nothing+ let glued = case prev of+ Just p -> p.text `notElem` ["(", ")", ","] && p.start + BS.length (TE.encodeUtf8 p.text) == tk.start+ Nothing -> False+ pure (if glued then Call else Open, "(")+ | tk.text `elem` [")", ","] -> pure (Close, pretty tk.text)+ | tk.text == "." -> pure (Dot, ".")+ | tk.isKeyword && tk.kind /= Pg.IDENT -> (Word,) <$> kw (T.toLower tk.text)+ | otherwise -> pure (Word, raw tk.text)+ Nothing -> unsupported "a clause pgstyle cannot read"+ pure case pieces of+ [] -> mempty+ (k, d) : rest -> d <> go k rest+ where+ go _ [] = mempty+ go prev ((k, d) : rest) = sep prev k <> d <> go k rest+ sep Open _ = mempty+ sep Call _ = mempty+ sep Dot _ = mempty+ sep _ Close = mempty+ sep _ Dot = mempty+ sep _ Call = mempty+ sep _ _ = " "+++-- | @create function@ and @create procedure@: the arguments on the first+-- line, or one per line if they do not fit; each clause before the body on+-- a line of its own, the last ending in @as@; the body from the start of+-- the line after, as written; the clauses after it on its last line.+createFunction :: (Pg.Node -> R D) -> Pg.CreateFunctionStmt -> R D+createFunction statement f = do+ names <- strsOf (f ^. Pg.funcname)+ -- The name: the first identifier after the words that start the+ -- statement.+ nameAt <- firstName 0+ header <- wordsRun 0 nameAt+ name <- qualNameAt nameAt names+ let open = nameAt + 2 * length names - 1+ close <- expectParen open+ params <- forM (f ^. Pg.parameters) \p -> case node p of+ Just (Pg.Node'FunctionParameter fp) -> pure fp+ _ -> unsupported "a function parameter pgstyle cannot read"+ let isTable fp = fp ^. Pg.mode == Pg.FUNC_PARAM_TABLE+ (tableCols, args) = (filter isTable params, filter (not . isTable) params)+ argDs <- paramList args (open + 1) close+ end <- (+ 1) <$> lastTok+ parts <- functionParts f close end+ returnsLine <- case parts.returnsEnd of+ Nothing -> pure mempty+ Just returnsEnd -> do+ d <- returnsClause f tableCols (close + 1) returnsEnd+ (<> d) <$> brk mempty (close + 1)+ beforeDs <- forM parts.before \c -> do+ d <- looseRun c.start c.end+ b <- brk mempty c.start+ pure (b <> d)+ argsD <- itemList functionHeaderThreshold (header <+> name) argDs close+ let clauseLines = returnsLine <> mconcat beforeDs+ bodyD <- case parts.body of+ StandardBody at b -> do+ bb <- brk mempty at+ d <- standardBody statement b at end+ pure (bb <> d)+ QuotedBody at -> quotedBody at parts.asEnd parts.after+ pure (header <+> name <> argsD <> nest indentSize clauseLines <> bodyD)+ where+ firstName j = do+ t <- tokM j+ case t of+ Just tk | tk.kind == Pg.IDENT || (tk.isKeyword && T.toLower tk.text `notElem` ["create", "or", "replace", "function", "procedure"]) -> pure j+ Just _ -> firstName (j + 1)+ Nothing -> unsupported "a function pgstyle cannot read"+++-- | Where the parts of a function after its arguments are.+data FunctionParts = FunctionParts+ { returnsEnd :: Maybe Int+ -- ^ With @returns@ right after the arguments, the token after it.+ , body :: FunctionBody+ , before :: [Clause]+ -- ^ The clauses before the body.+ , after :: [Clause]+ -- ^ The clauses after a quoted body.+ , asEnd :: Int+ -- ^ The token after @as@'s clause, the quoted body.+ }+++-- | Find the clauses of a function whose arguments close at @close@ and+-- which ends before @end@: @returns@ (right after the arguments, if+-- there), then each option, in source order, and the body.+functionParts :: Pg.CreateFunctionStmt -> Int -> Int -> R FunctionParts+functionParts f close end = do+ opts <- forM (f ^. Pg.options) \o -> case node o of+ Just (Pg.Node'DefElem de) -> (de,) <$> tokAt (fromIntegral (de ^. Pg.location))+ _ -> unsupported "a function option pgstyle cannot read"+ standardAt <- case f ^. Pg.maybe'sqlBody of+ Just _ -> Just <$> standardBodyStart (close + 1)+ Nothing -> pure Nothing+ let optStarts = map snd opts+ firstOpt = foldr min (fromMaybe end standardAt) optStarts+ returnsEnd <-+ if close + 1 < firstOpt+ then do+ isReturns <- tokIs (close + 1) "returns"+ unless isReturns (unsupported "a function pgstyle cannot read")+ pure (Just firstOpt)+ else pure Nothing+ -- Where the body starts: @as@, or a SQL-standard body after every+ -- clause.+ body <- case (f ^. Pg.maybe'sqlBody, [s | (de, s) <- opts, de ^. Pg.defname == "as"]) of+ (Nothing, [s]) -> pure (QuotedBody s)+ (Just b, []) | Just at <- standardAt -> pure (StandardBody at b)+ _ -> unsupported "a function without a body pgstyle can place"+ let bodyAt = case body of+ QuotedBody at -> at+ StandardBody at _ -> at+ -- A SQL-standard body ends the last clause; @as@ is a clause itself.+ ends = case body of+ StandardBody{} -> map (min bodyAt) (drop 1 optStarts ++ [end])+ QuotedBody{} -> drop 1 optStarts ++ [end]+ clauses = zipWith Clause optStarts ends+ pure+ FunctionParts+ { returnsEnd+ , body+ , before = [c | c <- clauses, c.start < bodyAt]+ , after = [c | c <- clauses, c.start > bodyAt]+ , asEnd = fromMaybe end (listToMaybe [c.end | c <- clauses, c.start == bodyAt])+ }+++-- | Where a function's body is: in quotes after @as@ at this token, or a+-- SQL-standard one starting at this token.+data FunctionBody+ = QuotedBody Int+ | StandardBody Int Pg.Node+++-- | A clause of a function, from its first token to before @end@.+data Clause = Clause+ { start :: Int+ , end :: Int+ }+++-- | A quoted body after @as@ at this token, up to before @asEnd@, and the+-- clauses after it. The body starts the line after @as@, as written; its+-- opening quote lines up with the closing one, when that starts a line of+-- its own. The clauses after it follow it on its last line; with a comment+-- among them, each after the first on a line of its own.+quotedBody :: Int -> Int -> [Clause] -> R D+quotedBody asAt asEnd after = do+ asK <- kw "as"+ bodyBrk <- brk mempty (asAt + 1)+ col <- asks (.column)+ bodyTok <- tokM (asAt + 1)+ let closeCol = case bodyTok of+ Just tk+ | asEnd == asAt + 2+ , Just tag <- dollarTag tk.text -> do+ let lastLine = snd (T.breakOnEnd "\n" tk.text)+ (spaces, rest) = T.span (== ' ') lastLine+ if T.isInfixOf "\n" tk.text && rest == tag then Just (T.length spaces) else Nothing+ _ -> Nothing+ openIndent = maybe mempty (\c -> pretty (T.replicate (max 0 (c - col)) " ")) closeCol+ body <- looseRun (asAt + 1) asEnd+ afterDs <- forM after \c -> looseRun c.start c.end+ commented <- or <$> forM (drop 1 after) \c -> not . null <$> gapBefore c.start+ rest <-+ if commented+ then forM (zip (drop 1 after) (drop 1 afterDs)) \(c, d) -> (<> d) <$> brk mempty c.start+ else pure [" " <> d | d <- drop 1 afterDs]+ let firstAfter = maybe mempty (" " <>) (listToMaybe afterDs)+ clausesAfter = if commented then nest indentSize (mconcat rest) else mconcat rest+ pure (" " <> asK <> bodyBrk <> openIndent <> body <> firstAfter <> clausesAfter)+++-- | Where a SQL-standard body starts: @begin atomic@ or @return@, at or+-- after this token.+standardBodyStart :: Int -> R Int+standardBodyStart j = do+ w <- tokL j+ w1 <- tokL (j + 1)+ t <- tokM j+ case t of+ Nothing -> unsupported "a function body pgstyle cannot find"+ Just _+ | w == "return" || (w == "begin" && w1 == "atomic") -> pure j+ | w == "(" -> do+ m <- matchOf j+ maybe (unsupported "an unclosed parenthesis") (standardBodyStart . (+ 1)) m+ | otherwise -> standardBodyStart (j + 1)+++-- | A SQL-standard body, from token @at@ to before @end@: @return@ and its+-- expression, or @begin atomic@, each statement laid out on the lines+-- after it, indented, and @end@.+standardBody :: (Pg.Node -> R D) -> Pg.Node -> Int -> Int -> R D+standardBody statement b at end = case node b of+ Just (Pg.Node'ReturnStmt r) -> do+ k <- kw "return"+ ex <- req "a return" (r ^. Pg.maybe'returnval)+ d <- ddlExpr ex+ pure (k <+> d)+ Just (Pg.Node'List outer)+ | [inner] <- outer ^. Pg.items+ , Just (Pg.Node'List l) <- node inner -> do+ let stmts = l ^. Pg.items+ isEnd <- tokIs (end - 1) "end"+ unless isEnd (unsupported "a function body pgstyle cannot read")+ -- Each statement starts after @atomic@ or after a semicolon; one+ -- right after @atomic@ is kept.+ semiFirst <- tokIs (at + 2) ";"+ let first = if semiFirst then at + 3 else at + 2+ semis <- semicolons first (end - 1)+ let starts = first : map (+ 1) semis+ unless (length semis == length stmts) (unsupported "a function body pgstyle cannot read")+ k <- (<> (if semiFirst then ";" else mempty)) <$> kw "begin atomic"+ ds <- forM (zip stmts starts) \(st, s) -> do+ d <- statement st+ br <- brk mempty s+ pure (br <> d <> ";")+ endBrk <- brk mempty (end - 1)+ e <- kw "end"+ pure (k <> nest indentSize (mconcat ds) <> endBrk <> e)+ _ -> unsupported "a function body pgstyle does not lay out"+ where+ semicolons j stop+ | j >= stop = pure []+ | otherwise = do+ w <- tokL j+ case w of+ ";" -> (j :) <$> semicolons (j + 1) stop+ "(" -> do+ m <- matchOf j+ maybe (unsupported "an unclosed parenthesis") (\c -> semicolons (c + 1) stop) m+ _ -> semicolons (j + 1) stop+++-- | A dollar-quoted string's tag, as in @$@ or @$body$@.+dollarTag :: Text -> Maybe Text+dollarTag t = case T.uncons t of+ Just ('$', rest) | (tag, r) <- T.breakOn "$" rest, not (T.null r) -> Just ("$" <> tag <> "$")+ _ -> Nothing+++-- | The longest @create function name(args)@ line that keeps its arguments+-- on it.+functionHeaderThreshold :: Int+functionHeaderThreshold = 100+++-- | A function's parameters, between the parentheses at these tokens, with+-- the token each starts at.+paramList :: [Pg.FunctionParameter] -> Int -> Int -> R [(Int, D)]+paramList ps from close = do+ starts <- traverse (tokAt . fromIntegral . (^. Pg.location)) ps+ case starts of+ [] -> unless (from == close) (unsupported "a function pgstyle cannot read")+ s0 : _ -> unless (s0 == from) (unsupported "a function pgstyle cannot read")+ let ends = map (subtract 1) (drop 1 starts) ++ [close]+ forM (zip3 ps starts ends) \(p, s, e) -> (s,) <$> param p s e+++-- | Whether 'commaRows' keeps a blank line the source has between two rows.+data BlankLines = KeepBlankLines | DropBlankLines+++-- | Rows, each with the token it starts at: each on a line of its own after+-- the comments before it, each but the last followed by its comma.+commaRows :: BlankLines -> [(Int, D)] -> R D+commaRows blankLines rows = do+ let n = length rows+ ls <- forM (zip [0 :: Int ..] rows) \(i, (s, d)) -> do+ b <- brk mempty s+ blank <- asks (IS.member s . (.blankLineBefore))+ let gap = case blankLines of+ KeepBlankLines | blank && i > 0 -> hardline+ _ -> mempty+ pure (b <> gap <> d <> (if i < n - 1 then "," else mempty))+ pure (mconcat ls)+++-- | The comments before a list's closing parenthesis: one sharing the last+-- row's line ends it, one on a line of its own stays one, indented with the+-- rows.+closingComments :: Int -> R D+closingComments close = do+ cs <- gapBefore close+ let (trailing, own) = span (not . (.ownLine)) cs+ pure $+ mconcat [" " <> raw x.ctext | x <- trailing]+ <> mconcat [hardline <> (if x.blankBefore then hardline else mempty) <> raw x.ctext | x <- own]+++-- | A parenthesized list (of parameters, of columns) after @lead@: on one+-- line if it fits in @width@ and has no comments, otherwise one item per+-- line with the comma at the end, the comments in their places.+itemList :: Int -> D -> [(Int, D)] -> Int -> R D+itemList width lead items close = do+ commented <- or <$> mapM (fmap (not . null) . gapBefore) (map fst items ++ [close])+ let inline = "(" <> commaJoin (map snd items) <> ")"+ if null items && not commented+ then pure "()"+ else+ if not commented && len (lead <> inline) <= width+ then pure inline+ else do+ rows <- commaRows DropBlankLines items+ endComments <- closingComments close+ pure ("(" <> nest indentSize (rows <> endComments) <> hardline <> ")")+++-- | One parameter, from token @s@ to before @e@: its mode, name, type and+-- default.+param :: Pg.FunctionParameter -> Int -> Int -> R D+param p s e = do+ w <- tokL s+ let explicitMode = w `elem` ["in", "out", "inout", "variadic"]+ modeD <- if explicitMode then Just <$> kw w else pure Nothing+ let nameAt = if explicitMode then s + 1 else s+ nameD <-+ if T.null (p ^. Pg.name)+ then pure Nothing+ else Just <$> identAt nameAt (p ^. Pg.name)+ tn <- req "a function parameter" (p ^. Pg.maybe'argType)+ ty <- typeName tn+ def <- case p ^. Pg.maybe'defexpr of+ Nothing -> pure Nothing+ Just ex -> do+ -- @default@ or @=@, the first such token after the type.+ tyAt <- tokAt (fromIntegral (tn ^. Pg.location))+ k <- findDefault tyAt+ kd <- if k == "=" then pure "=" else kw "default"+ d <- top ex >>= expr MR+ pure (Just (kd <+> d))+ pure (spaceJoin (catMaybes [modeD, nameD, Just ty, def]))+ where+ findDefault j+ | j >= e = unsupported "a parameter default pgstyle cannot read"+ | otherwise = do+ w <- tokL j+ if w `elem` ["default", "="] then pure w else findDefault (j + 1)+++-- | @returns type@, @returns setof type@ or @returns table (columns)@, from+-- token @s@ to before @e@.+returnsClause :: Pg.CreateFunctionStmt -> [Pg.FunctionParameter] -> Int -> Int -> R D+returnsClause f tableCols s e = do+ k <- kw "returns"+ isTable <- tokIs (s + 1) "table"+ if isTable+ then do+ t <- kw "table"+ close <- expectParen (s + 2)+ unless (close == e - 1) (unsupported "a returns table pgstyle cannot read")+ cols <- paramList tableCols (s + 3) close+ l <- itemList functionHeaderThreshold (k <+> t <> " ") cols close+ pure (k <+> t <+> l)+ else do+ tn <- req "a function's return type" (f ^. Pg.maybe'returnType)+ setof <- tokIs (s + 1) "setof"+ let tyStart = if setof then s + 2 else s + 1+ at <- tokM tyStart >>= maybe (unsupported "a return type pgstyle cannot read") (pure . (.start))+ ty <- typeName (tn & Pg.setof .~ False & Pg.location .~ fromIntegral at)+ sd <- if setof then (<> " ") <$> kw "setof" else pure mempty+ pure (k <+> sd <> ty)+++-- | @create trigger@: the trigger's name on the first line, then each+-- clause on a line of its own, at the statement's column: @after insert@,+-- @on t@, @referencing ...@, @for each row@, @when (...)@, @execute+-- function f()@.+createTrigger :: Pg.CreateTrigStmt -> R D+createTrigger t = do+ trigAt <- findTrigger 0+ header <- wordsRun 0 (trigAt + 1)+ let nameAt = trigAt + 1+ name <- identAt nameAt (t ^. Pg.trigname)+ end <- (+ 1) <$> lastTok+ clauses <- clauseStarts (nameAt + 1) end+ case clauses of+ (s0, _) : _ | s0 == nameAt + 1 -> pure ()+ _ -> unsupported "a trigger pgstyle cannot read"+ -- The clauses the tree says are there are the ones found.+ let found kind = kind `elem` map snd clauses+ unless+ ( found When == isJust (t ^. Pg.maybe'whenClause)+ && found Referencing == not (null (t ^. Pg.transitionRels))+ && found FromTable == isJust (t ^. Pg.maybe'constrrel)+ )+ (unsupported "a trigger pgstyle cannot read")+ let starts = map fst clauses+ ends = drop 1 starts ++ [end]+ ds <- forM (zip clauses ends) \((s, kind), e) -> do+ d <- case kind of+ When -> do+ close <- expectParen (s + 1)+ unless (close == e - 1) (unsupported "a trigger pgstyle cannot read")+ c <- req "a trigger's condition" (t ^. Pg.maybe'whenClause)+ k <- kw "when"+ (k <+>) <$> checkCondition c+ Execute -> do+ names <- strsOf (t ^. Pg.funcname)+ ws <- wordsRun s (s + 2)+ f <- qualNameAt (s + 2) names+ let open = s + 2 + 2 * length names - 1+ close <- expectParen open+ unless (close == e - 1) (unsupported "a trigger pgstyle cannot read")+ args <- looseRun (open + 1) close+ pure (ws <+> f <> "(" <> args <> ")")+ _ -> looseRun s e+ b <- brk mempty s+ pure (b <> d)+ pure (header <+> name <> mconcat ds)+ where+ findTrigger j = do+ w <- tokL j+ case w of+ "trigger" -> pure j+ _ | w `elem` ["create", "or", "replace", "constraint"] -> findTrigger (j + 1)+ _ -> unsupported "a trigger pgstyle cannot read"+ -- Where each clause starts, and what it is: the top-level words that+ -- start one.+ clauseStarts j b+ | j >= b = pure []+ | otherwise = do+ w <- tokL j+ prev <- tokL (j - 1)+ next <- tokL (j + 1)+ rest <-+ if w == "("+ then matchOf j >>= maybe (unsupported "an unclosed parenthesis") (\c -> clauseStarts (c + 1) b)+ else clauseStarts (j + 1) b+ pure case triggerClause prev w next of+ Just kind -> (j, kind) : rest+ Nothing -> rest+++-- | A clause of @create trigger@.+data TriggerClause+ = -- | @before@, @after@ or @instead of@, and the events.+ Timing+ | OnTable+ | -- | A constraint trigger's @from@ table.+ FromTable+ | -- | @deferrable@, @not deferrable@, @initially ...@.+ Deferral+ | Referencing+ | ForEach+ | When+ | Execute+ deriving stock (Eq)+++-- | The clause a word starts, given the words around it, if it starts one.+triggerClause :: Text -> Text -> Text -> Maybe TriggerClause+triggerClause prev w next = case w of+ _ | w `elem` ["before", "after", "instead"] -> Just Timing+ "on" -> Just OnTable+ "from" -> Just FromTable+ "referencing" -> Just Referencing+ "for" -> Just ForEach+ "when" -> Just When+ "execute" -> Just Execute+ "not" | next == "deferrable" -> Just Deferral+ "deferrable" | prev /= "not" -> Just Deferral+ "initially" | prev /= "deferrable" -> Just Deferral+ _ -> Nothing+++-- | The longest @grant@ or @revoke@ that stays on one line.+grantInlineThreshold :: Int+grantInlineThreshold = 80+++-- | The clauses of a @grant@ or @revoke@, as its tree says: whether it is of+-- privileges @on@ objects, or of roles; and the word before the roles.+data GrantClauses = GrantClauses+ { onObjects :: Bool+ , grantees :: Text+ }+++-- | @to@ for a grant, @from@ for a revoke.+granteesWord :: Bool -> Text+granteesWord isGrant = if isGrant then "to" else "from"+++-- | @grant@ and @revoke@, of privileges (@on@ objects) or of roles: on one+-- line if short; otherwise the privileges on the first line, then @on@ the+-- objects and @to@ (or @from@) the roles, each on a line of its own.+grantStmt :: GrantClauses -> R D+grantStmt clauses = do+ end <- (+ 1) <$> lastTok+ onAt <- if clauses.onObjects then Just <$> (firstTop ["on"] 1 end >>= req "a grant") else pure Nothing+ toAt <- firstTop [clauses.grantees] (maybe 1 (+ 1) onAt) end >>= req "a grant"+ let starts = 0 : catMaybes [onAt, Just toAt]+ ends = drop 1 starts ++ [end]+ ps <- forM (zip starts ends) (uncurry looseRun)+ cmts <- commentsBetween 0 (end - 1)+ let inline = spaceJoin ps+ case ps of+ first : rest | cmts || len inline > grantInlineThreshold -> do+ bs <- forM (drop 1 starts) (brk mempty)+ pure (first <> nest indentSize (mconcat (zipWith (<>) bs rest)))+ _ -> pure inline+ where+ -- The first of these words at the top level from @j@ to before @b@.+ firstTop ws j b+ | j >= b = pure Nothing+ | otherwise = do+ w <- tokL j+ if+ | w `elem` ws -> pure (Just j)+ | w == "(" -> matchOf j >>= maybe (unsupported "an unclosed parenthesis") (\c -> firstTop ws (c + 1) b)+ | otherwise -> firstTop ws (j + 1) b+++-- | Storage options, @(fillfactor = 70, fastupdate = off)@, in their+-- parentheses, which the caller has placed.+relOptions :: [Pg.Node] -> R D+relOptions items = do+ opts <- forM items \o -> case node o of+ Just (Pg.Node'DefElem de) | T.null (de ^. Pg.defnamespace) -> do+ at <- tokAt (fromIntegral (de ^. Pg.location))+ nm <- identAt at (de ^. Pg.defname)+ case de ^. Pg.maybe'arg of+ Nothing -> pure nm+ Just _ -> do+ eq <- tokIs (at + 1) "="+ v <- tokM (at + 2)+ case v of+ Just vt | eq, vt.kind `elem` [Pg.ICONST, Pg.FCONST] -> pure (nm <> " = " <> pretty (T.toLower vt.text))+ Just vt | eq, vt.kind == Pg.SCONST -> pure (nm <> " = " <> raw vt.text)+ Just vt | eq, vt.isKeyword, vt.kind /= Pg.IDENT -> (\k -> nm <> " = " <> k) <$> kw (T.toLower vt.text)+ Just vt | eq, vt.kind == Pg.IDENT, not ("\"" `T.isPrefixOf` vt.text) -> pure (nm <> " = " <> raw vt.text)+ _ -> cannot+ _ -> cannot+ pure ("(" <> commaJoin opts <> ")")+ where+ cannot :: R a+ cannot = unsupported "a storage option pgstyle cannot read"
+ src/PgStyle/Layout/Dml.hs view
@@ -0,0 +1,1599 @@+-- | Selects, from clauses, and insert, update and delete.+module PgStyle.Layout.Dml where++import Control.Monad (forM, unless, when, zipWithM)+import Control.Monad.Reader (asks)+import Data.Foldable (toList)+import Data.IntSet qualified as IS+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe)+import Data.ProtoLens.Message (Message (..))+import Data.Text (Text)+import Data.Text qualified as T+import Lens.Micro ((&), (.~), (^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Comments+import PgStyle.Layout.Expr+import PgStyle.Layout.Locations+import PgStyle.Layout.Monad+import PgStyle.Layout.Names+import PgStyle.Layout.Parens+import Prettyprinter (hardline, indent, nest, pretty, vsep, (<+>))+++-- | A select's first token: @with@, @select@, @values@, or the opening+-- parenthesis of its first operand.+selectFirst :: Pg.SelectStmt -> R Int+selectFirst s+ | Just w <- s ^. Pg.maybe'withClause = do+ i <- tokAt (fromIntegral (w ^. Pg.location))+ ok <- tokIs i "with"+ unless ok (unsupported "a with clause pgstyle cannot find")+ pure i+ | s ^. Pg.op /= Pg.SETOP_NONE = do+ l <- req "a set operation" (s ^. Pg.maybe'larg)+ r <- req "a set operation" (s ^. Pg.maybe'rarg)+ f <- selectFirst l+ rls <- nonEmptyLocs (locsMsg r)+ rStart <- tokAt (minimum rls)+ extendOver f rStart+ | otherwise = do+ ls <- nonEmptyLocs (locsMsg s)+ i <- tokAt (minimum ls)+ let isValues = not (null (s ^. Pg.valuesLists))+ target = if isValues then "values" else "select"+ skippable = if isValues then ["("] else ["(", "distinct", "all", "on"] ++ ["from" | null (s ^. Pg.targetList)]+ walk j = do+ w <- tokL j+ if+ | w == target -> pure j+ | w `elem` skippable -> walk (j - 1)+ | otherwise -> unsupported "a select pgstyle cannot find the start of"+ walk (i - 1)+++-- | Back over the opening parentheses before a token that close before+-- another.+extendOver :: Int -> Int -> R Int+extendOver f bound = do+ isParen <- tokIs (f - 1) "("+ m <- matchOf (f - 1)+ case m of+ Just close | isParen, close < bound -> extendOver (f - 1) bound+ _ -> pure f+++-- | How many parentheses the source has around a select, at or after a+-- token, placing them.+selectParens :: Int -> Pg.SelectStmt -> R Int+selectParens bound s = do+ ls <- nonEmptyLocs (locsMsg s)+ remembered AroundSelect ls (selectParens' bound s ls)+++selectParens' :: Int -> Pg.SelectStmt -> [Int] -> R Int+selectParens' bound s ls = do+ f <- selectFirst s+ placeWrapping bound f ls+++-- | Place the parentheses around the node with these (non-empty) locations+-- whose first token is @first@: back from the token before it, down to+-- @bound@, each opening parenthesis not yet placed whose closing one comes+-- after the node's last token, while the pair holds nothing but the node.+-- How many it placed.+placeWrapping :: Int -> Int -> [Int] -> R Int+placeWrapping bound first ls = do+ let set = IS.fromList ls+ maxTok <- tokAt (maximum ls)+ let go p n+ | p < bound = pure n+ | otherwise = do+ isParen <- tokIs p "("+ placed <- isConsumed p+ mm <- matchOf p+ case mm of+ Just m+ | isParen+ , not placed+ , m > maxTok -> do+ cov <- covers p m set+ if cov then consume p >> go (p - 1) (n + 1) else pure n+ _ -> pure n+ go (first - 1) 0+++-- | The parentheses around a select, not placing them: for finding where+-- a table reference starts.+selectParensPeek :: Pg.SelectStmt -> R Int+selectParensPeek s = do+ f <- selectFirst s+ ls <- nonEmptyLocs (locsMsg s)+ let set = IS.fromList ls+ maxTok <- tokAt (maximum ls)+ let go p n = do+ isParen <- tokIs p "("+ mm <- matchOf p+ case mm of+ Just m+ | isParen+ , m > maxTok -> do+ cov <- covers p m set+ if cov then go (p - 1) (n + 1) else pure n+ _ -> pure n+ go (f - 1) 0+++-- | "PgStyle.Render"'s @renderSelectStmt@: a statement-level select, with+-- however many parentheses around it.+selStmt :: Pg.SelectStmt -> Int -> R D+selStmt s 0 = selNoParens s+selStmt s n = selWithParens s n+++selWithParens :: Pg.SelectStmt -> Int -> R D+selWithParens s n = do+ inner <- if n <= 1 then selNoParens s else selWithParens s (n - 1)+ pure ("(" <> inner <> ")")+++selNoParens :: Pg.SelectStmt -> R D+selNoParens s = do+ w <- traverse withClause (s ^. Pg.maybe'withClause)+ c <- selClause s+ so <- if null (s ^. Pg.sortClause) then pure Nothing else Just <$> sortClause (s ^. Pg.sortClause)+ l <- selectLimit True s+ lk <- locking s+ cAt <- attempt (selectFirst (s & Pg.maybe'withClause .~ Nothing))+ soAt <- maybe (pure Nothing) (clauseAt [["order", "by"]]) (listToMaybe (s ^. Pg.sortClause))+ lAt <- limitAt s+ linesAt mempty (present [(Nothing, w), (cAt, Just c), (soAt, so), (lAt, l), (Nothing, lk)])+++-- | The clauses there are, with their first tokens.+present :: [(Maybe Int, Maybe D)] -> [(Maybe Int, D)]+present xs = [(q, d) | (q, Just d) <- xs]+++-- | Where a select's @limit@ or @offset@, whichever comes first, starts.+limitAt :: Pg.SelectStmt -> R (Maybe Int)+limitAt s = do+ l <- maybe (pure Nothing) (clauseAt [["limit"]]) (s ^. Pg.maybe'limitCount)+ o <- maybe (pure Nothing) (clauseAt [["offset"]]) (s ^. Pg.maybe'limitOffset)+ pure case catMaybes [l, o] of+ [] -> Nothing+ qs -> Just (minimum qs)+++-- | A set operation's operands, with their parentheses.+operands :: Pg.SelectStmt -> R (Sel, Sel)+operands s = do+ l <- req "a set operation" (s ^. Pg.maybe'larg)+ r <- req "a set operation" (s ^. Pg.maybe'rarg)+ lp <- selectParens 0 l+ rp <- selectParens 0 r+ let bare x n = n == 0 && (isJust (x ^. Pg.maybe'withClause) || not (null (x ^. Pg.sortClause)) || isJust (x ^. Pg.maybe'limitCount) || isJust (x ^. Pg.maybe'limitOffset) || not (null (x ^. Pg.lockingClause)))+ when (bare l lp || bare r rp) (unsupported "a set operation operand pgstyle cannot read")+ pure (Sel{stmt = l, parens = lp}, Sel{stmt = r, parens = rp})+++-- | @union all@ and the like, as written, and where.+setOperator :: Pg.SelectStmt -> Sel -> R (D, Int)+setOperator s r = do+ rFirst <- selectFirst r.stmt+ let k = rFirst - r.parens - 1+ w <- tokL k+ (opTok, modifier) <-+ if w `elem` ["all", "distinct"] then pure (k - 1, Just w) else pure (k, Nothing)+ op <- tokL opTok+ let expected = case s ^. Pg.op of+ Pg.SETOP_UNION -> "union"+ Pg.SETOP_INTERSECT -> "intersect"+ _ -> "except"+ unless (op == expected && (s ^. Pg.all) == (modifier == Just "all")) (unsupported "a set operator pgstyle cannot find")+ d <- kw (T.unwords (op : toList modifier))+ pure (d, opTok)+++-- | "PgStyle.Render"'s @renderSelectClause@ / @renderSimpleSelect@.+selClause :: Pg.SelectStmt -> R D+selClause s+ | s ^. Pg.op /= Pg.SETOP_NONE = do+ (l, r) <- operands s+ ld <- if l.parens == 0 then selClause l.stmt else selWithParens l.stmt l.parens+ (op, opAt) <- setOperator s r+ rd <- if r.parens == 0 then selClause r.stmt else selWithParens r.stmt r.parens+ rAt <- attempt (subtract r.parens <$> selectFirst r.stmt)+ linesAt mempty [(Nothing, ld), (Just opAt, op), (rAt, rd)]+ | not (null (s ^. Pg.valuesLists)) = valuesClause s+ | otherwise = do+ when (isJust (s ^. Pg.maybe'intoClause)) (unsupported "select into")+ t <- targeting s+ f <- if null (s ^. Pg.fromClause) then pure Nothing else Just <$> fromClause (s ^. Pg.fromClause)+ w <- traverse (condAligned 5 "where") (s ^. Pg.maybe'whereClause)+ g <- groupClause s+ h <- traverse (condAligned 6 "having") (s ^. Pg.maybe'havingClause)+ wi <- windowClause s+ fAt <- maybe (pure Nothing) (clauseAt [["from"], ["from", "lateral"]]) (listToMaybe (s ^. Pg.fromClause))+ wAt <- maybe (pure Nothing) (clauseAt [["where"]]) (s ^. Pg.maybe'whereClause)+ gAt <- maybe (pure Nothing) (clauseAt [["group", "by"]]) (listToMaybe (s ^. Pg.groupClause))+ hAt <- maybe (pure Nothing) (clauseAt [["having"]]) (s ^. Pg.maybe'havingClause)+ wiAt <- maybe (pure Nothing) (clauseAt [["window"]]) (listToMaybe (s ^. Pg.windowClause))+ linesAt mempty (present [(Nothing, Just t), (fAt, f), (wAt, w), (gAt, g), (hAt, h), (wiAt, wi)])+++-- | @select@, @select all@, @select distinct@, @select distinct on (...)@.+targetPrefix :: Mode -> Pg.SelectStmt -> R D+targetPrefix mode s = do+ sel <- kw "select"+ case s ^. Pg.distinctClause of+ [] -> do+ written <- allWritten s+ if written then (sel <+>) <$> kw "all" else pure sel+ [x] | isNothing (node x) -> (sel <+>) <$> kw "distinct"+ exprs -> do+ ls <- nonEmptyLocs (concatMap locsNode exprs)+ i <- tokAt (minimum ls)+ let findOn j = do+ w <- tokL j+ if+ | w == "on" -> pure j+ | w == "(" -> findOn (j - 1)+ | otherwise -> unsupported "a distinct on pgstyle cannot read"+ on <- findOn (i - 1)+ _ <- expectParen (on + 1)+ ds <- traverse (top >=> expr MP) exprs+ d <- kw "distinct on"+ pure (if mode == MP then d <> " (" <> commaJoin ds <> ")" else sel <+> d <+> "(" <> commaJoin ds <> ")")+++-- | Whether a select without @distinct@ has @all@ written before its+-- targets.+allWritten :: Pg.SelectStmt -> R Bool+allWritten s = case s ^. Pg.targetList of+ t : _ | Just (Pg.Node'ResTarget rt) <- node t -> tokAt (fromIntegral (rt ^. Pg.location)) >>= \i -> tokIs (i - 1) "all"+ _ -> pure False+++targeting :: Pg.SelectStmt -> R D+targeting s = do+ prefix <- targetPrefix MR s+ case s ^. Pg.targetList of+ [] -> pure prefix+ [single] -> do+ forces <- targetForcesMultiLine single+ q <- targetFirst single+ commented <- maybe (pure False) (fmap (not . null) . gapBefore) q+ if forces || commented then blockList prefix targetElDoc targetFirst [single] else (prefix <+>) <$> targetElDoc single+ items -> blockList prefix targetElDoc targetFirst items+++-- | A target's first token.+targetFirst :: Pg.Node -> R (Maybe Int)+targetFirst n = case node n of+ Just (Pg.Node'ResTarget rt) | rt ^. Pg.location >= 0 -> Just <$> tokAt (fromIntegral (rt ^. Pg.location))+ _ -> pure Nothing+++targetForcesMultiLine :: Pg.Node -> R Bool+targetForcesMultiLine n = case node n of+ Just (Pg.Node'ResTarget rt) | Just v <- rt ^. Pg.maybe'val -> top v >>= isTopLevelCase+ _ -> pure False+++-- | "PgStyle.Render"'s @renderBlockListWith@; with each item's first token,+-- for the comments before it.+blockList :: D -> (a -> R D) -> (a -> R (Maybe Int)) -> [a] -> R D+blockList prefix item first items = do+ rows <- zipWithM row [(0 :: Int) ..] items+ pure (prefix <> mconcat rows)+ where+ row i x = do+ b <- first x >>= brkAt " "+ d <- item x+ pure (b <> (if i == 0 then " " else " , ") <> d)+++-- | A target: its expression and alias.+resTarget :: Pg.Node -> R (Pg.ResTarget, E)+resTarget n = case node n of+ Just (Pg.Node'ResTarget rt) -> do+ v <- req "a target" (rt ^. Pg.maybe'val)+ e <- top v+ pure (rt, e)+ _ -> unsupported "a target pgstyle cannot read"+++targetWith :: (E -> R D) -> Pg.Node -> R D+targetWith render n = do+ (rt, e) <- resTarget n+ d <- render e+ a <- targetAlias rt+ pure (d <> a)+++-- | "PgStyle.Render"'s @renderTargetEl@, @renderTargetElDoc@, and+-- postgresql-syntax's own.+targetEl, targetElDoc, targetElP :: Pg.Node -> R D+targetEl = targetWith (expr MR)+targetElDoc = targetWith exprDoc+targetElP = targetWith (expr MP)+++-- | A target's alias, with @as@ if the source has it.+targetAlias :: Pg.ResTarget -> R D+targetAlias rt+ | T.null name = pure mempty+ | otherwise = do+ v <- req "a target" (rt ^. Pg.maybe'val)+ ls <- nonEmptyLocs (locsNode v)+ s <- tokAt (fromIntegral (rt ^. Pg.location))+ e <- tokAt (maximum ls)+ d0 <- depthBetween s (e + 1)+ found <- find (e + 1) d0+ hasAs <- tokIs (found - 1) "as"+ a <- ident name+ asK <- kw "as"+ pure (" " <> (if hasAs then asK <> " " else mempty) <> a)+ where+ name = rt ^. Pg.name+ find i d = do+ t <- tokM i+ case t of+ Nothing -> unsupported "an alias pgstyle cannot find"+ Just tk+ | d == 0+ , identText tk == Just name -> do+ -- An alias ends the target; a column of the same name in+ -- @t.name@ does not.+ next <- tokM (i + 1)+ let ends = case next of+ Nothing -> True+ Just n -> n.text `elem` [",", ")", ";"] || (n.isKeyword && T.toLower n.text `elem` clauseWords)+ if ends then pure i else find (i + 1) d+ | tk.text `elem` ["(", "["] -> find (i + 1) (d + 1)+ | tk.text `elem` [")", "]"] -> if d == 0 then unsupported "an alias pgstyle cannot find" else find (i + 1) (d - 1)+ | otherwise -> find (i + 1) d+++-- | Keywords that can follow a select or returning list.+clauseWords :: [Text]+clauseWords = ["from", "into", "where", "group", "having", "window", "order", "limit", "offset", "fetch", "for", "union", "intersect", "except", "returning", "on"]+++depthBetween :: Int -> Int -> R Int+depthBetween a b =+ sum <$> forM [a .. b - 1] \i -> do+ w <- tokL i+ pure if w `elem` ["(", "["] then 1 else if w `elem` [")", "]"] then -1 else 0+++-- | "PgStyle.Render"'s @renderSelectWithParensMaybeWrap@.+selMaybeWrap :: Sel -> R D+selMaybeWrap sel = do+ inline <- selInline sel+ if len inline > subqueryInlineThreshold then selWrapped sel else pure inline+++selWrapped :: Sel -> R D+selWrapped (Sel s n) = do+ inner <- if n <= 1 then selNoParens s else selWrapped (Sel s (n - 1))+ pure ("(" <> nest indentSize (hardline <> inner) <> hardline <> ")")+++-- | "PgStyle.Render"'s @renderSelectWithParensInline@.+selInline :: Sel -> R D+selInline (Sel s n) = do+ inner <- if n <= 1 then selNoParensInline s else selInline (Sel s (n - 1))+ pure ("(" <> inner <> ")")+++selNoParensInline :: Pg.SelectStmt -> R D+selNoParensInline s = do+ w <- traverse withP (s ^. Pg.maybe'withClause)+ c <- selClauseInline s+ so <- if null (s ^. Pg.sortClause) then pure Nothing else Just <$> sortClause (s ^. Pg.sortClause)+ l <- selectLimit False s+ lk <- locking s+ pure (spaceJoin (catMaybes [w, Just c, so, l, lk]))+++selClauseInline :: Pg.SelectStmt -> R D+selClauseInline s+ | s ^. Pg.op /= Pg.SETOP_NONE = do+ (l, r) <- operands s+ ld <- if l.parens == 0 then selClauseInline l.stmt else selInline l+ (op, _) <- setOperator s r+ rd <- if r.parens == 0 then selClauseInline r.stmt else selInline r+ pure (ld <+> op <+> rd)+ | not (null (s ^. Pg.valuesLists)) = valuesP s+ | otherwise = do+ when (isJust (s ^. Pg.maybe'intoClause)) (unsupported "select into")+ prefix <- targetPrefix MR s+ targets <- traverse targetEl (s ^. Pg.targetList)+ let t = if null targets then prefix else prefix <+> commaJoin targets+ f <-+ if null (s ^. Pg.fromClause)+ then pure Nothing+ else do+ k <- kw "from"+ ds <- traverse tableRefInline (s ^. Pg.fromClause)+ pure (Just (k <+> commaJoin ds))+ w <- forM (s ^. Pg.maybe'whereClause) \x -> do+ k <- kw "where"+ d <- top x >>= expr MR+ pure (k <+> d)+ g <- groupClause s+ h <- forM (s ^. Pg.maybe'havingClause) \x -> do+ k <- kw "having"+ d <- top x >>= expr MR+ pure (k <+> d)+ wi <- windowClause s+ pure (spaceJoin (catMaybes [Just t, f, w, g, h, wi]))+++-- | A select as postgresql-syntax writes it.+selP :: Sel -> R D+selP (Sel s n) = do+ inner <- if n <= 1 then selNoParensP s else selP (Sel s (n - 1))+ pure ("(" <> inner <> ")")+++selNoParensP :: Pg.SelectStmt -> R D+selNoParensP s = do+ w <- traverse withP (s ^. Pg.maybe'withClause)+ c <- selClauseP s+ so <- if null (s ^. Pg.sortClause) then pure Nothing else Just <$> sortClause (s ^. Pg.sortClause)+ l <- selectLimit False s+ lk <- locking s+ pure (spaceJoin (catMaybes [w, Just c, so, l, lk]))+++selClauseP :: Pg.SelectStmt -> R D+selClauseP s+ | s ^. Pg.op /= Pg.SETOP_NONE = do+ (l, r) <- operands s+ ld <- if l.parens == 0 then selClauseP l.stmt else selP l+ (op, _) <- setOperator s r+ rd <- if r.parens == 0 then selClauseP r.stmt else selP r+ pure (ld <+> op <+> rd)+ | not (null (s ^. Pg.valuesLists)) = valuesP s+ | otherwise = do+ when (isJust (s ^. Pg.maybe'intoClause)) (unsupported "select into")+ sel <- kw "select"+ targets <- traverse targetElP (s ^. Pg.targetList)+ quantifier <- case s ^. Pg.distinctClause of+ [] -> do+ written <- allWritten s+ if written then Just <$> kw "all" else pure Nothing+ _ -> Just <$> targetPrefixP s+ let t = case (quantifier, targets) of+ (Nothing, []) -> Nothing+ (Nothing, _) -> Just (commaJoin targets)+ (Just q, []) -> Just q+ (Just q, _) -> Just (q <+> commaJoin targets)+ f <-+ if null (s ^. Pg.fromClause)+ then pure Nothing+ else do+ k <- kw "from"+ ds <- traverse tableRefP (s ^. Pg.fromClause)+ pure (Just (k <+> commaJoin ds))+ w <- forM (s ^. Pg.maybe'whereClause) \x -> do+ k <- kw "where"+ d <- top x >>= expr MP+ pure (k <+> d)+ g <- groupClause s+ h <- forM (s ^. Pg.maybe'havingClause) \x -> do+ k <- kw "having"+ d <- top x >>= expr MP+ pure (k <+> d)+ wi <- windowClause s+ pure (spaceJoin (sel : catMaybes [t, f, w, g, h, wi]))+ where+ -- postgresql-syntax's @Targeting@ without the @select@: @all@,+ -- @distinct@, @distinct on (...)@.+ targetPrefixP st = case st ^. Pg.distinctClause of+ [x] | isNothing (node x) -> kw "distinct"+ _ -> do+ d <- targetPrefix MP st+ pure d+++groupClause :: Pg.SelectStmt -> R (Maybe D)+groupClause s+ | null (s ^. Pg.groupClause) = pure Nothing+ | s ^. Pg.groupDistinct = unsupported "group by distinct"+ | otherwise = do+ k <- kw "group by"+ ds <- traverse groupItem (s ^. Pg.groupClause)+ positions <- commentedGroup+ case positions of+ -- With comments, one item per line, as a select's targets.+ Just firsts -> Just <$> blockList k (pure . fst) (pure . Just . snd) (zip ds firsts)+ Nothing -> pure (Just (k <+> commaJoin ds))+ where+ items = s ^. Pg.groupClause+ commentedGroup = do+ start <- maybe (pure Nothing) (clauseAt [["group", "by"]]) (listToMaybe items)+ end <- maybe (pure Nothing) spanOf (listToMaybe (reverse items))+ case (start, end) of+ (Just g, Just (_, e)) -> do+ commented <- commentsBetween (g + 1) e+ if commented then listFirsts (g + 1) (e + 1) (length items) else pure Nothing+ _ -> pure Nothing+ groupItem n = case node n of+ Just (Pg.Node'GroupingSet g) -> do+ at <- tokAt (fromIntegral (g ^. Pg.location))+ case g ^. Pg.kind of+ Pg.GROUPING_SET_EMPTY -> do+ _ <- expectParen at+ txt "()"+ k | k `elem` [Pg.GROUPING_SET_ROLLUP, Pg.GROUPING_SET_CUBE] -> do+ open <- nextParen at+ _ <- expectParen open+ ds <- traverse (top >=> expr MP) (g ^. Pg.content)+ w <- kw (if k == Pg.GROUPING_SET_ROLLUP then "rollup" else "cube")+ pure (w <> " (" <> commaJoin ds <> ")")+ Pg.GROUPING_SET_SETS -> do+ open <- nextParen at+ _ <- expectParen open+ ds <- traverse groupItem (g ^. Pg.content)+ w <- kw "grouping sets"+ pure (w <> " (" <> commaJoin ds <> ")")+ _ -> unsupported "a grouping set pgstyle cannot read"+ _ -> top n >>= expr MP+++windowClause :: Pg.SelectStmt -> R (Maybe D)+windowClause s+ | null (s ^. Pg.windowClause) = pure Nothing+ | otherwise = do+ k <- kw "window"+ ds <- forM (s ^. Pg.windowClause) \n -> case node n of+ Just (Pg.Node'WindowDef w) -> do+ at <- tokAt (fromIntegral (w ^. Pg.location))+ open <- nextParen at+ _ <- expectParen open+ name <- ident (w ^. Pg.name)+ asK <- kw "as"+ spec <- windowSpec w+ pure (name <+> asK <+> spec)+ _ -> unsupported "a window pgstyle cannot read"+ pure (Just (k <+> commaJoin ds))+++sortClause :: [Pg.Node] -> R D+sortClause items = do+ k <- kw "order by"+ ds <- forM items \n -> case node n of+ Just (Pg.Node'SortBy sb) -> do+ e <- req "a sort" (sb ^. Pg.maybe'node) >>= top >>= expr MP+ dir <- case sb ^. Pg.sortbyDir of+ Pg.SORTBY_ASC -> Just <$> kw "asc"+ Pg.SORTBY_DESC -> Just <$> kw "desc"+ Pg.SORTBY_USING -> do+ ops <- strsOf (sb ^. Pg.useOp)+ case ops of+ [op] -> do+ u <- kw "using"+ pure (Just (u <+> pretty op))+ _ -> unsupported "a sort operator pgstyle cannot read"+ _ -> pure Nothing+ nulls <- case sb ^. Pg.sortbyNulls of+ Pg.SORTBY_NULLS_FIRST -> Just <$> kw "nulls first"+ Pg.SORTBY_NULLS_LAST -> Just <$> kw "nulls last"+ _ -> pure Nothing+ pure (spaceJoin (e : catMaybes [dir, nulls]))+ _ -> unsupported "a sort pgstyle cannot read"+ pure (k <+> commaJoin ds)+++-- | @limit@ and @offset@, in the source's order; on separate lines in a+-- multi-line select.+selectLimit :: Bool -> Pg.SelectStmt -> R (Maybe D)+selectLimit multiLine s = do+ unless (s ^. Pg.limitOption `elem` [Pg.LIMIT_OPTION_DEFAULT, Pg.LIMIT_OPTION_COUNT]) (unsupported "fetch with ties")+ l <- traverse limitPart (s ^. Pg.maybe'limitCount)+ o <- traverse offsetPart (s ^. Pg.maybe'limitOffset)+ let sep a b = if multiLine then a <> hardline <> b else a <+> b+ pure case (l, o) of+ (Nothing, Nothing) -> Nothing+ (Just (a, _), Nothing) -> Just a+ (Nothing, Just (b, _)) -> Just b+ (Just (a, la), Just (b, lb)) -> Just (if la < lb then sep a b else sep b a)+ where+ limitPart n = do+ e <- top n+ start <- clauseStart n e+ w <- tokL (start - 1)+ unless (w == "limit") (unsupported "fetch first")+ k <- kw "limit"+ v <- case node n of+ Just (Pg.Node'AConst c) | c ^. Pg.isnull -> do+ src <- tokAt (fromIntegral (c ^. Pg.location)) >>= tokL+ kw (if src == "all" then "all" else "null")+ _ -> expr MP e+ pure (k <+> v, start)+ offsetPart n = do+ e <- top n+ start <- clauseStart n e+ w <- tokL (start - 1)+ unless (w == "offset") (unsupported "an offset pgstyle cannot read")+ ls <- nonEmptyLocs (locsNode n)+ after <- tokAt (maximum ls) >>= \i -> tokL (i + 1)+ when (after `elem` ["row", "rows"]) (unsupported "offset ... rows")+ k <- kw "offset"+ v <- expr MP e+ pure (k <+> v, start)+ clauseStart n e = do+ ls <- nonEmptyLocs (locsNode n)+ i <- tokAt (minimum ls)+ pure (i - e.lv)+++locking :: Pg.SelectStmt -> R (Maybe D)+locking s+ | null (s ^. Pg.lockingClause) = pure Nothing+ | otherwise = do+ ds <- forM (s ^. Pg.lockingClause) \n -> case node n of+ Just (Pg.Node'LockingClause lc) -> do+ strength <- kw case lc ^. Pg.strength of+ Pg.LCS_FORKEYSHARE -> "for key share"+ Pg.LCS_FORSHARE -> "for share"+ Pg.LCS_FORNOKEYUPDATE -> "for no key update"+ _ -> "for update"+ rels <-+ if null (lc ^. Pg.lockedRels)+ then pure Nothing+ else do+ k <- kw "of"+ ds <- forM (lc ^. Pg.lockedRels) \r -> case node r of+ Just (Pg.Node'RangeVar rv) -> relationName rv+ _ -> unsupported "a locked relation pgstyle cannot read"+ pure (Just (k <+> commaJoin ds))+ wait <- case lc ^. Pg.waitPolicy of+ Pg.LockWaitSkip -> Just <$> kw "skip locked"+ Pg.LockWaitError -> Just <$> kw "nowait"+ _ -> pure Nothing+ pure (spaceJoin (catMaybes [Just strength, rels, wait]))+ _ -> unsupported "a locking clause pgstyle cannot read"+ pure (Just (spaceJoin ds))+++-- | Each row's items, with its parentheses placed.+valuesRows :: Pg.SelectStmt -> R [[Pg.Node]]+valuesRows s = map snd <$> valuesRowsAt s+++-- | Each row's opening parenthesis and items, its parentheses placed.+valuesRowsAt :: Pg.SelectStmt -> R [(Int, [Pg.Node])]+valuesRowsAt s = do+ when (isJust (s ^. Pg.maybe'withClause)) (unsupported "values with a with clause")+ rows <- forM (s ^. Pg.valuesLists) \r -> case node r of+ Just (Pg.Node'List l) -> pure (l ^. Pg.items)+ _ -> unsupported "a values row pgstyle cannot read"+ first <- selectFirst s+ let place _ [] = pure []+ place i (row : rest) = do+ close <- expectParen i+ unless (null rest) do+ comma <- tokIs (close + 1) ","+ unless comma (unsupported "values rows pgstyle cannot read")+ ((i, row) :) <$> place (close + 2) rest+ place (first + 1) rows+++-- | "PgStyle.Render"'s @renderValuesClause@.+valuesClause :: Pg.SelectStmt -> R D+valuesClause s = do+ rows <- valuesRowsAt s+ k <- kw "values"+ let lastIdx = length rows - 1+ laid <- forM rows \(open, items) -> do+ ds <- traverse (top >=> expr MR) items+ close <- matchOf open >>= req "a values row"+ commented <- commentsBetween open close+ pure (open, close, ds, commented)+ -- Each row on one line when every row fits and none has a comment in+ -- it; otherwise one value per line, as "PgStyle.Render" always does.+ let oneLine = all (\(_, _, ds, commented) -> not commented && len (inlineRow ds) <= valuesRowInlineThreshold) laid+ docs <- forM (zip [(0 :: Int) ..] laid) \(i, (open, close, ds, commented)) -> do+ bracketed <-+ if commented+ then do+ firsts <- listFirsts open close (length ds)+ bracketListAt ((,close) <$> firsts) ds+ else pure case ds of+ [_] -> inlineRow ds+ _ | oneLine -> inlineRow ds+ _ -> bracketList ds+ b <- brk mempty open+ -- A blank line the source has before a row, after the first, is+ -- kept: it separates groups of rows.+ blank <- asks (IS.member open . (.blankLineBefore))+ let gap = if blank && i > 0 then hardline else mempty+ pure (b <> gap <> if i < lastIdx then bracketed <> "," else bracketed)+ pure (k <> nest indentSize (mconcat docs))+ where+ inlineRow ds = "(" <> commaJoin ds <> ")"+++-- | The longest @values@ row that goes on one line.+-- | "PgStyle.Render"'s: the most columns a function alias or an insert keeps+-- on one line.+funcAliasInlineColumns, insertInlineColumns :: Int+funcAliasInlineColumns = 3+insertInlineColumns = 3+++valuesRowInlineThreshold :: Int+valuesRowInlineThreshold = 100+++valuesP :: Pg.SelectStmt -> R D+valuesP s = do+ rows <- valuesRows s+ k <- kw "values"+ docs <- forM rows \items -> do+ ds <- traverse (top >=> expr MP) items+ pure ("(" <> commaJoin ds <> ")")+ pure (k <+> commaJoin docs)+++bracketList :: [D] -> D+bracketList = \case+ [] -> "()"+ (x : xs) -> vsep (("( " <> x) : map (", " <>) xs ++ [")"])+++-- | 'bracketList', with the comments before each item and before the+-- closing parenthesis, if each item's first token and the parenthesis are+-- known.+bracketListAt :: Maybe ([Int], Int) -> [D] -> R D+bracketListAt Nothing ds = pure (bracketList ds)+bracketListAt (Just (firsts, close)) ds = case zip firsts ds of+ [] -> pure "()"+ (q0, x) : rest -> do+ -- After the opening parenthesis, a comment goes before the first+ -- item, on its own line.+ cs <- gapBefore q0+ let before = mconcat [raw c.ctext <> hardline | c <- cs]+ items <- forM rest \(q, d) -> do+ b <- brk " " q+ pure (b <> ", " <> d)+ end <- brk " " close+ pure (before <> "( " <> x <> mconcat items <> end <> ")")+++withClause :: Pg.WithClause -> R D+withClause w = do+ k <- kw (if w ^. Pg.recursive then "with recursive" else "with")+ let ctes = w ^. Pg.ctes+ lastIdx = length ctes - 1+ docs <- forM (zip [0 :: Int ..] ctes) \(i, c) -> do+ d <- cte (i == lastIdx) c+ at <- case node c of+ Just (Pg.Node'CommonTableExpr x) | x ^. Pg.location >= 0 -> Just <$> tokAt (fromIntegral (x ^. Pg.location))+ _ -> pure Nothing+ pure (at, if i == 0 then k <> " " <> d else d)+ linesAt mempty docs+++-- | A common table expression's header (@name (cols) as materialized@) and+-- body, its own parenthesis placed.+cteParts :: Pg.Node -> R (D, Pg.Node)+cteParts n = case node n of+ Just (Pg.Node'CommonTableExpr c) -> do+ when (isJust (c ^. Pg.maybe'searchClause) || isJust (c ^. Pg.maybe'cycleClause)) (unsupported "search or cycle")+ at <- tokAt (fromIntegral (c ^. Pg.location))+ name <- ident (c ^. Pg.ctename)+ cols <-+ if null (c ^. Pg.aliascolnames)+ then pure mempty+ else do+ _ <- expectParen (at + 1)+ cs <- strsOf (c ^. Pg.aliascolnames) >>= traverse ident+ pure (" (" <> commaJoin cs <> ")")+ mat <- case c ^. Pg.ctematerialized of+ Pg.CTEMaterializeAlways -> Just <$> kw "materialized"+ Pg.CTEMaterializeNever -> Just <$> kw "not materialized"+ _ -> pure Nothing+ open <- nextParen (at + 1 + (if null (c ^. Pg.aliascolnames) then 0 else 1))+ -- The body's parenthesis: after the column list, if any.+ open' <-+ if null (c ^. Pg.aliascolnames)+ then pure open+ else matchOf (at + 1) >>= req "a column list" >>= \close -> nextParen (close + 1)+ _ <- expectParen open'+ asK <- kw "as"+ q <- req "a common table expression" (c ^. Pg.maybe'ctequery)+ pure (name <> cols <> " " <> asK <> " " <> maybe mempty (<> " ") mat, q)+ _ -> unsupported "a common table expression pgstyle cannot read"+++cte :: Bool -> Pg.Node -> R D+cte isLast n = do+ (header, q) <- cteParts n+ body <- preparable q+ pure (header <> "(" <> hardline <> indent indentSize body <> hardline <> (if isLast then ")" else "),"))+++withP :: Pg.WithClause -> R D+withP w = do+ k <- kw (if w ^. Pg.recursive then "with recursive" else "with")+ docs <- forM (w ^. Pg.ctes) \c -> do+ (header, q) <- cteParts c+ body <- case node q of+ Just (Pg.Node'SelectStmt st) -> do+ n <- selectParens 0 st+ if n == 0 then selNoParensP st else selP (Sel st n)+ _ -> unsupported "a data-modifying common table expression inside an expression"+ pure (header <> "(" <> body <> ")")+ pure (k <+> commaJoin docs)+++----------------------------------------------------------------------+-- From.+----------------------------------------------------------------------++-- | "PgStyle.Render"'s @renderFromClause@: on one line, unless a join (or a+-- long call or subquery) puts each item on its own.+fromClause :: [Pg.Node] -> R D+fromClause items = do+ multi <- anyM forcesMultiLine items+ if multi+ then do+ let lastIdx = length items - 1+ docs <- forM (zip [0 :: Int ..] items) \(i, item) -> do+ d <- tableRef (i == 0) item+ pure (if i < lastIdx then d <> "," else d)+ pure (vsep docs)+ else do+ k <- kw "from"+ ds <- traverse tableRefInline items+ pure (k <+> commaJoin ds)+ where+ forcesMultiLine n = case node n of+ Just (Pg.Node'JoinExpr _) -> pure True+ Just (Pg.Node'RangeFunction rf) -> isJust <$> wrapEligibleFuncTable rf+ Just (Pg.Node'RangeSubselect rs) -> do+ sel <- rangeSubselectSel rs+ d <- selInline sel+ pure (len d > subqueryInlineThreshold)+ _ -> pure False+++-- | A set-returning call in a from list, when it wraps.+wrapEligibleFuncTable :: Pg.RangeFunction -> R (Maybe Pg.FuncCall)+wrapEligibleFuncTable rf = do+ f <- rangeFunctionCall rf+ case f of+ Just call | funcAppArgCount call >= funcWrapThreshold -> do+ plain <- classifyCall call+ case plain of+ Plain _ | not (hasExtras call) -> do+ e <- rangeFunctionNode rf >>= top+ d <- funcApplication MR e call+ pure if len d > inlineLengthThreshold then Just call else Nothing+ _ -> pure Nothing+ _ -> pure Nothing+++withFuncCall :: Pg.Node -> Pg.FuncCall -> Pg.Node+withFuncCall n f = n & Pg.funcCall .~ f+++-- | The function of a from-list call, if it is a call.+rangeFunctionCall :: Pg.RangeFunction -> R (Maybe Pg.FuncCall)+rangeFunctionCall rf = do+ when (rf ^. Pg.isRowsfrom) (unsupported "rows from")+ case rf ^. Pg.functions of+ [item] | Just (Pg.Node'List l) <- node item -> case l ^. Pg.items of+ fn : rest | all (isNothing . node) rest -> pure case node fn of+ Just (Pg.Node'FuncCall f) -> Just f+ _ -> Nothing+ _ -> unsupported "a from-list function pgstyle cannot read"+ _ -> unsupported "a from-list function pgstyle cannot read"+++rangeFunctionNode :: Pg.RangeFunction -> R Pg.Node+rangeFunctionNode rf = case rf ^. Pg.functions of+ [item] | Just (Pg.Node'List l) <- node item, fn : _ <- l ^. Pg.items -> pure fn+ _ -> unsupported "a from-list function pgstyle cannot read"+++rangeSubselectSel :: Pg.RangeSubselect -> R Sel+rangeSubselectSel rs = do+ q <- req "a subquery" (rs ^. Pg.maybe'subquery)+ st <- case node q of+ Just (Pg.Node'SelectStmt st) -> pure st+ _ -> unsupported "a from-list subquery that is not a select"+ n <- selectParens 0 st+ when (n < 1) (unsupported "a from-list subquery without parentheses")+ pure (Sel st n)+++-- | The first token of a table reference.+tableRefFirst :: Pg.Node -> R Int+tableRefFirst n = case node n of+ Just (Pg.Node'RangeVar rv) -> tokAt (fromIntegral (rv ^. Pg.location)) >>= lateral False+ Just (Pg.Node'RangeTableSample ts) -> req "a table sample" (ts ^. Pg.maybe'relation) >>= tableRefFirst+ Just (Pg.Node'RangeSubselect rs) -> do+ q <- req "a subquery" (rs ^. Pg.maybe'subquery)+ st <- case node q of+ Just (Pg.Node'SelectStmt st) -> pure st+ _ -> unsupported "a from-list subquery that is not a select"+ f <- selectFirst st+ k <- selectParensPeek st+ lateral (rs ^. Pg.lateral) (f - k)+ Just (Pg.Node'RangeFunction rf) -> do+ fn <- rangeFunctionNode rf+ ls <- nonEmptyLocs (locsNode fn)+ tokAt (minimum ls) >>= lateral (rf ^. Pg.lateral)+ Just (Pg.Node'JoinExpr j) -> do+ l <- req "a join" (j ^. Pg.maybe'larg)+ r <- req "a join" (j ^. Pg.maybe'rarg)+ f <- tableRefFirst l+ rf <- tableRefFirst r+ extendOver f rf+ _ -> unsupported (nodeName n)+ where+ lateral isLateral i = do+ w <- tokL (i - 1)+ pure if isLateral && w == "lateral" then i - 1 else i+++-- | The parentheses around a join, placing them.+joinParens :: Pg.JoinExpr -> Pg.Node -> R Int+joinParens _ n = do+ ls0 <- nonEmptyLocs (locsNode n)+ remembered AroundJoin ls0 (joinParens' n)+++joinParens' :: Pg.Node -> R Int+joinParens' n = do+ f <- tableRefFirst n+ ls <- nonEmptyLocs (locsNode n)+ -- Before the first token there is no parenthesis, so 0 bounds nothing.+ placeWrapping 0 f ls+++-- | A relation's name.+relationName :: Pg.RangeVar -> R D+relationName rv = do+ unless (rv ^. Pg.inh) (unsupported "only")+ at <- tokAt (fromIntegral (rv ^. Pg.location))+ qualNameAt at (filter (not . T.null) [rv ^. Pg.catalogname, rv ^. Pg.schemaname, rv ^. Pg.relname])+++-- | A relation with its alias, as postgresql-syntax writes it.+relation :: Pg.RangeVar -> R D+relation rv = do+ name <- relationName rv+ at <- tokAt (fromIntegral (rv ^. Pg.location))+ let parts = length (filter (not . T.null) [rv ^. Pg.catalogname, rv ^. Pg.schemaname, rv ^. Pg.relname])+ after = at + 2 * parts - 1+ star <- tokIs after "*"+ when star (unsupported "a relation with *")+ a <- alias (rv ^. Pg.maybe'alias) after+ pure (name <> a)+++-- | @t tablesample system (10) repeatable (1)@, as postgresql-syntax+-- writes it.+tableSample :: Pg.RangeTableSample -> R D+tableSample ts = do+ rel <- case ts ^. Pg.maybe'relation >>= node of+ Just (Pg.Node'RangeVar rv) -> relation rv+ _ -> unsupported "a table sample pgstyle cannot read"+ at <- tokAt (fromIntegral (ts ^. Pg.location))+ open <- nextParen at+ close <- expectParen open+ k <- kw "tablesample"+ method <- strsOf (ts ^. Pg.method) >>= qualName+ args <- traverse (top >=> expr MP) (ts ^. Pg.args)+ rep' <- case ts ^. Pg.maybe'repeatable of+ Nothing -> pure mempty+ Just r -> do+ ropen <- nextParen (close + 1)+ _ <- expectParen ropen+ rk <- kw "repeatable"+ rd <- top r >>= expr MP+ pure (" " <> rk <> " (" <> rd <> ")")+ pure (rel <+> k <+> method <> " (" <> commaJoin args <> ")" <> rep')+++-- | An alias starting at this token, with a space before it.+alias :: Maybe Pg.Alias -> Int -> R D+alias Nothing _ = pure mempty+alias (Just a) i = do+ hasAs <- tokIs i "as"+ let nameTok = if hasAs then i + 1 else i+ t <- tokM nameTok+ unless ((t >>= identText) == Just (a ^. Pg.aliasname)) (unsupported "an alias pgstyle cannot find")+ name <- ident (a ^. Pg.aliasname)+ asK <- kw "as"+ cols <-+ if null (a ^. Pg.colnames)+ then pure mempty+ else do+ _ <- expectParen (nameTok + 1)+ cs <- strsOf (a ^. Pg.colnames) >>= traverse ident+ pure (" (" <> commaJoin cs <> ")")+ pure (" " <> (if hasAs then asK <> " " else mempty) <> name <> cols)+++-- | "PgStyle.Render"'s @renderFuncAliasClauseDoc@: more than three columns go+-- on their own lines.+funcAlias :: Maybe Pg.Alias -> Int -> R D+funcAlias Nothing _ = pure mempty+funcAlias (Just a) i+ | length (a ^. Pg.colnames) > funcAliasInlineColumns = do+ hasAs <- tokIs i "as"+ let nameTok = if hasAs then i + 1 else i+ name <- ident (a ^. Pg.aliasname)+ asK <- kw "as"+ _ <- expectParen (nameTok + 1)+ cs <- strsOf (a ^. Pg.colnames) >>= traverse ident+ pure (" " <> (if hasAs then asK <> " " else mempty) <> name <> hardline <> indent indentSize (bracketList cs))+ | otherwise = alias (Just a) i+++-- | A from-list call's alias, maybe with column definitions+-- (@as t (a int, b text)@), starting at this token.+funcAliasClause :: Mode -> Pg.RangeFunction -> Int -> R D+funcAliasClause mode rf i+ | null (rf ^. Pg.coldeflist) = (if mode == MP then alias else funcAlias) (rf ^. Pg.maybe'alias) i+ | otherwise = do+ hasAs <- tokIs i "as"+ asK <- kw "as"+ (name, open) <- case rf ^. Pg.maybe'alias of+ Nothing -> do+ unless hasAs (unsupported "a column definition list pgstyle cannot read")+ pure (Nothing, i + 1)+ Just a -> do+ unless (null (a ^. Pg.colnames)) (unsupported "an alias with both columns and definitions")+ let nameTok = if hasAs then i + 1 else i+ t <- tokM nameTok+ unless ((t >>= identText) == Just (a ^. Pg.aliasname)) (unsupported "an alias pgstyle cannot find")+ n <- ident (a ^. Pg.aliasname)+ pure (Just n, nameTok + 1)+ _ <- expectParen open+ defs <- forM (rf ^. Pg.coldeflist) \n -> case node n of+ Just (Pg.Node'ColumnDef cd) -> do+ when (isJust (cd ^. Pg.maybe'collClause) || not (null (cd ^. Pg.constraints))) (unsupported "a column definition with options")+ c <- ident (cd ^. Pg.colname)+ t <- req "a column definition" (cd ^. Pg.maybe'typeName) >>= typeName+ pure (c <> " " <> t)+ _ -> unsupported "a column definition pgstyle cannot read"+ pure (" " <> spaceJoin ([asK | hasAs] ++ toList name) <> " (" <> commaJoin defs <> ")")+++-- | The token after a from-list call (and @with ordinality@).+afterFunction :: Pg.RangeFunction -> R Int+afterFunction rf = do+ fn <- rangeFunctionNode rf+ ls <- nonEmptyLocs (locsNode fn)+ at <- tokAt (minimum ls)+ open <- nextParen at+ close <- matchOf open >>= req "a call"+ pure (if rf ^. Pg.ordinality then close + 3 else close + 1)+++lateralD :: Bool -> R D+lateralD False = pure mempty+lateralD True = (<> " ") <$> kw "lateral"+++ordinalityD :: Pg.RangeFunction -> R D+ordinalityD rf = if rf ^. Pg.ordinality then (" " <>) <$> kw "with ordinality" else pure mempty+++-- | A from-list call laid out by 'MR' or 'MP'.+funcTable :: Mode -> Pg.RangeFunction -> R D+funcTable mode rf = do+ fn <- rangeFunctionNode rf+ e <- top fn+ d <- case node fn of+ Just (Pg.Node'FuncCall f) | not (hasExtras f) -> do+ call <- classifyCall f+ case call of+ Plain _ -> funcApplication mode e f+ AtTimeZone _ _ -> unsupported "at time zone in a from list"+ _ -> funcCall mode e f+ Just (Pg.Node'CoalesceExpr _) -> expr mode e+ Just (Pg.Node'MinMaxExpr _) -> expr mode e+ Just (Pg.Node'SqlvalueFunction _) -> expr mode e+ _ -> unsupported "a from-list function pgstyle cannot read"+ o <- ordinalityD rf+ pure (d <> o)+++subselectAlias :: Pg.RangeSubselect -> Sel -> R D+subselectAlias rs sel = do+ f <- selectFirst sel.stmt+ close <- matchOf (f - sel.parens) >>= req "a subquery"+ alias (rs ^. Pg.maybe'alias) (close + 1)+++-- | "PgStyle.Render"'s @renderTableRef@.+tableRef :: Bool -> Pg.Node -> R D+tableRef isFirst n = do+ pfx <- if isFirst then (<> " ") <$> kw "from" else pure mempty+ (pfx <>) <$> case node n of+ Just (Pg.Node'RangeVar rv) -> relation rv+ Just (Pg.Node'RangeTableSample ts) -> tableSample ts+ Just (Pg.Node'RangeFunction rf) -> do+ wrap <- wrapEligibleFuncTable rf+ l <- lateralD (rf ^. Pg.lateral)+ after <- afterFunction rf+ a <- funcAliasClause MR rf after+ case wrap of+ Just f -> do+ fn <- rangeFunctionNode rf+ e <- top fn+ d <- funcApplicationWrapped e f+ o <- ordinalityD rf+ pure (l <> d <> o <> a)+ Nothing -> do+ d <- funcTable MR rf+ pure (l <> d <> a)+ Just (Pg.Node'RangeSubselect rs) -> do+ sel <- rangeSubselectSel rs+ l <- lateralD (rs ^. Pg.lateral)+ d <- selMaybeWrap sel+ a <- subselectAlias rs sel+ pure (l <> d <> a)+ Just (Pg.Node'JoinExpr j) -> do+ k <- joinParens j n+ joinedTable j k+ _ -> unsupported (nodeName n)+++-- | "PgStyle.Render"'s @renderTableRefInline@.+tableRefInline :: Pg.Node -> R D+tableRefInline n = case node n of+ Just (Pg.Node'RangeVar rv) -> relation rv+ Just (Pg.Node'RangeTableSample ts) -> tableSample ts+ Just (Pg.Node'RangeFunction rf) -> do+ l <- lateralD (rf ^. Pg.lateral)+ d <- funcTable MR rf+ after <- afterFunction rf+ a <- funcAliasClause MR rf after+ pure (l <> d <> a)+ Just (Pg.Node'RangeSubselect rs) -> do+ sel <- rangeSubselectSel rs+ l <- lateralD (rs ^. Pg.lateral)+ d <- selInline sel+ a <- subselectAlias rs sel+ pure (l <> d <> a)+ Just (Pg.Node'JoinExpr _) -> tableRefP n+ _ -> unsupported (nodeName n)+++-- | "PgStyle.Render"'s @renderTableRefDoc@, for the right side of a join.+tableRefDoc :: Pg.Node -> R D+tableRefDoc n = case node n of+ Just (Pg.Node'RangeFunction rf) -> do+ wrap <- wrapEligibleFuncTable rf+ case wrap of+ Just f -> do+ l <- lateralD (rf ^. Pg.lateral)+ fn <- rangeFunctionNode rf+ e <- top fn+ d <- funcApplicationWrapped e f+ o <- ordinalityD rf+ after <- afterFunction rf+ a <- funcAliasClause MR rf after+ pure (l <> d <> o <> a)+ Nothing -> tableRefInline n+ Just (Pg.Node'RangeSubselect rs) -> do+ sel <- rangeSubselectSel rs+ l <- lateralD (rs ^. Pg.lateral)+ d <- selMaybeWrap sel+ a <- subselectAlias rs sel+ pure (l <> d <> a)+ _ -> tableRefInline n+++-- | A table reference as postgresql-syntax writes it.+tableRefP :: Pg.Node -> R D+tableRefP n = case node n of+ Just (Pg.Node'RangeVar rv) -> relation rv+ Just (Pg.Node'RangeTableSample ts) -> tableSample ts+ Just (Pg.Node'RangeFunction rf) -> do+ l <- lateralD (rf ^. Pg.lateral)+ d <- funcTable MP rf+ after <- afterFunction rf+ a <- funcAliasClause MP rf after+ pure (l <> d <> a)+ Just (Pg.Node'RangeSubselect rs) -> do+ sel <- rangeSubselectSel rs+ l <- lateralD (rs ^. Pg.lateral)+ d <- selP sel+ a <- subselectAlias rs sel+ pure (l <> d <> a)+ Just (Pg.Node'JoinExpr j) -> do+ k <- joinParens j n+ joinP j k+ _ -> unsupported (nodeName n)+++data JoinKind = CrossJoin | NaturalJoin | QualJoin+++-- | A join's keywords as written (@left outer join@), and what kind of join+-- it is.+joinWords :: Pg.JoinExpr -> Pg.Node -> R ([Text], JoinKind)+joinWords j r = do+ when (isJust (j ^. Pg.maybe'alias) || isJust (j ^. Pg.maybe'joinUsingAlias)) (unsupported "a join with an alias")+ rFirst <- tableRefFirst r+ isJoin <- tokIs (rFirst - 1) "join"+ unless isJoin (unsupported "a join pgstyle cannot read")+ let collect i acc = do+ w <- tokL i+ if w `elem` ["inner", "left", "right", "full", "outer", "natural", "cross"]+ then collect (i - 1) (w : acc)+ else pure acc+ ws <- collect (rFirst - 2) []+ let kind+ | "natural" `elem` ws = NaturalJoin+ | "cross" `elem` ws = CrossJoin+ | otherwise = QualJoin+ joinType = filter (`notElem` ["natural", "cross"]) ws+ expected = case j ^. Pg.jointype of+ Pg.JOIN_INNER -> [[], ["inner"]]+ Pg.JOIN_LEFT -> [["left"], ["left", "outer"]]+ Pg.JOIN_RIGHT -> [["right"], ["right", "outer"]]+ Pg.JOIN_FULL -> [["full"], ["full", "outer"]]+ _ -> []+ hasQual = isJust (j ^. Pg.maybe'quals) || not (null (j ^. Pg.usingClause))+ unless (joinType `elem` expected) (unsupported "a join type pgstyle cannot read")+ case kind of+ NaturalJoin -> unless (j ^. Pg.isNatural && not hasQual) (unsupported "a natural join pgstyle cannot read")+ CrossJoin -> unless (not (j ^. Pg.isNatural) && not hasQual && null joinType) (unsupported "a cross join pgstyle cannot read")+ QualJoin -> unless (not (j ^. Pg.isNatural) && hasQual) (unsupported "a join without a condition")+ pure (ws ++ ["join"], kind)+++-- | "PgStyle.Render"'s @renderJoinedTable@.+joinedTable :: Pg.JoinExpr -> Int -> R D+joinedTable j k+ | k > 0 = do+ inner <- joinedTable j (k - 1)+ pure ("(" <> inner <> ")")+ | otherwise = do+ l <- req "a join" (j ^. Pg.maybe'larg)+ r <- req "a join" (j ^. Pg.maybe'rarg)+ ld <- tableRef False l+ (ws, kind) <- joinWords j r+ keyword <- kw (T.unwords ws)+ rd <- tableRefDoc r+ let header = ld <> hardline <> (keyword <+> rd)+ case kind of+ QualJoin -> do+ q <- joinQual MR (T.length (fromMaybe "" (listToMaybe ws))) j r+ pure (header <> hardline <> q)+ _ -> pure header+++joinQual :: Mode -> Int -> Pg.JoinExpr -> Pg.Node -> R D+joinQual mode anchor j r = case j ^. Pg.maybe'quals of+ Just q+ | mode == MR -> condAligned anchor "on" q+ | otherwise -> do+ k <- kw "on"+ d <- top q >>= expr MP+ pure (k <+> d)+ Nothing -> do+ rFirst <- tableRefFirst r+ let find i = do+ w <- tokL i+ t <- tokM i+ case t of+ Nothing -> unsupported "a using pgstyle cannot find"+ _ | w == "using" -> pure i+ _ -> find (i + 1)+ u <- find rFirst+ _ <- expectParen (u + 1)+ k <- kw "using"+ cs <- strsOf (j ^. Pg.usingClause) >>= traverse ident+ pure (k <+> "(" <> commaJoin cs <> ")")+++-- | A join as postgresql-syntax writes it, on one line.+joinP :: Pg.JoinExpr -> Int -> R D+joinP j k+ | k > 0 = do+ inner <- joinP j (k - 1)+ pure ("(" <> inner <> ")")+ | otherwise = do+ l <- req "a join" (j ^. Pg.maybe'larg)+ r <- req "a join" (j ^. Pg.maybe'rarg)+ ld <- tableRefP l+ (ws, kind) <- joinWords j r+ keyword <- kw (T.unwords ws)+ rd <- tableRefP r+ case kind of+ QualJoin -> do+ q <- joinQual MP 0 j r+ pure (ld <+> keyword <+> rd <+> q)+ _ -> pure (ld <+> keyword <+> rd)+++----------------------------------------------------------------------++-- | "PgStyle.Render"'s @renderPreparableStmt@, for a common table+-- expression's body.+preparable :: Pg.Node -> R D+preparable n = case node n of+ Just (Pg.Node'SelectStmt s) -> do+ k <- selectParens 0 s+ selStmt s k+ Just (Pg.Node'InsertStmt s) -> insertStmt s+ Just (Pg.Node'UpdateStmt s) -> updateStmt s+ Just (Pg.Node'DeleteStmt s) -> deleteStmt s+ _ -> unsupported (nodeName n)+++-- | Where a @returning@ clause starts.+returningAt :: Maybe Pg.ReturningClause -> R (Maybe Int)+returningAt = \case+ Just rc | t : _ <- rc ^. Pg.exprs -> do+ q <- targetFirst t+ maybe (pure Nothing) (wordsBefore ["returning"]) q+ _ -> pure Nothing+++-- | A range variable as a node, for its locations.+toNode :: Pg.RangeVar -> Pg.Node+toNode rv = defMessage & Pg.rangeVar .~ rv+++returning :: Maybe Pg.ReturningClause -> R (Maybe D)+returning Nothing = pure Nothing+returning (Just rc) = do+ unless (null (rc ^. Pg.options)) (unsupported "returning with old/new")+ k <- kw "returning"+ ds <- traverse targetEl (rc ^. Pg.exprs)+ pure (Just (k <+> commaJoin ds))+++insertStmt :: Pg.InsertStmt -> R D+insertStmt s = do+ w <- traverse withClause (s ^. Pg.maybe'withClause)+ rv <- req "an insert" (s ^. Pg.maybe'relation)+ name <- relationName rv+ target <- case rv ^. Pg.maybe'alias of+ Nothing -> pure name+ Just a -> do+ asK <- kw "as"+ an <- ident (a ^. Pg.aliasname)+ pure (name <> " " <> asK <> " " <> an)+ ins <- kw "insert into"+ rest <- case s ^. Pg.maybe'selectStmt of+ Nothing -> kw "default values"+ Just q -> do+ cols <-+ if null (s ^. Pg.cols)+ then pure Nothing+ else Just <$> insertColumns (s ^. Pg.cols)+ override <- case s ^. Pg.override of+ Pg.OVERRIDING_USER_VALUE -> overriding "user"+ Pg.OVERRIDING_SYSTEM_VALUE -> overriding "system"+ _ -> pure mempty+ st <- case node q of+ Just (Pg.Node'SelectStmt st) -> pure st+ _ -> unsupported "an insert of something other than a select"+ k <- selectParens 0 st+ selD <- selStmt st k+ selAt <- attempt (subtract k <$> selectFirst st)+ case cols of+ Nothing -> pure (override <> selD)+ Just c -> do+ b <- brkAt mempty selAt+ pure (c <> b <> override <> selD)+ conflict <- traverse onConflict (s ^. Pg.maybe'onConflictClause)+ ret <- returning (s ^. Pg.maybe'returningClause)+ insAt <- clauseAt [["insert", "into"]] (toNode rv)+ restAt <- case s ^. Pg.maybe'selectStmt of+ Nothing -> pure Nothing+ Just q -> case (s ^. Pg.cols, node q) of+ (c : _, _) -> fmap (subtract 1) <$> targetFirst c+ (_, Just (Pg.Node'SelectStmt st)) -> attempt (selectParensPeek st >>= \k -> subtract k <$> selectFirst st)+ _ -> pure Nothing+ conflictAt <- case s ^. Pg.maybe'onConflictClause of+ Just oc | oc ^. Pg.location >= 0 -> Just <$> tokAt (fromIntegral (oc ^. Pg.location))+ _ -> pure Nothing+ retAt <- returningAt (s ^. Pg.maybe'returningClause)+ linesAt mempty (present [(Nothing, w), (insAt, Just (ins <+> target)), (restAt, Just rest), (conflictAt, conflict), (retAt, ret)])+ where+ overriding who = do+ k <- kw ("overriding " <> who <> " value")+ pure (k <> hardline)+++-- | "PgStyle.Render"'s @renderInsertColumnList@.+insertColumns :: [Pg.Node] -> R D+insertColumns cols = do+ ds <- forM cols \n -> case node n of+ Just (Pg.Node'ResTarget rt) -> setTarget rt+ _ -> unsupported "an insert column pgstyle cannot read"+ first <- case cols of+ n : _ | Just (Pg.Node'ResTarget rt) <- node n -> tokAt (fromIntegral (rt ^. Pg.location))+ _ -> unsupported "an insert column list"+ _ <- expectParen (first - 1)+ close <- matchOf (first - 1) >>= req "an insert column list"+ commented <- commentsBetween (first - 1) close+ if commented+ then do+ firsts <- listFirsts (first - 1) close (length ds)+ indent indentSize <$> bracketListAt ((,close) <$> firsts) ds+ else+ pure+ if length ds <= insertInlineColumns+ then indent indentSize ("(" <> commaJoin ds <> ")")+ else indent indentSize (bracketList ds)+++-- | A column being set: its name and indirection.+setTarget :: Pg.ResTarget -> R D+setTarget rt = do+ name <- ident (rt ^. Pg.name)+ i <- indirection MP defMessage (rt ^. Pg.indirection)+ pure (name <> i)+++-- | An UPDATE or ON CONFLICT's assignments, a multi-column assignment+-- (@(a, b) = (1, 2)@) as one.+data SetItem+ = SetOne Pg.ResTarget Pg.Node+ | SetMany [Pg.ResTarget] Pg.Node+++setItems :: [Pg.Node] -> R [SetItem]+setItems [] = pure []+setItems (n : rest) = case node n of+ Just (Pg.Node'ResTarget rt) -> case rt ^. Pg.maybe'val >>= node of+ Just (Pg.Node'MultiAssignRef m) -> do+ let count = fromIntegral (m ^. Pg.ncolumns) - 1+ (more, rest') = splitAt count rest+ others <- forM more \x -> case node x of+ Just (Pg.Node'ResTarget r) -> pure r+ _ -> unsupported "a multi-column assignment pgstyle cannot read"+ source <- req "a multi-column assignment" (m ^. Pg.maybe'source)+ (SetMany (rt : others) source :) <$> setItems rest'+ Just _ -> do+ v <- req "an assignment" (rt ^. Pg.maybe'val)+ (SetOne rt v :) <$> setItems rest+ Nothing -> unsupported "an assignment without a value"+ _ -> unsupported "an assignment pgstyle cannot read"+++-- | An assignment's first token.+setFirst :: SetItem -> R (Maybe Int)+setFirst = \case+ SetOne rt _ -> at rt 0+ SetMany (rt : _) _ -> at rt 1+ SetMany [] _ -> pure Nothing+ where+ at rt back+ | rt ^. Pg.location >= 0 = Just . subtract back <$> tokAt (fromIntegral (rt ^. Pg.location))+ | otherwise = pure Nothing+++-- | "PgStyle.Render"'s @renderSetClause@.+setClause :: SetItem -> R D+setClause = \case+ SetOne rt v -> do+ t <- setTarget rt+ d <- top v >>= exprMaybeWrap+ pure (t <+> "=" <+> nest indentSize d)+ SetMany rts source -> do+ first <- case rts of+ rt : _ -> tokAt (fromIntegral (rt ^. Pg.location))+ [] -> unsupported "an empty assignment"+ _ <- expectParen (first - 1)+ ts <- traverse setTarget rts+ d <- top source >>= exprMaybeWrap+ pure ("(" <> commaJoin ts <> ") =" <+> nest indentSize d)+++onConflict :: Pg.OnConflictClause -> R D+onConflict oc = do+ header <- kw "on conflict"+ target <- case oc ^. Pg.maybe'infer of+ Nothing -> pure mempty+ Just inf+ | not (T.null (inf ^. Pg.conname)) -> do+ k <- kw "on constraint"+ n <- ident (inf ^. Pg.conname)+ pure (" " <> k <+> n)+ | otherwise -> do+ at <- tokAt (fromIntegral (oc ^. Pg.location))+ open <- nextParen at+ _ <- expectParen open+ elems <- forM (inf ^. Pg.indexElems) \n -> case node n of+ Just (Pg.Node'IndexElem ie) -> do+ unless (null (ie ^. Pg.collation) && null (ie ^. Pg.opclass) && ie ^. Pg.ordering == Pg.SORTBY_DEFAULT && ie ^. Pg.nullsOrdering == Pg.SORTBY_NULLS_DEFAULT) (unsupported "an index element with options")+ case ie ^. Pg.maybe'expr of+ Just x -> top x >>= expr MP+ Nothing -> ident (ie ^. Pg.name)+ _ -> unsupported "an index element pgstyle cannot read"+ w <- forM (inf ^. Pg.maybe'whereClause) \x -> do+ k <- kw "where"+ d <- top x >>= expr MP+ pure (" " <> k <+> d)+ pure (" (" <> commaJoin elems <> ")" <> fromMaybe mempty w)+ action <- case oc ^. Pg.action of+ Pg.ONCONFLICT_NOTHING -> kw "do nothing"+ Pg.ONCONFLICT_UPDATE -> do+ items <- setItems (oc ^. Pg.targetList)+ k <- kw "do update set"+ docs <- traverse setClause items+ let lastIdx = length docs - 1+ body = case docs of+ [single] -> k <> hardline <> indent indentSize single+ _ -> k <> hardline <> indent indentSize (vsep [if i < lastIdx then d <> "," else d | (i, d) <- zip [0 ..] docs])+ w <- traverse (condAligned 5 "where") (oc ^. Pg.maybe'whereClause)+ pure (maybe body (\wd -> body <> hardline <> wd) w)+ _ -> unsupported "an on conflict pgstyle cannot read"+ pure (header <> target <> hardline <> action)+++updateStmt :: Pg.UpdateStmt -> R D+updateStmt s = do+ w <- traverse withClause (s ^. Pg.maybe'withClause)+ rv <- req "an update" (s ^. Pg.maybe'relation)+ rel <- relation rv+ up <- kw "update"+ items <- setItems (s ^. Pg.targetList)+ setK <- kw "set"+ commented <- case items of+ [single] -> setFirst single >>= maybe (pure False) (fmap (not . null) . gapBefore)+ _ -> pure False+ sets <- case items of+ [single] | not commented -> (setK <+>) <$> setClause single+ _ -> blockList setK setClause setFirst items+ from <- if null (s ^. Pg.fromClause) then pure Nothing else Just <$> fromClause (s ^. Pg.fromClause)+ wh <- traverse whereOrCurrent (s ^. Pg.maybe'whereClause)+ ret <- returning (s ^. Pg.maybe'returningClause)+ upAt <- clauseAt [["update"]] (toNode rv)+ setAt <- case items of+ i : _ -> setFirst i >>= maybe (pure Nothing) (wordsBefore ["set"])+ [] -> pure Nothing+ fromAt <- maybe (pure Nothing) (clauseAt [["from"], ["from", "lateral"]]) (listToMaybe (s ^. Pg.fromClause))+ whAt <- maybe (pure Nothing) (clauseAt [["where"], ["where", "current", "of"]]) (s ^. Pg.maybe'whereClause)+ retAt <- returningAt (s ^. Pg.maybe'returningClause)+ linesAt mempty (present [(Nothing, w), (upAt, Just (up <+> rel)), (setAt, Just sets), (fromAt, from), (whAt, wh), (retAt, ret)])+++deleteStmt :: Pg.DeleteStmt -> R D+deleteStmt s = do+ w <- traverse withClause (s ^. Pg.maybe'withClause)+ rv <- req "a delete" (s ^. Pg.maybe'relation)+ rel <- relation rv+ del <- kw "delete from"+ using <-+ if null (s ^. Pg.usingClause)+ then pure Nothing+ else do+ k <- kw "using"+ ds <- traverse tableRefP (s ^. Pg.usingClause)+ pure (Just (k <+> commaJoin ds))+ wh <- traverse whereOrCurrent (s ^. Pg.maybe'whereClause)+ ret <- returning (s ^. Pg.maybe'returningClause)+ delAt <- clauseAt [["delete", "from"]] (toNode rv)+ usingAt <- maybe (pure Nothing) (clauseAt [["using"]]) (listToMaybe (s ^. Pg.usingClause))+ whAt <- maybe (pure Nothing) (clauseAt [["where"], ["where", "current", "of"]]) (s ^. Pg.maybe'whereClause)+ retAt <- returningAt (s ^. Pg.maybe'returningClause)+ linesAt mempty (present [(Nothing, w), (delAt, Just (del <+> rel)), (usingAt, using), (whAt, wh), (retAt, ret)])+++whereOrCurrent :: Pg.Node -> R D+whereOrCurrent n = case node n of+ Just (Pg.Node'CurrentOfExpr c) -> do+ k <- kw "where current of"+ name <- ident (c ^. Pg.cursorName)+ pure (k <+> name)+ _ -> condAligned 5 "where" n
+ src/PgStyle/Layout/Dml.hs-boot view
@@ -0,0 +1,12 @@+module PgStyle.Layout.Dml where++import PgQuery qualified as Pg+import PgStyle.Layout.Monad (D, R)+import PgStyle.Layout.Parens (Sel)+++selMaybeWrap :: Sel -> R D+selP :: Sel -> R D+selWrapped :: Sel -> R D+selectParens :: Int -> Pg.SelectStmt -> R Int+sortClause :: [Pg.Node] -> R D
+ src/PgStyle/Layout/Expr.hs view
@@ -0,0 +1,1639 @@+-- | Expressions, inline and wrapped, function calls, subqueries and+-- conditions.+module PgStyle.Layout.Expr where++import Control.Monad (forM, unless, when)+import Control.Monad.Reader (local)+import Control.Monad.State.Strict (gets, modify')+import Data.Bits ((.&.))+import Data.Int (Int32)+import Data.IntSet qualified as IS+import Data.Maybe (catMaybes, fromMaybe, isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Comments+import {-# SOURCE #-} PgStyle.Layout.Dml (selMaybeWrap, selP, selWrapped, selectParens, sortClause)+import PgStyle.Layout.Locations+import PgStyle.Layout.Monad+import PgStyle.Layout.Names+import PgStyle.Layout.Parens+import Prettyprinter (align, hardline, hcat, nest, pretty, punctuate, vsep, (<+>))+++-- | An expression on one line: "PgStyle.Render"'s @renderExpr@ ('MR'), its+-- @renderBExpr@ ('MB'), or postgresql-syntax's renderer ('MP').+expr :: Mode -> E -> R D+expr mode e+ | e.lv > 0 = do+ -- In parentheses, an expression is a full one again.+ inner <- expr (if mode == MP then MP else MR) e{lv = e.lv - 1}+ pure ("(" <> inner <> ")")+ | otherwise = core mode e+++-- | 'MB' renders its own operators and goes back to 'MR' below them, as+-- @renderBExpr@ does for anything that is a @c_expr@.+core :: Mode -> E -> R D+core mode e = case node e.en of+ Just (Pg.Node'ColumnRef c) -> columnRef c+ Just (Pg.Node'ParamRef p) -> txt ("$" <> T.pack (show (p ^. Pg.number)))+ Just (Pg.Node'AConst c) -> aConst mode c+ Just (Pg.Node'TypeCast tc) -> typeCast mode e tc+ Just (Pg.Node'AExpr a) -> aExpr mode e a+ Just (Pg.Node'BoolExpr b) -> boolExpr (sub mode) e b+ Just (Pg.Node'NullTest t) -> do+ arg <- req "a null test" (t ^. Pg.maybe'arg) >>= child e.en+ i <- tokAt (fromIntegral (t ^. Pg.location))+ w <- tokL i+ a <- expr (sub mode) arg+ test <- case (t ^. Pg.nulltesttype, w) of+ (_, "isnull") -> kw "isnull"+ (_, "notnull") -> kw "notnull"+ (Pg.IS_NULL, _) -> kw "is null"+ _ -> kw "is not null"+ pure (a <+> test)+ Just (Pg.Node'BooleanTest t) -> do+ arg <- req "a boolean test" (t ^. Pg.maybe'arg) >>= child e.en+ a <- expr (sub mode) arg+ test <- kw case t ^. Pg.booltesttype of+ Pg.IS_TRUE -> "is true"+ Pg.IS_NOT_TRUE -> "is not true"+ Pg.IS_FALSE -> "is false"+ Pg.IS_NOT_FALSE -> "is not false"+ Pg.IS_UNKNOWN -> "is unknown"+ _ -> "is not unknown"+ pure (a <+> test)+ Just (Pg.Node'FuncCall f) -> funcCall (sub mode) e f+ Just (Pg.Node'SubLink s) -> subLink (sub mode) e s+ Just (Pg.Node'CaseExpr c) -> caseInline (sub mode) e c+ Just (Pg.Node'CoalesceExpr c) -> keywordCall (sub mode) "coalesce" (c ^. Pg.location) (c ^. Pg.args) e+ Just (Pg.Node'MinMaxExpr c) ->+ keywordCall (sub mode) (if c ^. Pg.op == Pg.IS_GREATEST then "greatest" else "least") (c ^. Pg.location) (c ^. Pg.args) e+ Just (Pg.Node'RowExpr r) -> rowExpr (sub mode) e r+ Just (Pg.Node'AArrayExpr a) -> arrayExpr (sub mode) e a+ Just (Pg.Node'AIndirection ind) -> indirectionExpr (sub mode) e ind+ Just (Pg.Node'CollateClause c) -> do+ arg <- req "a collation" (c ^. Pg.maybe'arg) >>= child e.en+ let m = if mode == MB then MP else mode+ a <- expr m arg+ name <- strsOf (c ^. Pg.collname) >>= qualName+ k <- kw "collate"+ pure (a <+> k <+> name)+ Just (Pg.Node'SqlvalueFunction f) -> sqlValueFunction f+ Just (Pg.Node'SetToDefault _) -> kw "default"+ Just (Pg.Node'GroupingFunc g) -> do+ open <- tokAt (fromIntegral (g ^. Pg.location)) >>= nextParen+ _ <- expectParen open+ args <- traverse (child e.en >=> expr MP) (g ^. Pg.args)+ k <- kw "grouping"+ pure (k <> " (" <> commaJoin args <> ")")+ _ -> unsupported (nodeName e.en)+ where+ sub MB = MR+ sub m = m+++(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c+f >=> g = \x -> f x >>= g+++columnRef :: Pg.ColumnRef -> R D+columnRef c = do+ at <- tokAt (fromIntegral (c ^. Pg.location))+ parts <- forM (zip [0 ..] (c ^. Pg.fields)) \(k, f) -> case node f of+ Just (Pg.Node'String s) -> identAt (at + 2 * k) (s ^. Pg.sval)+ Just (Pg.Node'AStar _) -> txt "*"+ _ -> unsupported "a column reference pgstyle cannot read"+ pure (hcat (punctuate "." parts))+++typeCast :: Mode -> E -> Pg.TypeCast -> R D+typeCast mode e tc = do+ tn <- req "a cast" (tc ^. Pg.maybe'typeName)+ arg <- req "a cast" (tc ^. Pg.maybe'arg)+ form <- castForm tc+ case form of+ TypedLiteral -> typedLiteral tc+ CastCall -> do+ argE <- child e.en arg+ open <- tokAt (fromIntegral (tc ^. Pg.location)) >>= nextParen+ _ <- expectParen open+ a <- expr (if mode == MP then MP else MR) argE+ t <- typeName tn+ k <- kw "cast"+ as <- kw "as"+ pure (k <> (if mode == MP then " (" else "(") <> a <+> as <+> t <> ")")+ ColonCast -> do+ argE <- child e.en arg+ a <- expr mode argE+ t <- typeName tn+ pure (a <> "::" <> t)+++data CastForm = ColonCast | CastCall | TypedLiteral+++castForm :: Pg.TypeCast -> R CastForm+castForm tc+ | tc ^. Pg.location < 0 = pure TypedLiteral+ | otherwise = do+ w <- tokAt (fromIntegral (tc ^. Pg.location)) >>= tokL+ pure if w == "cast" then CastCall else ColonCast+++-- | @date '2020-01-01'@, @interval '1' day@.+typedLiteral :: Pg.TypeCast -> R D+typedLiteral tc = do+ tn <- req "a typed literal" (tc ^. Pg.maybe'typeName)+ arg <- req "a typed literal" (tc ^. Pg.maybe'arg)+ value <- case node arg of+ Just (Pg.Node'AConst c) | Just (Pg.A_Const'Sval s) <- c ^. Pg.maybe'val -> do+ i <- tokAt (fromIntegral (c ^. Pg.location))+ source <- maybe "" (.text) <$> tokM i+ (,) i <$> stringConst (s ^. Pg.sval) source+ _ -> unsupported "a typed literal that is not a string"+ unless (null (tn ^. Pg.arrayBounds)) (unsupported "a typed literal of an array type")+ i <- tokAt (fromIntegral (tn ^. Pg.location))+ w <- tokL i+ (ty, next) <- typeWords True i+ unless (next == fst value) (unsupported "a typed literal pgstyle cannot read")+ if w == "interval"+ then do+ (fields, _) <- intervalFields (fst value + 1)+ pure (ty <> " " <> snd value <> maybe mempty (" " <>) fields)+ else pure (ty <> " " <> snd value)+++-- | The operator token of an operator expression, as written.+operatorText :: Pg.A_Expr -> R Text+operatorText a = do+ names <- strsOf (a ^. Pg.name)+ op <- case names of+ [op] -> pure op+ _ -> unsupported "a schema-qualified operator"+ source <- tokAt (fromIntegral (a ^. Pg.location)) >>= tokL+ if source == op || (op == "<>" && source == "!=")+ then pure source+ else unsupported "an operator pgstyle cannot find in the source"+++jsonOps :: [Text]+jsonOps = ["->", "->>", "#>", "#>>"]+++aExpr :: Mode -> E -> Pg.A_Expr -> R D+aExpr mode e a = case a ^. Pg.kind of+ Pg.AEXPR_OP -> do+ op <- operatorText a+ r <- req "an operator" (a ^. Pg.maybe'rexpr) >>= child e.en+ case a ^. Pg.maybe'lexpr of+ Nothing+ | op `elem` ["-", "+"] -> do+ rd <- expr mode r+ pure (pretty op <> (if mode == MP then " " else mempty) <> rd)+ | otherwise -> do+ -- Any other prefix operator: @~ x@.+ rd <- expr (if mode == MB then MP else mode) r+ pure (pretty op <+> rd)+ Just lexpr -> do+ l <- child e.en lexpr+ ld <- expr mode l+ rd <- expr mode r+ pure+ if mode == MR && op `elem` jsonOps+ then ld <> pretty op <> rd+ else ld <+> pretty op <+> rd+ _ | mode == MB -> aExpr MP e a+ k | k `elem` [Pg.AEXPR_OP_ANY, Pg.AEXPR_OP_ALL] -> do+ op <- operatorText a+ opTok <- tokAt (fromIntegral (a ^. Pg.location))+ subType <- tokL (opTok + 1)+ unless (subType `elem` ["any", "some", "all"]) (unsupported "an any/all pgstyle cannot read")+ _ <- expectParen (opTok + 2)+ l <- req "an any/all" (a ^. Pg.maybe'lexpr) >>= child e.en+ r <- req "an any/all" (a ^. Pg.maybe'rexpr) >>= child e.en+ ld <- expr mode l+ st <- kw subType+ rd <- if mode == MP then expr MP r else exprMaybeWrap r+ pure (ld <+> pretty op <+> st <> (if mode == MP then " (" else "(") <> rd <> ")")+ k | k `elem` [Pg.AEXPR_DISTINCT, Pg.AEXPR_NOT_DISTINCT] -> do+ l <- req "a distinct" (a ^. Pg.maybe'lexpr) >>= child e.en+ r <- req "a distinct" (a ^. Pg.maybe'rexpr) >>= child e.en+ ld <- expr mode l+ rd <- expr mode r+ k' <- kw (if k == Pg.AEXPR_DISTINCT then "is distinct from" else "is not distinct from")+ pure (ld <+> k' <+> rd)+ Pg.AEXPR_NULLIF -> do+ open <- tokAt (fromIntegral (a ^. Pg.location)) >>= nextParen+ _ <- expectParen open+ l <- req "a nullif" (a ^. Pg.maybe'lexpr) >>= child e.en+ r <- req "a nullif" (a ^. Pg.maybe'rexpr) >>= child e.en+ ld <- expr mode l+ rd <- expr mode r+ k <- kw "nullif"+ pure (k <> (if mode == MP then " (" else "(") <> ld <> ", " <> rd <> ")")+ Pg.AEXPR_IN -> do+ names <- strsOf (a ^. Pg.name)+ open <- tokAt (fromIntegral (a ^. Pg.rexprListStart))+ _ <- expectParen open+ l <- req "an in" (a ^. Pg.maybe'lexpr) >>= child e.en+ items <- case a ^. Pg.maybe'rexpr >>= node of+ Just (Pg.Node'List xs) -> pure (xs ^. Pg.items)+ _ -> unsupported "an in without a list"+ ld <- expr mode l+ k <- kw (if names == ["<>"] then "not in" else "in")+ positions <- commentedList open (length items)+ case positions of+ Nothing -> do+ ds <- traverse (child e.en >=> expr MP) items+ pure (ld <+> k <+> "(" <> commaJoin ds <> ")")+ Just _ -> do+ ds <- traverse (child e.en >=> exprMaybeWrap) items+ (rows, end) <- argRowsAt positions ds+ pure (ld <+> k <+> "(" <> nest indentSize rows <> end <> ")")+ k | k `elem` [Pg.AEXPR_LIKE, Pg.AEXPR_ILIKE] -> do+ names <- strsOf (a ^. Pg.name)+ word <- case names of+ ["~~"] -> pure "like"+ ["!~~"] -> pure "not like"+ ["~~*"] -> pure "ilike"+ ["!~~*"] -> pure "not ilike"+ _ -> unsupported "a like pgstyle cannot read"+ l <- req "a like" (a ^. Pg.maybe'lexpr) >>= child e.en+ rn <- req "a like" (a ^. Pg.maybe'rexpr)+ case node rn of+ Just (Pg.Node'FuncCall _) -> unsupported "like ... escape"+ _ -> pure ()+ r <- child e.en rn+ ld <- expr mode l+ rd <- expr mode r+ k' <- kw word+ pure (ld <+> k' <+> rd)+ k | k `elem` [Pg.AEXPR_BETWEEN, Pg.AEXPR_NOT_BETWEEN, Pg.AEXPR_BETWEEN_SYM, Pg.AEXPR_NOT_BETWEEN_SYM] -> do+ i <- tokAt (fromIntegral (a ^. Pg.location))+ w <- tokL i+ w1 <- tokL (i + 1)+ let negated = k `elem` [Pg.AEXPR_NOT_BETWEEN, Pg.AEXPR_NOT_BETWEEN_SYM]+ symmetric = k `elem` [Pg.AEXPR_BETWEEN_SYM, Pg.AEXPR_NOT_BETWEEN_SYM]+ afterBetween = if w == "not" then i + 2 else i + 1+ asym <- tokIs afterBetween "asymmetric"+ when (asym || (w /= "between" && not (w == "not" && w1 == "between"))) (unsupported "a between pgstyle cannot read")+ l <- req "a between" (a ^. Pg.maybe'lexpr) >>= child e.en+ (lo, hi) <- case a ^. Pg.maybe'rexpr >>= node of+ Just (Pg.Node'List xs) | [x, y] <- xs ^. Pg.items -> (,) <$> child e.en x <*> child e.en y+ _ -> unsupported "a between without two bounds"+ ld <- expr mode l+ bk <- kw ((if negated then "not " else "") <> (if symmetric then "between symmetric" else "between"))+ andK <- kw "and"+ (lod, hid) <-+ if mode == MP || symmetric+ then (,) <$> expr MP lo <*> expr MP hi+ else (,) <$> expr MB lo <*> expr MR hi+ pure (ld <+> bk <+> lod <+> andK <+> hid)+ _ -> unsupported "an operator expression pgstyle does not lay out"+++boolExpr :: Mode -> E -> Pg.BoolExpr -> R D+boolExpr mode e b = case b ^. Pg.boolop of+ Pg.NOT_EXPR -> do+ argN <- case b ^. Pg.args of+ [x] -> pure x+ _ -> unsupported "a not with several arguments"+ arg <- child e.en argN+ notAt <- tokAt (fromIntegral (b ^. Pg.location))+ argStart <- tokAt (minimum (fromIntegral (b ^. Pg.location) : locsNode argN))+ if argStart < notAt+ then -- @x not in (select ...)@+ case node argN of+ Just (Pg.Node'SubLink s)+ | s ^. Pg.subLinkType == Pg.ANY_SUBLINK+ , null (s ^. Pg.operName) -> do+ test <- req "a not in" (s ^. Pg.maybe'testexpr) >>= child arg.en+ inSubLink mode test s True+ _ -> unsupported "a not pgstyle cannot read"+ else do+ k <- kw "not"+ d <- expr mode arg+ pure (k <+> d)+ op -> do+ args <- traverse (child e.en) (b ^. Pg.args)+ k <- kw (if op == Pg.AND_EXPR then "and" else "or")+ boolArgs mode (fromIntegral (b ^. Pg.location)) (" " <> k <> " ") args+++-- | The arguments of an @and@ or @or@. PostgreSQL flattens @(a and b) and c@+-- into one list of three (at the location of the first @and@), so+-- parentheses the source has around a run of them are placed here.+boolArgs :: Mode -> Int -> D -> [E] -> R D+boolArgs mode loc sep = boolRun mode loc sep IS.empty+++-- | 'boolArgs' inside the parentheses already placed around a run.+boolRun :: Mode -> Int -> D -> IS.IntSet -> [E] -> R D+boolRun mode loc sep outer args = hcat . punctuate sep <$> go args+ where+ go [] = pure []+ go (x : rest) = do+ grouped <- group x rest+ case grouped of+ Just (p, inside, after) -> do+ d <- boolRun (if mode == MP then MP else MR) loc sep (IS.insert p outer) inside+ (("(" <> d <> ")") :) <$> go after+ Nothing -> (:) <$> expr mode x <*> go rest+ -- The longest run from this argument that a parenthesis pair encloses+ -- exactly, trying the outermost of the parentheses before it first.+ group x rest = do+ s <- argStart x+ ps <- parensBefore (s - 1)+ firstJustM (tryParen x rest) (reverse (filter (`IS.notMember` outer) ps))+ parensBefore p = do+ isParen <- tokIs p "("+ if isParen then (p :) <$> parensBefore (p - 1) else pure []+ tryParen x rest p = do+ placed <- isConsumed p+ -- Rendering again finds the same run: the pair is placed by now.+ mine <- gets (IS.member p . (.boolGroups))+ mm <- matchOf p+ case mm of+ Just m | not placed || mine -> do+ let candidates = [(take k (x : rest), drop k (x : rest)) | k <- [length rest + 1, length rest .. 2]]+ found <- firstM (encloses p m . fst) candidates+ case found of+ Just (inside, after) -> do+ consume p+ modify' \st -> st{boolGroups = IS.insert p st.boolGroups}+ pure (Just (p, inside, after))+ Nothing -> pure Nothing+ _ -> pure Nothing+ encloses p m run = do+ let ls = concatMap (locsNode . (.en)) run+ inside <- allInside p m ls+ cov <- covers p m (IS.fromList (loc : ls))+ pure (inside && cov)+ argStart x = do+ ls <- nonEmptyLocs (locsNode x.en)+ i <- tokAt (minimum ls)+ e0 <- tokAt (maximum ls)+ let back j = do+ isParen <- tokIs (j - 1) "("+ m <- matchOf (j - 1)+ case m of+ Just close | isParen, close <= e0 -> back (j - 1)+ _ -> pure j+ j <- back i+ pure (j - x.lv)+++firstM :: (a -> R Bool) -> [a] -> R (Maybe a)+firstM _ [] = pure Nothing+firstM f (x : xs) = f x >>= \b -> if b then pure (Just x) else firstM f xs+++sqlValueFunction :: Pg.SQLValueFunction -> R D+sqlValueFunction f = do+ let precision = " (" <> pretty (f ^. Pg.typmod) <> ")"+ case f ^. Pg.op of+ Pg.SVFOP_CURRENT_DATE -> kw "current_date"+ Pg.SVFOP_CURRENT_TIME -> kw "current_time"+ Pg.SVFOP_CURRENT_TIME_N -> (<> precision) <$> kw "current_time"+ Pg.SVFOP_CURRENT_TIMESTAMP -> kw "current_timestamp"+ Pg.SVFOP_CURRENT_TIMESTAMP_N -> (<> precision) <$> kw "current_timestamp"+ Pg.SVFOP_LOCALTIME -> kw "localtime"+ Pg.SVFOP_LOCALTIME_N -> (<> precision) <$> kw "localtime"+ Pg.SVFOP_LOCALTIMESTAMP -> kw "localtimestamp"+ Pg.SVFOP_LOCALTIMESTAMP_N -> (<> precision) <$> kw "localtimestamp"+ Pg.SVFOP_CURRENT_ROLE -> kw "current_role"+ Pg.SVFOP_CURRENT_USER -> kw "current_user"+ Pg.SVFOP_USER -> kw "user"+ Pg.SVFOP_SESSION_USER -> kw "session_user"+ Pg.SVFOP_CURRENT_CATALOG -> kw "current_catalog"+ Pg.SVFOP_CURRENT_SCHEMA -> kw "current_schema"+ _ -> unsupported "an SQL value function pgstyle does not know"+++-- | @coalesce(a, b)@, @greatest(a, b)@: in 'MP', postgresql-syntax puts a+-- space before the parenthesis.+keywordCall :: Mode -> Text -> Int32 -> [Pg.Node] -> E -> R D+keywordCall mode name loc args e = do+ open <- tokAt (fromIntegral loc) >>= nextParen+ _ <- expectParen open+ ds <- traverse (child e.en >=> expr mode) args+ k <- kw name+ pure (k <> (if mode == MP then " (" else "(") <> commaJoin ds <> ")")+++rowExpr :: Mode -> E -> Pg.RowExpr -> R D+rowExpr mode e r = do+ at <- tokAt (fromIntegral (r ^. Pg.location))+ explicit <- tokIs at "row"+ open <- if explicit then nextParen at else pure at+ _ <- expectParen open+ ds <- traverse (child e.en >=> expr mode) (r ^. Pg.args)+ if explicit+ then do+ k <- kw "row"+ pure (k <> (if mode == MP then " (" else "(") <> commaJoin ds <> ")")+ else pure ("(" <> commaJoin ds <> ")")+++-- | Whether an array expression has the @array@ keyword (nested ones do not).+arrayKeyword :: Pg.A_ArrayExpr -> R Bool+arrayKeyword a = tokAt (fromIntegral (a ^. Pg.location)) >>= (`tokIs` "array")+++arrayExpr :: Mode -> E -> Pg.A_ArrayExpr -> R D+arrayExpr mode e a = do+ keyword <- arrayKeyword a+ commented <- hasCmts e.en+ inner <- if commented then arrayWrapped e a else arrayBody mode e a+ k <- kw "array"+ pure if keyword then k <> (if mode == MP && not commented then " " else mempty) <> inner else inner+++arrayBody :: Mode -> E -> Pg.A_ArrayExpr -> R D+arrayBody mode e a = do+ ds <- traverse (child e.en >=> expr mode) (a ^. Pg.elements)+ pure ("[" <> commaJoin ds <> "]")+++indirectionExpr :: Mode -> E -> Pg.A_Indirection -> R D+indirectionExpr mode e ind = do+ argN <- req "an indirection" (ind ^. Pg.maybe'arg)+ arg <- child e.en argN+ (a, m) <- case node argN of+ -- postgresql-syntax reads a subscripted column as one column+ -- reference.+ Just (Pg.Node'ColumnRef c) | arg.lv == 0 -> (,MP) <$> columnRef c+ _ -> (,mode) <$> expr mode arg+ i <- indirection m e.en (ind ^. Pg.indirection)+ pure (a <> i)+++indirection :: Mode -> Pg.Node -> [Pg.Node] -> R D+indirection mode p els = mconcat <$> traverse el els+ where+ el n = case node n of+ Just (Pg.Node'String s) -> ("." <>) <$> ident (s ^. Pg.sval)+ Just (Pg.Node'AStar _) -> txt ".*"+ Just (Pg.Node'AIndices ix)+ | ix ^. Pg.isSlice -> do+ lo <- maybe (pure mempty) (child p >=> expr mode) (ix ^. Pg.maybe'lidx)+ hi <- maybe (pure mempty) (child p >=> expr mode) (ix ^. Pg.maybe'uidx)+ pure ("[" <> lo <> ":" <> hi <> "]")+ | otherwise -> do+ i <- maybe (unsupported "a subscript") (child p >=> expr mode) (ix ^. Pg.maybe'uidx)+ pure ("[" <> i <> "]")+ _ -> unsupported "an indirection pgstyle cannot read"+++caseInline :: Mode -> E -> Pg.CaseExpr -> R D+caseInline mode e c = do+ k <- kw "case"+ arg <- maybe (pure mempty) (\a -> (" " <>) <$> (child e.en a >>= expr mode)) (c ^. Pg.maybe'arg)+ whens <- forM (c ^. Pg.args) \w -> case node w of+ Just (Pg.Node'CaseWhen cw) -> do+ cond <- req "a when" (cw ^. Pg.maybe'expr) >>= child e.en >>= expr mode+ result <- req "a when" (cw ^. Pg.maybe'result) >>= child e.en >>= expr mode+ whenK <- kw "when"+ thenK <- kw "then"+ pure (" " <> whenK <+> cond <+> thenK <+> result)+ _ -> unsupported "a case branch pgstyle cannot read"+ def <- case c ^. Pg.maybe'defresult of+ Nothing -> pure mempty+ Just d -> do+ elseK <- kw "else"+ dd <- child e.en d >>= expr mode+ pure (" " <> elseK <+> dd)+ endK <- kw "end"+ pure (k <> arg <> mconcat whens <> def <+> endK)+++----------------------------------------------------------------------+-- Function calls.+----------------------------------------------------------------------++-- | A function call as written: an ordinary call, or one with SQL's own+-- syntax (@extract(year from x)@, @x at time zone 'utc'@).+data Call+ = Plain Pg.FuncCall+ | Extract Pg.Node Pg.Node+ | Position Pg.Node Pg.Node+ | -- | @substring(x from a for b)@: the string and each keyword with its+ -- argument, in source order; or the comma form.+ Substring Pg.Node [(Text, Pg.Node)]+ | SubstringCommas [Pg.Node]+ | -- | @trim(both 'x' from y)@.+ Trim+ { modifier :: Maybe Text+ -- ^ @both@, @leading@ or @trailing@.+ , chars :: Maybe Pg.Node+ -- ^ The characters to trim, before @from@.+ , hasFrom :: Bool+ , strings :: [Pg.Node]+ }+ | -- | @overlay(x placing y from a for b)@.+ Overlay {string :: Pg.Node, placing :: Pg.Node, from :: Pg.Node, for :: Maybe Pg.Node}+ | AtTimeZone Pg.Node Pg.Node+++classifyCall :: Pg.FuncCall -> R Call+classifyCall f = do+ names <- strsOf (f ^. Pg.funcname)+ at <- tokAt (fromIntegral (f ^. Pg.location))+ first <- tokL at+ let args = f ^. Pg.args+ sqlSyntax = f ^. Pg.funcformat == Pg.COERCE_SQL_SYNTAX+ keywordForm = case names of+ ["pg_catalog", _] -> first /= "pg_catalog" && first /= "\"pg_catalog\""+ -- postgresql-syntax reads @substring(a, b, c)@ as its own form.+ ["substring"] -> first == "substring"+ _ -> False+ if not (sqlSyntax || keywordForm)+ then pure (Plain f)+ else do+ when (hasExtras f) (unsupported "an SQL-syntax function with extras")+ open <- if names == ["pg_catalog", "timezone"] then pure (-1) else nextParen at+ close <- if open < 0 then pure (-1) else expectParen open+ pieces <- if open < 0 then pure [] else depthOneWords (open + 1) close+ case (names, args) of+ (["pg_catalog", "extract"], [field, x]) | sqlSyntax -> pure (Extract field x)+ (["pg_catalog", "position"], [haystack, needle]) | sqlSyntax -> pure (Position needle haystack)+ (["substring"], _) -> pure (SubstringCommas args)+ (["pg_catalog", "substring"], x : rest)+ | not sqlSyntax -> pure (SubstringCommas args)+ | otherwise -> do+ -- Each argument after the string comes after a+ -- @from@ or @for@; PostgreSQL adds a @from 1@ for a+ -- lone @for@, which has no location.+ let located = [r | r <- rest, not (null (locsNode r))]+ keyed <- forM located \r -> do+ s <- tokAt (minimum (locsNode r))+ pure (lastBefore s pieces, r)+ sorted <- sortByStart keyed+ if all (\(k, _) -> k `elem` ["from", "for"]) sorted+ then pure (Substring x sorted)+ else unsupported "a substring pgstyle cannot read"+ ([_, fn], _)+ | fn `elem` ["btrim", "ltrim", "rtrim"]+ , sqlSyntax -> do+ let modifier = case [w | (_, w) <- pieces, w `elem` ["both", "leading", "trailing"]] of+ w : _ -> Just w+ [] -> Nothing+ hasFrom = "from" `elem` map snd pieces+ case args of+ [s] -> pure Trim{modifier, chars = Nothing, hasFrom, strings = [s]}+ [s, chars]+ | hasFrom -> pure Trim{modifier, chars = Just chars, hasFrom = True, strings = [s]}+ | otherwise -> pure Trim{modifier, chars = Nothing, hasFrom = False, strings = [s, chars]}+ _ -> unsupported "a trim pgstyle cannot read"+ (["pg_catalog", "overlay"], [x, placing, from]) | sqlSyntax -> pure Overlay{string = x, placing, from, for = Nothing}+ (["pg_catalog", "overlay"], [x, placing, from, for]) | sqlSyntax -> pure Overlay{string = x, placing, from, for = Just for}+ (["pg_catalog", "timezone"], [zone, x]) | sqlSyntax -> pure (AtTimeZone x zone)+ _ -> unsupported ("function " <> T.intercalate "." names <> " in SQL syntax")+ where+ lastBefore s pieces = case [w | (i, w) <- pieces, i < s] of+ [] -> ""+ ws -> last ws+ sortByStart xs = do+ keyed <- forM xs \(k, r) -> do+ s <- tokAt (minimum (locsNode r))+ pure (s, (k, r))+ pure (map snd (sortOnFst keyed))+ sortOnFst = foldr insert []+ insert x [] = [x]+ insert x (y : ys) = if fst x <= fst y then x : y : ys else y : insert x ys+++-- | The keyword tokens directly inside a call's parentheses, with their+-- indices.+depthOneWords :: Int -> Int -> R [(Int, Text)]+depthOneWords from to = go from (0 :: Int)+ where+ go i depth+ | i >= to = pure []+ | otherwise = do+ t <- tokM i+ case t of+ Just tk+ | tk.text `elem` ["(", "["] -> go (i + 1) (depth + 1)+ | tk.text `elem` [")", "]"] -> go (i + 1) (depth - 1)+ | depth == 0 && tk.isKeyword -> ((i, T.toLower tk.text) :) <$> go (i + 1) depth+ _ -> go (i + 1) depth+++hasExtras :: Pg.FuncCall -> Bool+hasExtras f = isJust (f ^. Pg.maybe'aggFilter) || isJust (f ^. Pg.maybe'over) || f ^. Pg.aggWithinGroup+++funcCall :: Mode -> E -> Pg.FuncCall -> R D+funcCall mode e f = do+ call <- classifyCall f+ case call of+ Plain _ -> plainCall mode e f+ AtTimeZone x zone -> do+ xd <- child e.en x >>= expr mode+ zd <- child e.en zone >>= expr mode+ k <- kw "at time zone"+ pure (xd <+> k <+> zd)+ _ -> do+ k <- kw (callName call)+ body <- callBody mode e call+ pure (k <> (if mode == MP then " (" else "(") <> body <> ")")+++callName :: Call -> Text+callName = \case+ Plain _ -> ""+ Extract _ _ -> "extract"+ Position _ _ -> "position"+ Substring _ _ -> "substring"+ SubstringCommas _ -> "substring"+ Trim{} -> "trim"+ Overlay{} -> "overlay"+ AtTimeZone _ _ -> ""+++-- | What goes between an SQL-syntax function's parentheses.+callBody :: Mode -> E -> Call -> R D+callBody mode e = \case+ Extract field x -> do+ i <- tokAt (minimum (locsNode field))+ t <- tokM i+ fd <- case t of+ Just tk+ | tk.kind == Pg.SCONST -> stringConst (fromMaybe "" (strConst field)) tk.text+ | T.toLower tk.text `elem` ["year", "month", "day", "hour", "minute", "second"] -> kw (T.toLower tk.text)+ | otherwise -> ident (fromMaybe "" (strConst field))+ Nothing -> unsupported "an extract field"+ xd <- child e.en x >>= expr mode+ k <- kw "from"+ pure (fd <+> k <+> xd)+ Position needle haystack -> do+ nd' <- child e.en needle >>= expr MP+ hd <- child e.en haystack >>= expr MP+ k <- kw "in"+ pure (nd' <+> k <+> hd)+ Substring x keyed -> do+ xd <- child e.en x >>= expr mode+ rest <- forM keyed \(k, r) -> do+ kd <- kw k+ rd <- child e.en r >>= expr mode+ pure (kd <+> rd)+ pure (spaceJoin (xd : rest))+ SubstringCommas args -> commaJoin <$> traverse (child e.en >=> expr mode) args+ Trim{modifier, chars, hasFrom, strings} -> do+ md <- maybe (pure mempty) (fmap (<> " ") . kw) modifier+ cd <- maybe (pure Nothing) (fmap Just . (child e.en >=> expr mode)) chars+ sd <- commaJoin <$> traverse (child e.en >=> expr mode) strings+ fromK <- kw "from"+ pure $+ md <> case (cd, hasFrom) of+ (Just c, _) -> c <+> fromK <+> sd+ (Nothing, True) -> fromK <+> sd+ (Nothing, False) -> sd+ Overlay{string, placing, from, for} -> do+ xd <- child e.en string >>= expr mode+ pd <- child e.en placing >>= expr mode+ fd <- child e.en from >>= expr mode+ forD <- maybe (pure mempty) (\n -> do k <- kw "for"; d <- child e.en n >>= expr mode; pure (" " <> k <+> d)) for+ placingK <- kw "placing"+ fromK <- kw "from"+ pure (xd <+> placingK <+> pd <+> fromK <+> fd <> forD)+ Plain _ -> unsupported "a plain call"+ AtTimeZone _ _ -> unsupported "at time zone"+++strConst :: Pg.Node -> Maybe Text+strConst n = case node n of+ Just (Pg.Node'AConst c) | Just (Pg.A_Const'Sval s) <- c ^. Pg.maybe'val -> Just (s ^. Pg.sval)+ _ -> Nothing+++-- | An ordinary call's name, and its opening parenthesis, placed.+callHead :: Pg.FuncCall -> R D+callHead f = do+ names <- strsOf (f ^. Pg.funcname)+ at <- tokAt (fromIntegral (f ^. Pg.location))+ open <- nextParen at+ _ <- expectParen open+ qualNameAt at names+++-- | The arguments of an ordinary call: none, @*@, or a list.+data Params+ = NoParams+ | Star+ | -- | The arguments, with @distinct@ or @all@ before them if written,+ -- and an @order by@ among them.+ Normal Quantifier [Pg.Node] [Pg.Node]+ | Variadic [Pg.Node] Pg.Node [Pg.Node]+++callParams :: Pg.FuncCall -> R Params+callParams f+ | f ^. Pg.aggStar = pure Star+ | null args = pure NoParams+ | f ^. Pg.funcVariadic = pure (Variadic (init args) (last args) sort)+ | otherwise = do+ explicitAll <- do+ at <- tokAt (fromIntegral (f ^. Pg.location))+ open <- nextParen at+ tokIs (open + 1) "all"+ pure (Normal (if f ^. Pg.aggDistinct then Distinct else if explicitAll then All else Unwritten) args sort)+ where+ args = f ^. Pg.args+ sort = if f ^. Pg.aggWithinGroup then [] else f ^. Pg.aggOrder+++plainCall :: Mode -> E -> Pg.FuncCall -> R D+plainCall mode e f = do+ app <- funcApplication mode e f+ within <-+ if f ^. Pg.aggWithinGroup+ then do+ k <- kw "within group"+ sd <- withinGroupParen f >> sortClause (f ^. Pg.aggOrder)+ pure (" " <> k <> " (" <> sd <> ")")+ else pure mempty+ filt <- case f ^. Pg.maybe'aggFilter of+ Nothing -> pure mempty+ Just x -> do+ filterParen f+ k <- kw "filter"+ w <- kw "where"+ xd <- child e.en x >>= expr mode+ pure (" " <> k <> " (" <> w <+> xd <> ")")+ over <- case f ^. Pg.maybe'over of+ Nothing -> pure mempty+ Just w -> (" " <>) <$> overClause f w+ pure (app <> within <> filt <> over)+++-- | The parenthesis after a call's closing one and a keyword or two+-- (@within group (@, @filter (@).+afterCallParen :: Pg.FuncCall -> [Text] -> R ()+afterCallParen f words' = do+ at <- tokAt (fromIntegral (f ^. Pg.location))+ open <- nextParen at+ close <- matchOf open >>= req "a call"+ let find i = do+ t <- tokM i+ case t of+ Nothing -> unsupported "a call's clause pgstyle cannot find"+ Just _ -> do+ ws <- traverse (\k -> tokL (i + k)) [0 .. length words' - 1]+ if ws == words' then pure (i + length words') else find (i + 1)+ p <- find (close + 1)+ _ <- expectParen p+ pure ()+++withinGroupParen :: Pg.FuncCall -> R ()+withinGroupParen f = afterCallParen f ["within", "group"]+++filterParen :: Pg.FuncCall -> R ()+filterParen f = afterCallParen f ["filter"]+++funcApplication :: Mode -> E -> Pg.FuncCall -> R D+funcApplication mode e f = do+ commented <- callCommented f+ if commented then funcApplicationWrapped e f else funcApplicationInline mode e f+++-- | Whether a call has a comment between its parentheses.+callCommented :: Pg.FuncCall -> R Bool+callCommented f = do+ any' <- anyComments+ if not any'+ then pure False+ else do+ open <- tokAt (fromIntegral (f ^. Pg.location)) >>= nextParen+ close <- matchOf open+ maybe (pure False) (commentsBetween open) close+++funcApplicationInline :: Mode -> E -> Pg.FuncCall -> R D+funcApplicationInline mode e f = do+ name <- callHead f+ params <- callParams f+ body <- case params of+ NoParams -> pure mempty+ Star -> txt "*"+ Normal distinct args sort -> do+ prefix <- distinctPrefix distinct+ ds <- traverse (funcArg mode e) args+ sd <- if null sort then pure mempty else (" " <>) <$> sortClause sort+ pure (prefix <> commaJoin ds <> sd)+ Variadic regular var sort -> do+ ds <- traverse (funcArg mode e) regular+ v <- funcArg mode e var+ k <- kw "variadic"+ sd <- if null sort then pure mempty else (" " <>) <$> sortClause sort+ pure ((if null ds then mempty else commaJoin ds <> ", ") <> k <> " " <> v <> sd)+ pure (name <> "(" <> body <> ")")+++-- | An aggregate's @distinct@ or @all@, or neither.+data Quantifier = Unwritten | Distinct | All+++distinctPrefix :: Quantifier -> R D+distinctPrefix = \case+ Unwritten -> pure mempty+ Distinct -> (<> " ") <$> kw "distinct"+ All -> (<> " ") <$> kw "all"+++-- | A call's argument, maybe named.+funcArg :: Mode -> E -> Pg.Node -> R D+funcArg mode e n = case node n of+ Just (Pg.Node'NamedArgExpr na) -> do+ (name, arrow) <- namedArg na+ arg <- req "a named argument" (na ^. Pg.maybe'arg) >>= child e.en >>= expr mode+ pure (name <> arrow <> arg)+ _ -> child e.en n >>= expr mode+++namedArg :: Pg.NamedArgExpr -> R (D, D)+namedArg na = do+ i <- tokAt (fromIntegral (na ^. Pg.location))+ arrow <- tokL (i + 1)+ name <- ident (na ^. Pg.name)+ pure (name, if arrow == ":=" then " := " else " => ")+++overClause :: Pg.FuncCall -> Pg.WindowDef -> R D+overClause f w = do+ k <- kw "over"+ if not (T.null (w ^. Pg.name))+ then (k <+>) <$> ident (w ^. Pg.name)+ else do+ afterCallParen f ["over"]+ spec <- windowSpec w+ pure (k <+> spec)+++windowSpec :: Pg.WindowDef -> R D+windowSpec w = do+ ref <- if T.null (w ^. Pg.refname) then pure Nothing else Just <$> ident (w ^. Pg.refname)+ part <-+ if null (w ^. Pg.partitionClause)+ then pure Nothing+ else do+ k <- kw "partition by"+ ds <- traverse (top >=> expr MP) (w ^. Pg.partitionClause)+ pure (Just (k <+> commaJoin ds))+ order <- if null (w ^. Pg.orderClause) then pure Nothing else Just <$> sortClause (w ^. Pg.orderClause)+ frame <- frameClause w+ pure ("(" <> spaceJoin (catMaybes [ref, part, order, frame]) <> ")")+++frameClause :: Pg.WindowDef -> R (Maybe D)+frameClause w+ | not (has frameNonDefault) = pure Nothing+ | otherwise = do+ modeD <- kw if has frameRows then "rows" else if has frameGroups then "groups" else "range"+ start' <- bound startBound (w ^. Pg.maybe'startOffset)+ extent <-+ if has frameBetween+ then do+ end' <- bound endBound (w ^. Pg.maybe'endOffset)+ b <- kw "between"+ a <- kw "and"+ pure (b <+> start' <+> a <+> end')+ else pure start'+ exclusion <-+ if+ | has frameExcludeCurrentRow -> Just <$> kw "exclude current row"+ | has frameExcludeGroup -> Just <$> kw "exclude group"+ | has frameExcludeTies -> Just <$> kw "exclude ties"+ | otherwise -> pure Nothing+ pure (Just (spaceJoin (catMaybes [Just modeD, Just extent, exclusion])))+ where+ has flag = w ^. Pg.frameOptions .&. flag /= 0+ bound flags offset+ | has flags.unboundedPreceding = kw "unbounded preceding"+ | has flags.unboundedFollowing = kw "unbounded following"+ | has flags.currentRow = kw "current row"+ | has flags.offsetPreceding = do+ o <- maybe (unsupported "a frame offset") (top >=> expr MP) offset+ (o <+>) <$> kw "preceding"+ | has flags.offsetFollowing = do+ o <- maybe (unsupported "a frame offset") (top >=> expr MP) offset+ (o <+>) <$> kw "following"+ | otherwise = unsupported "a frame bound"+++-- | The flags of a window definition's @frameOptions@ that say what its+-- frame is: PostgreSQL's @FRAMEOPTION_@ constants (nodes/parsenodes.h).+frameNonDefault, frameRows, frameGroups, frameBetween, frameExcludeCurrentRow, frameExcludeGroup, frameExcludeTies :: Int32+frameNonDefault = 0x1+frameRows = 0x4+frameGroups = 0x8+frameBetween = 0x10+frameExcludeCurrentRow = 0x8000+frameExcludeGroup = 0x10000+frameExcludeTies = 0x20000+++-- | The flags that say what one end of a frame is.+data BoundFlags = BoundFlags+ { unboundedPreceding :: Int32+ , unboundedFollowing :: Int32+ , currentRow :: Int32+ , offsetPreceding :: Int32+ , offsetFollowing :: Int32+ }+++startBound, endBound :: BoundFlags+startBound = BoundFlags{unboundedPreceding = 0x20, unboundedFollowing = 0x80, currentRow = 0x200, offsetPreceding = 0x800, offsetFollowing = 0x2000}+endBound = BoundFlags{unboundedPreceding = 0x40, unboundedFollowing = 0x100, currentRow = 0x400, offsetPreceding = 0x1000, offsetFollowing = 0x4000}+++----------------------------------------------------------------------+-- Subqueries in expressions.+----------------------------------------------------------------------++subLinkSel :: Pg.SubLink -> R Sel+subLinkSel s = do+ q <- req "a subquery" (s ^. Pg.maybe'subselect)+ st <- case node q of+ Just (Pg.Node'SelectStmt st) -> pure st+ _ -> unsupported "a subquery that is not a select"+ bound <- tokAt (fromIntegral (s ^. Pg.location))+ n <- selectParens bound st+ when (n < 1) (unsupported "a subquery without parentheses")+ pure Sel{stmt = st, parens = n}+++subLink :: Mode -> E -> Pg.SubLink -> R D+subLink mode e s = case s ^. Pg.subLinkType of+ t | t `elem` [Pg.EXPR_SUBLINK, Pg.MULTIEXPR_SUBLINK] -> subquery+ Pg.EXISTS_SUBLINK -> do+ k <- kw "exists"+ q <- subquery+ pure (k <+> q)+ Pg.ARRAY_SUBLINK -> do+ k <- kw "array"+ q <- subquery+ pure (k <> (if mode == MP then " " else mempty) <> q)+ Pg.ANY_SUBLINK | null (s ^. Pg.operName) -> do+ arg <- req "an in" (s ^. Pg.maybe'testexpr) >>= child e.en+ inSubLink mode arg s False+ t | t `elem` [Pg.ANY_SUBLINK, Pg.ALL_SUBLINK] -> do+ names <- strsOf (s ^. Pg.operName)+ op <- case names of+ [o] -> pure o+ _ -> unsupported "a schema-qualified operator"+ at <- tokAt (fromIntegral (s ^. Pg.location))+ source <- tokL at+ unless (source == op || (op == "<>" && source == "!=")) (unsupported "an operator pgstyle cannot find")+ subType <- tokL (at + 1)+ unless (subType `elem` ["any", "some", "all"]) (unsupported "an any/all pgstyle cannot read")+ arg <- req "an any" (s ^. Pg.maybe'testexpr) >>= child e.en+ ad <- expr mode arg+ st <- kw subType+ q <- subquery+ pure (ad <+> pretty source <+> st <+> q)+ _ -> unsupported "a subquery pgstyle does not lay out"+ where+ subquery = do+ sel <- subLinkSel s+ if mode == MP then selP sel else selMaybeWrap sel+++-- | @x in (select ...)@: "PgStyle.Render" hands its subquery to+-- postgresql-syntax's renderer whatever its length.+inSubLink :: Mode -> E -> Pg.SubLink -> Bool -> R D+inSubLink mode arg s negated = do+ ad <- expr mode arg+ k <- kw (if negated then "not in" else "in")+ sel <- subLinkSel s+ q <- selP sel+ pure (ad <+> k <+> q)+++----------------------------------------------------------------------+-- Expressions, wrapped: "PgStyle.Render"'s rules, over libpg_query's nodes.+----------------------------------------------------------------------++-- | One parenthesis level off an expression, as postgresql-syntax's+-- @InParensCExpr@ would hold it, with the indirection after it if any.+inParens :: E -> R (Maybe (E, Maybe Pg.A_Indirection))+inParens e+ | e.lv > 0 = pure (Just (e{lv = e.lv - 1}, Nothing))+ | Just (Pg.Node'AIndirection ind) <- node e.en+ , Just argN <- ind ^. Pg.maybe'arg = do+ arg <- child e.en argN+ pure+ if arg.lv > 0+ then Just (arg{lv = arg.lv - 1}, Just ind)+ else Nothing+ | otherwise = pure Nothing+++-- | A @::@ cast, not in parentheses: its argument and type.+asColonCast :: E -> R (Maybe (E, Pg.TypeName))+asColonCast e+ | e.lv == 0+ , Just (Pg.Node'TypeCast tc) <- node e.en+ , Just tn <- tc ^. Pg.maybe'typeName+ , Just arg <- tc ^. Pg.maybe'arg = do+ form <- castForm tc+ case form of+ ColonCast -> Just . (,tn) <$> child e.en arg+ _ -> pure Nothing+ | otherwise = pure Nothing+++-- | An ordinary call with no @within group@, @filter@ or @over@.+asFuncApp :: E -> R (Maybe Pg.FuncCall)+asFuncApp e+ | e.lv == 0+ , Just (Pg.Node'FuncCall f) <- node e.en+ , not (hasExtras f) = do+ call <- classifyCall f+ pure case call of+ Plain _ -> Just f+ _ -> Nothing+ | otherwise = pure Nothing+++-- | postgresql-syntax's @func_expr_common_subexpr@ forms.+data Subexpr+ = -- | @coalesce@, @greatest@, @least@ or @nullif@: its keyword, its+ -- location, and its arguments.+ SubRows Text Int32 [Pg.Node]+ | -- | @cast(x as t)@: its location, the expression and the type.+ SubCast Int32 Pg.Node Pg.TypeName+ | -- | @extract@, @position@, @substring@, @trim@, @overlay@.+ SubSyntax+ | -- | @current_date@ and the like.+ SubValue+++asSubexpr :: E -> R (Maybe Subexpr)+asSubexpr e+ | e.lv > 0 = pure Nothing+ | otherwise = case node e.en of+ Just (Pg.Node'CoalesceExpr c) -> pure (Just (SubRows "coalesce" (c ^. Pg.location) (c ^. Pg.args)))+ Just (Pg.Node'MinMaxExpr c) -> pure (Just (SubRows (if c ^. Pg.op == Pg.IS_GREATEST then "greatest" else "least") (c ^. Pg.location) (c ^. Pg.args)))+ Just (Pg.Node'AExpr a)+ | a ^. Pg.kind == Pg.AEXPR_NULLIF+ , Just l <- a ^. Pg.maybe'lexpr+ , Just r <- a ^. Pg.maybe'rexpr ->+ pure (Just (SubRows "nullif" (a ^. Pg.location) [l, r]))+ Just (Pg.Node'TypeCast tc)+ | Just tn <- tc ^. Pg.maybe'typeName+ , Just arg <- tc ^. Pg.maybe'arg -> do+ form <- castForm tc+ pure case form of+ CastCall -> Just (SubCast (tc ^. Pg.location) arg tn)+ _ -> Nothing+ Just (Pg.Node'FuncCall f) | not (hasExtras f) -> do+ call <- classifyCall f+ pure case call of+ Plain _ -> Nothing+ AtTimeZone _ _ -> Nothing+ _ -> Just SubSyntax+ Just (Pg.Node'SqlvalueFunction _) -> pure (Just SubValue)+ _ -> pure Nothing+++-- | What an expression is, as the wrapped layout tells expressions apart:+-- in parentheses, under a @::@ cast, an ordinary call, one of+-- postgresql-syntax's common subexpressions, or something else.+data Shape+ = InParens E (Maybe Pg.A_Indirection)+ | UnderCast E Pg.TypeName+ | Application Pg.FuncCall+ | CommonSubexpr Subexpr+ | OtherShape+++-- | An expression's 'Shape'. All four classifiers run, in this order,+-- whichever matches: they are not pure. 'inParens' and 'asColonCast' take+-- the child expression, which places the parentheses around it, and+-- 'asFuncApp' and 'asSubexpr' classify calls, which places a call's own+-- parenthesis. Stopping at the first match would leave some unplaced, or+-- change which refusal comes first.+shapeOf :: E -> R Shape+shapeOf e = do+ paren <- inParens e+ cast <- asColonCast e+ app <- asFuncApp e+ subexpr <- asSubexpr e+ pure case (paren, cast, app, subexpr) of+ (Just (inner, ind), _, _, _) -> InParens inner ind+ (_, Just (inner, tn), _, _) -> UnderCast inner tn+ (_, _, Just f, _) -> Application f+ (_, _, _, Just sub) -> CommonSubexpr sub+ _ -> OtherShape+++isWrapEligible :: E -> R Bool+isWrapEligible e = do+ shape <- shapeOf e+ case shape of+ InParens inner _ -> isWrapEligible inner+ UnderCast inner _ -> isWrapEligible inner+ Application _ -> pure True+ CommonSubexpr SubValue -> pure False+ CommonSubexpr _ -> pure True+ OtherShape -> case node e.en of+ _ | e.lv > 0 -> pure False+ Just (Pg.Node'AArrayExpr a) -> do+ keyword <- arrayKeyword a+ if keyword then arrayEligible e a else pure False+ Just (Pg.Node'RowExpr r) -> anyM (child e.en >=> isWrapEligible) (r ^. Pg.args)+ Just (Pg.Node'CaseExpr _) -> pure True+ _ -> pure False+++arrayEligible :: E -> Pg.A_ArrayExpr -> R Bool+arrayEligible e a = anyM el (a ^. Pg.elements)+ where+ el n = case node n of+ Just (Pg.Node'AArrayExpr sub) -> do+ keyword <- arrayKeyword sub+ if keyword then child e.en n >>= isWrapEligible else child e.en n >>= \se -> arrayEligible se sub+ _ -> child e.en n >>= isWrapEligible+++-- | A call under any number of @::@ casts.+data CastedCall = CastedCall+ { call :: Pg.FuncCall+ , callExpr :: E+ , recast :: D -> R D+ -- ^ Put the casts back after the call's layout.+ }+++-- | The call an expression is, maybe under @::@ casts.+topLevelFuncApp :: E -> R (Maybe CastedCall)+topLevelFuncApp e = do+ cast <- asColonCast e+ case cast of+ Just (inner, tn) -> do+ found <- topLevelFuncApp inner+ pure case found of+ Just c -> Just c{recast = \d -> do d' <- c.recast d; t <- typeName tn; pure (d' <> "::" <> t)}+ Nothing -> Nothing+ Nothing -> do+ app <- asFuncApp e+ pure ((\f -> CastedCall{call = f, callExpr = e, recast = pure}) <$> app)+++funcAppArgCount :: Pg.FuncCall -> Int+funcAppArgCount f+ | f ^. Pg.aggStar = 0+ | otherwise = length (f ^. Pg.args)+++-- | Arguments shaped like keys and values: at least four, an even number,+-- every other one from the first a string literal.+looksLikeKeyValuePairs :: E -> [Pg.Node] -> R Bool+looksLikeKeyValuePairs e args+ | n < keyValueMinArguments || odd n = pure False+ | otherwise = allM key [a | (i, a) <- zip [0 :: Int ..] args, even i]+ where+ n = length args+ key a = case node a of+ Just (Pg.Node'AConst c) | Just (Pg.A_Const'Sval _) <- c ^. Pg.maybe'val -> do+ ae <- child e.en a+ source <- tokAt (fromIntegral (c ^. Pg.location)) >>= tokM+ pure (ae.lv == 0 && maybe False (\t -> "'" `T.isPrefixOf` t.text || "$" `T.isPrefixOf` t.text) source)+ _ -> pure False+++allM :: (a -> R Bool) -> [a] -> R Bool+allM f = fmap not . anyM (fmap not . f)+++-- | Whether an expression is a call (maybe under @::@ casts) with key/value+-- shaped arguments.+hasPairShapedCall :: E -> R Bool+hasPairShapedCall e = do+ found <- topLevelFuncApp e+ case found of+ Just CastedCall{call = f, callExpr = fe} -> do+ params <- callParams f+ case params of+ Normal _ args _ -> looksLikeKeyValuePairs fe args+ _ -> pure False+ Nothing -> pure False+++-- | "PgStyle.Render"'s: the fewest arguments a call laid out as key/value+-- pairs has.+keyValueMinArguments :: Int+keyValueMinArguments = 4+++inlineLengthThreshold, selectTargetInlineThreshold, subqueryInlineThreshold, funcWrapThreshold :: Int+inlineLengthThreshold = 60+selectTargetInlineThreshold = 150+subqueryInlineThreshold = 100+funcWrapThreshold = 2+++exprMaybeWrap :: E -> R D+exprMaybeWrap e = do+ inline <- expr MR e+ force <- hasPairShapedCall e+ commented <- hasCmts e.en+ eligible <- isWrapEligible e+ if (len inline > inlineLengthThreshold || force || commented) && eligible+ then exprWrapped e+ else pure inline+++exprWrapped :: E -> R D+exprWrapped e = do+ shape <- shapeOf e+ case shape of+ InParens inner ind -> inParensWrapped e inner ind+ UnderCast inner tn -> do+ d <- exprWrapped inner+ t <- typeName tn+ pure (d <> "::" <> t)+ Application f -> funcApplicationWrapped e f+ CommonSubexpr sub -> subexprWrapped e sub+ OtherShape -> case node e.en of+ Just (Pg.Node'AArrayExpr a) -> do+ keyword <- arrayKeyword a+ if keyword+ then do+ k <- kw "array"+ body <- arrayWrapped e a+ pure (k <> body)+ else expr MR e+ Just (Pg.Node'RowExpr r) -> do+ at <- tokAt (fromIntegral (r ^. Pg.location))+ explicit <- tokIs at "row"+ open <- if explicit then nextParen at else pure at+ _ <- expectParen open+ args <- traverse (child e.en >=> exprMaybeWrap) (r ^. Pg.args)+ k <- kw "row"+ pure ((if explicit then k <> "(" else "(") <> nest indentSize (argRows args) <> hardline <> ")")+ Just (Pg.Node'CaseExpr c) -> caseWrapped e c+ _ -> expr MR e+++inParensWrapped :: E -> E -> Maybe Pg.A_Indirection -> R D+inParensWrapped outer inner mInd = do+ isCase <- case node inner.en of+ Just (Pg.Node'CaseExpr c) | inner.lv == 0 -> pure (Just c)+ _ -> pure Nothing+ case (mInd, isCase) of+ (Nothing, Just c) -> do+ body <- caseWrapped inner c+ pure (align ("(" <> body <> ")"))+ _ -> do+ topCase <- isTopLevelCase inner+ body <- if topCase then exprWrapped inner else exprMaybeWrap inner+ ind <- maybe (pure mempty) (\i -> indirection MR outer.en (i ^. Pg.indirection)) mInd+ pure ("(" <> nest indentSize (hardline <> body) <> hardline <> ")" <> ind)+++isTopLevelCase :: E -> R Bool+isTopLevelCase e = do+ paren <- inParens e+ cast <- asColonCast e+ case (paren, cast) of+ (Just (inner, _), _) -> isTopLevelCase inner+ (_, Just (inner, _)) -> isTopLevelCase inner+ _ -> pure case node e.en of+ Just (Pg.Node'CaseExpr _) -> e.lv == 0+ _ -> False+++argRows :: [D] -> D+argRows = \case+ [] -> mempty+ (x : xs) -> (hardline <> " " <> x) <> mconcat [hardline <> ", " <> r | r <- xs]+++-- | 'argRows', and the line break before the closing parenthesis (to go+-- outside the rows' nesting), with the comments before each argument and+-- before the parenthesis, if each argument's first token and the+-- parenthesis are known.+argRowsAt :: Maybe ([Int], Int) -> [D] -> R (D, D)+argRowsAt Nothing ds = pure (argRows ds, hardline)+argRowsAt (Just (firsts, close)) ds = do+ rows <- forM (zip3 [0 :: Int ..] firsts ds) \(i, q, d) -> do+ b <- brk " " q+ pure (b <> (if i == 0 then " " else ", ") <> d)+ end <- closeBrk close+ pure (mconcat rows, end)+++-- | The line break before a list's closing bracket, outside the list's+-- nesting: comments before it line up with the list's items.+closeBrk :: Int -> R D+closeBrk = brk (pretty (T.replicate (indentSize + 2) " "))+++-- | 'argPairRows' and the line break before the closing parenthesis, like+-- 'argRowsAt': comments go before a key, or after its value.+argPairRowsAt :: Maybe ([Int], Int) -> [D] -> R (D, D)+argPairRowsAt Nothing ds = pure (argPairRows ds, hardline)+argPairRowsAt (Just (firsts, close)) ds = do+ -- A comment between a key and its value has nowhere to go.+ inside <- or <$> forM (pairs firsts) \(_, v) -> not . null <$> gapBefore v+ if inside+ then pure (argPairRows ds, hardline)+ else do+ rows <- forM (zip3 [0 :: Int ..] (map fst (pairs firsts)) (pairs ds)) \(i, q, (k, v)) -> do+ b <- brk " " q+ pure (b <> (if i == 0 then " " else ", ") <> k <> ", " <> v)+ end <- closeBrk close+ pure (mconcat rows, end)+ where+ pairs (a : b : rest) = (a, b) : pairs rest+ pairs _ = []+++argPairRows :: [D] -> D+argPairRows = goFirst . pairs+ where+ pairs (a : b : rest) = (a, b) : pairs rest+ pairs _ = []+ goFirst [] = mempty+ goFirst ((k, v) : rest) =+ (hardline <> " " <> k <> ", " <> v)+ <> mconcat [hardline <> ", " <> k' <> ", " <> v' | (k', v') <- rest]+++-- | The first token of each of a call's arguments, and its closing+-- parenthesis.+callArgsAt :: Pg.FuncCall -> Int -> R (Maybe ([Int], Int))+callArgsAt f n = do+ any' <- anyComments+ if not any'+ then pure Nothing+ else do+ at <- tokAt (fromIntegral (f ^. Pg.location))+ open <- nextParen at+ mclose <- matchOf open+ case mclose of+ Nothing -> pure Nothing+ Just close -> do+ lead <- tokL (open + 1)+ let open' = if lead `elem` ["distinct", "all"] then open + 1 else open+ firsts <- listFirsts open' close n+ pure ((,close) <$> firsts)+++funcApplicationWrapped :: E -> Pg.FuncCall -> R D+funcApplicationWrapped e f = do+ name <- callHead f+ params <- callParams f+ (body, end) <- case params of+ NoParams -> pure (mempty, hardline)+ Star -> pure (hardline <> "*", hardline)+ Normal distinct args sort -> do+ prefix <- distinctPrefix distinct+ ds <- traverse (funcArgMaybeWrap e) args+ pairShaped <- looksLikeKeyValuePairs e args+ if null sort+ then do+ at <- callArgsAt f (length args)+ (rows, end) <- (if pairShaped then argPairRowsAt else argRowsAt) at ds+ pure (prefix <> rows, end)+ else do+ sd <- (hardline <>) <$> sortClause sort+ pure (prefix <> (if pairShaped then argPairRows ds else argRows ds) <> sd, hardline)+ Variadic regular var sort -> do+ ds <- traverse (funcArgMaybeWrap e) regular+ v <- funcArgMaybeWrap e var+ k <- kw "variadic"+ sd <- if null sort then pure mempty else (hardline <>) <$> sortClause sort+ pure (argRows (ds ++ [k <> " " <> v]) <> sd, hardline)+ pure (name <> "(" <> nest indentSize body <> end <> ")")+++funcArgMaybeWrap :: E -> Pg.Node -> R D+funcArgMaybeWrap e n = do+ inline <- funcArg MR e n+ (prefix, argN) <- case node n of+ Just (Pg.Node'NamedArgExpr na) -> do+ (name, arrow) <- namedArg na+ a <- req "a named argument" (na ^. Pg.maybe'arg)+ pure (name <> arrow, a)+ _ -> pure (mempty, n)+ arg <- child e.en argN+ force <- hasPairShapedCall arg+ commented <- hasCmts argN+ eligible <- isWrapEligible arg+ if (len inline > inlineLengthThreshold || force || commented) && eligible+ then (prefix <>) <$> exprWrapped arg+ else pure inline+++subexprWrapped :: E -> Subexpr -> R D+subexprWrapped e = \case+ SubRows name at args -> do+ open <- tokAt (fromIntegral at) >>= nextParen+ _ <- expectParen open+ ds <- traverse (child e.en >=> exprMaybeWrap) args+ k <- kw name+ pure (k <> "(" <> nest indentSize (argRows ds) <> hardline <> ")")+ SubCast at arg tn -> do+ open <- tokAt (fromIntegral at) >>= nextParen+ _ <- expectParen open+ a <- child e.en arg >>= exprMaybeWrap+ t <- typeName tn+ k <- kw "cast"+ as <- kw "as"+ pure (k <> "(" <> nest indentSize (hardline <> a <+> as <+> t) <> hardline <> ")")+ _ -> expr MR e+++arrayWrapped :: E -> Pg.A_ArrayExpr -> R D+arrayWrapped e a = do+ let els = a ^. Pg.elements+ nested <- case els of+ n : _ | Just (Pg.Node'AArrayExpr sub) <- node n -> not <$> arrayKeyword sub+ _ -> pure False+ if null els+ then pure "[]"+ else do+ ds <-+ if nested+ then forM els \n -> case node n of+ Just (Pg.Node'AArrayExpr sub) -> do+ se <- child e.en n+ k <- kw "array"+ (k <>) <$> arrayWrapped se sub+ _ -> unsupported "a nested array pgstyle cannot read"+ else traverse (child e.en >=> exprMaybeWrap) els+ keyword <- arrayKeyword a+ at <- tokAt (fromIntegral (a ^. Pg.location))+ positions <- commentedList (if keyword then at + 1 else at) (length els)+ (rows, end) <- argRowsAt positions ds+ pure ("[" <> nest indentSize rows <> end <> "]")+++caseWrapped :: E -> Pg.CaseExpr -> R D+caseWrapped e c = do+ k <- kw "case"+ arg <- maybe (pure mempty) (\a -> (" " <>) <$> (child e.en a >>= expr MR)) (c ^. Pg.maybe'arg)+ whens <- forM (c ^. Pg.args) \w -> case node w of+ Just (Pg.Node'CaseWhen cw) -> do+ cond <- req "a when" (cw ^. Pg.maybe'expr) >>= child e.en >>= exprMaybeWrap+ result <- req "a when" (cw ^. Pg.maybe'result) >>= child e.en >>= exprForceSubqueryWrap+ whenK <- kw "when"+ thenK <- kw "then"+ pure (hardline <> whenK <+> cond <+> thenK <+> result)+ _ -> unsupported "a case branch pgstyle cannot read"+ def <- case c ^. Pg.maybe'defresult of+ Nothing -> pure mempty+ Just d -> do+ elseK <- kw "else"+ dd <- child e.en d >>= exprForceSubqueryWrap+ pure (hardline <> elseK <+> dd)+ endK <- kw "end"+ pure (k <> arg <> nest indentSize (mconcat whens <> def) <> hardline <> endK)+++exprForceSubqueryWrap :: E -> R D+exprForceSubqueryWrap e+ | e.lv == 0+ , Just (Pg.Node'SubLink s) <- node e.en+ , s ^. Pg.subLinkType == Pg.EXPR_SUBLINK =+ subLinkSel s >>= selWrapped+ | e.lv == 0+ , Just (Pg.Node'AIndirection ind) <- node e.en+ , Just argN <- ind ^. Pg.maybe'arg+ , Just (Pg.Node'SubLink s) <- node argN+ , s ^. Pg.subLinkType == Pg.EXPR_SUBLINK = do+ arg <- child e.en argN+ if arg.lv > 0+ then exprMaybeWrap e+ else do+ q <- subLinkSel s >>= selWrapped+ i <- indirection MR e.en (ind ^. Pg.indirection)+ pure (q <> i)+ | otherwise = do+ cast <- asColonCast e+ case cast of+ Just (inner, tn) -> do+ d <- exprForceSubqueryWrap inner+ t <- typeName tn+ pure (d <> "::" <> t)+ Nothing -> exprMaybeWrap e+++-- | A select target or SET value: "PgStyle.Render"'s @renderExprDoc@.+exprDoc :: E -> R D+exprDoc e = do+ found <- topLevelFuncApp e+ case found of+ Just CastedCall{call = f, callExpr = fe, recast}+ | funcAppArgCount f >= funcWrapThreshold -> funcApplicationWrapped fe f >>= recast+ _ -> do+ topCase <- isTopLevelCase e+ if topCase+ then align <$> exprWrapped e+ else do+ inline <- expr MR e+ eligible <- isWrapEligible e+ commented <- hasCmts e.en+ if (len inline > selectTargetInlineThreshold || commented) && eligible+ then exprWrapped e+ else pure inline+++----------------------------------------------------------------------+-- Conditions.+----------------------------------------------------------------------++-- | @where@ / @having@ / @on@: the first condition after the keyword, each+-- further top-level @and@ on its own line, right-aligned to the keyword.+condAligned :: Int -> Text -> Pg.Node -> R D+condAligned anchor keyword n = do+ commented <- hasCmts n+ if commented then condCommented anchor keyword n else condPlain anchor keyword n+++-- | 'condAligned' for a condition with comments in it: split on its+-- top-level @and@s by the tree rather than the text, the comments before+-- each @and@ at the line break before it.+condCommented :: Int -> Text -> Pg.Node -> R D+condCommented anchor keyword n = do+ e <- top n+ let kwPad = pretty (T.replicate (max 0 (anchor - T.length keyword)) " ")+ andPad = pretty (T.replicate (max 0 (anchor - 3)) " ")+ k <- kw keyword+ case node n of+ Just (Pg.Node'BoolExpr b)+ | e.lv == 0+ , b ^. Pg.boolop == Pg.AND_EXPR+ , first : rest <- b ^. Pg.args -> do+ andK <- kw "and"+ fd <- child n first >>= exprMaybeWrap+ rds <- forM rest \x -> do+ xd <- child n x >>= exprMaybeWrap+ andAt <- clauseAt [["and"]] x+ -- The comments before the @and@ (one after it has no+ -- place).+ b' <- (<> (andPad <> andK)) <$> brkAt andPad andAt+ pure (b' <+> xd)+ pure (kwPad <> k <+> fd <> mconcat rds)+ _ -> do+ d <- exprMaybeWrap e+ pure (kwPad <> k <+> d)+++condPlain :: Int -> Text -> Pg.Node -> R D+condPlain anchor keyword n = do+ e <- top n+ lower <- local (\env -> env{upper = False}) (expr MR e)+ cased <- expr MR e+ let parts = splitOnAnd (renderToText lower) (renderToText cased)+ kwPad = pretty (T.replicate (max 0 (anchor - T.length keyword)) " ")+ andPad = pretty (T.replicate (max 0 (anchor - 3)) " ")+ k <- kw keyword+ andK <- kw "and"+ eligible <- isWrapEligible e+ commented <- hasCmts n+ case parts of+ [single]+ | (T.length single > inlineLengthThreshold || commented) && eligible -> do+ d <- exprMaybeWrap e+ pure (kwPad <> k <+> d)+ | otherwise -> pure (kwPad <> k <+> raw single)+ (first : rest) -> pure (vsep ((kwPad <> k <+> raw first) : map (\p -> andPad <> andK <+> raw p) rest))+ [] -> pure mempty+++-- | "PgStyle.Render"'s @splitOnAnd@, deciding on the lower-case rendering and+-- cutting the one in the requested case (the same text but for the case of+-- its keywords).+splitOnAnd :: Text -> Text -> [Text]+splitOnAnd lower cased = go 0 False Nothing "" (zip (T.unpack lower) (T.unpack cased))+ where+ go :: Int -> Bool -> Maybe Char -> String -> [(Char, Char)] -> [Text]+ go _ _ _ acc [] = [T.strip (T.pack (reverse acc))]+ go d btwn (Just q) acc ((c1, o1) : (c2, o2) : rest)+ | c1 == q && c2 == q = go d btwn (Just q) (o2 : o1 : acc) rest+ go d btwn (Just q) acc ((c, o) : rest)+ | c == q = go d btwn Nothing (o : acc) rest+ | otherwise = go d btwn (Just q) (o : acc) rest+ go d btwn Nothing acc (('\'', o) : rest) = go d btwn (Just '\'') (o : acc) rest+ go d btwn Nothing acc (('"', o) : rest) = go d btwn (Just '"') (o : acc) rest+ go d btwn Nothing acc (('(', o) : rest) = go (d + 1) btwn Nothing (o : acc) rest+ go d btwn Nothing acc ((')', o) : rest) = go (max 0 (d - 1)) btwn Nothing (o : acc) rest+ go 0 True Nothing acc ((' ', a) : ('a', b) : ('n', c) : ('d', d') : (' ', e) : rest) =+ go 0 False Nothing (e : d' : c : b : a : acc) rest+ go 0 _ Nothing acc ((' ', _) : ('a', _) : ('n', _) : ('d', _) : (' ', _) : rest) =+ T.strip (T.pack (reverse acc)) : go 0 False Nothing "" rest+ go d _ Nothing acc (('b', a) : ('e', b) : ('t', c) : ('w', d') : ('e', e) : ('e', f) : ('n', g) : (' ', h) : rest) =+ go d True Nothing (h : g : f : e : d' : c : b : a : acc) rest+ go d btwn st acc ((_, o) : rest) = go d btwn st (o : acc) rest
+ src/PgStyle/Layout/Locations.hs view
@@ -0,0 +1,103 @@+{-# LANGUAGE GADTs #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++-- | The source locations in a parse tree, found through protobuf+-- reflection.+module PgStyle.Layout.Locations where++import Data.List (isSuffixOf)+import Data.Map.Strict qualified as Map+import Data.ProtoLens.Message (FieldAccessor (..), FieldDescriptor (..), FieldTypeDescriptor (..), Message (..), ScalarField (..))+import Data.Proxy (Proxy (..))+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import Unsafe.Coerce (unsafeCoerce)+++-- | Every location in a node's subtree.+locsNode :: Pg.Node -> [Int]+locsNode n = case n ^. Pg.maybe'node of+ Nothing -> []+ Just x -> case x of+ Pg.Node'AExpr v -> locsMsg v+ Pg.Node'ColumnRef v -> locsMsg v+ Pg.Node'ParamRef v -> locsMsg v+ Pg.Node'AConst v -> locsMsg v+ Pg.Node'FuncCall v -> locsMsg v+ Pg.Node'TypeCast v -> locsMsg v+ Pg.Node'BoolExpr v -> locsMsg v+ Pg.Node'NullTest v -> locsMsg v+ Pg.Node'BooleanTest v -> locsMsg v+ Pg.Node'SubLink v -> locsMsg v+ Pg.Node'CaseExpr v -> locsMsg v+ Pg.Node'CaseWhen v -> locsMsg v+ Pg.Node'CoalesceExpr v -> locsMsg v+ Pg.Node'MinMaxExpr v -> locsMsg v+ Pg.Node'RowExpr v -> locsMsg v+ Pg.Node'AArrayExpr v -> locsMsg v+ Pg.Node'AIndirection v -> locsMsg v+ Pg.Node'AIndices v -> locsMsg v+ Pg.Node'AStar v -> locsMsg v+ Pg.Node'CollateClause v -> locsMsg v+ Pg.Node'SqlvalueFunction v -> locsMsg v+ Pg.Node'SetToDefault v -> locsMsg v+ Pg.Node'NamedArgExpr v -> locsMsg v+ Pg.Node'GroupingFunc v -> locsMsg v+ Pg.Node'CurrentOfExpr v -> locsMsg v+ Pg.Node'List v -> locsMsg v+ Pg.Node'String v -> locsMsg v+ Pg.Node'Integer v -> locsMsg v+ Pg.Node'ResTarget v -> locsMsg v+ Pg.Node'MultiAssignRef v -> locsMsg v+ Pg.Node'SortBy v -> locsMsg v+ Pg.Node'WindowDef v -> locsMsg v+ Pg.Node'RangeVar v -> locsMsg v+ Pg.Node'RangeTableSample v -> locsMsg v+ Pg.Node'RangeSubselect v -> locsMsg v+ Pg.Node'RangeFunction v -> locsMsg v+ Pg.Node'JoinExpr v -> locsMsg v+ Pg.Node'TypeName v -> locsMsg v+ Pg.Node'ColumnDef v -> locsMsg v+ Pg.Node'IndexElem v -> locsMsg v+ Pg.Node'GroupingSet v -> locsMsg v+ Pg.Node'LockingClause v -> locsMsg v+ Pg.Node'WithClause v -> locsMsg v+ Pg.Node'CommonTableExpr v -> locsMsg v+ Pg.Node'InferClause v -> locsMsg v+ Pg.Node'OnConflictClause v -> locsMsg v+ Pg.Node'SelectStmt v -> locsMsg v+ Pg.Node'InsertStmt v -> locsMsg v+ Pg.Node'UpdateStmt v -> locsMsg v+ Pg.Node'DeleteStmt v -> locsMsg v+ Pg.Node'ReturningClause v -> locsMsg v+ _ -> locsMsg n+++-- | Every location in a message's subtree, through protobuf reflection.+locsMsg :: forall m. Message m => m -> [Int]+locsMsg m = concatMap field (Map.elems (fieldsByTag @m))+ where+ field :: FieldDescriptor m -> [Int]+ field (FieldDescriptor name ty acc) = case ty of+ ScalarField Int32Field+ | isLocation name -> case acc of+ PlainField _ l -> located (m ^. l)+ OptionalField l -> maybe [] located (m ^. l)+ _ -> []+ MessageField _ -> case acc of+ PlainField _ l -> locsAny (m ^. l)+ OptionalField l -> maybe [] locsAny (m ^. l)+ RepeatedField _ l -> concatMap locsAny (m ^. l)+ _ -> []+ _ -> []+ located v = [fromIntegral v | v >= 0]+ isLocation name = name == "location" || "_location" `isSuffixOf` name+++locsAny :: forall v. Message v => v -> [Int]+locsAny v+ -- The node wrapper has a field for each of its 250-odd kinds; going+ -- through 'locsNode' visits only the one it holds.+ | messageName (Proxy @v) == "pg_query.Node" = locsNode (unsafeCoerce v)+ | otherwise = locsMsg v
+ src/PgStyle/Layout/Monad.hs view
@@ -0,0 +1,397 @@+-- | The layout's monad: the statement's source and tokens, what is placed so+-- far, and the small helpers every part of the layout uses.+module PgStyle.Layout.Monad where++import Control.Monad.Except (MonadError (catchError, throwError))+import Control.Monad.Reader (ReaderT, asks)+import Control.Monad.State.Strict (StateT, gets, modify')+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.Char (isAsciiUpper, toLower)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Locations+import Prettyprinter (Doc, LayoutOptions (..), PageWidth (..), hcat, layoutPretty, pretty, punctuate)+import Prettyprinter.Internal (unsafeTextWithoutNewlines)+import Prettyprinter.Render.Text (renderStrict)+++isComment :: Pg.ScanToken -> Bool+isComment t = t ^. Pg.token `elem` [Pg.SQL_COMMENT, Pg.C_COMMENT]+++layoutOpts :: LayoutOptions+layoutOpts = LayoutOptions Unbounded+++indentSize :: Int+indentSize = 4+++----------------------------------------------------------------------+-- The renderer's monad: the source and its tokens, and which parentheses+-- are already placed.+----------------------------------------------------------------------++data Tok = Tok+ { start :: Int+ , text :: Text+ , kind :: Pg.Token+ , isKeyword :: Bool+ , reserved :: Bool+ -- ^ A reserved keyword, which an identifier can only be quoted.+ }+++data Env = Env+ { toks :: IM.IntMap Tok+ -- ^ By index.+ , byStart :: IM.IntMap Int+ -- ^ Token index by byte offset.+ , matching :: IM.IntMap Int+ -- ^ The other parenthesis of each parenthesis, by token index.+ , allLocs :: IS.IntSet+ -- ^ Every location in the statement's tree.+ , upper :: Bool+ , names :: Map.Map Text NameSpelling+ -- ^ Each identifier of the source, case-folded as PostgreSQL does, and+ -- how it is written.+ , cmts :: IM.IntMap [Cmt]+ -- ^ The comments after each token (by index), in order.+ , column :: Int+ -- ^ The column the statement starts at, which its lines are indented+ -- to.+ , tightTypes :: Bool+ -- ^ Types written with no space before their modifiers, @numeric(10, 2)@,+ -- as in DDL.+ , blankLineBefore :: IS.IntSet+ -- ^ The tokens (by index) with a blank line directly before them, after+ -- the token or comment that precedes them.+ }+++-- | A comment, as written.+data Cmt = Cmt+ { ctext :: Text+ , ownLine :: Bool+ -- ^ Nothing but whitespace before it on its line.+ , blankBefore :: Bool+ -- ^ A blank line before it.+ }+++data St = St+ { consumed :: IS.IntSet+ -- ^ Opening parentheses placed so far, by token index.+ , parenCounts :: Map.Map (ParenQuestion, NodeSpan) Int+ -- ^ How many parentheses wrap a node, once worked out.+ , boolGroups :: IS.IntSet+ -- ^ Opening parentheses placed around a group of a boolean run's+ -- arguments, which laying the run out again finds again.+ }+++-- | What is asked of a node's parentheses: those around it as an+-- expression, as an indirection (whose own come before its argument's), as+-- a select, or as a join.+data ParenQuestion = AroundExpr | AroundIndirection | AroundSelect | AroundJoin+ deriving stock (Eq, Ord)+++-- | A node, by its locations: the first, the last, and how many.+data NodeSpan = NodeSpan {firstLoc :: Int, lastLoc :: Int, locCount :: Int}+ deriving stock (Eq, Ord)+++-- | Work out once how many parentheses wrap the node with these (non-empty)+-- locations: placing parentheses must give the same answer when asked+-- again.+remembered :: ParenQuestion -> [Int] -> R Int -> R Int+remembered question ls compute = do+ let key = (question, NodeSpan{firstLoc = minimum ls, lastLoc = maximum ls, locCount = length ls})+ known <- gets (Map.lookup key . (.parenCounts))+ case known of+ Just k -> pure k+ Nothing -> do+ k <- compute+ modify' \st -> st{parenCounts = Map.insert key k st.parenCounts}+ pure k+++type R = ReaderT Env (StateT St (Either Text))+++type D = Doc ()+++unsupported :: Text -> R a+unsupported = throwError+++-- | A part of a node that must be there.+req :: Text -> Maybe a -> R a+req what = maybe (unsupported (what <> " with a part missing")) pure+++-- | What a check finds, or 'Nothing' where it fails.+attempt :: R a -> R (Maybe a)+attempt m = (Just <$> m) `catchError` \_ -> pure Nothing+++mkEnv :: Bool -> ByteString -> Pg.ScanResult -> Pg.Node -> Env+mkEnv upper sql scan stmt =+ Env+ { toks = IM.fromList (zip [0 ..] ts)+ , byStart = IM.fromList (zip (map (.start) ts) [0 ..])+ , matching = IM.fromList (matchingParens ts)+ , allLocs = IS.fromList (locsNode stmt)+ , upper+ , names = Map.fromListWith (<>) (mapMaybe nameSpelling ts)+ , cmts = IM.fromListWith (flip (++)) (commentsAfter sql scanned)+ , column = 0+ , tightTypes = False+ , blankLineBefore = IS.fromList (blankLinesBefore sql scanned)+ }+ where+ scanned = scan ^. Pg.tokens+ ts = tokens sql scanned+++-- | The statement's tokens, comments left out, numbered from 0 in order.+tokens :: ByteString -> [Pg.ScanToken] -> [Tok]+tokens sql scanned =+ [ Tok+ { start = s+ , text = TE.decodeUtf8Lenient (BS.take (e - s) (BS.drop s sql))+ , kind = t ^. Pg.token+ , isKeyword = t ^. Pg.keywordKind /= Pg.NO_KEYWORD+ , reserved = t ^. Pg.keywordKind == Pg.RESERVED_KEYWORD+ }+ | t <- scanned+ , not (isComment t)+ , let s = fromIntegral (t ^. Pg.start)+ , let e = fromIntegral (t ^. Pg.end)+ ]+++-- | Each parenthesis's index with the other one's, both ways round.+matchingParens :: [Tok] -> [(Int, Int)]+matchingParens = go [] . zip [0 ..]+ where+ go _ [] = []+ go stack ((i, t) : rest)+ | t.text == "(" = go (i : stack) rest+ | t.text == ")", o : stack' <- stack = (o, i) : (i, o) : go stack' rest+ | otherwise = go stack rest+++-- | How the source writes an identifier: quoted, unquoted, or both.+data NameSpelling = NameSpelling+ { quoted :: Bool+ , unquoted :: Bool+ }+++instance Semigroup NameSpelling where+ a <> b = NameSpelling{quoted = a.quoted || b.quoted, unquoted = a.unquoted || b.unquoted}+++-- | The identifier a token spells, case-folded as PostgreSQL does, and how.+nameSpelling :: Tok -> Maybe (Text, NameSpelling)+nameSpelling t+ | t.kind == Pg.IDENT+ , Just q <- T.stripPrefix "\"" t.text =+ Just (T.replace "\"\"" "\"" (T.dropEnd 1 q), NameSpelling{quoted = True, unquoted = False})+ | t.kind == Pg.IDENT || (t.isKeyword && not t.reserved) =+ Just (foldCase t.text, NameSpelling{quoted = False, unquoted = True})+ | otherwise = Nothing+++-- | Each comment with the index of the token before it (-1 before the+-- first), in order.+commentsAfter :: ByteString -> [Pg.ScanToken] -> [(Int, [Cmt])]+commentsAfter sql = go (-1) 0+ where+ go _ _ [] = []+ go prev prevEnd (t : rest)+ | isComment t =+ (prev, [Cmt{ctext = TE.decodeUtf8Lenient (slice sql s e), ownLine = prev < 0 || BS.elem 10 (slice sql prevEnd s), blankBefore = BS.count 10 (slice sql prevEnd s) >= 2}])+ : go prev e rest+ | otherwise = go (prev + 1) e rest+ where+ s = fromIntegral (t ^. Pg.start)+ e = fromIntegral (t ^. Pg.end)+++-- | The index of each token with a blank line directly before it, after the+-- token or comment that precedes it.+blankLinesBefore :: ByteString -> [Pg.ScanToken] -> [Int]+blankLinesBefore sql = go 0 Nothing+ where+ go _ _ [] = []+ go i prevEnd (t : rest)+ | isComment t = go i (Just e) rest+ | otherwise = [i | Just pe <- [prevEnd], BS.count 10 (slice sql pe s) >= 2] ++ go (i + 1) (Just e) rest+ where+ s = fromIntegral (t ^. Pg.start)+ e = fromIntegral (t ^. Pg.end)+++-- | The bytes from @a@ to before @b@.+slice :: ByteString -> Int -> Int -> ByteString+slice sql a b = BS.take (b - a) (BS.drop a sql)+++-- | PostgreSQL folds unquoted identifiers' ASCII letters to lower case.+foldCase :: Text -> Text+foldCase = T.map (\c -> if isAsciiUpper c then toLower c else c)+++tokM :: Int -> R (Maybe Tok)+tokM i = asks (IM.lookup i . (.toks))+++-- | The token's text, lower-cased; empty past either end.+tokL :: Int -> R Text+tokL i = maybe "" (T.toLower . (.text)) <$> tokM i+++tokIs :: Int -> Text -> R Bool+tokIs i t = (== t) <$> tokL i+++-- | The index of the token at a byte offset.+tokAt :: Int -> R Int+tokAt loc = do+ m <- asks (.byStart)+ case IM.lookupLE loc m of+ Just (_, i) -> pure i+ Nothing -> unsupported "a location before the statement"+++matchOf :: Int -> R (Maybe Int)+matchOf i = asks (IM.lookup i . (.matching))+++consume :: Int -> R ()+consume i = modify' \s -> s{consumed = IS.insert i s.consumed}+++isConsumed :: Int -> R Bool+isConsumed i = gets (IS.member i . (.consumed))+++-- | Place the opening parenthesis at this token, which a construct's syntax+-- has there; its closing one's index.+expectParen :: Int -> R Int+expectParen i = do+ isParen <- tokIs i "("+ m <- matchOf i+ case m of+ Just close | isParen -> consume i >> pure close+ _ -> unsupported "a construct without the parenthesis it needs"+++-- | The first opening parenthesis at or after this token.+nextParen :: Int -> R Int+nextParen i = do+ t <- tokM i+ case t of+ Nothing -> unsupported "no parenthesis where one is needed"+ Just tk | tk.text == "(" -> pure i+ _ -> nextParen (i + 1)+++-- | Whether every location strictly between two tokens is one of these.+covers :: Int -> Int -> IS.IntSet -> R Bool+covers p m ls = do+ a <- maybe 0 (.start) <$> tokM p+ b <- maybe maxBound (.start) <$> tokM m+ every <- asks (.allLocs)+ let inside = fst (IS.split b (snd (IS.split a every)))+ pure (inside `IS.isSubsetOf` ls)+++-- | Whether every one of these locations is strictly between two tokens.+allInside :: Int -> Int -> [Int] -> R Bool+allInside p m ls = do+ a <- maybe 0 (.start) <$> tokM p+ b <- maybe maxBound (.start) <$> tokM m+ pure (not (null ls) && all (\l -> l > a && l < b) ls)+++kw :: Text -> R D+kw t = do+ u <- asks (.upper)+ pure (pretty (if u then T.toUpper t else t))+++txt :: Text -> R D+txt = pure . pretty+++-- | Text that may hold line breaks (a string literal), written as it is:+-- 'pretty' would indent its later lines with the layout.+raw :: Text -> D+raw = unsafeTextWithoutNewlines+++commaJoin :: [D] -> D+commaJoin = hcat . punctuate ", "+++spaceJoin :: [D] -> D+spaceJoin = hcat . punctuate " "+++renderToText :: D -> Text+renderToText = renderStrict . layoutPretty layoutOpts+++len :: D -> Int+len = T.length . renderToText+++----------------------------------------------------------------------+-- Nodes.+----------------------------------------------------------------------++node :: Pg.Node -> Maybe Pg.Node'Node+node n = n ^. Pg.maybe'node+++strOf :: Pg.Node -> Maybe Text+strOf n = case node n of+ Just (Pg.Node'String s) -> Just (s ^. Pg.sval)+ _ -> Nothing+++strsOf :: [Pg.Node] -> R [Text]+strsOf = traverse \n -> maybe (unsupported "a name that is not a string") pure (strOf n)+++nodeName :: Pg.Node -> Text+nodeName n = case node n of+ Nothing -> "an empty node"+ Just x -> T.takeWhile (/= ' ') (T.drop 6 (T.pack (show x)))+++firstJustM :: (a -> R (Maybe b)) -> [a] -> R (Maybe b)+firstJustM _ [] = pure Nothing+firstJustM f (x : xs) = f x >>= maybe (firstJustM f xs) (pure . Just)+++anyM :: (a -> R Bool) -> [a] -> R Bool+anyM _ [] = pure False+anyM f (x : xs) = f x >>= \b -> if b then pure True else anyM f xs+++nonEmptyLocs :: [Int] -> R [Int]+nonEmptyLocs ls = if null ls then unsupported "a node without a location" else pure ls
+ src/PgStyle/Layout/Names.hs view
@@ -0,0 +1,294 @@+-- | Identifiers, constants and types.+module PgStyle.Layout.Names where++import Control.Monad (forM, unless, when, zipWithM)+import Control.Monad.Reader (asks)+import Data.Char (isAscii, isAsciiLower, isDigit)+import Data.Map.Strict qualified as Map+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Monad+import Prettyprinter (hcat, pretty, punctuate, (<+>))+++-- | An identifier as the source writes it, quoted or not.+ident :: Text -> R D+ident name = do+ ns <- asks (.names)+ let plain = case T.uncons name of+ Just (c, rest) -> (isAsciiLower c || c == '_') && T.all (\x -> isAsciiLower x || isDigit x || x == '_' || x == '$') rest+ Nothing -> False+ when (T.any (== '"') name) (unsupported "an identifier with a double quote in it")+ case Map.lookup name ns of+ Just NameSpelling{quoted = True, unquoted = False} -> txt ("\"" <> name <> "\"")+ Just NameSpelling{quoted = False, unquoted = True} | plain -> txt name+ Just NameSpelling{quoted = True, unquoted = True} -> unsupported ("identifier " <> name <> " written both quoted and unquoted")+ _ | not plain -> unsupported ("identifier " <> name <> " not found quoted")+ _ -> unsupported ("identifier " <> name <> " not found in the source")+++-- | A dotted name.+qualName :: [Text] -> R D+qualName parts = hcat . punctuate "." <$> traverse ident parts+++-- | An identifier at a known token: written as that token writes it, if it+-- spells the identifier.+identAt :: Int -> Text -> R D+identAt i name = do+ t <- tokM i+ case t of+ Just tk | identText tk == Just name -> txt (if "\"" `T.isPrefixOf` tk.text then "\"" <> name <> "\"" else name)+ -- PostgreSQL cuts a name longer than 63 bytes to 63.+ Just tk+ | Just full <- identText tk+ , not ("\"" `T.isPrefixOf` tk.text)+ , T.all isAscii full+ , T.length full > 63+ , T.take 63 full == name ->+ txt full+ _ -> ident name+++-- | A dotted name starting at a known token.+qualNameAt :: Int -> [Text] -> R D+qualNameAt i parts = hcat . punctuate "." <$> zipWithM (\k p -> identAt (i + 2 * k) p) [0 ..] parts+++-- | Rendering modes for expressions. 'MR' is "PgStyle.Render"'s own+-- @renderExpr@; 'MP' is postgresql-syntax's renderer, lower-cased, which+-- "PgStyle.Render" uses for the nodes it does not lay out itself; 'MB' is+-- "PgStyle.Render"'s @renderBExpr@, for the lower bound of a @between@.+data Mode = MR | MB | MP+ deriving stock (Eq)+++aConst :: Mode -> Pg.A_Const -> R D+aConst mode c = do+ i <- tokAt (fromIntegral (c ^. Pg.location))+ t <- tokM i+ let source = maybe "" (.text) t+ case c ^. Pg.maybe'val of+ _ | c ^. Pg.isnull -> kw "null"+ Nothing -> kw "null"+ Just (Pg.A_Const'Ival v) -> number (fromIntegral (v ^. Pg.ival) :: Integer) i source+ Just (Pg.A_Const'Fval v) -> do+ let s = v ^. Pg.fval+ case T.stripPrefix "-" s of+ Just _ | source == "-" -> do+ digits <- tokL (i + 1)+ pure (minus <> pretty (normalNumber digits))+ _ -> pure (pretty (normalNumber (T.toLower source)))+ Just (Pg.A_Const'Boolval v) -> kw (if v ^. Pg.boolval then "true" else "false")+ Just (Pg.A_Const'Sval v) -> stringConst (v ^. Pg.sval) source+ Just (Pg.A_Const'Bsval v) -> do+ let b = v ^. Pg.bsval+ pure (pretty (T.toLower (T.take 1 b)) <> "'" <> pretty (T.drop 1 b) <> "'")+ where+ minus = if mode == MP then "- " else "-"+ number v i source+ | v < 0+ , source == "-" = do+ digits <- tokL (i + 1)+ pure (minus <> pretty (if T.all isDigit digits then T.pack (show (negate v)) else digits))+ | T.all isDigit source = txt (T.pack (show v))+ | otherwise = txt (T.toLower source)+ -- postgresql-syntax reads integers that do not fit an int4 as integers+ -- too, without leading zeros.+ normalNumber s+ | not (T.null s), T.all isDigit s = T.pack (show (read (T.unpack s) :: Integer))+ | otherwise = s+++-- | A string constant: a plain one as postgresql-syntax writes it (which+-- joins a string continued over lines into one); any other kind+-- (dollar-quoted, @E'...'@) as written.+stringConst :: Text -> Text -> R D+stringConst value source+ | "'" `T.isPrefixOf` source = pure (raw ("'" <> T.replace "'" "''" value <> "'"))+ | otherwise = pure (raw source)+++-- | A type name, as postgresql-syntax spells it: SQL's own type names are+-- keywords, written with a space before their modifiers (@numeric (10, 2)@);+-- any other is a name.+typeName :: Pg.TypeName -> R D+typeName tn = do+ when (tn ^. Pg.setof || tn ^. Pg.pctType) (unsupported "setof or %type")+ i <- tokAt (fromIntegral (tn ^. Pg.location))+ (d, next) <- typeWords False i+ arr <- arrayBounds next (length (tn ^. Pg.arrayBounds))+ pure (d <> arr)+++-- | The words of a type starting at this token, and the token after them.+-- In a typed literal (@date '...'@), a type that is not one of SQL's has no+-- space before its modifiers.+typeWords :: Bool -> Int -> R (D, Int)+typeWords literal i = do+ w <- tokL i+ w1 <- tokL (i + 1)+ w2 <- tokL (i + 2)+ let fixed n words' = do+ d <- kw (T.unwords words')+ pure (d, i + n)+ case w of+ "interval" -> do+ -- @interval (p)@+ isParen <- tokIs (i + 1) "("+ if isParen && not literal+ then do+ (args, next) <- modifiers (i + 1)+ d <- kw "interval"+ sep <- modifierSep+ pure (d <> sep <> args, next)+ else do+ d <- kw "interval"+ (fields, next) <- intervalFields (i + 1)+ pure (maybe d (\f -> d <> " " <> f) fields, next)+ _ | w `elem` ["timestamp", "time"] -> do+ d <- kw w+ isParen <- tokIs (i + 1) "("+ (precision, j) <- if isParen then (\(a, n) -> (Just a, n)) <$> modifiers (i + 1) else pure (Nothing, i + 1)+ a <- tokL j+ b <- tokL (j + 1)+ c <- tokL (j + 2)+ zone <-+ if a `elem` ["with", "without"] && b == "time" && c == "zone"+ then Just <$> kw (T.unwords [a, b, c])+ else pure Nothing+ sep <- modifierSep+ pure ((d <> maybe mempty (sep <>) precision) <> maybe mempty (" " <>) zone, if isJust zone then j + 3 else j)+ _ | w `elem` ["integer", "int", "smallint", "bigint", "real", "boolean"] -> fixed 1 [w]+ "double" | w1 == "precision" -> fixed 2 [w, w1]+ _ | w `elem` ["float", "decimal", "dec", "numeric"] -> withModifiers 1 [w]+ "bit" | w1 == "varying" -> withModifiers 2 [w, w1]+ "bit" -> withModifiers 1 [w]+ _ | w `elem` ["character", "char", "nchar"], w1 == "varying" -> withModifiers 2 [w, w1]+ _ | w `elem` ["character", "char", "nchar", "varchar"] -> withModifiers 1 [w]+ "national" | w1 `elem` ["character", "char"], w2 == "varying" -> withModifiers 3 [w, w1, w2]+ "national" | w1 `elem` ["character", "char"] -> withModifiers 2 [w, w1]+ _ -> do+ -- A name, maybe qualified, maybe with modifiers.+ (parts, j) <- dotted i+ name <- qualName parts+ isParen <- tokIs j "("+ if isParen+ then do+ (args, next) <- modifiers j+ sep <- modifierSep+ pure (name <> (if literal then mempty else sep) <> args, next)+ else pure (name, j)+ where+ withModifiers n words' = do+ d <- kw (T.unwords words')+ isParen <- tokIs (i + n) "("+ if isParen+ then do+ (args, next) <- modifiers (i + n)+ sep <- modifierSep+ pure (d <> sep <> args, next)+ else pure (d, i + n)+ dotted j = do+ t <- tokM j+ case t of+ Just tk | tk.kind == Pg.IDENT || tk.isKeyword -> do+ let part = if "\"" `T.isPrefixOf` tk.text then T.replace "\"\"" "\"" (T.drop 1 (T.dropEnd 1 tk.text)) else foldCase tk.text+ isDot <- tokIs (j + 1) "."+ if isDot+ then do+ (rest, k) <- dotted (j + 2)+ pure (part : rest, k)+ else pure ([part], j + 1)+ _ -> unsupported "a type name pgstyle cannot read"+++-- | What goes between a type and its modifiers.+modifierSep :: R D+modifierSep = asks \env -> if env.tightTypes then mempty else " "+++-- | A type's modifiers, @(10, 2)@, from the parenthesis at this token: the+-- rendered list and the token after it.+modifiers :: Int -> R (D, Int)+modifiers i = do+ close <- expectParen i+ items <- forM [i + 1 .. close - 1] \j -> do+ t <- tokM j+ case t of+ Just tk+ | tk.text == "," -> pure ", "+ | tk.kind `elem` [Pg.ICONST, Pg.FCONST] -> pure (pretty (T.toLower tk.text))+ | tk.kind == Pg.IDENT || tk.isKeyword -> ident (if "\"" `T.isPrefixOf` tk.text then T.drop 1 (T.dropEnd 1 tk.text) else foldCase tk.text)+ _ -> unsupported "a type modifier pgstyle cannot read"+ pure ("(" <> mconcat items <> ")", close + 1)+++-- | @year@, @day to second@, @second (3)@ after @interval@.+intervalFields :: Int -> R (Maybe D, Int)+intervalFields i = do+ w <- tokL i+ if w `notElem` ["year", "month", "day", "hour", "minute", "second"]+ then pure (Nothing, i)+ else do+ (first, j) <- field w i+ to <- tokL j+ if to == "to"+ then do+ w' <- tokL (j + 1)+ (second, k) <- field w' (j + 1)+ toD <- kw "to"+ pure (Just (first <+> toD <+> second), k)+ else pure (Just first, j)+ where+ field w j = do+ d <- kw w+ isParen <- tokIs (j + 1) "("+ if w == "second" && isParen+ then do+ (p, next) <- modifiers (j + 1)+ pure (d <> " " <> p, next)+ else pure (d, j + 1)+++-- | Array bounds after a type: @[]@, @[3]@, or @array@, @array[3]@.+arrayBounds :: Int -> Int -> R D+arrayBounds _ 0 = pure mempty+arrayBounds i n = do+ w <- tokL i+ if w == "array"+ then do+ d <- kw "array"+ isBracket <- tokIs (i + 1) "["+ if isBracket+ then do+ size <- tokL (i + 2)+ pure (" " <> d <> "[" <> pretty size <> "]")+ else pure (" " <> d)+ else do+ dims <- go i n+ pure (spaceJoin dims)+ where+ go _ 0 = pure []+ go j k = do+ isBracket <- tokIs j "["+ unless isBracket (unsupported "array bounds pgstyle cannot read")+ close <- tokIs (j + 1) "]"+ if close+ then ("[]" :) <$> go (j + 2) (k - 1)+ else do+ size <- tokL (j + 1)+ ("[" <> pretty size <> "]" :) <$> go (j + 3) (k - 1)+++----------------------------------------------------------------------++-- | The identifier a token spells, if it is one.+identText :: Tok -> Maybe Text+identText tk+ | tk.kind == Pg.IDENT, Just q <- T.stripPrefix "\"" tk.text = Just (T.replace "\"\"" "\"" (T.dropEnd 1 q))+ | tk.kind == Pg.IDENT || tk.isKeyword = Just (foldCase tk.text)+ | otherwise = Nothing
+ src/PgStyle/Layout/Parens.hs view
@@ -0,0 +1,152 @@+-- | Expressions and subqueries where they occur, and the parentheses the+-- source has around them.+module PgStyle.Layout.Parens where++import Control.Monad (unless, when)+import Data.IntSet qualified as IS+import Data.Maybe (fromMaybe, isNothing)+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.Layout.Locations+import PgStyle.Layout.Monad+++-- | An expression where it occurs: its node, the parentheses the source has+-- around it, and its parent expression (for telling whose parentheses are+-- whose).+data E = E+ { en :: Pg.Node+ , lv :: Int+ , parent :: Maybe Pg.Node+ }+++-- | A child expression of an expression.+child :: Pg.Node -> Pg.Node -> R E+child p n = mkE (Just p) n+++-- | An expression with no expression around it.+top :: Pg.Node -> R E+top = mkE Nothing+++mkE :: Maybe Pg.Node -> Pg.Node -> R E+mkE parent n = do+ let ls = locsNode n+ lv <-+ if null ls+ then pure 0+ else case node n of+ Just (Pg.Node'AIndirection ind) -> remembered AroundIndirection ls (indirectionLevels ind (IS.fromList ls))+ _ -> remembered AroundExpr ls do+ s0 <- tokAt (minimum ls)+ e0 <- tokAt (maximum ls)+ levels s0 e0 (IS.fromList ls) (parentTakes parent)+ pure E{en = n, lv, parent}+++-- | Whether a parenthesis pair is the parent expression's rather than the+-- child's: the parent lies wholly inside it.+parentTakes :: Maybe Pg.Node -> Int -> Int -> R Bool+parentTakes parent p m = case parent of+ Nothing -> pure False+ Just pn -> case node pn of+ -- An indirection's own parentheses are placed before its argument's.+ Just (Pg.Node'AIndirection _) -> pure False+ _ -> allInside p m (locsNode pn)+++-- | How many parenthesis pairs wrap exactly the node spanning these tokens+-- (from its first located token to its last), placing them.+levels :: Int -> Int -> IS.IntSet -> (Int -> Int -> R Bool) -> R Int+levels s0 e0 ls takes = do+ s <- extendLeft s0+ go s e0 0+ where+ -- Parentheses inside the node that open before its first located token,+ -- as in @(a) + b@.+ extendLeft s = do+ isParen <- tokIs (s - 1) "("+ m <- matchOf (s - 1)+ case m of+ Just close | isParen, close <= e0 -> extendLeft (s - 1)+ _ -> pure s+ go s e n = do+ let p = s - 1+ isParen <- tokIs p "("+ placed <- isConsumed p+ mm <- matchOf p+ case mm of+ Just m+ | isParen+ , not placed+ , m > e -> do+ cov <- covers p m ls+ theirs <- takes p m+ if cov && not theirs+ then consume p >> go p m (n + 1)+ else pure n+ _ -> pure n+++-- | An indirection's parentheses: @((a).b)@ has one around the indirection+-- and one around its argument; work out where the argument ends.+indirectionLevels :: Pg.A_Indirection -> IS.IntSet -> R Int+indirectionLevels ind ls = do+ arg <- maybe (unsupported "an indirection without an argument") pure (ind ^. Pg.maybe'arg)+ let als = locsNode arg+ when (null als) (unsupported "an indirection without a location")+ s0 <- tokAt (minimum als)+ (start, argEnd) <- case node arg of+ Just (Pg.Node'ParamRef _) -> pure (s0, s0)+ Just (Pg.Node'ColumnRef c) -> pure (s0, s0 + 2 * length (c ^. Pg.fields) - 2)+ _ -> do+ -- The outermost of the parentheses before the argument whose+ -- closing one the indirection follows.+ let walk p best = do+ isParen <- tokIs p "("+ if not isParen+ then pure best+ else do+ m <- matchOf p+ next <- maybe (pure "") (\c -> tokL (c + 1)) m+ walk (p - 1) (if next `elem` [".", "["] then (p, fromMaybe p m) <$ m else best)+ found <- walk (s0 - 1) Nothing+ case node arg of+ Just (Pg.Node'SubLink sl) | isNothing found -> do+ o <- tokAt (fromIntegral (sl ^. Pg.location))+ c <- matchOf o+ maybe (unsupported "a subquery without parentheses") (\c' -> pure (o, c')) c+ _ -> maybe (unsupported "an indirection on an expression without parentheses") pure found+ end <- indirectionEnd (argEnd + 1) (ind ^. Pg.indirection)+ levels start end ls (\_ _ -> pure False)+++-- | The last token of an indirection starting at this token.+indirectionEnd :: Int -> [Pg.Node] -> R Int+indirectionEnd i [] = pure (i - 1)+indirectionEnd i (el : rest) = case node el of+ Just (Pg.Node'AIndices _) -> do+ isBracket <- tokIs i "["+ unless isBracket (unsupported "a subscript without brackets")+ close <- bracketEnd (i + 1) (0 :: Int)+ indirectionEnd (close + 1) rest+ _ -> indirectionEnd (i + 2) rest+ where+ bracketEnd j depth = do+ t <- tokM j+ case (.text) <$> t of+ Nothing -> unsupported "an unclosed subscript"+ Just "]" | depth == 0 -> pure j+ Just "]" -> bracketEnd (j + 1) (depth - 1)+ Just "[" -> bracketEnd (j + 1) (depth + 1)+ _ -> bracketEnd (j + 1) depth+++-- | A subquery: the select, and how many parentheses the source has around+-- it (at least one).+data Sel = Sel+ { stmt :: Pg.SelectStmt+ , parens :: Int+ }
+ src/PgStyle/LibPgQuery.hs view
@@ -0,0 +1,252 @@+-- | The libpg_query calls pgstyle needs that the @libpg-query@ package does not+-- expose: parsing and scanning bytes rather than a 'String' (so statement+-- locations are byte offsets into exactly what we passed), and pretty-printed+-- deparsing with the source's comments put back.+--+-- The C side is @cbits/pgstyle.c@.+module PgStyle.LibPgQuery (+ LibPgQueryError (..),+ parse,+ parsePlpgsql,+ scan,+ deparse,+ PrettyOptions (..),+ defaultPrettyOptions,+ deparsePretty,+ Statement (..),+ statements,+ Token (..),+ tokens,+ canonical,+) where++import Control.Exception (finally, mask_)+import Data.Aeson (Value (..))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Data.Foldable (toList)+import Data.ProtoLens (Message, decodeMessage, encodeMessage)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.Encoding.Error qualified as TE+import Foreign (Ptr, alloca, free, nullPtr, peek, poke)+import Foreign.C (CInt (..), CSize (..), CString)+import Lens.Micro ((^.))+import PgQuery qualified as Pg+++-- | An error libpg_query reported. @cursor@ is the 1-based byte position in+-- the input, or 0 when it gave none.+data LibPgQueryError = LibPgQueryError+ { message :: Text+ , cursor :: Int+ }+ deriving stock (Eq, Show)+++type Out = Ptr CString -> Ptr CSize -> Ptr CInt -> IO CInt+++foreign import ccall safe "pgstyle_parse"+ c_parse :: CString -> Out+++foreign import ccall safe "pgstyle_parse_json"+ c_parse_json :: CString -> Out+++foreign import ccall safe "pgstyle_parse_plpgsql"+ c_parse_plpgsql :: CString -> Out+++foreign import ccall safe "pgstyle_scan"+ c_scan :: CString -> Out+++foreign import ccall safe "pgstyle_deparse"+ c_deparse :: CString -> CSize -> CInt -> CInt -> CInt -> CString -> Out+++-- | Run a shim call and take ownership of the buffer it hands back.+runOut :: Out -> IO (Either LibPgQueryError ByteString)+runOut call =+ alloca \pOut -> alloca \pLen -> alloca \pCursor -> do+ poke pOut nullPtr+ -- Masked from the call until the buffer is copied and freed, so an+ -- asynchronous exception cannot leave it allocated.+ (rc, bytes, cur) <- mask_ do+ rc <- call pOut pLen pCursor+ buf <- peek pOut+ len <- peek pLen+ cur <- peek pCursor+ bytes <-+ if buf == nullPtr+ then pure BS.empty+ else BS.packCStringLen (buf, fromIntegral len) `finally` free buf+ pure (rc, bytes, cur)+ pure+ if rc == 0+ then Right bytes+ else Left LibPgQueryError{message = decodeUtf8 bytes, cursor = fromIntegral cur}+++-- | A NUL-terminated copy of the input. libpg_query reads C strings, so a NUL+-- inside the input would end it early; SQL cannot contain one anyway.+withSql :: ByteString -> (CString -> IO a) -> IO a+withSql sql = BS.useAsCString sql+++decodeProto :: Message msg => Either LibPgQueryError ByteString -> Either LibPgQueryError msg+decodeProto = \case+ Left err -> Left err+ Right bytes -> case decodeMessage bytes of+ Left err -> Left LibPgQueryError{message = "protobuf: " <> T.pack err, cursor = 0}+ Right msg -> Right msg+++-- | PostgreSQL's parse tree of UTF-8 SQL.+parse :: ByteString -> IO (Either LibPgQueryError Pg.ParseResult)+parse sql = decodeProto <$> withSql sql (runOut . c_parse)+++-- | libpg_query's JSON for the PL/pgSQL functions UTF-8 SQL creates: an+-- array with one @PLpgSQL_function@ per function, empty when it creates none.+parsePlpgsql :: ByteString -> IO (Either LibPgQueryError ByteString)+parsePlpgsql sql = withSql sql (runOut . c_parse_plpgsql)+++-- | PostgreSQL's token stream of UTF-8 SQL, comments included.+scan :: ByteString -> IO (Either LibPgQueryError Pg.ScanResult)+scan sql = decodeProto <$> withSql sql (runOut . c_scan)+++-- | Compact SQL for a parse tree: libpg_query's normal form, one line per+-- statement.+deparse :: Pg.ParseResult -> IO (Either LibPgQueryError Text)+deparse tree =+ fmap decodeUtf8+ <$> unsafeUseAsCStringLen (encodeMessage tree) \(ptr, len) ->+ runOut (c_deparse ptr (fromIntegral len) 0 0 0 nullPtr)+++-- | libpg_query's pretty-printer settings.+data PrettyOptions = PrettyOptions+ { indentSize :: Int+ , maxLineLength :: Int+ }+ deriving stock (Eq, Show)+++defaultPrettyOptions :: PrettyOptions+defaultPrettyOptions = PrettyOptions{indentSize = 4, maxLineLength = 80}+++-- | Pretty-printed SQL for a parse tree. With the source the tree was parsed+-- from, its comments are put back where they were.+deparsePretty :: PrettyOptions -> Maybe ByteString -> Pg.ParseResult -> IO (Either LibPgQueryError Text)+deparsePretty opts commentSource tree =+ fmap decodeUtf8 <$> unsafeUseAsCStringLen (encodeMessage tree) \(ptr, len) ->+ let call src =+ runOut+ ( c_deparse+ ptr+ (fromIntegral len)+ 1+ (fromIntegral opts.indentSize)+ (fromIntegral opts.maxLineLength)+ src+ )+ in case commentSource of+ Nothing -> call nullPtr+ Just source -> withSql source call+++-- | One top-level statement of a parsed source, as byte offsets into it.+-- @end@ is exclusive and stops before the terminating semicolon. The span+-- starts right after the previous statement's semicolon, so it includes the+-- whitespace and comments in front of the statement.+data Statement = Statement+ { start :: Int+ , end :: Int+ , raw :: Pg.RawStmt+ }+++statements :: ByteString -> Pg.ParseResult -> [Statement]+statements source tree = map toStatement (tree ^. Pg.stmts)+ where+ toStatement raw =+ let start = fromIntegral (raw ^. Pg.stmtLocation)+ len = fromIntegral (raw ^. Pg.stmtLen)+ -- 0 means "to the end of the input": the last statement, with no+ -- semicolon after it.+ end = if len == 0 then BS.length source else start + len+ in Statement{start, end, raw}+++-- | A token of the source, as byte offsets into it, end exclusive.+data Token = Token+ { start :: Int+ , end :: Int+ , isComment :: Bool+ , isKeyword :: Bool+ -- ^ Spelled like a keyword. Unreserved keywords can also be identifiers+ -- (@name@, @type@), which the scanner cannot tell apart.+ }+ deriving stock (Eq, Show)+++tokens :: Pg.ScanResult -> [Token]+tokens result =+ [ Token+ { start = fromIntegral (t ^. Pg.start)+ , end = fromIntegral (t ^. Pg.end)+ , isComment = t ^. Pg.token `elem` [Pg.SQL_COMMENT, Pg.C_COMMENT]+ , isKeyword = t ^. Pg.keywordKind /= Pg.NO_KEYWORD+ }+ | t <- result ^. Pg.tokens+ ]+++-- | The normal form of each statement in UTF-8 SQL: its parse tree, from+-- libpg_query's JSON output, with every source position removed: @location@+-- and @name_location@, @stmt_location@ and @stmt_len@, and where a list's+-- brackets are (@list_start@, @list_end@, and @rexpr_list_start@ and+-- @rexpr_list_end@ for @IN@ lists). Two statements with the same+-- normal form are the same statement to PostgreSQL, however they are laid out.+--+-- This compares trees, not text: two trees the deparser happens to write the+-- same way still count as different. libpg_query 18 leaves empty strings out+-- of its trees, so @comment on t is ''@ and @comment on t is null@ are the+-- same tree to it; PostgreSQL treats them the same too.+canonical :: ByteString -> IO (Either LibPgQueryError [Value])+canonical sql = do+ json <- withSql sql (runOut . c_parse_json)+ pure do+ bytes <- json+ case Aeson.eitherDecodeStrict bytes of+ Left err -> Left LibPgQueryError{message = "libpg_query's JSON does not decode: " <> T.pack err, cursor = 0}+ Right v -> Right (statementsOf v)+ where+ statementsOf = \case+ Object o | Just (Array xs) <- KeyMap.lookup "stmts" o -> map withoutPositions (toList xs)+ _ -> []+ withoutPositions = \case+ Object o -> Object (KeyMap.map withoutPositions (KeyMap.filterWithKey (\k _ -> not (isPosition (Key.toText k))) o))+ Array xs -> Array (fmap withoutPositions xs)+ v -> v+ isPosition k =+ k == "location"+ || "_location" `T.isSuffixOf` k+ || k == "stmt_len"+ || "list_start" `T.isSuffixOf` k+ || "list_end" `T.isSuffixOf` k+++decodeUtf8 :: ByteString -> Text+decodeUtf8 = TE.decodeUtf8With TE.lenientDecode
+ src/PgStyle/Plpgsql.hs view
@@ -0,0 +1,340 @@+-- | The SQL statements inside PL/pgSQL function bodies.+--+-- To PostgreSQL's SQL parser a function body is one string constant, so the+-- file-level pass leaves it byte for byte. This pass parses the body as+-- PL/pgSQL (libpg_query's @pg_query_parse_plpgsql@) and lays out the plain SQL+-- statements in it: statements run for their effect+-- (@PLpgSQL_stmt_execsql@) and @RETURN QUERY@. The PL/pgSQL around them+-- (@DECLARE@, @IF@, loops, assignments) is left as it is, as are statements+-- with an @INTO@ clause (PL/pgSQL takes it out of the query text, so the+-- query is no longer what the source says).+--+-- libpg_query gives each statement's line within the body and its source+-- text, so a statement is found by searching for its text from the start of+-- its line.+--+-- The result is checked on its own: the function's PL/pgSQL parse before and+-- after must match once line numbers are dropped and every embedded query is+-- replaced by its normal form.+module PgStyle.Plpgsql (+ formatBodies,+) where++import Data.Aeson (Value (..))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BC+import Data.Foldable (toList)+import Data.List (sortOn)+import Data.Maybe (mapMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Lens.Micro ((^.))+import PgQuery qualified as Pg+import PgStyle.LibPgQuery (Token (..))+import PgStyle.LibPgQuery qualified as LibPgQuery+++-- | An embedded statement to lay out: its line within the body (1 is the line+-- the body starts on) and its text.+data Target = Target+ { lineNo :: Int+ , query :: ByteString+ }+++-- | Lay out the SQL statements in a statement's PL/pgSQL function body.+--+-- The callback lays out one embedded statement, given the column its line is+-- indented to: 'Right' 'Nothing' leaves it as it is, 'Left' is a formatter+-- bug. The result is the statement with its new body, 'Nothing' when nothing+-- changed (or the statement is not a PL/pgSQL function), or 'Left' why the+-- new body was refused.+--+-- Three checks guard the new body: the statement must still parse to the+-- same tree apart from the body string; the body's PL/pgSQL parse must match+-- once line numbers are dropped and queries are compared by normal form; and+-- the body's comments must be the same, in the same order (PL/pgSQL's parse+-- drops them, so the second check cannot see them).+formatBodies ::+ (Int -> ByteString -> IO (Either Text (Maybe Text))) ->+ ByteString ->+ Pg.RawStmt ->+ IO (Either Text (Maybe ByteString))+formatBodies layOut stmt raw = case functionBody raw of+ Nothing -> pure (Right Nothing)+ Just bodyText -> do+ parsed <- LibPgQuery.parsePlpgsql stmt+ range <- bodyRange stmt (TE.encodeUtf8 bodyText)+ case (parsed >>= decodeJson, range) of+ (Right [fn], Just (bodyStart, bodyEnd)) -> do+ let body = slice bodyStart bodyEnd stmt+ formatted <- formatQueries layOut body fn+ case formatted of+ Left reason -> pure (Left reason)+ Right Nothing -> pure (Right Nothing)+ Right (Just newBody) -> do+ let newStmt = BS.take bodyStart stmt <> newBody <> BS.drop bodyEnd stmt+ problem <- bodyProblem stmt newStmt body newBody+ pure case problem of+ Nothing -> Right (Just newStmt)+ Just reason -> Left ("PL/pgSQL body: " <> reason)+ -- One libpg_query cannot compile, or a body this pass cannot find:+ -- leave it.+ _ -> pure (Right Nothing)+++-- | A body with each of its function's queries laid out: 'Nothing' when+-- none changes or the body does not scan, 'Left' when laying one out+-- fails.+formatQueries ::+ (Int -> ByteString -> IO (Either Text (Maybe Text))) ->+ ByteString ->+ Value ->+ IO (Either Text (Maybe ByteString))+formatQueries layOut body fn = do+ bodyScan <- LibPgQuery.scan body+ case bodyScan of+ Left _ -> pure (Right Nothing)+ Right scanResult -> do+ let located = locateAll body (LibPgQuery.tokens scanResult) (targets fn)+ laidOut <- traverse layOutQuery located+ pure case sequence laidOut of+ Left reason -> Left reason+ Right edits -> case [e | Just e <- edits] of+ [] -> Right Nothing+ changes -> Right (Just (splice body changes))+ where+ layOutQuery q = do+ result <- layOut q.indent (slice q.start q.end body)+ pure case result of+ Left reason -> Left reason+ Right Nothing -> Right Nothing+ Right (Just new)+ | TE.encodeUtf8 new == slice q.start q.end body -> Right Nothing+ | otherwise -> Right (Just Edit{start = q.start, end = q.end, text = TE.encodeUtf8 new})+++-- | Why a statement with a rewritten body is not the same function, if it+-- is not: text outside the body changed, the PL/pgSQL parse differs, or+-- the comments do. All three are checked; the first problem is reported.+bodyProblem :: ByteString -> ByteString -> ByteString -> ByteString -> IO (Maybe Text)+bodyProblem stmt newStmt body newBody = do+ checks <-+ sequence+ [ sameOutsideBody stmt newStmt+ , samePlpgsql stmt newStmt+ , sameComments body newBody+ ]+ pure case [r | Just r <- checks] of+ [] -> Nothing+ reason : _ -> Just reason+++decodeJson :: ByteString -> Either LibPgQuery.LibPgQueryError [Value]+decodeJson bytes = case Aeson.eitherDecodeStrict bytes of+ Right (Array fns) -> Right (toList fns)+ Right _ -> Left LibPgQuery.LibPgQueryError{message = "PL/pgSQL JSON is not an array", cursor = 0}+ Left err -> Left LibPgQuery.LibPgQueryError{message = T.pack err, cursor = 0}+++-- | The body of a @CREATE FUNCTION@: the one string of its @AS@ clause.+functionBody :: Pg.RawStmt -> Maybe Text+functionBody raw = do+ cfs <- raw ^. Pg.stmt . Pg.maybe'createFunctionStmt+ [item] <- Just (concatMap asItems (cfs ^. Pg.options))+ str <- item ^. Pg.maybe'string+ Just (str ^. Pg.sval)+ where+ asItems o = case o ^. Pg.maybe'defElem of+ Just d | d ^. Pg.defname == "as", Just l <- d ^. Pg.arg . Pg.maybe'list -> l ^. Pg.items+ _ -> []+++-- | The byte range of the function body: the inside of the one dollar-quoted+-- string of the statement whose contents are exactly the body. A body in+-- single quotes, or a dollar-quoted argument default or @SET@ value spelled+-- the same as the body, is not handled.+bodyRange :: ByteString -> ByteString -> IO (Maybe (Int, Int))+bodyRange stmt body = do+ scanned <- LibPgQuery.scan stmt+ pure case scanned of+ Right result+ | [r] <- mapMaybe inner (LibPgQuery.tokens result)+ , uncurry slice r stmt == body ->+ Just r+ _ -> Nothing+ where+ -- The inside of a dollar-quoted string token: @$tag$...$tag$@.+ inner t+ | t.isComment = Nothing+ | BS.take 1 (BS.drop t.start stmt) /= "$" = Nothing+ | BS.take 1 (BS.drop (t.end - 1) stmt) /= "$" = Nothing+ | t.end - t.start < 4 = Nothing+ | otherwise = do+ tagEnd <- BS.elemIndex 36 (BS.drop (t.start + 1) stmt)+ let tagLen = tagEnd + 2+ if t.start + tagLen <= t.end - tagLen+ then Just (t.start + tagLen, t.end - tagLen)+ else Nothing+++-- | 'Nothing' when the new statement is the old one with only its body+-- changed: their normal forms match once every @AS@ clause is left out.+sameOutsideBody :: ByteString -> ByteString -> IO (Maybe Text)+sameOutsideBody oldStmt newStmt = do+ before <- LibPgQuery.canonical oldStmt+ after <- LibPgQuery.canonical newStmt+ pure case (before, after) of+ (Right [b], Right [a])+ | withoutBody a == withoutBody b -> Nothing+ | otherwise -> Just "the statement changed outside its body"+ _ -> Just "the statement does not parse"+ where+ withoutBody = \case+ Object o+ | Just (String "as") <- KeyMap.lookup "defname" o -> Object (KeyMap.delete "arg" o)+ | otherwise -> Object (KeyMap.map withoutBody o)+ Array xs -> Array (fmap withoutBody xs)+ v -> v+++-- | 'Nothing' when both bodies hold the same comments in the same order.+sameComments :: ByteString -> ByteString -> IO (Maybe Text)+sameComments before after = do+ a <- comments before+ b <- comments after+ pure if a == b && a /= Nothing then Nothing else Just "comments changed"+ where+ comments bytes = do+ scanned <- LibPgQuery.scan bytes+ pure case scanned of+ Right r -> Just [slice t.start t.end bytes | t <- LibPgQuery.tokens r, t.isComment]+ Left _ -> Nothing+++-- | The statements of a function to lay out.+targets :: Value -> [Target]+targets = go+ where+ go = \case+ Object o ->+ let here = case (KeyMap.lookup "PLpgSQL_stmt_execsql" o, KeyMap.lookup "PLpgSQL_stmt_return_query" o) of+ (Just (Object s), _)+ | KeyMap.lookup "into" s /= Just (Bool True) ->+ target s (field "sqlstmt" s)+ (_, Just (Object s)) -> target s (field "query" s)+ _ -> []+ in here <> concatMap go (KeyMap.elems o)+ Array xs -> concatMap go (toList xs)+ _ -> []+ field k s = KeyMap.lookup (Key.fromText k) s+ target s expr = case (KeyMap.lookup "lineno" s, expr >>= exprQuery) of+ (Just (Number n), Just q) -> [Target{lineNo = round n, query = TE.encodeUtf8 q}]+ _ -> []+ exprQuery = \case+ Object e | Just (Object x) <- KeyMap.lookup "PLpgSQL_expr" e, Just (String q) <- KeyMap.lookup "query" x -> Just q+ _ -> Nothing+++-- | Where each target's text is in the body, and the indentation of the line+-- it starts on. A match must start and end on token boundaries of the body,+-- outside comments and strings, and not overlap an earlier match; the first+-- such occurrence from the start of the target's line is taken. Targets with+-- no such occurrence are left out.+locateAll :: ByteString -> [Token] -> [Target] -> [Located]+locateAll body toks = go []+ where+ starts = [t.start | t <- toks, not t.isComment]+ ends = [t.end | t <- toks, not t.isComment]+ lineStarts = 0 : map (+ 1) (BS.elemIndices 10 body)+ nthLineStart n+ | n >= 1, (s : _) <- drop (n - 1) lineStarts = Just s+ | otherwise = Nothing+ go _ [] = []+ go used (t : ts) = case nthLineStart t.lineNo >>= \from -> firstMatch used t.query from of+ Just m -> m : go ((m.start, m.end) : used) ts+ Nothing -> go used ts+ firstMatch used q from+ | BS.null q = Nothing+ | otherwise =+ let (before, rest) = BS.breakSubstring q (BS.drop from body)+ start = from + BS.length before+ end = start + BS.length q+ in if BS.null rest+ then Nothing+ else+ if start `elem` starts+ && end `elem` ends+ && not (any (\(s, e) -> start < e && s < end) used)+ then Just Located{start, end, indent = indentOf start}+ else firstMatch used q (start + 1)+ indentOf start =+ let startOfLine = maybe 0 (+ 1) (BS.elemIndexEnd 10 (BS.take start body))+ in BS.length (BC.takeWhile (== ' ') (BS.drop startOfLine body))+++-- | Where a query is in a body: its byte range, and the indentation of the+-- line it starts on.+data Located = Located+ { start :: Int+ , end :: Int+ , indent :: Int+ }+++-- | A byte range of a body, and its new text.+data Edit = Edit+ { start :: Int+ , end :: Int+ , text :: ByteString+ }+++-- | Replace byte ranges of the body, in order.+splice :: ByteString -> [Edit] -> ByteString+splice body changes = BS.concat (go 0 (sortOn (.start) changes))+ where+ go pos [] = [BS.drop pos body]+ go pos (c : rest) = slice pos c.start body : c.text : go c.end rest+++-- | 'Nothing' when both statements' PL/pgSQL parses match once line numbers+-- are dropped and every query is replaced by its normal form.+samePlpgsql :: ByteString -> ByteString -> IO (Maybe Text)+samePlpgsql before after = do+ a <- LibPgQuery.parsePlpgsql before+ b <- LibPgQuery.parsePlpgsql after+ case (a >>= decodeJson, b >>= decodeJson) of+ (Right fa, Right fb) -> do+ na <- traverse normalise fa+ nb <- traverse normalise fb+ pure if na == nb then Nothing else Just "the formatted body is a different function"+ (_, Left err) -> pure (Just ("the formatted body does not parse: " <> err.message))+ (Left err, _) -> pure (Just ("the original body does not parse: " <> err.message))+++normalise :: Value -> IO Value+normalise = \case+ Object o -> Object <$> KeyMap.traverseWithKey step (KeyMap.delete "lineno" o)+ Array xs -> Array <$> traverse normalise xs+ v -> pure v+ where+ step k v+ | k == "query", String q <- v = normalForm q+ | otherwise = normalise v+ -- A query that parses as SQL compares by its normal form; anything else+ -- (an expression such as @v > 1@) compares as written.+ normalForm q = do+ parsed <- LibPgQuery.canonical (TE.encodeUtf8 q)+ pure case parsed of+ Right [tree] -> tree+ _ -> String q+++slice :: Int -> Int -> ByteString -> ByteString+slice a b = BS.take (b - a) . BS.drop a
+ src/PgStyle/Render.hs view
@@ -0,0 +1,2072 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE FunctionalDependencies #-}++-- | The postgresql-syntax backend: pgstyle's own layout for DML statements+-- (SELECT, INSERT, UPDATE, DELETE, VALUES), with hasql-th's extensions.+--+-- Built against Hackage's postgresql-syntax, the hasql-th dialect is upstream+-- hasql-th's: nullability markers (@int8?@). With the @kronor-syntax@ flag,+-- which needs Kronor's fork of postgresql-syntax, it also takes the fork's+-- Haskell targets (@$Record {..}@, @$f (a, b)@) and param fields (@$1.$field@).+module PgStyle.Render (+ Dialect (..),+ FormatError (..),+ formatStatement,+ renderIdentifiersMasked,+ formatSql,+ formatQuasiQuote,+)+where++import Data.Char (toLower)+import Data.Generics (everywhere, mkT)+import Data.List.NonEmpty qualified as NE+import Data.Maybe (catMaybes, fromMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import PostgresqlSyntax qualified as Ast+import Prettyprinter (Doc, LayoutOptions (..), PageWidth (..), align, hardline, hcat, indent, layoutPretty, nest, pretty, punctuate, vsep, (<+>))+import Prettyprinter.Render.Text (renderStrict)+import TextBuilder (TextBuilder)+import TextBuilder qualified+import Prelude+++-- | postgresql-syntax 0.5 wraps every comma-separated production in its own+-- newtype where 0.4 used a bare @NonEmpty@. Rather than unwrap at each of the+-- forty-odd call sites, 'toL' names "give me the elements" once and covers+-- both shapes.+class ToList a b | a -> b where+ toL :: a -> [b]+++instance ToList (NE.NonEmpty a) a where+ toL = NE.toList+++instance ToList Ast.ArrayExprList Ast.ArrayExpr where toL (Ast.ArrayExprList xs) = NE.toList xs+instance ToList Ast.Attrs Ast.Ident where toL (Ast.Attrs xs) = NE.toList xs+instance ToList Ast.ExprList Ast.AExpr where toL (Ast.ExprList xs) = NE.toList xs+instance ToList Ast.FromList Ast.TableRef where toL (Ast.FromList xs) = NE.toList xs+instance ToList Ast.FromClause Ast.TableRef where toL (Ast.FromClause xs) = toL xs+instance ToList Ast.GroupClause Ast.GroupByItem where toL (Ast.GroupClause xs) = NE.toList xs+instance ToList Ast.Indirection Ast.IndirectionEl where toL (Ast.Indirection xs) = NE.toList xs+#ifdef KRONOR_SYNTAX+instance ToList Ast.HsTargetList Ast.HsTargetEl where toL (Ast.HsTargetList xs) = NE.toList xs+#endif+++instance ToList Ast.SetClauseList Ast.SetClause where toL (Ast.SetClauseList xs) = NE.toList xs+instance ToList Ast.SortClause Ast.SortBy where toL (Ast.SortClause xs) = NE.toList xs+instance ToList Ast.RowsfromList Ast.RowsfromItem where toL (Ast.RowsfromList xs) = NE.toList xs+instance ToList Ast.NameList Ast.Ident where toL (Ast.NameList xs) = NE.toList xs+instance ToList Ast.IndexParams Ast.IndexElem where toL (Ast.IndexParams xs) = NE.toList xs+instance ToList Ast.InsertColumnList Ast.InsertColumnItem where toL (Ast.InsertColumnList xs) = NE.toList xs+instance ToList Ast.TableFuncElementList Ast.TableFuncElement where toL (Ast.TableFuncElementList xs) = NE.toList xs+instance ToList Ast.TargetList Ast.TargetEl where toL (Ast.TargetList xs) = NE.toList xs+instance ToList Ast.ValuesClause Ast.ExprList where toL (Ast.ValuesClause xs) = NE.toList xs+instance ToList Ast.SetTargetList Ast.SetTarget where toL (Ast.SetTargetList xs) = NE.toList xs+instance ToList Ast.TypeList Ast.Typename where toL (Ast.TypeList xs) = NE.toList xs+instance ToList Ast.WhenClauseList Ast.WhenClause where toL (Ast.WhenClauseList xs) = NE.toList xs+instance ToList Ast.WindowClause Ast.WindowDefinition where toL (Ast.WindowClause xs) = NE.toList xs+++-- | Indentation size: 4 spaces per level.+indentSize :: Int+indentSize = 4+++-- | Layout options: unbounded width so explicit `line`/`hardline` are the only+-- source of line breaks; the layout never tries to flatten or reflow.+layoutOpts :: LayoutOptions+layoutOpts = LayoutOptions Unbounded+++-- | Which syntax the parser accepts.+data Dialect+ = -- | Plain PostgreSQL.+ PlainSql+ | -- | The SQL inside hasql-th quasiquotes: @$1 :: int8?@ nullability+ -- markers, @$f (..)@ \/ @$R {..}@ Haskell targets and @$1.$field@+ -- Haskell param fields.+ HasqlTh+ deriving stock (Eq, Show)+++-- | Why 'formatStatement' produced no output.+data FormatError+ = -- | postgresql-syntax does not parse the statement (DDL, a syntax it+ -- lacks, or invalid SQL). Not an error for callers that fall back.+ Unsupported Text+ | -- | The rendered SQL parses to a different AST, or does not parse: a+ -- renderer bug. Callers must not use the output.+ RendererBug Text+ deriving stock (Eq, Show)+++-- | Format one statement, without its terminating semicolon, starting at+-- column 0 and without a trailing newline.+--+-- The output is only returned if it parses back to the AST of the input.+formatStatement :: Dialect -> Text -> Either FormatError Text+formatStatement dialect sql =+ case parseStmt dialect (T.strip sql) of+ Left err -> Left (Unsupported err)+ Right ast ->+ let formatted = renderStrict (layoutPretty layoutOpts (renderPreparableStmt ast))+ in roundTrip dialect ast formatted+++-- | What 'formatStatement' renders, with every unquoted identifier's+-- characters replaced by @q@ and nothing else changed. That keeps each+-- identifier's length (so the layout, and the token stream, are the same as+-- 'formatStatement''s) and survives the renderer lower-casing what it inlines:+-- a token whose text differs between the two renderings is an identifier.+-- That is how "PgStyle.File" tells keywords from identifiers spelled like+-- keywords (@name@, @type@, @value@) when it changes keyword case.+renderIdentifiersMasked :: Dialect -> Text -> Either FormatError Text+renderIdentifiersMasked dialect sql =+ case parseStmt dialect (T.strip sql) of+ Left err -> Left (Unsupported err)+ Right ast ->+ Right (renderStrict (layoutPretty layoutOpts (renderPreparableStmt (everywhere (mkT mask) ast))))+ where+ mask = \case+ Ast.UnquotedIdent t -> Ast.UnquotedIdent (T.map (const 'q') t)+ quoted -> quoted+++-- | Format the SQL of a hasql-th quasiquote. qqIndent is the 0-based column of+-- the quasiquote opening bracket. The formatted output starts with a leading+-- newline (so the first SQL line is on its own line under the bracket) and ends+-- with a newline + qqIndent spaces (so the closing `|]` lines up under the+-- opening bracket).+--+-- Returns @Right formatted@ on success, @Left reason@ if the formatter+-- emitted an AST-divergent rewrite. Callers should surface @Left@ as a+-- hard failure (the file is left untouched; callers exit non-zero rather+-- than silently committing a renderer bug). Inputs the parser rejects are+-- not considered an error — they round-trip as @Right input@ since the+-- formatter never tried to rewrite them.+formatSql :: Int -> Text -> Either Text Text+formatSql qqIndent sql = case formatQuasiQuote qqIndent sql of+ Right formatted -> Right (fromMaybe sql formatted)+ Left (Unsupported _) -> Right sql+ Left (RendererBug reason) -> Left reason+++-- | 'formatSql', saying why a quasiquote is left as it is: 'Right' 'Nothing'+-- for an empty or single-line one, which are never rewritten, and+-- 'Unsupported' for SQL postgresql-syntax does not parse.+formatQuasiQuote :: Int -> Text -> Either FormatError (Maybe Text)+formatQuasiQuote qqIndent sql+ | T.null (T.strip sql) = Right Nothing+ -- Single-line queries (no newlines) are left untouched.+ | not (T.isInfixOf "\n" sql) = Right Nothing+ | otherwise =+ case parseStmt HasqlTh (T.strip sql) of+ Left err -> Left (Unsupported err)+ Right ast ->+ let doc :: Doc ()+ doc = renderPreparableStmt ast+ body = renderStrict (layoutPretty layoutOpts (indent (qqIndent + indentSize) doc))+ qqIndentText = T.replicate qqIndent " "+ formatted = "\n" <> body <> "\n" <> qqIndentText+ in case roundTrip HasqlTh ast formatted of+ Right _ -> Right (Just formatted)+ -- The output not parsing at all is a renderer bug too.+ Left (RendererBug reason) -> Left (RendererBug reason)+ Left (Unsupported reason) -> Left (RendererBug reason)+++-- | Round-trip safety: compare the re-parsed AST to the original. Parse-only+-- equivalence isn't enough — the renderer could drop or alter a clause and+-- still produce valid SQL (see the `DistinctTargeting` regression that+-- motivated this check).+roundTrip :: Dialect -> Ast.PreparableStmt -> Text -> Either FormatError Text+roundTrip dialect ast formatted =+ case parseStmt dialect (T.strip formatted) of+ Right ast' | ast' == ast -> Right formatted+ Right _ ->+ Left (RendererBug "AST mismatch: formatter rendered semantically-different SQL (renderer bug)")+ Left err ->+ Left (RendererBug ("AST mismatch: formatter output did not re-parse (" <> err <> ")"))+++-- | The renderer writes every extension back out, so it renders with all of+-- them enabled whatever the dialect; plain SQL has none of them in its AST.+-- Only parsing depends on the dialect.+settings :: Ast.Settings+settings = settingsFor HasqlTh+++settingsFor :: Dialect -> Ast.Settings+settingsFor = \case+ PlainSql -> mempty+ HasqlTh -> Ast.nullabilityMarkers True <> kronorSettings+++-- | Kronor's extensions to hasql-th's syntax, in a build with them.+kronorSettings :: Ast.Settings+#ifdef KRONOR_SYNTAX+kronorSettings = Ast.haskellTargets True <> Ast.haskellParamFields True+#else+kronorSettings = mempty+#endif+++-- | Parse a statement in the given dialect.+parseStmt :: Dialect -> Text -> Either Text Ast.PreparableStmt+parseStmt dialect = Ast.parse (settingsFor dialect)+++-- | Render any AST node with postgresql-syntax's own renderer, extensions on.+render :: Ast.IsAst a => a -> TextBuilder+render = Ast.toTextBuilder settings+++-- | 'Ast.VerbalExprBinOp' renders without its @NOT@, which lives in the+-- enclosing 'Ast.VerbalExprBinOpAExpr'. Mirrors postgresql-syntax's own+-- rendering of that node.+verbalExprBinOp :: Bool -> Ast.VerbalExprBinOp -> TextBuilder+verbalExprBinOp negated op = (if negated then "NOT " else mempty) <> render op+++-- | Same story for 'Ast.AExprReversableOp': the negation is external to the+-- type, and each alternative places it differently (@IS NOT NULL@ but+-- @NOT BETWEEN@). Mirrors postgresql-syntax's @renderAExprReversableOp@.+aExprReversableOp :: Bool -> Ast.AExprReversableOp -> TextBuilder+aExprReversableOp negated = \case+ Ast.NullAExprReversableOp -> isNot <> "NULL"+ Ast.TrueAExprReversableOp -> isNot <> "TRUE"+ Ast.FalseAExprReversableOp -> isNot <> "FALSE"+ Ast.UnknownAExprReversableOp -> isNot <> "UNKNOWN"+ Ast.DistinctFromAExprReversableOp a -> isNot <> "DISTINCT FROM " <> render a+ Ast.OfAExprReversableOp a -> isNot <> "OF (" <> render a <> ")"+ Ast.BetweenAExprReversableOp asymmetric a b ->+ notPfx <> (if asymmetric then "BETWEEN ASYMMETRIC " else "BETWEEN ") <> render a <> " AND " <> render b+ Ast.BetweenSymmetricAExprReversableOp a b ->+ notPfx <> "BETWEEN SYMMETRIC " <> render a <> " AND " <> render b+ Ast.InAExprReversableOp a -> notPfx <> "IN " <> render a+ Ast.DocumentAExprReversableOp -> isNot <> "DOCUMENT"+ where+ isNot = if negated then "IS NOT " else "IS "+ notPfx = if negated then "NOT " else mempty+++-- | 0.5 models @ROW ()@ as its own 'Ast.ExplicitRow' type where 0.4 used a+-- @Maybe@ of the expression list. The formatter still branches on the @Maybe@.+explicitRowExprs :: Ast.ExplicitRow -> Maybe Ast.ExprList+explicitRowExprs = \case+ Ast.EmptyExplicitRow -> Nothing+ Ast.ExprListExplicitRow xs -> Just xs+++-- | JSON/JSONB access operators rendered without surrounding spaces, since+-- they act like field accessors.+jsonOps :: [Text]+jsonOps = ["->", "->>", "#>", "#>>"]+++-- | Whether an operator is one of 'jsonOps', written plainly: not as+-- @operator(...)@.+isJsonOp :: Ast.SymbolicExprBinOp -> Bool+isJsonOp = \case+ Ast.QualSymbolicExprBinOp (Ast.OpQualOp (Ast.Op op)) -> op `elem` jsonOps+ _ -> False+++-- | Render via postgresql-syntax's renderer as a 'Doc'. Output is lowercased+-- and @:: @ typecast spacing is tightened to @::@, while content inside+-- single-quoted string literals (@'...'@) and double-quoted identifiers+-- (@"..."@) is preserved verbatim.+inline :: (a -> TextBuilder) -> a -> Doc ann+inline f = pretty . inlineText f+++-- | Same as 'inline' but stays at the Text layer. Useful when we need to do+-- a string comparison on the rendered output (e.g. detecting a JSON access+-- operator) before lifting it into a 'Doc'.+inlineText :: (a -> TextBuilder) -> a -> Text+inlineText f = inlineNormalize . TextBuilder.toText . f+++-- | Lowercase keywords and tighten @ :: @ to @::@ in a single pass, while+-- preserving the contents of single-quoted string literals and double-quoted+-- identifiers verbatim. Standard SQL doubled-quote escapes (@''@ and @""@)+-- are recognised so the scanner stays inside the literal until the real+-- closing quote.+inlineNormalize :: Text -> Text+inlineNormalize = T.pack . goCode . T.unpack+ where+ goCode :: String -> String+ goCode [] = []+ goCode ('\'' : rest) = '\'' : goString '\'' rest+ goCode ('"' : rest) = '"' : goString '"' rest+ goCode (' ' : ':' : ':' : ' ' : rest) = "::" ++ goCode rest+ goCode (c : rest) = toLower c : goCode rest++ goString :: Char -> String -> String+ goString _ [] = []+ -- Doubled-quote escape: stay inside the literal.+ goString q (c1 : c2 : rest) | c1 == q && c2 == q = c1 : c2 : goString q rest+ goString q (c : rest)+ | c == q = c : goCode rest+ | otherwise = c : goString q rest+++----------------------------------------------------------------------+-- Expression / leaf renderers (return 'Doc ann' — inline single-line by+-- construction; structural renderers below use the same type for+-- multi-line layouts).+----------------------------------------------------------------------++renderExpr :: Ast.AExpr -> Doc ann+renderExpr = \case+ Ast.TypecastAExpr expr tn ->+ renderExpr expr <> "::" <> renderTypename tn+ Ast.AndAExpr left right ->+ renderExpr left <+> "and" <+> renderExpr right+ Ast.OrAExpr left right ->+ renderExpr left <+> "or" <+> renderExpr right+ Ast.NotAExpr expr ->+ "not" <+> renderExpr expr+ Ast.CExprAExpr cexpr -> renderCExpr cexpr+ Ast.SymbolicBinOpAExpr left op right ->+ let opDoc = pretty (inlineText render op)+ in if isJsonOp op+ then renderExpr left <> opDoc <> renderExpr right+ else renderExpr left <+> opDoc <+> renderExpr right+ Ast.PlusAExpr expr -> "+" <> renderExpr expr+ Ast.MinusAExpr expr -> "-" <> renderExpr expr+ Ast.ReversableOpAExpr expr negated op ->+ renderExpr expr <+> renderReversableOp negated op+ Ast.IsnullAExpr expr -> renderExpr expr <+> "isnull"+ Ast.NotnullAExpr expr -> renderExpr expr <+> "notnull"+ Ast.CollateAExpr expr name -> renderExpr expr <+> "collate" <+> inline render name+ Ast.AtTimeZoneAExpr expr tz -> renderExpr expr <+> "at time zone" <+> renderExpr tz+ Ast.PrefixQualOpAExpr op expr -> inline render op <+> renderExpr expr+ Ast.VerbalExprBinOpAExpr left negated op right mEscape ->+ renderExpr left+ <+> inline (verbalExprBinOp negated) op+ <+> renderExpr right+ <> maybe mempty (\e -> " escape" <+> renderExpr e) mEscape+ Ast.SubqueryAExpr expr op subType subq ->+ renderExpr expr+ <+> inline render op+ <+> inline render subType+ <> either+ ((" " <>) . renderSelectWithParensMaybeWrap)+ (\e -> "(" <> renderExprMaybeWrap e <> ")")+ subq+ Ast.DefaultAExpr -> "default"+ Ast.UniqueAExpr swp -> "unique" <+> renderSelectWithParensMaybeWrap swp+ Ast.OverlapsAExpr r1 r2 -> inline render r1 <+> "overlaps" <+> inline render r2+++renderCExpr :: Ast.CExpr -> Doc ann+renderCExpr = \case+ Ast.ParamCExpr n mInd ->+ "$" <> pretty n <> maybe mempty renderIndirection mInd+ Ast.InParensCExpr expr mInd ->+ "(" <> renderExpr expr <> ")" <> maybe mempty renderIndirection mInd+ Ast.FuncCExpr fe -> renderFuncExpr fe+ Ast.ColumnrefCExpr cr -> inline render cr+ Ast.AexprConstCExpr ac -> inline render ac+ Ast.SelectWithParensCExpr swp mInd ->+ renderSelectWithParensMaybeWrap swp <> maybe mempty renderIndirection mInd+ Ast.ExistsCExpr swp -> "exists" <+> renderSelectWithParensMaybeWrap swp+ Ast.CaseCExpr caseExpr -> renderCaseExpr caseExpr+ Ast.ArrayCExpr arr -> "array" <> either renderSelectWithParensMaybeWrap renderArrayExpr arr+ Ast.ExplicitRowCExpr row ->+ "row(" <> maybe mempty (commaJoin . map renderExpr . toL) (explicitRowExprs row) <> ")"+ Ast.ImplicitRowCExpr (Ast.ImplicitRow exprs expr) ->+ "(" <> commaJoin (map renderExpr (toL exprs) ++ [renderExpr expr]) <> ")"+ other -> inline render other+++-- | Comma-and-space-separated concatenation of inline 'Doc's. Used wherever+-- the previous Text-based renderer used 'T.intercalate ", "'.+commaJoin :: [Doc ann] -> Doc ann+commaJoin = hcat . punctuate ", "+++renderArrayExpr :: Ast.ArrayExpr -> Doc ann+renderArrayExpr = \case+ Ast.ExprListArrayExpr exprs ->+ "[" <> commaJoin (map renderExpr (toL exprs)) <> "]"+ Ast.ArrayExprListArrayExpr nested ->+ "[" <> commaJoin (map renderArrayExpr (toL nested)) <> "]"+ Ast.EmptyArrayExpr -> "[]"+++renderCaseExpr :: Ast.CaseExpr -> Doc ann+renderCaseExpr (Ast.CaseExpr mArg whenClauses mDefault) =+ "case"+ <> maybe mempty (\arg -> " " <> renderExpr arg) mArg+ <> mconcat [" " <> renderWhenClause w | w <- toL whenClauses]+ <> maybe mempty (\d -> " else" <+> renderExpr d) mDefault+ <+> "end"+++renderWhenClause :: Ast.WhenClause -> Doc ann+renderWhenClause (Ast.WhenClause cond result) =+ "when" <+> renderExpr cond <+> "then" <+> renderExpr result+++renderIndirection :: Ast.Indirection -> Doc ann+renderIndirection = mconcat . map renderIndirectionEl . toL+++renderIndirectionEl :: Ast.IndirectionEl -> Doc ann+#ifdef KRONOR_SYNTAX+renderIndirectionEl = \case+ Ast.AttrNameIndirectionEl ident -> "." <> renderIdent ident+ Ast.AllIndirectionEl -> ".*"+ Ast.ExprIndirectionEl expr -> "[" <> renderExpr expr <> "]"+ Ast.SliceIndirectionEl mFrom mTo -> renderSlice mFrom mTo+ -- Kronor extension: a Haskell field selector on a @$n@ placeholder.+ Ast.HsAttrNameIndirectionEl t -> ".$" <> pretty t+#else+renderIndirectionEl = \case+ Ast.AttrNameIndirectionEl ident -> "." <> renderIdent ident+ Ast.AllIndirectionEl -> ".*"+ Ast.ExprIndirectionEl expr -> "[" <> renderExpr expr <> "]"+ Ast.SliceIndirectionEl mFrom mTo -> renderSlice mFrom mTo+#endif+++renderSlice :: Maybe Ast.AExpr -> Maybe Ast.AExpr -> Doc ann+renderSlice mFrom mTo = "[" <> maybe mempty renderExpr mFrom <> ":" <> maybe mempty renderExpr mTo <> "]"+++renderIdent :: Ast.Ident -> Doc ann+renderIdent = \case+ Ast.QuotedIdent t -> "\"" <> pretty t <> "\""+ Ast.UnquotedIdent t -> pretty t+++renderFuncExpr :: Ast.FuncExpr -> Doc ann+renderFuncExpr = \case+ Ast.ApplicationFuncExpr app mWithin mFilter mOver ->+ renderFuncApplication app+ <> maybe mempty (\w -> " " <> inline render w) mWithin+ <> maybe mempty (\f -> " filter (where" <+> renderExpr f <> ")") mFilter+ <> maybe mempty (\o -> " " <> inline render o) mOver+ Ast.SubexprFuncExpr sub -> renderFuncExprCommonSubexpr sub+++renderFuncApplication :: Ast.FuncApplication -> Doc ann+renderFuncApplication (Ast.FuncApplication name mParams) =+ inline render name <> "(" <> maybe mempty renderFuncAppParams mParams <> ")"+++-- | Threshold (number of positional arguments) at which a function call's+-- argument list is broken onto its own line per argument. A call with+-- fewer args than this threshold renders inline; one with this many or more+-- wraps. Currently set to 2, so single-arg calls (e.g. @count(*)@,+-- @md5(x)@, @unnest(arr)@) stay inline.+funcWrapThreshold :: Int+funcWrapThreshold = 2+++-- | The fewest arguments a call laid out as key/value pairs has.+keyValueMinArguments :: Int+keyValueMinArguments = 4+++-- | The most columns a function alias or an insert keeps on one line.+funcAliasInlineColumns, insertInlineColumns :: Int+funcAliasInlineColumns = 3+insertInlineColumns = 3+++-- | Number of positional arguments in a function application (variadic args+-- count as one each, star/none count as zero).+funcAppArgCount :: Ast.FuncApplication -> Int+funcAppArgCount (Ast.FuncApplication _ mParams) = case mParams of+ Nothing -> 0+ Just (Ast.NormalFuncApplicationParams _ args _) -> length (toL args)+ Just (Ast.VariadicFuncApplicationParams mArgs _ _) -> maybe 0 (length . toL) mArgs + 1+ Just Ast.StarFuncApplicationParams -> 0+++-- | Multi-line rendering of a function application using the leading-comma+-- block-list layout that's standard elsewhere in this formatter:+--+-- @+-- fn(+-- arg1+-- , arg2+-- , arg3+-- )+-- @+--+-- The args sit at @outer + indentSize + 2@ (first) and @outer + indentSize@+-- (`, ` prefix on subsequent), where @outer@ is the surrounding nesting+-- level. The closing paren returns to @outer@; this can put it visually+-- left of the function name when the function call is itself indented+-- (e.g. as a leading-comma item), but it keeps the layout predictable.+renderFuncApplicationWrapped :: Ast.FuncApplication -> Doc ann+renderFuncApplicationWrapped (Ast.FuncApplication name mParams) =+ inline render name+ <> "("+ <> nest indentSize (maybe mempty wrappedBody mParams)+ <> hardline+ <> ")"+ where+ wrappedBody params = case params of+ Ast.NormalFuncApplicationParams mDistinct args mSort ->+ let argList = toL args+ argDocs = map renderFuncArgExprMaybeWrap argList+ prefix = maybe mempty (\b -> if b then "distinct " else "all ") mDistinct+ rows =+ if looksLikeKeyValuePairs argList+ then renderArgPairRows argDocs+ else renderArgRows argDocs+ sortDoc = maybe mempty (\sc -> hardline <> inline render sc) mSort+ in prefix <> rows <> sortDoc+ Ast.VariadicFuncApplicationParams mArgs varArg mSort ->+ let regular = maybe [] (map renderFuncArgExprMaybeWrap . toL) mArgs+ variadic = "variadic " <> renderFuncArgExprMaybeWrap varArg+ rows = renderArgRows (regular ++ [variadic])+ sortDoc = maybe mempty (\sc -> hardline <> inline render sc) mSort+ in rows <> sortDoc+ Ast.StarFuncApplicationParams -> hardline <> "*"+++-- | First arg: hardline, then 2 extra spaces (so arg sits at col + 6), then+-- the arg. Subsequent args: hardline, then @, @ (so the comma sits at col ++-- 4 and the arg content also at col + 6). Used by every wrapped renderer+-- that emits a leading-comma block-list.+renderArgRows :: [Doc ann] -> Doc ann+renderArgRows = \case+ [] -> mempty+ (x : xs) ->+ (hardline <> " " <> x)+ <> mconcat [hardline <> ", " <> r | r <- xs]+++-- | Pair layout for key/value-shaped arg lists. Each pair lives on its own+-- line (key + inline @, @ + value). The first pair uses the same " " row+-- prefix as 'renderArgRows'; subsequent pairs use the leading @, @ row+-- separator. Caller guarantees an even-length input.+renderArgPairRows :: [Doc ann] -> Doc ann+renderArgPairRows = goFirst . pairs+ where+ pairs (a : b : rest) = (a, b) : pairs rest+ pairs _ = []++ goFirst [] = mempty+ goFirst ((k, v) : rest) =+ (hardline <> " " <> k <> ", " <> v)+ <> mconcat [hardline <> ", " <> k' <> ", " <> v' | (k', v') <- rest]+++-- | If an expression is a top-level function call (optionally wrapped in any+-- number of chained typecasts), return the function application along with a+-- function that re-attaches the typecasts to a Doc, preserving their order.+-- Used to detect "wrap-eligible" expressions in select target lists.+topLevelFuncApp :: Ast.AExpr -> Maybe (Ast.FuncApplication, Doc ann -> Doc ann)+topLevelFuncApp = \case+ Ast.TypecastAExpr inner tn+ | Just (app, attach) <- topLevelFuncApp inner ->+ Just (app, \d -> attach d <> "::" <> renderTypename tn)+ Ast.CExprAExpr (Ast.FuncCExpr (Ast.ApplicationFuncExpr app Nothing Nothing Nothing)) ->+ Just (app, id)+ _ -> Nothing+++-- | Heuristic: an arg list "looks like" alternating key/value pairs when it+-- has at least 4 args, an even count, and every even-indexed argument+-- (positions 0, 2, 4, ...) is a string-literal expression. This catches+-- @jsonb_build_object('k1', v1, 'k2', v2, ...)@ and friends without naming+-- specific functions, so the layout adapts to anything with the same shape.+looksLikeKeyValuePairs :: [Ast.FuncArgExpr] -> Bool+looksLikeKeyValuePairs args =+ let n = length args+ in even n && n >= keyValueMinArguments && all isLiteralKey (zip [0 :: Int ..] args)+ where+ isLiteralKey (i, arg)+ | even i = case arg of+ Ast.ExprFuncArgExpr e -> isStringLiteral e+ _ -> False+ | otherwise = True++ isStringLiteral :: Ast.AExpr -> Bool+ isStringLiteral = \case+ Ast.CExprAExpr (Ast.AexprConstCExpr (Ast.SAexprConst _)) -> True+ _ -> False+++-- | An expression is "wrap-eligible" when it has a structural shape the+-- multi-line renderers know how to lay out: a function call (optionally+-- under chained typecasts), an @array[...]@ literal whose elements+-- themselves contain wrap-eligible content, a @row(...)@ / @(a, b, c)@+-- tuple, a parenthesized expression, a @case@ expression, or one of the+-- SQL keyword-form pseudo-functions (@coalesce@, @cast@, @nullif@,+-- @greatest@, @least@, @position@, @substring@, @trim@, @overlay@,+-- @treat@). The decision to actually wrap (vs render inline) is made by+-- 'renderFuncArgExprMaybeWrap' / 'renderExprMaybeWrap' based on the+-- inline rendered length.+isWrapEligibleExpr :: Ast.AExpr -> Bool+isWrapEligibleExpr = \case+ Ast.TypecastAExpr inner _ -> isWrapEligibleExpr inner+ Ast.CExprAExpr cexpr -> isWrapEligibleCExpr cexpr+ _ -> False+++isWrapEligibleCExpr :: Ast.CExpr -> Bool+isWrapEligibleCExpr = \case+ Ast.FuncCExpr (Ast.ApplicationFuncExpr _ Nothing Nothing Nothing) -> True+ Ast.FuncCExpr (Ast.SubexprFuncExpr sub) -> isWrapEligibleSubexpr sub+ Ast.ArrayCExpr (Right arr) -> isWrapEligibleArray arr+ Ast.InParensCExpr inner _ -> isWrapEligibleExpr inner+ Ast.ExplicitRowCExpr row ->+ any isWrapEligibleExpr (maybe [] toL (explicitRowExprs row))+ Ast.ImplicitRowCExpr (Ast.ImplicitRow exprs expr) ->+ any isWrapEligibleExpr (toL exprs) || isWrapEligibleExpr expr+ -- @case ... when ... end@ is always wrap-eligible: even when the+ -- WHEN/THEN bodies are simple, the multi-line layout reads much+ -- better once the inline form gets long (e.g. multi-clause SET RHS+ -- assignments). The length gate decides when to actually wrap.+ Ast.CaseCExpr _ -> True+ _ -> False+++-- | An array literal is wrap-eligible when any of its elements is itself+-- wrap-eligible (so a long @array[fn(...)]@ expands to multi-line by+-- propagating the wrap into the contained function call).+isWrapEligibleArray :: Ast.ArrayExpr -> Bool+isWrapEligibleArray = \case+ Ast.ExprListArrayExpr exprs -> any isWrapEligibleExpr (toL exprs)+ Ast.ArrayExprListArrayExpr nested -> any isWrapEligibleArray (toL nested)+ Ast.EmptyArrayExpr -> False+++-- | The SQL keyword-form pseudo-functions (@coalesce@, @cast@, @nullif@,+-- @greatest@, @least@, @position@, @substring@, @trim@, @overlay@,+-- @treat@, @extract@) are always wrap-eligible — when their inline form+-- gets too long, the wrapped layout puts each argument on its own line+-- using 'renderArgRows'.+isWrapEligibleSubexpr :: Ast.FuncExprCommonSubexpr -> Bool+isWrapEligibleSubexpr = \case+ Ast.CoalesceFuncExprCommonSubexpr _ -> True+ Ast.CastFuncExprCommonSubexpr _ _ -> True+ Ast.NullIfFuncExprCommonSubexpr _ _ -> True+ Ast.GreatestFuncExprCommonSubexpr _ -> True+ Ast.LeastFuncExprCommonSubexpr _ -> True+ Ast.PositionFuncExprCommonSubexpr _ -> True+ Ast.SubstringFuncExprCommonSubexpr _ -> True+ Ast.TrimFuncExprCommonSubexpr _ _ -> True+ Ast.OverlayFuncExprCommonSubexpr _ -> True+ Ast.TreatFuncExprCommonSubexpr _ _ -> True+ Ast.ExtractFuncExprCommonSubexpr _ -> True+ _ -> False+++-- | Inline-length threshold above which a wrap-eligible sub-expression+-- switches from inline to multi-line rendering inside an already-wrapped+-- function call. Short calls like @jsonb_build_object('a', $1)@ stay on+-- one line; long ones like+-- @array_agg(mk_payload(caller => '...', payload => ...))::jsonb[]@ break+-- onto multiple lines, recursing into their own arguments.+inlineLengthThreshold :: Int+inlineLengthThreshold = 60+++-- | Wrap-aware variant of 'renderFuncArgExpr'. Used inside+-- 'renderFuncApplicationWrapped' so that nested function-call arguments+-- expand to multi-line when their inline form exceeds+-- 'inlineLengthThreshold', and stay inline otherwise. Pair-shaped+-- sub-calls (e.g. nested @jsonb_build_object(...)@) always wrap when+-- they appear inside an already-wrapped parent — keeping the visual+-- consistency of the @(key, value)@ pairs even when the inner call's+-- inline form would fit under the threshold.+renderFuncArgExprMaybeWrap :: Ast.FuncArgExpr -> Doc ann+renderFuncArgExprMaybeWrap arg =+ let inlineDoc = renderFuncArgExpr arg+ inlineLen = T.length (renderToText inlineDoc)+ forceWrap = isPairShapedArg arg+ in if (inlineLen > inlineLengthThreshold || forceWrap) && argIsWrapEligible arg+ then renderFuncArgExprWrapped arg+ else inlineDoc+ where+ argIsWrapEligible :: Ast.FuncArgExpr -> Bool+ argIsWrapEligible = \case+ Ast.ExprFuncArgExpr e -> isWrapEligibleExpr e+ Ast.ColonEqualsFuncArgExpr _ e -> isWrapEligibleExpr e+ Ast.EqualsGreaterFuncArgExpr _ e -> isWrapEligibleExpr e++ isPairShapedArg :: Ast.FuncArgExpr -> Bool+ isPairShapedArg = \case+ Ast.ExprFuncArgExpr e -> hasPairShapedCall e+ Ast.ColonEqualsFuncArgExpr _ e -> hasPairShapedCall e+ Ast.EqualsGreaterFuncArgExpr _ e -> hasPairShapedCall e+++-- | True when the expression is a function call (optionally under chained+-- typecasts) whose argument list satisfies 'looksLikeKeyValuePairs'. Used+-- to force-wrap nested @jsonb_build_object@-shaped values so a wrapped+-- pair-grouped parent doesn't have inline pair-grouped children+-- (visually inconsistent).+hasPairShapedCall :: Ast.AExpr -> Bool+hasPairShapedCall = \case+ Ast.TypecastAExpr inner _ -> hasPairShapedCall inner+ Ast.CExprAExpr (Ast.FuncCExpr (Ast.ApplicationFuncExpr (Ast.FuncApplication _ (Just (Ast.NormalFuncApplicationParams _ args _))) Nothing Nothing Nothing)) ->+ looksLikeKeyValuePairs (toL args)+ _ -> False+++-- | Render a wrap-eligible 'FuncArgExpr' multi-line. The named-arg prefix+-- (@name := @ / @name => @) stays on the same line as the function name and+-- @(@; only the function body wraps.+renderFuncArgExprWrapped :: Ast.FuncArgExpr -> Doc ann+renderFuncArgExprWrapped = \case+ Ast.ExprFuncArgExpr e -> renderExprWrapped e+ Ast.ColonEqualsFuncArgExpr ident e -> inline render ident <> " := " <> renderExprWrapped e+ Ast.EqualsGreaterFuncArgExpr ident e -> inline render ident <> " => " <> renderExprWrapped e+++-- | Render a wrap-eligible expression multi-line: peel chained typecasts,+-- then dispatch the underlying function application through+-- 'renderFuncApplicationWrapped' (or @array[...]@ literals through+-- 'renderArrayExprWrapped'). Recursion into deeper levels happens via+-- those wrappers calling 'renderFuncArgExprMaybeWrap' /+-- 'renderExprMaybeWrap' on their own elements.+renderExprWrapped :: Ast.AExpr -> Doc ann+renderExprWrapped = \case+ Ast.TypecastAExpr inner tn ->+ renderExprWrapped inner <> "::" <> renderTypename tn+ Ast.CExprAExpr (Ast.FuncCExpr (Ast.ApplicationFuncExpr app Nothing Nothing Nothing)) ->+ renderFuncApplicationWrapped app+ Ast.CExprAExpr (Ast.FuncCExpr (Ast.SubexprFuncExpr sub)) ->+ renderFuncExprCommonSubexprWrapped sub+ Ast.CExprAExpr (Ast.ArrayCExpr (Right arr)) ->+ "array" <> renderArrayExprWrapped arr+ Ast.CExprAExpr (Ast.InParensCExpr inner mInd) ->+ renderInParensWrapped inner mInd+ Ast.CExprAExpr (Ast.ExplicitRowCExpr row) ->+ renderExplicitRowWrapped (explicitRowExprs row)+ Ast.CExprAExpr (Ast.ImplicitRowCExpr row) ->+ renderImplicitRowWrapped row+ Ast.CExprAExpr (Ast.CaseCExpr caseExpr) ->+ renderCaseExprWrapped caseExpr+ other -> renderExpr other+++-- | Multi-line @(expr)@: open paren on the current line, inner expression+-- nested one level deeper on its own block, closing paren back at the+-- caller's column. The optional indirection (@.field@, @[index]@) appends+-- after the closing paren on the same line.+--+-- When the inner expression is a @case@ (with optional surrounding parens+-- / typecasts) we force-wrap it via 'renderExprWrapped' regardless of its+-- inline length, matching the top-level @case@-always-wraps rule used in+-- 'renderExprDoc' — otherwise a short CASE inside a wrapped parens would+-- collapse onto a single line while its enclosing parens stay multi-line.+--+-- When the inner is a direct @CaseCExpr@ (with no indirection) we emit+-- the compact form @(case ... end)@ — the @case@ keyword on the same+-- line as @(@, and @end)@ together at the close. The @case@/@end@+-- keywords already give the block clear visual structure; opening/closing+-- parens on their own lines are redundant ceremony.+renderInParensWrapped :: Ast.AExpr -> Maybe Ast.Indirection -> Doc ann+renderInParensWrapped expr mInd =+ case (mInd, expr) of+ (Nothing, Ast.CExprAExpr (Ast.CaseCExpr c)) ->+ -- Compact form: `(case ... end)`. We use 'align' to capture+ -- the actual column at @(@ so the case body indents relative+ -- to that column regardless of how the caller positioned us+ -- mid-line (e.g. via explicit @firstPad@ in a SELECT block+ -- list, or via the @" "@ prefix from 'renderArgRows' inside+ -- a wrapped function call). Body lands at @(-col ++ -- indentSize@; @end@ lines up with @(@; @)@ follows @end@ on+ -- the same line.+ align ("(" <> renderCaseExprWrapped c <> ")")+ _ ->+ let body =+ if isTopLevelCase expr+ then renderExprWrapped expr+ else renderExprMaybeWrap expr+ in "("+ <> nest indentSize (hardline <> body)+ <> hardline+ <> ")"+ <> maybe mempty renderIndirection mInd+++-- | Multi-line @row(...)@ / @(a, b, c)@: same leading-comma block-list+-- as a wrapped function call.+renderExplicitRowWrapped :: Maybe Ast.ExprList -> Doc ann+renderExplicitRowWrapped mExprs =+ let argDocs = maybe [] (map renderExprMaybeWrap . toL) mExprs+ in "row(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+++renderImplicitRowWrapped :: Ast.ImplicitRow -> Doc ann+renderImplicitRowWrapped (Ast.ImplicitRow exprs expr) =+ let argDocs = map renderExprMaybeWrap (toL exprs) ++ [renderExprMaybeWrap expr]+ in "(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+++-- | Multi-line @case@ expression: each @when ... then ...@ on its own line,+-- @else@ and @end@ on their own lines too. Matches the layout convention+-- used by hand-written SQL.+--+-- Inside a wrapped CASE, any @(select ...)@ subquery in a THEN or ELSE+-- body force-wraps as a multi-line SELECT block (regardless of length)+-- via 'renderExprForceSubqueryWrap'. The convention is that once we've+-- decided the CASE itself reads better multi-line, an inline+-- @(select x from t)@ inside one of its arms looks visually inconsistent+-- next to the multi-line WHEN/ELSE structure — so we expand it too.+renderCaseExprWrapped :: Ast.CaseExpr -> Doc ann+renderCaseExprWrapped (Ast.CaseExpr mArg whenClauses mDefault) =+ "case"+ <> maybe mempty (\arg -> " " <> renderExpr arg) mArg+ <> nest+ indentSize+ ( mconcat [hardline <> renderWhenClauseWrapped w | w <- toL whenClauses]+ <> maybe mempty (\d -> hardline <> "else" <+> renderExprForceSubqueryWrap d) mDefault+ )+ <> hardline+ <> "end"+++renderWhenClauseWrapped :: Ast.WhenClause -> Doc ann+renderWhenClauseWrapped (Ast.WhenClause cond result) =+ "when" <+> renderExprMaybeWrap cond <+> "then" <+> renderExprForceSubqueryWrap result+++-- | Like 'renderExprMaybeWrap' but force-wraps any directly-applied+-- @(select ...)@ subquery (with optional chained typecast) regardless of+-- inline length. Used inside wrapped CASE arms; falls through to+-- 'renderExprMaybeWrap' for everything that isn't a parenthesized SELECT.+renderExprForceSubqueryWrap :: Ast.AExpr -> Doc ann+renderExprForceSubqueryWrap = \case+ Ast.CExprAExpr (Ast.SelectWithParensCExpr swp mInd) ->+ renderSelectWithParensWrapped swp <> maybe mempty renderIndirection mInd+ Ast.TypecastAExpr inner tn ->+ renderExprForceSubqueryWrap inner <> "::" <> renderTypename tn+ e -> renderExprMaybeWrap e+++-- | Multi-line keyword-form pseudo-function: @coalesce@, @greatest@,+-- @least@ and @nullif@ with one argument per row ('renderArgRows'), and+-- @cast@ and @treat@ with @expr as type@ on a line of its own. The others+-- (@extract@, @substring@, @trim@, @position@, @overlay@, ...) are written+-- inline whatever their length.+renderFuncExprCommonSubexprWrapped :: Ast.FuncExprCommonSubexpr -> Doc ann+renderFuncExprCommonSubexprWrapped = \case+ Ast.CoalesceFuncExprCommonSubexpr exprs ->+ let argDocs = map renderExprMaybeWrap (toL exprs)+ in "coalesce(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+ Ast.GreatestFuncExprCommonSubexpr exprs ->+ let argDocs = map renderExprMaybeWrap (toL exprs)+ in "greatest(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+ Ast.LeastFuncExprCommonSubexpr exprs ->+ let argDocs = map renderExprMaybeWrap (toL exprs)+ in "least(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+ Ast.NullIfFuncExprCommonSubexpr e1 e2 ->+ let argDocs = [renderExprMaybeWrap e1, renderExprMaybeWrap e2]+ in "nullif(" <> nest indentSize (renderArgRows argDocs) <> hardline <> ")"+ Ast.CastFuncExprCommonSubexpr expr tn ->+ "cast("+ <> nest indentSize (hardline <> renderExprMaybeWrap expr <+> "as" <+> renderTypename tn)+ <> hardline+ <> ")"+ Ast.TreatFuncExprCommonSubexpr expr tn ->+ "treat("+ <> nest indentSize (hardline <> renderExprMaybeWrap expr <+> "as" <+> renderTypename tn)+ <> hardline+ <> ")"+ other -> renderFuncExprCommonSubexpr other+++-- | Wrap-aware variant for an 'AExpr'. Renders inline first; if the inline+-- form exceeds 'inlineLengthThreshold' AND the expression is structurally+-- wrap-eligible, switches to 'renderExprWrapped'. Pair-shaped sub-calls+-- (nested @jsonb_build_object@-style) force-wrap regardless of length so a+-- wrapped pair-grouped parent doesn't have inline pair-grouped children.+renderExprMaybeWrap :: Ast.AExpr -> Doc ann+renderExprMaybeWrap e =+ let inlineDoc = renderExpr e+ inlineLen = T.length (renderToText inlineDoc)+ forceWrap = hasPairShapedCall e+ in if (inlineLen > inlineLengthThreshold || forceWrap) && isWrapEligibleExpr e+ then renderExprWrapped e+ else inlineDoc+++-- | Multi-line render of an @array[...]@ literal: open bracket on the+-- current line, elements laid out with the same leading-comma block-list+-- as 'renderFuncApplicationWrapped', closing bracket back at the caller's+-- column. Each element is rendered through 'renderExprMaybeWrap', so a+-- long inner function call wraps recursively.+renderArrayExprWrapped :: Ast.ArrayExpr -> Doc ann+renderArrayExprWrapped = \case+ Ast.ExprListArrayExpr exprs ->+ let argDocs = map renderExprMaybeWrap (toL exprs)+ in "[" <> nest indentSize (renderArgRows argDocs) <> hardline <> "]"+ Ast.ArrayExprListArrayExpr nested ->+ let argDocs = map (\a -> "array" <> renderArrayExprWrapped a) (toL nested)+ in "[" <> nest indentSize (renderArgRows argDocs) <> hardline <> "]"+ Ast.EmptyArrayExpr -> "[]"+++renderFuncAppParams :: Ast.FuncApplicationParams -> Doc ann+renderFuncAppParams = \case+ Ast.NormalFuncApplicationParams mDistinct args mSort ->+ maybe mempty (\b -> if b then "distinct " else "all ") mDistinct+ <> commaJoin (map renderFuncArgExpr (toL args))+ <> maybe mempty (\sc -> " " <> inline render sc) mSort+ Ast.VariadicFuncApplicationParams mArgs varArg mSort ->+ maybe mempty (\args -> commaJoin (map renderFuncArgExpr (toL args)) <> ", ") mArgs+ <> "variadic "+ <> renderFuncArgExpr varArg+ <> maybe mempty (\sc -> " " <> inline render sc) mSort+ Ast.StarFuncApplicationParams -> "*"+++renderFuncArgExpr :: Ast.FuncArgExpr -> Doc ann+renderFuncArgExpr = \case+ Ast.ExprFuncArgExpr e -> renderExpr e+ Ast.ColonEqualsFuncArgExpr ident e -> inline render ident <> " := " <> renderExpr e+ Ast.EqualsGreaterFuncArgExpr ident e -> inline render ident <> " => " <> renderExpr e+++renderFuncExprCommonSubexpr :: Ast.FuncExprCommonSubexpr -> Doc ann+renderFuncExprCommonSubexpr = \case+ Ast.CoalesceFuncExprCommonSubexpr exprs ->+ "coalesce(" <> commaJoin (map renderExpr (toL exprs)) <> ")"+ Ast.CastFuncExprCommonSubexpr expr tn ->+ "cast(" <> renderExpr expr <+> "as" <+> renderTypename tn <> ")"+ Ast.NullIfFuncExprCommonSubexpr e1 e2 ->+ "nullif(" <> renderExpr e1 <> ", " <> renderExpr e2 <> ")"+ Ast.GreatestFuncExprCommonSubexpr exprs ->+ "greatest(" <> commaJoin (map renderExpr (toL exprs)) <> ")"+ Ast.LeastFuncExprCommonSubexpr exprs ->+ "least(" <> commaJoin (map renderExpr (toL exprs)) <> ")"+ Ast.ExtractFuncExprCommonSubexpr mList ->+ "extract(" <> maybe mempty renderExtractList mList <> ")"+ Ast.TreatFuncExprCommonSubexpr expr tn ->+ "treat(" <> renderExpr expr <+> "as" <+> renderTypename tn <> ")"+ Ast.PositionFuncExprCommonSubexpr mList ->+ "position(" <> maybe mempty renderPositionList mList <> ")"+ Ast.SubstringFuncExprCommonSubexpr mList ->+ "substring(" <> maybe mempty renderSubstrList mList <> ")"+ Ast.TrimFuncExprCommonSubexpr mModifier list ->+ "trim(" <> renderTrimModifier mModifier <> renderTrimList list <> ")"+ Ast.OverlayFuncExprCommonSubexpr list ->+ "overlay(" <> renderOverlayList list <> ")"+ other -> inline render other+++renderPositionList :: Ast.PositionList -> Doc ann+renderPositionList (Ast.PositionList needle haystack) =+ inline render needle <+> "in" <+> inline render haystack+++renderSubstrList :: Ast.SubstrList -> Doc ann+renderSubstrList = \case+ Ast.ExprListSubstrList exprs -> commaJoin (map renderExpr (toL exprs))+ Ast.ExprSubstrList expr fromFor -> renderExpr expr <+> renderSubstrListFromFor fromFor+++renderSubstrListFromFor :: Ast.SubstrListFromFor -> Doc ann+renderSubstrListFromFor = \case+ Ast.FromForSubstrListFromFor e1 e2 ->+ "from" <+> renderExpr e1 <+> "for" <+> renderExpr e2+ Ast.ForFromSubstrListFromFor e1 e2 ->+ "for" <+> renderExpr e1 <+> "from" <+> renderExpr e2+ Ast.FromSubstrListFromFor e -> "from" <+> renderExpr e+ Ast.ForSubstrListFromFor e -> "for" <+> renderExpr e+++renderTrimModifier :: Maybe Ast.TrimModifier -> Doc ann+renderTrimModifier = \case+ Nothing -> mempty+ Just Ast.BothTrimModifier -> "both "+ Just Ast.LeadingTrimModifier -> "leading "+ Just Ast.TrailingTrimModifier -> "trailing "+++renderTrimList :: Ast.TrimList -> Doc ann+renderTrimList = \case+ Ast.ExprFromExprListTrimList chars from ->+ renderExpr chars <+> "from" <+> commaJoin (map renderExpr (toL from))+ Ast.FromExprListTrimList from ->+ "from" <+> commaJoin (map renderExpr (toL from))+ Ast.ExprListTrimList exprs ->+ commaJoin (map renderExpr (toL exprs))+++renderOverlayList :: Ast.OverlayList -> Doc ann+renderOverlayList (Ast.OverlayList target placing fromE mForE) =+ renderExpr target+ <+> "placing"+ <+> renderExpr placing+ <+> "from"+ <+> renderExpr fromE+ <> maybe mempty (\forE -> " for" <+> renderExpr forE) mForE+++renderExtractList :: Ast.ExtractList -> Doc ann+renderExtractList (Ast.ExtractList arg expr) =+ renderExtractArg arg <+> "from" <+> renderExpr expr+++renderExtractArg :: Ast.ExtractArg -> Doc ann+renderExtractArg = \case+ Ast.IdentExtractArg ident -> renderIdent ident+ Ast.YearExtractArg -> "year"+ Ast.MonthExtractArg -> "month"+ Ast.DayExtractArg -> "day"+ Ast.HourExtractArg -> "hour"+ Ast.MinuteExtractArg -> "minute"+ Ast.SecondExtractArg -> "second"+ Ast.SconstExtractArg (Ast.Sconst s) -> "'" <> pretty s <> "'"+++renderBExpr :: Ast.BExpr -> Doc ann+renderBExpr = \case+ Ast.CExprBExpr ce -> renderCExpr ce+ Ast.TypecastBExpr be tn -> renderBExpr be <> "::" <> renderTypename tn+ Ast.PlusBExpr be -> "+" <> renderBExpr be+ Ast.MinusBExpr be -> "-" <> renderBExpr be+ Ast.SymbolicBinOpBExpr left op right ->+ renderBExpr left <+> inline render op <+> renderBExpr right+ other -> inline render other+++renderReversableOp :: Bool -> Ast.AExprReversableOp -> Doc ann+renderReversableOp negated = \case+ Ast.BetweenAExprReversableOp symmetric low high ->+ (if negated then "not " else mempty)+ <> (if symmetric then "between symmetric " else "between ")+ <> renderBExpr low+ <+> "and"+ <+> renderExpr high+ Ast.InAExprReversableOp inExpr ->+ (if negated then "not in " else "in ") <> inline render inExpr+ Ast.DistinctFromAExprReversableOp expr ->+ "is " <> (if negated then "not " else mempty) <> "distinct from" <+> renderExpr expr+ other -> inline (aExprReversableOp negated) other+++renderTypename :: Ast.Typename -> Doc ann+renderTypename (Ast.Typename _setof stn questionMark mArrayDims) =+ inline render stn+ <> (if questionMark then "?" else mempty)+ <> maybe mempty (\(ad, q) -> inline render ad <> if q then "?" else mempty) mArrayDims+++renderTargetEl :: Ast.TargetEl -> Doc ann+renderTargetEl = \case+ Ast.AsteriskTargetEl -> "*"+ Ast.ExprTargetEl e -> renderExpr e+ Ast.AliasedExprTargetEl e alias -> renderExpr e <+> "as" <+> inline render alias+ Ast.ImplicitlyAliasedExprTargetEl e alias -> renderExpr e <+> inline render alias+++-- | Wrap-aware target renderer that prefers a multi-line layout when the+-- expression is a top-level function call (optionally with a trailing+-- typecast) and the call has enough arguments to trigger wrapping.+renderTargetElDoc :: Ast.TargetEl -> Doc ann+renderTargetElDoc = \case+ Ast.ExprTargetEl e -> renderExprDoc e+ Ast.AliasedExprTargetEl e alias -> renderExprDoc e <+> "as" <+> inline render alias+ Ast.ImplicitlyAliasedExprTargetEl e alias -> renderExprDoc e <+> inline render alias+ other -> renderTargetEl other+++-- | Inline-length threshold used at the top-level select-target / SET-RHS+-- position. Higher than 'inlineLengthThreshold' (which gates wrapping+-- inside a function-arg context) because a select target is allowed to be+-- somewhat longer before wrapping pays off — e.g. @select enqueue(array+-- [mk_payload(...)])@ at ~110 chars reads fine inline, but @select unnest+-- (array[format(...), format(...)])@ at 500+ chars does not.+selectTargetInlineThreshold :: Int+selectTargetInlineThreshold = 150+++-- | Wrap-aware expression renderer for SELECT targets and similar+-- top-level positions. Wraps a top-level function application (or a+-- chained-typecast over one) whenever it has enough arguments to trigger+-- the existing arg-count rule. A top-level @case ... end@ (with optional+-- surrounding parens / typecast) always wraps regardless of length —+-- inline @case@ in a SELECT target reads poorly even at moderate widths,+-- and the wrapped form matches the convention of hand-written SQL.+-- Additionally, when the expression's inline form exceeds+-- 'selectTargetInlineThreshold' and the expression is structurally+-- wrap-eligible, it expands multi-line — covers single-arg calls with+-- deeply nested content (e.g. @unnest(array[fn(...), fn(...)])::text@)+-- and other wrap-eligible shapes (parenthesized expressions,+-- @row(...)@, @coalesce@/@cast@, etc.).+renderExprDoc :: Ast.AExpr -> Doc ann+renderExprDoc e = case topLevelFuncApp e of+ Just (app, wrapTypecast)+ | funcAppArgCount app >= funcWrapThreshold ->+ wrapTypecast (renderFuncApplicationWrapped app)+ _+ | isTopLevelCase e ->+ -- 'align' captures the actual column where this expression+ -- starts (which is mid-line after the block-list's+ -- @firstPad@ / @, @ prefix). Subsequent nest-driven indents+ -- inside 'renderExprWrapped' / 'renderCaseExprWrapped' add+ -- to that column, so body @when@ / @else@ land at+ -- @case-col + indentSize@ and @end@ aligns under @case@.+ -- Without this, a bare @case ... end@ has its body indent+ -- driven by the outer nest level, which makes @when@ land+ -- at the same column as @case@ (visually confusing).+ align (renderExprWrapped e)+ | otherwise ->+ let inlineDoc = renderExpr e+ inlineLen = T.length (renderToText inlineDoc)+ in if inlineLen > selectTargetInlineThreshold && isWrapEligibleExpr e+ then renderExprWrapped e+ else inlineDoc+++-- | True when the expression is a @case ... end@ (with optional surrounding+-- parens and/or chained typecasts). Used in 'renderExprDoc' to force CASE+-- expressions in SELECT-target position to always wrap multi-line.+isTopLevelCase :: Ast.AExpr -> Bool+isTopLevelCase = \case+ Ast.TypecastAExpr inner _ -> isTopLevelCase inner+ Ast.CExprAExpr (Ast.InParensCExpr inner _) -> isTopLevelCase inner+ Ast.CExprAExpr (Ast.CaseCExpr _) -> True+ _ -> False+++-- | Wrap-aware table reference renderer used for JOIN right-hand sides.+-- Wraps the call when the operand is a 'FuncTableRef' with a wrap-eligible+-- function call; any other table ref falls back to the inline renderer.+renderTableRefDoc :: Ast.TableRef -> Doc ann+renderTableRefDoc = \case+ Ast.FuncTableRef lp ft mFuncAlias+ | Just (app, ordinality) <- wrapEligibleFuncTable ft ->+ (if lp then "lateral " else mempty)+ <> renderFuncApplicationWrapped app+ <> (if ordinality then " with ordinality" else mempty)+ <> maybe mempty (\a -> " " <> renderFuncAliasClauseDoc a) mFuncAlias+ Ast.SelectTableRef lp swp mAlias ->+ (if lp then "lateral " else mempty)+ <> renderSelectWithParensMaybeWrap swp+ <> maybe mempty (\a -> " " <> inline render a) mAlias+ other -> renderTableRefInline other+++-- | Render a function-alias clause (the @as alias_name (col1, col2, ...)@+-- after a FROM-list / JOIN function call). Short column lists stay inline;+-- lists of more than 3 columns wrap onto their own bracket-list block+-- below the alias name.+renderFuncAliasClauseDoc :: Ast.FuncAliasClause -> Doc ann+renderFuncAliasClauseDoc = \case+ Ast.AliasFuncAliasClause (Ast.AliasClause hasAs name (Just cols))+ | length (toL cols) > funcAliasInlineColumns ->+ let prefix = if hasAs then "as " else mempty+ colDocs = map (inline render) (toL cols)+ in prefix+ <> inline render name+ <> hardline+ <> indent indentSize (renderBracketList colDocs)+ other -> inline render other+++-- | If the FuncTable wraps a single ApplicationFuncExprWindowless with enough+-- arguments to trigger wrapping, return the application and its WITH ORDINALITY+-- flag; otherwise Nothing.+wrapEligibleFuncTable :: Ast.FuncTable -> Maybe (Ast.FuncApplication, Bool)+wrapEligibleFuncTable = \case+ Ast.FuncExprFuncTable (Ast.ApplicationFuncExprWindowless app) (Ast.OptOrdinality ordinality)+ | funcAppArgCount app >= funcWrapThreshold+ , T.length (renderToText (renderFuncApplication app)) > inlineLengthThreshold ->+ Just (app, ordinality)+ _ -> Nothing+++renderTargetListInline :: Ast.TargetList -> Doc ann+renderTargetListInline = commaJoin . map renderTargetEl . toL+++renderSetClause :: Ast.SetClause -> Doc ann+renderSetClause = \case+ Ast.TargetSetClause target expr ->+ inline render target+ <+> "="+ <+> nest indentSize (renderExprMaybeWrap expr)+ Ast.TargetListSetClause targets expr ->+ "("+ <> commaJoin (map (inline render) (toL targets))+ <> ") ="+ <+> nest indentSize (renderExprMaybeWrap expr)+++renderInsertTarget :: Ast.InsertTarget -> Doc ann+renderInsertTarget (Ast.InsertTarget name mAlias) =+ inline render name <> maybe mempty (\a -> " as " <> inline render a) mAlias+++-- Inline renderers for table refs / function tables — used inside FROM lists+-- that fit on a single line, and inside joined-table renderings where the+-- right-hand side is always inline.++renderTableRefInline :: Ast.TableRef -> Doc ann+renderTableRefInline = \case+ Ast.RelationExprTableRef re mAlias mSample ->+ let base = inline render re+ aliased = maybe base (\a -> base <+> inline render a) mAlias+ in maybe aliased (\s -> aliased <+> inline render s) mSample+ Ast.FuncTableRef lp ft mFuncAlias ->+ (if lp then "lateral " else mempty) <> renderFuncTable ft <> maybe mempty (\a -> " " <> renderFuncAliasClauseDoc a) mFuncAlias+ Ast.SelectTableRef lp swp mAlias ->+ (if lp then "lateral " else mempty) <> renderSelectWithParensInline swp <> maybe mempty (\a -> " " <> inline render a) mAlias+ Ast.JoinTableRef jt mAlias ->+ inline render jt <> maybe mempty (\a -> " " <> inline render a) mAlias+++renderFuncTable :: Ast.FuncTable -> Doc ann+renderFuncTable = \case+ Ast.FuncExprFuncTable few (Ast.OptOrdinality ordinality) ->+ renderFuncExprWindowless few <> if ordinality then " with ordinality" else mempty+ Ast.RowsFromFuncTable rowsList (Ast.OptOrdinality ordinality) ->+ "rows from (" <> commaJoin (map renderRowsfromItem (toL rowsList)) <> ")" <> if ordinality then " with ordinality" else mempty+++renderFuncExprWindowless :: Ast.FuncExprWindowless -> Doc ann+renderFuncExprWindowless = \case+ Ast.ApplicationFuncExprWindowless app -> renderFuncApplication app+ Ast.CommonSubexprFuncExprWindowless sub -> renderFuncExprCommonSubexpr sub+++renderRowsfromItem :: Ast.RowsfromItem -> Doc ann+renderRowsfromItem (Ast.RowsfromItem few mColDef) =+ renderFuncExprWindowless few <> maybe mempty (\cd -> " as (" <> inline render cd <> ")") mColDef+++-- Inline select renderers for subqueries that appear on a single line+-- (e.g. inside `EXISTS (...)`, `= (select ...)`, etc.).++renderSelectWithParensInline :: Ast.SelectWithParens -> Doc ann+renderSelectWithParensInline = \case+ Ast.NoParensSelectWithParens snp -> "(" <> renderSelectNoParensInline snp <> ")"+ Ast.WithParensSelectWithParens swp -> "(" <> renderSelectWithParensInline swp <> ")"+++-- | Inline-length threshold for in-expression parenthesized SELECTs. Higher+-- than 'inlineLengthThreshold' (which gates function-argument wrapping)+-- because subqueries are naturally wider than a function arg, so the+-- threshold needs to admit shapes like @(select 1::int from gen(...))@+-- without forcing them onto multiple lines.+subqueryInlineThreshold :: Int+subqueryInlineThreshold = 100+++-- | Render an in-expression parenthesized SELECT (used for @EXISTS (...)@,+-- @ARRAY (...)@, @UNIQUE (...)@, scalar subselects, and @ANY/ALL (subquery)@)+-- inline when its inline form fits within 'subqueryInlineThreshold',+-- otherwise expand it onto multiple lines so the inner query reads as a+-- normal block (FROM split off, WHERE on its own line with right-aligned+-- AND continuations, leading-comma SELECT lists, etc. — the same layout+-- principles a top-level SELECT uses).+renderSelectWithParensMaybeWrap :: Ast.SelectWithParens -> Doc ann+renderSelectWithParensMaybeWrap swp =+ let inlineDoc = renderSelectWithParensInline swp+ inlineLen = T.length (renderToText inlineDoc)+ in if inlineLen > subqueryInlineThreshold+ then renderSelectWithParensWrapped swp+ else inlineDoc+++-- | Multi-line render of a parenthesized SELECT: open paren on the current+-- line, inner statement on its own block one indent deeper, closing paren+-- back at the caller's column. Mirrors the layout used by+-- 'renderCte' / @WITH ... AS (...)@.+renderSelectWithParensWrapped :: Ast.SelectWithParens -> Doc ann+renderSelectWithParensWrapped = \case+ Ast.NoParensSelectWithParens snp ->+ "(" <> nest indentSize (hardline <> renderSelectNoParens snp) <> hardline <> ")"+ Ast.WithParensSelectWithParens inner ->+ "(" <> nest indentSize (hardline <> renderSelectWithParensWrapped inner) <> hardline <> ")"+++renderSelectNoParensInline :: Ast.SelectNoParens -> Doc ann+renderSelectNoParensInline (Ast.SelectNoParens mWith selectClause mSort mLimit mLocking) =+ spaceJoin $+ catMaybes+ [ inline render <$> mWith+ , Just (renderSelectClauseInline selectClause)+ , inline render <$> mSort+ , inline render <$> mLimit+ , inline render <$> mLocking+ ]+++-- | Concatenate inline 'Doc's with a single space between each. Used wherever+-- the previous Text-based renderer used 'T.unwords'.+spaceJoin :: [Doc ann] -> Doc ann+spaceJoin = hcat . punctuate " "+++renderSelectClauseInline :: Ast.SelectClause -> Doc ann+renderSelectClauseInline = \case+ Ast.SimpleSelectSelectClause ss -> renderSimpleSelectInline ss+ Ast.WithParensSelectClause swp -> renderSelectWithParensInline swp+++renderSimpleSelectInline :: Ast.SimpleSelect -> Doc ann+renderSimpleSelectInline = \case+ Ast.NormalSimpleSelect mTargeting mInto mFrom mWhere mGroup mHaving mWindow ->+ spaceJoin $+ catMaybes+ [ Just (renderTargetingInline mTargeting)+ , inline render <$> mInto+ , renderFromClauseInline <$> mFrom+ , (\(Ast.WhereClause w) -> "where" <+> renderExpr w) <$> mWhere+ , inline render <$> mGroup+ , (\(Ast.HavingClause h) -> "having" <+> renderExpr h) <$> mHaving+ , inline render <$> mWindow+ ]+ Ast.BinSimpleSelect op left mAll right ->+ renderSelectClauseInline left+ <+> inline render op+ <> maybe mempty (\distinct -> if distinct then " distinct" else " all") mAll+ <+> renderSelectClauseInline right+ other -> inline render other+++renderFromClauseInline :: Ast.FromClause -> Doc ann+renderFromClauseInline fromList =+ "from " <> commaJoin (map renderTableRefInline (toL fromList))+++-- | A plain select's targets, each on one line: hasql-th's, with Kronor's+-- extensions, in a build with them.+#ifdef KRONOR_SYNTAX+normalTargetsInline :: Ast.HsTargetList -> [Doc ann]+normalTargetsInline tl = map renderHsTargetElInline (toL tl)+#else+normalTargetsInline :: Ast.TargetList -> [Doc ann]+normalTargetsInline tl = map renderTargetEl (toL tl)+#endif+++renderTargetingInline :: Maybe Ast.Targeting -> Doc ann+renderTargetingInline = \case+ Nothing -> "select"+ Just (Ast.NormalTargeting tl) -> "select " <> commaJoin (normalTargetsInline tl)+ Just (Ast.AllTargeting Nothing) -> "select all"+ Just (Ast.AllTargeting (Just tl)) -> "select all " <> commaJoin (map renderTargetEl (toL tl))+ Just (Ast.DistinctTargeting mExprs tl) ->+ let prefix = case mExprs of+ Nothing -> "select distinct"+ Just exprs -> "select distinct on (" <> inline render exprs <> ")"+ in prefix <> " " <> commaJoin (map renderTargetEl (toL tl))++#ifdef KRONOR_SYNTAX+-- | Render a hasql-th target element on a single line. Used in inline subquery+-- contexts. The multi-line `$Name{...}` layout is handled separately by+-- 'renderHsTargetEl'.+renderHsTargetElInline :: Ast.HsTargetEl -> Doc ann+renderHsTargetElInline = \case+ Ast.HsFuncTargetEl name args ->+ "$" <> pretty name <> " (" <> commaJoin (map renderHsTargetElInline args) <> ")"+ Ast.HsRecTargetEl name fields ->+ "$"+ <> pretty name+ <> "{ "+ <> commaJoin (map renderHsFieldContentInline (toL fields))+ <> " }"+ Ast.SqlTargetEl te -> renderTargetEl te+++renderHsFieldContentInline :: Ast.HsFieldTargetEl -> Doc ann+renderHsFieldContentInline (Ast.HsFieldEl name target) =+ pretty name <> " = " <> renderHsTargetElInline target+#endif+++----------------------------------------------------------------------+-- Multi-line statement / clause renderers (return Doc).+----------------------------------------------------------------------++renderPreparableStmt :: Ast.PreparableStmt -> Doc ann+renderPreparableStmt = \case+ Ast.SelectPreparableStmt s -> renderSelectStmt s+ Ast.InsertPreparableStmt s -> renderInsertStmt s+ Ast.UpdatePreparableStmt s -> renderUpdateStmt s+ Ast.DeletePreparableStmt s -> renderDeleteStmt s+ Ast.CallPreparableStmt s -> inline render s+++renderSelectStmt :: Ast.SelectStmt -> Doc ann+renderSelectStmt = \case+ Ast.NoParensSelectStmt snp -> renderSelectNoParens snp+ Ast.WithParensSelectStmt swp -> renderSelectWithParens swp+++renderSelectWithParens :: Ast.SelectWithParens -> Doc ann+renderSelectWithParens = \case+ Ast.NoParensSelectWithParens snp -> "(" <> renderSelectNoParens snp <> ")"+ Ast.WithParensSelectWithParens swp -> "(" <> renderSelectWithParens swp <> ")"+++renderSelectNoParens :: Ast.SelectNoParens -> Doc ann+renderSelectNoParens (Ast.SelectNoParens mWith selectClause mSort mLimit mLocking) =+ vsep $+ catMaybes+ [ renderWithClause <$> mWith+ , Just (renderSelectClause selectClause)+ , inline render <$> mSort+ , renderSelectLimit <$> mLimit+ , inline render <$> mLocking+ ]+++renderSelectClause :: Ast.SelectClause -> Doc ann+renderSelectClause = \case+ Ast.SimpleSelectSelectClause ss -> renderSimpleSelect ss+ Ast.WithParensSelectClause swp -> renderSelectWithParens swp+++renderSimpleSelect :: Ast.SimpleSelect -> Doc ann+renderSimpleSelect = \case+ Ast.NormalSimpleSelect mTargeting mInto mFrom mWhere mGroup mHaving mWindow ->+ vsep $+ catMaybes+ [ Just (renderTargeting mTargeting)+ , inline render <$> mInto+ , renderFromClause <$> mFrom+ , renderWhereClause <$> mWhere+ , inline render <$> mGroup+ , (\(Ast.HavingClause h) -> renderCondWithAndAligned (T.length "having") "having" h) <$> mHaving+ , inline render <$> mWindow+ ]+ Ast.ValuesSimpleSelect vc ->+ renderValuesClause vc+ Ast.TableSimpleSelect re ->+ "table" <+> inline render re+ Ast.BinSimpleSelect op left mAll right ->+ vsep+ [ renderSelectClause left+ , inline render op <> maybe mempty (\d -> if d then " distinct" else " all") mAll+ , renderSelectClause right+ ]+++-- | A plain select's target list after @prefix@: hasql-th's, with Kronor's+-- extensions, in a build with them.+#ifdef KRONOR_SYNTAX+renderNormalTargets :: Doc ann -> Ast.HsTargetList -> Doc ann+renderNormalTargets = renderHsTargetList+#else+renderNormalTargets :: Doc ann -> Ast.TargetList -> Doc ann+renderNormalTargets = renderSqlTargetList+#endif+++-- | Render the SELECT targeting (column list).+renderTargeting :: Maybe Ast.Targeting -> Doc ann+renderTargeting = \case+ Nothing -> "select"+ Just (Ast.NormalTargeting tl) -> renderNormalTargets "select" tl+ Just (Ast.AllTargeting Nothing) -> "select all"+ Just (Ast.AllTargeting (Just tl)) -> renderSqlTargetList "select all" tl+ Just (Ast.DistinctTargeting mExprs tl) ->+ let prefix = case mExprs of+ Nothing -> "select distinct"+ Just exprs -> "select distinct on (" <> inline render exprs <> ")"+ in renderSqlTargetList prefix tl++#ifdef KRONOR_SYNTAX+-- | Block-list layout for hasql-th target lists. First item lands at one+-- indent past the SELECT keyword; subsequent items are emitted as `, item` at+-- (indent - 2), so every item's content column lines up vertically.+--+-- A single target that's a top-level @case ... end@ (with optional+-- surrounding parens / typecasts) forces the block-list layout too, so+-- @case@ lands at the item-content column rather than mid-line after+-- @select @. Otherwise the @align@ inside 'renderExprDoc' would capture+-- the @case@ keyword's mid-line column and push the body / @end@ far to+-- the right.+renderHsTargetList :: Doc ann -> Ast.HsTargetList -> Doc ann+renderHsTargetList prefix tl =+ let items = toL tl+ hasRecord = any isRecTarget items+ in case items of+ [single]+ | not hasRecord && not (singleHsItemForcesMultiLine single) ->+ prefix <+> renderHsTargetEl single+ _ -> renderBlockListWith prefix renderHsTargetEl items+ where+ isRecTarget (Ast.HsRecTargetEl _ _) = True+ isRecTarget _ = False+#endif+++renderSqlTargetList :: Doc ann -> Ast.TargetList -> Doc ann+renderSqlTargetList prefix tl =+ let items = toL tl+ in case items of+ [single]+ | not (singleSqlItemForcesMultiLine single) ->+ prefix <+> renderTargetElDoc single+ _ -> renderBlockListWith prefix renderTargetElDoc items+++-- | A single SELECT target item forces block-list layout when its+-- expression would render multi-line via 'renderExprDoc'. Currently this+-- is just the top-level CASE rule (peeling typecasts and parens) — keeping+-- the predicate narrow avoids unintended layout changes for short single+-- targets.+#ifdef KRONOR_SYNTAX+singleHsItemForcesMultiLine :: Ast.HsTargetEl -> Bool+singleHsItemForcesMultiLine = \case+ Ast.SqlTargetEl te -> singleSqlItemForcesMultiLine te+ _ -> False+#endif+++singleSqlItemForcesMultiLine :: Ast.TargetEl -> Bool+singleSqlItemForcesMultiLine = \case+ Ast.ExprTargetEl e -> isTopLevelCase e+ Ast.AliasedExprTargetEl e _ -> isTopLevelCase e+ Ast.ImplicitlyAliasedExprTargetEl e _ -> isTopLevelCase e+ _ -> False+++-- | Build the block-list layout used by SELECT target lists and the+-- multi-assignment UPDATE SET. Pattern:+--+-- @+-- prefix+-- first+-- , second+-- , third+-- @+--+-- The body sits at indent 4; commas at indent 2.+--+-- Note: padding is applied as explicit spaces in the Doc rather than via+-- 'indent'/'nest'. This is deliberate — we want the *first* item one indent+-- deeper than the comma rows, so that the comma column lines up under the+-- prefix while item content aligns. 'indent' would push every row to the same+-- column.+renderBlockListWith :: Doc ann -> (a -> Doc ann) -> [a] -> Doc ann+renderBlockListWith prefix renderItem items =+ prefix+ <> hardline+ <> vsep (zipWith renderRow [(0 :: Int) ..] items)+ where+ firstPad = pretty (T.replicate indentSize " ")+ commaPad = pretty (T.replicate (max 0 (indentSize - 2)) " ")+ renderRow 0 item = firstPad <> renderItem item+ renderRow _ item = commaPad <> ", " <> renderItem item++#ifdef KRONOR_SYNTAX+-- | Multi-line `$Name{...}` record layout:+--+-- @++-- $Name+-- { field1 = ...+-- , field2 = ...+-- }+-- @+--+-- Wrapped in 'align' so any hard line break within the record body picks up+-- the column where `$Name` was placed (rather than the outer block's column);+-- 'indent' then takes us one level deeper for the brace/fields/closing brace.+++renderHsTargetEl :: Ast.HsTargetEl -> Doc ann+renderHsTargetEl = \case+ Ast.HsFuncTargetEl name args ->+ let inlineDoc = "$" <> pretty name <> " (" <> commaJoin (map renderHsTargetElInline args) <> ")"+ inlineLen = T.length (renderToText inlineDoc)+ in if not (null args) && inlineLen > selectTargetInlineThreshold+ then renderHsFuncTargetWrapped name args+ else inlineDoc+ Ast.HsRecTargetEl name fields ->+ align $+ "$"+ <> pretty name+ <> hardline+ <> indent indentSize (renderRecordFields fields)+ Ast.SqlTargetEl te -> renderTargetElDoc te+++-- | Multi-line layout for hasql-th @$Name (...)@: each arg on its own+-- line in a leading-comma block, same shape as+-- 'renderFuncApplicationWrapped'. Each arg is rendered wrap-aware so a+-- long inner SQL expression (CASE, function call, parenthesized cast,+-- etc.) wraps the same way it would at the top-level SELECT-target+-- position. Used both for top-level @$Foo (...)@ targets (gated by+-- 'selectTargetInlineThreshold') and for nested @$Foo (...)@ values+-- inside record fields (gated by 'inlineLengthThreshold' via+-- 'renderHsTargetElMaybeWrap').+renderHsFuncTargetWrapped :: Text -> [Ast.HsTargetEl] -> Doc ann+renderHsFuncTargetWrapped name args =+ "$"+ <> pretty name+ <> " ("+ <> nest indentSize (renderArgRows (map renderHsFuncTargetArg args))+ <> hardline+ <> ")"+++-- | Render one arg of a wrapped @$Name (...)@. SQL args go through+-- 'renderTargetElDoc' (the wrap-aware SELECT-target renderer); nested+-- @$Foo (...)@ / @$Foo{...}@ args recurse via 'renderHsTargetElMaybeWrap'+-- so a deeply nested splice picks up the same inline-vs-wrap rule it+-- would in a record field.+renderHsFuncTargetArg :: Ast.HsTargetEl -> Doc ann+renderHsFuncTargetArg = \case+ Ast.SqlTargetEl te -> renderTargetElDoc te+ other -> renderHsTargetElMaybeWrap other+++-- | Same as 'renderHsTargetEl' but without the outer 'align' — for use+-- when this target is a nested record value (rendered inside+-- 'renderRecordFields'). We rely on the surrounding @indent indentSize@+-- to give us the right base column, and propagate it via plain+-- @hardline + indent indentSize@ so each nesting level adds exactly+-- @indentSize@ of indent rather than capturing the field's mid-line+-- column (which would cascade rightward).+renderHsTargetElWrappedInner :: Ast.HsTargetEl -> Doc ann+renderHsTargetElWrappedInner = \case+ Ast.HsRecTargetEl name fields ->+ "$"+ <> pretty name+ <> hardline+ <> indent indentSize (renderRecordFields fields)+ Ast.HsFuncTargetEl name args ->+ renderHsFuncTargetWrapped name args+ other -> renderHsTargetEl other+++renderRecordFields :: NE.NonEmpty Ast.HsFieldTargetEl -> Doc ann+renderRecordFields fields =+ let firstField = NE.head fields+ restFields = NE.tail fields+ renderField (Ast.HsFieldEl name target) =+ pretty name <> " = " <> renderHsTargetElMaybeWrap target+ firstLine = "{ " <> renderField firstField+ restLines = map (\f -> ", " <> renderField f) restFields+ in vsep $ firstLine : restLines ++ ["}"]+++-- | Wrap-aware renderer for hasql-th @$Foo@ / @$Foo{...}@ target+-- expressions used inside record fields. Renders inline first; if the+-- inline form exceeds 'inlineLengthThreshold' AND the target is a+-- record-shaped @$Foo{...}@ or a function-shaped @$f(...)@ with+-- arguments, expands to multi-line via+-- 'renderHsTargetElWrappedInner' so each nested level adds exactly+-- @indentSize@ of indent rather than cascading rightward.+renderHsTargetElMaybeWrap :: Ast.HsTargetEl -> Doc ann+renderHsTargetElMaybeWrap el =+ let inlineDoc = renderHsTargetElInline el+ inlineLen = T.length (renderToText inlineDoc)+ in if inlineLen > inlineLengthThreshold && isHsTargetWrapEligible el+ then renderHsTargetElWrappedInner el+ else inlineDoc+++isHsTargetWrapEligible :: Ast.HsTargetEl -> Bool+isHsTargetWrapEligible = \case+ Ast.HsRecTargetEl _ _ -> True+ Ast.HsFuncTargetEl _ args -> not (null args)+ Ast.SqlTargetEl _ -> False+#endif+++-- | Render the FROM clause. A list with no joins stays on a single line+-- (`from t1, t2`). Any join forces multi-line layout so each join lands on its+-- own line with its ON/USING qualification below.+renderFromClause :: Ast.FromClause -> Doc ann+renderFromClause fromList =+ let items = toL fromList+ lastIdx = length items - 1+ in if any forcesMultiLine items+ then+ vsep $+ zipWith+ ( \i item ->+ renderTableRef (i == (0 :: Int)) item+ <> if i < lastIdx then "," else mempty+ )+ [0 ..]+ items+ else "from" <+> commaJoin (map renderTableRefInline items)+ where+ -- A FROM item forces multi-line layout when it's a JOIN (each arm on+ -- its own line), a wrap-eligible function call (e.g.+ -- @from job_queue.enqueue_payload(array[...]::jsonb[], priority_ :=+ -- 5000)@), or a parenthesized SELECT whose inline form exceeds+ -- 'subqueryInlineThreshold'.+ forcesMultiLine (Ast.JoinTableRef _ _) = True+ forcesMultiLine (Ast.FuncTableRef _ ft _) =+ case wrapEligibleFuncTable ft of+ Just _ -> True+ Nothing -> False+ forcesMultiLine (Ast.SelectTableRef _ swp _) =+ T.length (renderToText (renderSelectWithParensInline swp)) > subqueryInlineThreshold+ forcesMultiLine _ = False+++renderTableRef :: Bool -> Ast.TableRef -> Doc ann+renderTableRef isFirst = \case+ Ast.RelationExprTableRef re mAlias mSample ->+ let base = inline render re+ aliased = maybe base (\a -> base <> " " <> inline render a) mAlias+ sampled = maybe aliased (\s -> aliased <> " " <> inline render s) mSample+ in pfx <> sampled+ Ast.FuncTableRef lp ft mFuncAlias+ | Just (app, ordinality) <- wrapEligibleFuncTable ft ->+ pfx+ <> (if lp then "lateral " else mempty)+ <> renderFuncApplicationWrapped app+ <> (if ordinality then " with ordinality" else mempty)+ <> maybe mempty (\a -> " " <> renderFuncAliasClauseDoc a) mFuncAlias+ Ast.FuncTableRef lp ft mFuncAlias ->+ pfx+ <> ( (if lp then "lateral " else mempty)+ <> renderFuncTable ft+ <> maybe mempty (\a -> " " <> renderFuncAliasClauseDoc a) mFuncAlias+ )+ Ast.SelectTableRef lp swp mAlias ->+ pfx+ <> (if lp then "lateral " else mempty)+ <> renderSelectWithParensMaybeWrap swp+ <> maybe mempty (\a -> " " <> inline render a) mAlias+ Ast.JoinTableRef jt mAlias ->+ pfx <> renderJoinedTable jt <> maybe mempty (\a -> " " <> inline render a) mAlias+ where+ pfx = if isFirst then "from " else mempty+++-- | Render a joined table. The @from @ prefix is the caller's responsibility+-- (added by 'renderTableRef' when the surrounding 'JoinTableRef' is the first+-- FROM item) so that parenthesized or non-first joins don't end up with the+-- @from@ keyword inside the parens or duplicated mid-list.+renderJoinedTable :: Ast.JoinedTable -> Doc ann+renderJoinedTable = \case+ Ast.InParensJoinedTable jt -> "(" <> renderJoinedTable jt <> ")"+ Ast.CrossJoinedTable left right ->+ renderTableRef False left <> hardline <> ("cross join" <+> renderTableRefDoc right)+ Ast.NaturalJoinedTable left mType right ->+ let prefix = "natural " <> maybe "" (\t -> renderJoinType t <> " ") mType <> "join"+ in renderTableRef False left <> hardline <> (pretty prefix <+> renderTableRefDoc right)+ Ast.QualJoinedTable left mType right qual ->+ -- Right-align the ON keyword (and any AND continuations) under the+ -- first word of the JOIN-block (`join` itself for a plain join, or+ -- `left` / `right` / `inner` / `full` for a prefixed one). This keeps+ -- the qualifier visually attached to the join opener regardless of+ -- how long the full keyword sequence is.+ let mTypePrefix = maybe "" (\t -> renderJoinType t <> " ") mType+ keyword = mTypePrefix <> "join"+ anchor = firstWordLen keyword+ joinHeader = pretty keyword <+> renderTableRefDoc right+ in renderTableRef False left <> hardline <> joinHeader <> hardline <> renderJoinQual anchor qual+++-- | Length of the first whitespace-delimited word in @t@ (or 0 for empty).+firstWordLen :: Text -> Int+firstWordLen = T.length . T.takeWhile (/= ' ')+++renderJoinType :: Ast.JoinType -> Text+renderJoinType = \case+ Ast.FullJoinType outer -> "full" <> if outer then " outer" else ""+ Ast.LeftJoinType outer -> "left" <> if outer then " outer" else ""+ Ast.RightJoinType outer -> "right" <> if outer then " outer" else ""+ Ast.InnerJoinType -> "inner"+++renderJoinQual :: Int -> Ast.JoinQual -> Doc ann+renderJoinQual anchor = \case+ Ast.OnJoinQual expr -> renderCondWithAndAligned anchor "on" expr+ Ast.UsingJoinQual cols ->+ "using (" <> commaJoin (map (inline render) (toL cols)) <> ")"+++-- | Render WHERE clause; AND continuations right-align with `where`'s end.+renderWhereClause :: Ast.WhereClause -> Doc ann+renderWhereClause (Ast.WhereClause expr) = renderCondWithAndAligned (T.length "where") "where" expr+++-- | Render a condition expression. AND continuations are emitted with explicit+-- left-padding so their last letter lines up with the @anchor@-wide opening+-- keyword (e.g. @anchor = 5@ for `where`, @anchor = 4@ for `join`-block ON).+--+-- AND splitting works on the rendered Text rather than the AST because+-- @postgresql-syntax@ parses @a = 1 AND b = 2@ as+-- @SymbolicBinOpAExpr a (=) (AndAExpr 1 (SymbolicBinOpAExpr b (=) ...))@ —+-- the AND ends up nested inside the comparison rather than at the top level.+renderCondWithAndAligned :: Int -> Text -> Ast.AExpr -> Doc ann+renderCondWithAndAligned anchor keyword expr =+ let renderedText = renderToText (renderExpr expr)+ parts = splitOnAnd renderedText+ kwPadLen = max 0 (anchor - T.length keyword)+ andPadLen = max 0 (anchor - T.length "and")+ kwPad = pretty (T.replicate kwPadLen " ")+ andPad = pretty (T.replicate andPadLen " ")+ in case parts of+ -- Single condition (no top-level AND): if its inline form is+ -- long and the expression is wrap-eligible, hand it off to+ -- 'renderExprMaybeWrap' so the inner shape (e.g. a long+ -- function call or @case@) can expand multi-line.+ [single]+ | T.length single > inlineLengthThreshold && isWrapEligibleExpr expr ->+ kwPad <> pretty keyword <+> renderExprMaybeWrap expr+ | otherwise ->+ kwPad <> pretty keyword <+> pretty single+ (first : rest) ->+ vsep $+ (kwPad <> pretty keyword <+> pretty first)+ : map (\p -> andPad <> "and" <+> pretty p) rest+ [] -> mempty+++-- | Render an inline 'Doc' down to 'Text'. Used in the few places we need+-- to do text-level operations (e.g. AND splitting) on the rendered output+-- before re-wrapping into a 'Doc'.+renderToText :: Doc ann -> Text+renderToText = renderStrict . layoutPretty layoutOpts+++-- | Split rendered SQL text at top-level @ and @ boundaries. Skips+-- occurrences inside parens, under a @between@, and inside single-quoted+-- string literals or double-quoted identifiers (@'@ / @"@, with standard+-- doubled-quote escapes).+splitOnAnd :: Text -> [Text]+splitOnAnd = go 0 False Nothing "" . T.unpack+ where+ go :: Int -> Bool -> Maybe Char -> String -> String -> [Text]+ go _ _ _ acc [] = [T.strip (T.pack (reverse acc))]+ -- Inside a string/quoted-identifier: doubled-quote escape stays inside;+ -- otherwise the real closing quote exits.+ go d btwn (Just q) acc (c1 : c2 : rest)+ | c1 == q && c2 == q = go d btwn (Just q) (c2 : c1 : acc) rest+ go d btwn (Just q) acc (c : rest)+ | c == q = go d btwn Nothing (c : acc) rest+ | otherwise = go d btwn (Just q) (c : acc) rest+ -- Outside strings:+ go d btwn Nothing acc ('\'' : rest) = go d btwn (Just '\'') ('\'' : acc) rest+ go d btwn Nothing acc ('"' : rest) = go d btwn (Just '"') ('"' : acc) rest+ go d btwn Nothing acc ('(' : rest) = go (d + 1) btwn Nothing ('(' : acc) rest+ go d btwn Nothing acc (')' : rest) = go (max 0 (d - 1)) btwn Nothing (')' : acc) rest+ go 0 True Nothing acc (' ' : 'a' : 'n' : 'd' : ' ' : rest) =+ go 0 False Nothing (reverse " and " ++ acc) rest+ go 0 _ Nothing acc (' ' : 'a' : 'n' : 'd' : ' ' : rest) =+ T.strip (T.pack (reverse acc)) : go 0 False Nothing "" rest+ go d _ Nothing acc ('b' : 'e' : 't' : 'w' : 'e' : 'e' : 'n' : ' ' : rest) =+ go d True Nothing (reverse "between " ++ acc) rest+ go d btwn st acc (c : rest) = go d btwn st (c : acc) rest+++renderSelectLimit :: Ast.SelectLimit -> Doc ann+renderSelectLimit = \case+ Ast.LimitOffsetSelectLimit lc oc ->+ inline render lc <> hardline <> inline render oc+ Ast.OffsetLimitSelectLimit oc lc ->+ inline render oc <> hardline <> inline render lc+ Ast.LimitSelectLimit lc -> inline render lc+ Ast.OffsetSelectLimit oc -> inline render oc+++renderWithClause :: Ast.WithClause -> Doc ann+renderWithClause (Ast.WithClause recursive ctes) =+ let keyword :: Text+ keyword = if recursive then "with recursive" else "with"+ cteList = toL ctes+ lastIdx = length cteList - 1+ in vsep $+ zipWith+ ( \i cte ->+ let isLast = i == lastIdx+ prefix = if i == (0 :: Int) then pretty keyword <> " " else mempty+ in prefix <> renderCte isLast cte+ )+ [0 :: Int ..]+ cteList+++renderCte :: Bool -> Ast.CommonTableExpr -> Doc ann+renderCte isLast (Ast.CommonTableExpr name mCols mMaterialized stmt) =+ let suffix = if isLast then ")" else "),"+ materializedKeyword = case mMaterialized of+ Nothing -> ""+ Just True -> "materialized "+ Just False -> "not materialized "+ header =+ inline render name+ <> maybe+ mempty+ (\cols -> " (" <> commaJoin (map (inline render) (toL cols)) <> ")")+ mCols+ <> " as "+ <> materializedKeyword+ <> "("+ in header+ <> hardline+ <> indent indentSize (renderPreparableStmt stmt)+ <> hardline+ <> suffix+++-- | Render INSERT statement.+renderInsertStmt :: Ast.InsertStmt -> Doc ann+renderInsertStmt (Ast.InsertStmt mWith target rest mConflict mReturning) =+ vsep $+ catMaybes+ [ renderWithClause <$> mWith+ , Just ("insert into" <+> renderInsertTarget target)+ , Just (renderInsertRest rest)+ , renderOnConflict <$> mConflict+ , (\(Ast.ReturningClause rc) -> "returning" <+> renderTargetListInline rc) <$> mReturning+ ]+++renderInsertRest :: Ast.InsertRest -> Doc ann+renderInsertRest = \case+ Ast.SelectInsertRest mCols mOverride selectStmt ->+ let colsDoc = maybe mempty renderInsertColumnList mCols+ overrideDoc = case mOverride of+ Nothing -> mempty+ Just o -> "overriding " <> inline render o <> " value" <> hardline+ selectDoc = overrideDoc <> renderSelectStmt selectStmt+ in case mCols of+ Nothing -> selectDoc+ Just _ -> colsDoc <> hardline <> selectDoc+ Ast.DefaultValuesInsertRest -> "default values"+++-- | Render the bracketed INSERT column list. Short lists (≤ 3 cols) stay on+-- one line wrapped in `(...)`; longer lists use the bracket-list block-comma+-- layout.+renderInsertColumnList :: Ast.InsertColumnList -> Doc ann+renderInsertColumnList cols =+ let items = toL cols+ rendered = map (inline render) items+ in if length items <= insertInlineColumns+ then indent indentSize ("(" <> commaJoin rendered <> ")")+ else indent indentSize (renderBracketList rendered)+++-- | Build the bracket-list layout used for long INSERT column lists and+-- VALUES tuples:+--+-- @+-- ( first+-- , second+-- , third+-- )+-- @+renderBracketList :: [Doc ann] -> Doc ann+renderBracketList = \case+ [] -> "()"+ (x : xs) ->+ vsep $+ ("( " <> x)+ : map (", " <>) xs+ ++ [")"]+++-- | Render VALUES clause. The keyword `values` lands on its own line with the+-- tuples emitted as bracket-lists below it.+renderValuesClause :: Ast.ValuesClause -> Doc ann+renderValuesClause vc =+ let rows = toL vc+ lastIdx = length rows - 1+ renderRow i row =+ let bracketed = renderValuesRow row+ in if i < lastIdx then bracketed <> "," else bracketed+ in "values"+ <> hardline+ <> indent indentSize (vsep (zipWith renderRow [(0 :: Int) ..] rows))+++renderValuesRow :: Ast.ExprList -> Doc ann+renderValuesRow exprs =+ let items = toL exprs+ rendered = map renderExpr items+ in case items of+ [_] -> "(" <> commaJoin rendered <> ")"+ _ -> renderBracketList rendered+++renderOnConflict :: Ast.OnConflict -> Doc ann+renderOnConflict (Ast.OnConflict mConfExpr onDo) =+ let header = "on conflict" <> maybe mempty (\ce -> " " <> inline render ce) mConfExpr+ in header <> hardline <> renderOnConflictDo onDo+++renderOnConflictDo :: Ast.OnConflictDo -> Doc ann+renderOnConflictDo = \case+ Ast.NothingOnConflictDo -> "do nothing"+ Ast.UpdateOnConflictDo setClauses mWhere ->+ let items = toL setClauses+ base = case items of+ [single] ->+ "do update set"+ <> hardline+ <> indent indentSize (renderSetClause single)+ _ ->+ let renderItem i clause =+ let d = renderSetClause clause+ in if i < length items - 1+ then d <> ","+ else d+ in "do update set"+ <> hardline+ <> indent indentSize (vsep (zipWith renderItem [(0 :: Int) ..] items))+ in case mWhere of+ Nothing -> base+ Just w -> base <> hardline <> renderWhereClause (Ast.WhereClause w)+++-- | Render UPDATE statement.+renderUpdateStmt :: Ast.UpdateStmt -> Doc ann+renderUpdateStmt (Ast.UpdateStmt mWith rel setClauses mFrom mWhere mReturning) =+ vsep $+ catMaybes+ [ renderWithClause <$> mWith+ , Just ("update" <+> inline render rel)+ , Just (renderSetClauseLines setClauses)+ , renderFromClause <$> mFrom+ , renderWhereOrCurrent <$> mWhere+ , (\(Ast.ReturningClause rc) -> "returning" <+> renderTargetListInline rc) <$> mReturning+ ]+++-- | Render DELETE statement.+renderDeleteStmt :: Ast.DeleteStmt -> Doc ann+renderDeleteStmt (Ast.DeleteStmt mWith rel mUsing mWhere mReturning) =+ vsep $+ catMaybes+ [ renderWithClause <$> mWith+ , Just ("delete from" <+> inline render rel)+ , (\(Ast.UsingClause u) -> "using" <+> inline render u) <$> mUsing+ , renderWhereOrCurrent <$> mWhere+ , (\(Ast.ReturningClause rc) -> "returning" <+> renderTargetListInline rc) <$> mReturning+ ]+++renderWhereOrCurrent :: Ast.WhereOrCurrentClause -> Doc ann+renderWhereOrCurrent = \case+ Ast.ExprWhereOrCurrentClause expr -> renderWhereClause (Ast.WhereClause expr)+ Ast.CursorWhereOrCurrentClause name -> "where current of" <+> inline render name+++-- | Multi-assignment SETs put `set` on its own line and use the same+-- block-list layout as multi-target SELECTs. Single-assignment SETs stay+-- inline (`set col = val`).+renderSetClauseLines :: Ast.SetClauseList -> Doc ann+renderSetClauseLines setClauses =+ let items = toL setClauses+ in case items of+ [single] -> "set" <+> renderSetClause single+ _ -> renderBlockListWith "set" renderSetClause items
+ test/FileSpec.hs view
@@ -0,0 +1,262 @@+module Main (main) where++import Control.Monad (unless)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import PgStyle+import System.Exit (exitFailure)+++data Case = Case+ { name :: Text+ , backend :: Backend+ , keywordCase :: KeywordCase+ , input :: Text+ , expected :: Expected+ }+++data Expected+ = -- | This output, with no statement failed.+ Output Text+ | -- | Unchanged, each statement kept for this reason.+ Unchanged Text+ | -- | Output containing each of these, with no statement failed.+ Contains [Text]+ | -- | Not valid SQL.+ Invalid+ | -- | Unchanged, a backend's output refused as a different statement.+ Refused+++cases :: [Case]+cases =+ [ Case+ { name = "syntax: DML is laid out, the text between statements kept"+ , backend = Syntax+ , keywordCase = Lower+ , input = "-- header\n\nSELECT a, b FROM t WHERE x = 1;\n\n/* between */\nselect 1 ;\n"+ , expected = Output "-- header\n\nselect\n a\n , b\nfrom t\nwhere x = 1;\n\n/* between */\nselect 1 ;\n"+ }+ , Case+ { name = "syntax: DDL it has no layout for is left alone"+ , backend = Syntax+ , keywordCase = Lower+ , input = "CREATE SEQUENCE s;\n"+ , expected = Unchanged "pgstyle does not lay it out: not DML or DDL pgstyle lays out"+ }+ , Case+ { name = "syntax: a comment inside a statement stays at its place"+ , backend = Syntax+ , keywordCase = Lower+ , input = "SELECT a -- the a\nFROM t;\n"+ , expected = Output "select a -- the a\nfrom t;\n"+ }+ , Case+ { name = "syntax: a comment with no line break at its place leaves the statement alone"+ , backend = Syntax+ , keywordCase = Lower+ , input = "SELECT a + -- inside\n b FROM t;\n"+ , expected = Unchanged "pgstyle does not lay it out: a comment pgstyle cannot place"+ }+ , Case+ { name = "syntax: an indented statement's comment lines are indented with it"+ , backend = Syntax+ , keywordCase = Lower+ , input = "begin;\n select a, -- x\n -- y\n b from t;\ncommit;\n"+ , expected = Output "begin;\n select\n a -- x\n -- y\n , b\n from t;\ncommit;\n"+ }+ , Case+ { name = "libpg-query: DDL is pretty-printed"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "create table t (a int, b text not null);\n"+ , expected = Output "create table t (\n a int,\n b text not null\n);\n"+ }+ , Case+ { name = "libpg-query: a comment it moves to the end does not swallow the semicolon"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "SELECT a -- the a\nFROM t;\nSELECT 2;\n"+ , expected = Output "select a\nfrom t\n-- the a\n;\nselect 2;\n"+ }+ , Case+ { name = "libpg-query: a SET value stays a string, not a quoted identifier"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "set lock_timeout to '50ms';\nset statement_timeout to '50ms';\n"+ , expected = Output "set lock_timeout to '50ms';\nset statement_timeout to '50ms';\n"+ }+ , Case+ { name = "libpg-query: a search_path with \"$user\" parses to the same statement"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "set search_path to \"$user\", public;\n"+ , expected = Output "set search_path to '$user', public;\n"+ }+ , Case+ { name = "libpg-query: SET values that are words, numbers or default stay bare"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "set x to on;\nset search_path to public;\nset statement_timeout to 10000;\nset x to default;\n"+ , expected = Output "set x to on;\nset search_path to public;\nset statement_timeout to 10000;\nset x to default;\n"+ }+ , Case+ { name = "libpg-query: a function's language stays a bare word"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "create function f() returns int language plpgsql as $$ begin return 1; end; $$;\n"+ , expected = Output "create function f() returns int language plpgsql as $$ begin return 1; end; $$;\n"+ }+ , Case+ { name = "auto: DDL to libpg_query, DML to the syntax backend"+ , backend = Auto+ , keywordCase = Lower+ , input = "create table t (a int, b text);\nselect a, b from t;\n"+ , expected = Output "create table t (\n a int,\n b text\n);\nselect\n a\n , b\nfrom t;\n"+ }+ , Case+ { name = "an indented statement keeps its indent"+ , backend = Syntax+ , keywordCase = Lower+ , input = "begin;\n select a, b from t;\ncommit;\n"+ , expected = Output "begin;\n select\n a\n , b\n from t;\ncommit;\n"+ }+ , Case+ { name = "lines inside a string are not indented"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "begin;\n select 'a\nb';\ncommit;\n"+ , expected = Output "begin;\n select 'a\nb';\ncommit;\n"+ }+ , Case+ { name = "comments around a statement stay put"+ , backend = Syntax+ , keywordCase = Lower+ , input = "/* before */ select a, b from t -- after\n;\n"+ , expected = Output "/* before */ select\n a\n , b\nfrom t -- after\n;\n"+ }+ , Case+ { name = "upper: keywords from both backends, identifiers spelled like keywords untouched"+ , backend = Auto+ , keywordCase = Upper+ , input = "create table t (name text, type int);\ncomment on column t.type is 'the type';\nselect name, type from t where name = 'x';\n"+ , expected = Output "CREATE TABLE t (\n name text,\n type INT\n);\nCOMMENT ON COLUMN t.type IS 'the type';\nSELECT\n name\n , type\nFROM t\nWHERE name = 'x';\n"+ }+ , Case+ { name = "PL/pgSQL: embedded statements are laid out, INTO and control flow left alone"+ , backend = Auto+ , keywordCase = Lower+ , input = "create function f(p int) returns void language plpgsql as $$\ndeclare\n v int;\nbegin\n select a into v from t where id = p;\n update t set a = 1, b = 2 where id = p;\n if v > 1 then\n delete from t where id = p;\n end if;\nend;\n$$;\n"+ , expected = Output "create function f(p int)\n returns void\n language plpgsql as\n$$\ndeclare\n v int;\nbegin\n select a into v from t where id = p;\n update t\n set\n a = 1\n , b = 2\n where id = p;\n if v > 1 then\n delete from t\n where id = p;\n end if;\nend;\n$$;\n"+ }+ , Case+ { name = "PL/pgSQL: a dollar-quoted argument default is not taken for the body"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "create function f(p text default $$update t set a=1$$)\nreturns text language plpgsql\nas 'begin update t set a=1; return p; end';\n"+ , expected = Contains ["'update t set a=1'"]+ }+ , Case+ { name = "PL/pgSQL: a default spelled like the body leaves the body alone"+ , backend = Auto+ , keywordCase = Lower+ , input = "create function f(p text default $$begin update t set a=1; return p; end$$)\nreturns text language plpgsql\nas $$begin update t set a=1; return p; end$$;\n"+ , expected = Contains ["as\n$$begin update t set a=1; return p; end$$"]+ }+ , Case+ { name = "standard_conforming_strings off leaves the file alone"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "set standard_conforming_strings = off;\nselect '\\n';\n"+ , expected = Unchanged "the file sets standard_conforming_strings"+ }+ , Case+ { name = "PL/pgSQL: SQL in a comment is not taken for the statement"+ , backend = Auto+ , keywordCase = Lower+ , input = "create function f() returns void language plpgsql as $$\nbegin\n /* update t set a=1 */ update t set a=1;\nend;\n$$;\n"+ , expected = Contains ["/* update t set a=1 */ update t\n set a = 1;"]+ }+ , Case+ { name = "PL/pgSQL: identical statements on one line are each matched once"+ , backend = Auto+ , keywordCase = Lower+ , input = "create function f() returns void language plpgsql as $$\nbegin\n update t set a=1; update t set a=1;\nend;\n$$;\n"+ , expected = Contains [" update t\n set a = 1; update t\n set a = 1;"]+ }+ , Case+ { name = "libpg-query: IN lists and array literals, whose bracket positions are in the tree, verify"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "SELECT a FROM t WHERE x IN (1, 2) AND y = ARRAY[1,2];\n"+ , expected = Output "select a\nfrom t\nwhere\n x in (1, 2)\n and y = array[1, 2];\n"+ }+ , Case+ { name = "libpg-query: a quoted parameter name it would unquote is refused"+ , backend = LibPgQuery+ , keywordCase = Lower+ , input = "create function f(\"startDate\" date) returns int language sql as 'select 1';\n"+ , expected = Refused+ }+ , Case+ { name = "not SQL"+ , backend = Auto+ , keywordCase = Lower+ , input = "\\set x 1\nselect :x;\n"+ , expected = Invalid+ }+ ]+++main :: IO ()+main = do+ failures <- newIORef (0 :: Int)+ let failWith n msg = do+ TIO.putStrLn ("FAIL: " <> n <> "\n" <> msg)+ modifyIORef' failures (+ 1)+ mapM_ (runCase failWith) cases+ n <- readIORef failures+ unless (n == 0) exitFailure+ putStrLn ("All " <> show (length cases) <> " file tests passed.")+++runCase :: (Text -> Text -> IO ()) -> Case -> IO ()+runCase failWith c = do+ let opts = Options{backend = c.backend, dialect = defaultOptions.dialect, keywordCase = c.keywordCase, pretty = defaultOptions.pretty}+ result <- formatFile opts c.input+ case (c.expected, result) of+ (Invalid, Left _) -> pure ()+ (Invalid, Right r) -> failWith c.name ("expected a parse error, got:\n" <> r.output)+ (_, Left err) -> failWith c.name ("parse error: " <> T.pack (show err))+ (Refused, Right r) -> do+ unless (r.output == c.input) $ failWith c.name ("changed:\n" <> r.output)+ unless (any (isFailed . (.outcome)) r.reports) $+ failWith c.name ("reports: " <> T.pack (show r.reports))+ (Unchanged reason, Right r) -> do+ unless (r.output == c.input) $ failWith c.name ("changed:\n" <> r.output)+ unless (all ((== Kept reason) . (.outcome)) r.reports) $+ failWith c.name ("reports: " <> T.pack (show r.reports))+ (Contains needles, Right r) -> do+ mapM_+ (\n -> unless (n `T.isInfixOf` r.output) $ failWith c.name ("missing " <> T.pack (show n) <> " in:\n" <> r.output))+ needles+ unless (not (any (isFailed . (.outcome)) r.reports)) $+ failWith c.name ("reports: " <> T.pack (show r.reports))+ (Output out, Right r) -> do+ unless (r.output == out) $+ failWith c.name ("=== expected ===\n" <> out <> "=== actual ===\n" <> r.output)+ unless (not (any (isFailed . (.outcome)) r.reports)) $+ failWith c.name ("reports: " <> T.pack (show r.reports))+ -- Formatting is idempotent.+ again <- formatFile opts r.output+ case again of+ Right r' | r'.output == r.output -> pure ()+ Right r' -> failWith c.name ("not idempotent:\n" <> r'.output)+ Left err -> failWith c.name ("output does not parse: " <> T.pack (show err))+ where+ isFailed = \case+ Failed _ -> True+ _ -> False
+ test/HaskellSpec.hs view
@@ -0,0 +1,187 @@+module Main (main) where++import Control.Monad (unless)+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import PgStyle+import PgStyle.Haskell (Quoters, defaultQuoters, formatHaskell)+import System.Exit (exitFailure)+++data Case = Case+ { name :: Text+ , quoters :: Quoters+ , input :: [Text]+ , output :: [Text]+ , reports :: [(Int, Outcome)]+ -- ^ The line of each quasiquote of 'quoters', and what happened to it.+ }+++-- | Each quasiquote below opens at column 4, so its SQL is laid out at+-- column 8 and its closing bar at column 4.+cases :: [Case]+cases =+ [ Case+ { name = "a quasiquote is laid out under its opening bracket"+ , quoters = defaultQuoters+ , input =+ [ "q = [singletonStatement|"+ , " select a :: int8, b :: text from t where id = $1 :: int8"+ , " |]"+ ]+ , output =+ [ "q = [singletonStatement|"+ , " select"+ , " a::int8"+ , " , b::text"+ , " from t"+ , " where id = $1::int8"+ , " |]"+ ]+ , reports = [(1, FormattedBy Syntax)]+ }+ , Case+ { name = "quasiquotes in comments and strings are not quasiquotes"+ , quoters = defaultQuoters+ , input =+ [ "-- [singletonStatement|"+ , "-- select 1 |]"+ , "{- {- nested [vectorStatement|"+ , "select 1 |] -} -}"+ , "a = \"[maybeStatement|\\"+ , " \\select 1 |]\""+ ]+ , output =+ [ "-- [singletonStatement|"+ , "-- select 1 |]"+ , "{- {- nested [vectorStatement|"+ , "select 1 |] -} -}"+ , "a = \"[maybeStatement|\\"+ , " \\select 1 |]\""+ ]+ , reports = []+ }+ , Case+ { name = "quotes in character literals, primes and quoted names do not start strings"+ , quoters = defaultQuoters+ , input =+ [ "c = '\"'"+ , "e = '\\''"+ , "x' = ''Int"+ , "(-->) = 'id"+ , "r = [vectorStatement|"+ , " select a :: int8 from t"+ , " |]"+ ]+ , output =+ [ "c = '\"'"+ , "e = '\\''"+ , "x' = ''Int"+ , "(-->) = 'id"+ , "r = [vectorStatement|"+ , " select a::int8"+ , " from t"+ , " |]"+ ]+ , reports = [(5, FormattedBy Syntax)]+ }+ , Case+ { name = "another quoter's body is skipped, quotes and all; a qualified quoter counts"+ , quoters = defaultQuoters+ , input =+ [ "g = [i|it's \"odd |]"+ , "r = [Hasql.TH.maybeStatement|"+ , " select a :: int8 from t"+ , " |]"+ ]+ , output =+ [ "g = [i|it's \"odd |]"+ , "r = [Hasql.TH.maybeStatement|"+ , " select a::int8"+ , " from t"+ , " |]"+ ]+ , reports = [(2, FormattedBy Syntax)]+ }+ , Case+ { name = "a quoter added to the defaults is formatted"+ , quoters = defaultQuoters <> ["sql"]+ , input =+ [ "s = [sql|"+ , " select a :: int8 from t"+ , " |]"+ ]+ , output =+ [ "s = [sql|"+ , " select a::int8"+ , " from t"+ , " |]"+ ]+ , reports = [(1, FormattedBy Syntax)]+ }+ , Case+ { name = "single-line and unparsed quasiquotes are kept; the others are still formatted"+ , quoters = defaultQuoters+ , input =+ [ "a = [singletonStatement|select 1 :: int4|]"+ , "b = [uncheckedSql|"+ , " create table t (a int)"+ , " |]"+ , "c = [singletonStatement|"+ , " select 1 :: int4"+ , " |]"+ ]+ , output =+ [ "a = [singletonStatement|select 1 :: int4|]"+ , "b = [uncheckedSql|"+ , " create table t (a int)"+ , " |]"+ , "c = [singletonStatement|"+ , " select 1::int4"+ , " |]"+ ]+ , reports =+ [ (1, Kept "single-line quasiquotes are left as they are")+ , (2, Kept "postgresql-syntax does not parse it")+ , (5, FormattedBy Syntax)+ ]+ }+ , Case+ { name = "an opening with no closing bar is a list comprehension"+ , quoters = defaultQuoters <> ["x"]+ , input = ["xs = [x|x <- [1, 2]]"]+ , output = ["xs = [x|x <- [1, 2]]"]+ , reports = []+ }+ ]+++main :: IO ()+main = do+ failures <- newIORef (0 :: Int)+ let failWith label lines' = do+ modifyIORef' failures (+ 1)+ TIO.putStrLn ("FAIL: " <> label)+ mapM_ TIO.putStrLn lines'+ mapM_+ ( \c -> do+ let source = T.unlines c.input+ expected = T.unlines c.output+ r = formatHaskell c.quoters source+ got = [(rep.line, rep.outcome) | rep <- r.reports]+ again = formatHaskell c.quoters r.output+ unless (r.output == expected) $+ failWith c.name ["=== expected ===", expected, "=== actual ===", r.output]+ unless (got == c.reports) $+ failWith (c.name <> " (reports)") [T.pack (show got)]+ unless (again.output == r.output) $+ failWith (c.name <> " (not idempotent)") [again.output]+ )+ cases+ n <- readIORef failures+ if n == 0+ then putStrLn ("All " <> show (length cases) <> " Haskell tests passed.")+ else exitFailure
+ test/LayoutSpec.hs view
@@ -0,0 +1,232 @@+module Main (main) where++import Control.Monad (forM, unless)+import Data.Either (isLeft)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.IO qualified as TIO+import PgStyle.Layout qualified as Layout+import PgStyle.Render (Dialect (..))+import PgStyle.Render qualified as Render+import System.Exit (exitFailure)+++-- | Statements both renderers lay out: "PgStyle.Layout", over libpg_query's+-- tree, must write each exactly as "PgStyle.Render" does over+-- postgresql-syntax's.+sameAsRender :: [Text]+sameAsRender =+ [ "select a, b from t where x = 1"+ , "select (a).b, $1.f, ((a)).c from t"+ , "select a != b, a <> b, a->>'k', a -> 'k' = b, -a, +a, - 1, ~a from t"+ , "select f(a => 1, b := 2), count(*), count(distinct x), string_agg(x, ',' order by y), sum(x) filter (where y > 0) over (partition by z order by w desc nulls last) from t"+ , "select x::int, x::integer, x::int4, x::numeric(10, 2), x::text[], x::timestamp with time zone, x::double precision, cast(x as bigint), interval '1 day', date '2020-01-01', interval '1' day from t"+ , "select coalesce(a, b), greatest(a, b), least(a, 1), nullif(a, b), row(1, 2), (1, 2), array[1, 2], array[[1, 2], [3, 4]], array(select 1) from t"+ , "select exists (select 1 from u), (select max(x) from u), a in (select x from u), a not in (select x from u), a = any (select x from u), a = any(b), a <> all(b) from t"+ , "select extract(year from x), extract(epoch from x), position('a' in b), substring(x from 1 for 2), substring(x, 1, 2), trim(both 'x' from y), trim(y), now() at time zone 'utc', current_date, current_timestamp, localtime from t"+ , "select case when a then b when c then d else e end, case x when 1 then 'a' end from t"+ , "select a is null, a isnull, a is not null, a is true, a is distinct from b, a is not distinct from b, a between 1 and 2, a not between 1 and 2, a like 'x%', a not ilike 'y' from t"+ , "select * from a join b on a.id = b.id left join c using (id) cross join d natural join e inner join f on true left outer join g on g.x = a.x and g.y = 2"+ , "select * from (select 1) s, lateral (select 2) l, generate_series(1, 10) with ordinality as g(i, n), unnest(arr) u"+ , "select * from ((a join b on true) join c on true)"+ , "with x as (select 1), y (a, b) as materialized (select 1, 2) select * from x, y"+ , "with recursive r as (select 1 union all select n + 1 from r where n < 10) select * from r"+ , "select 1 union select 2 union all select 3 intersect select 4 except select 5"+ , "(select 1 order by 1) union (select 2)"+ , "select a from t order by a desc, b asc nulls first limit 10 offset 5"+ , "select a from t offset 5 limit 10"+ , "select a from t for update of t skip locked"+ , "select distinct on (a) a, b from t"+ , "select a, count(*) from t group by rollup (a, b) having count(*) > 1"+ , "insert into t as x (a, b, c, d) select 1, 2, 3, 4 on conflict on constraint t_pk do nothing"+ , "insert into t default values"+ , "update t set a = 1, b = 2 from u where t.id = u.id returning t.a as aa, t.b bb"+ , "update t set (a, b) = (1, 2) where id = 1"+ , "update t x set a = (select max(y) from u) where x.id = 1"+ , "delete from t using u where t.id = u.id returning *"+ , "select jsonb_build_object('a', 1, 'b', 2, 'c', jsonb_build_object('d', 3, 'e', 4))"+ , "select f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ccccccccccccccccccccccccccc(ddddddddddddddddddddddd, eeeeeeeeeeeeeeeeeeeee, fffffffffffffffffffffff))"+ , "select a from t where exists (select 1 from uuuuuuuuuuuuuuuuuuuuuu u where u.aaaaaaaaaaaaaaaaaaaaaaaa = t.aaaaaaaaaaaaaaaaaaaaaaaaaaaaa and u.b = 1)"+ , "select (case when a then 1 else 2 end)::text, (x + 1) * 2, -(x), not (a and b) from t"+ , "select \"Foo\", \"select\", t.\"Bar\", \"left\"(x, 1), left(x, 2) from \"MyTable\" t"+ , "select 007, 1.5, 100.0, 'it''s', b'0101', x'FF', true, null"+ , "select a from t where a = 1 and (b = 2 or c = 3) and d between 1 and 2 and e = 4"+ , "select x from t where (a = 1 and b = 2) and c = 3"+ , "select x from t where ((a and b) and c) and d or e"+ , "select (a or b) or c, ((a)) and b from t"+ , "select row_number() over (order by a rows between unbounded preceding and current row) from t window w as (partition by b)"+ , "select x from t tablesample bernoulli (5) repeatable (42) where a = 1"+ , "select a as \"Alias\", b \"B\", t.c as c from t"+ , "select a[1], a[1:2], b.c[3] from t"+ , "call my_proc(1, 'a')"+ , "select x collate \"C\" from t"+ , "update t set a = case when b then 1 else 2 end, c = coalesce(d, e, fffffffffffffffffffffffffffffffffffffff, gggggggggggggggggggggggggggggggggggg) where id = 1"+ , "select a from t where a in (1, -2) and b = -1"+ , "select x from t join (select a from u) s on s.a = t.a join lateral f(t.a, t.b) z on true"+ , "select * from t where not exists (select 1 from u where u.a = t.a) and t.b is not null"+ , "select pc.a from p pc, jsonb_to_recordset(pc.j) as c (fingerprint text, masked_pan text)"+ , "select x from t where a in (select all b from u) and c in (select distinct d from u)"+ ]+++-- | A statement and the layout it should get, keywords in lower or upper+-- case.+data Expected = Expected+ { upperKeywords :: Bool+ , sql :: Text+ , want :: Text+ }+++lower, upper :: Text -> Text -> Expected+lower sql want = Expected{upperKeywords = False, sql, want}+upper sql want = Expected{upperKeywords = True, sql, want}+++-- | Statements with an expected layout: keywords in upper case, what+-- postgresql-syntax could not read, and comments.+expected :: [Expected]+expected =+ [ upper "select a, x::int, x::text, count(*) from t where x is not null" "SELECT\n a\n , x::INT\n , x::text\n , count(*)\nFROM t\nWHERE x IS NOT NULL"+ , upper "select name, type from t where value = 1 and y between 1 and 2" "SELECT\n name\n , type\nFROM t\nWHERE value = 1\n AND y BETWEEN 1 AND 2"+ , lower "select x::varchar(10), y::time(3) with time zone from t" "select\n x::varchar (10)\n , y::time (3) with time zone\nfrom t"+ , lower "select E'a\\nb', 1.50" "select\n E'a\\nb'\n , 1.50"+ , -- Values rows go on one line each when every row fits, unlike+ -- "PgStyle.Render"; a row too long, or with a comment inside, puts+ -- every row's values one per line.+ lower "values (1, 'a'), (2, 'b')" "values\n (1, 'a'),\n (2, 'b')"+ , lower "insert into t (a, b) values (1, 2) on conflict (a) do update set b = excluded.b where t.b <> excluded.b returning *" "insert into t\n (a, b)\nvalues\n (1, 2)\non conflict (a)\ndo update set\n b = excluded.b\nwhere t.b <> excluded.b\nreturning *"+ , lower "values (1, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), (2, 'b')" "values\n ( 1\n , 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\n ),\n ( 2\n , 'b'\n )"+ , lower "values (1, -- one\n 'a'), (2, 'b')" "values\n ( 1 -- one\n , 'a'\n ),\n ( 2\n , 'b'\n )"+ , -- A blank line between rows is kept; one after "values" is not.+ lower "values\n\n(1), (2),\n\n(3), -- x\n\n(4)" "values\n (1),\n (2),\n\n (3), -- x\n\n (4)"+ , -- Dollar-quoted strings are kept as written; plain ones continued over+ -- lines are joined.+ lower "select $$it's$$, $f$ a\n b $f$, 'a'\n 'b'" "select\n $$it's$$\n , $f$ a\n b $f$\n , 'ab'"+ , -- A string's lines stay as they are, however deep the layout puts it.+ lower "with x as (select 'a\nb' as s) select s from x" "with x as (\n select 'a\nb' as s\n)\nselect s\nfrom x"+ , -- Comments go where the layout breaks a line at their place: one on a+ -- line with code at the end of the line before the break, one on a+ -- line of its own on a line of its own after it.+ lower "select a, -- the a\n -- before b\n b /* the b */\n from t -- the t\n /* where next */ where x = 1" "select\n a -- the a\n -- before b\n , b /* the b */\nfrom t -- the t\n/* where next */\nwhere x = 1"+ , -- A list with a comment in it takes its multi-line form.+ lower "select f(a, -- first\n b)" "select f(\n a -- first\n , b\n)"+ , lower "select x from t where a in (1, -- one\n 2) and b = 1" "select x\nfrom t\nwhere a in (\n 1 -- one\n , 2\n)\n and b = 1"+ , lower "select array[1, -- one\n 2]" "select array[\n 1 -- one\n , 2\n]"+ , lower "values (1, 'a'), -- one\n (2, 'b')" "values\n (1, 'a'), -- one\n (2, 'b')"+ , lower "update t set a = 1, -- the a\n b = 2 where id = 1" "update t\nset\n a = 1 -- the a\n , b = 2\nwhere id = 1"+ , lower "insert into t (a, b) -- columns\n select 1, 2 -- values\n on conflict do nothing" "insert into t\n (a, b) -- columns\nselect\n 1\n , 2 -- values\non conflict\ndo nothing"+ , lower "select a from t group by -- grouped\n a" "select a\nfrom t\ngroup by -- grouped\n a"+ , lower "with x as (select 1), -- first\n y as (select 2) select * from x, y" "with x as (\n select 1\n), -- first\ny as (\n select 2\n)\nselect *\nfrom x, y"+ , upper "select 1 -- one\nunion all select 2" "SELECT 1 -- one\nUNION ALL\nSELECT 2"+ , -- A blank line before a comment is kept.+ lower "select f(a, -- one\n\n -- two\n b)" "select f(\n a -- one\n\n -- two\n , b\n)"+ , -- create table: one element per line, trailing commas, the source's+ -- own keywords; types with no space before their modifiers.+ lower "CREATE TEMPORARY TABLE IF NOT EXISTS s.t (id bigint NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1 CACHE 10), price numeric (10,2) DEFAULT 0, ref text references u (id) on delete no action, PRIMARY KEY (id)) ON COMMIT DROP" "create temporary table if not exists s.t (\n id bigint not null generated always as identity (start with 1 cache 10),\n price numeric(10, 2) default 0,\n ref text references u(id) on delete no action,\n primary key (id)\n) on commit drop"+ , upper "create table t (a int not null, constraint a_positive check (a > 0)) partition by range (a)" "CREATE TABLE t (\n a INT NOT NULL,\n CONSTRAINT a_positive CHECK (a > 0)\n) PARTITION BY RANGE (a)"+ , lower "create table t (like u including defaults)" "create table t (\n like u including defaults\n)"+ , lower "create table t ()" "create table t ()"+ , -- A long check breaks at its top-level ands (or ors); a long foreign+ -- key before references.+ lower "create table t (a text, b text, constraint some_check check (char_length(a) <= 100 and trim(both ' ' from a) <> '' and b is not null and b <> 'none'), constraint fk_t_long foreign key (a, b) references some_schema.other_table(a, b) on delete cascade)" "create table t (\n a text,\n b text,\n constraint some_check check (\n char_length(a) <= 100\n and trim(both ' ' from a) <> ''\n and b is not null\n and b <> 'none'\n ),\n constraint fk_t_long foreign key (a, b)\n references some_schema.other_table(a, b) on delete cascade\n)"+ , lower "create table t (total int generated always as (a + b) stored, d date default current_date unique deferrable initially deferred)" "create table t (\n total int generated always as (a + b) stored,\n d date default current_date unique deferrable initially deferred\n)"+ , -- Comments and blank lines between columns are kept; a comment+ -- between a constraint's name and its body puts the body under it.+ lower "create table t ( -- the table\n a int, -- the a\n\n -- the b\n b int,\n constraint b_check\n -- b is small\n check (b < 10)\n -- the end\n)" "create table t ( -- the table\n a int, -- the a\n\n -- the b\n b int,\n constraint b_check\n -- b is small\n check (b < 10)\n -- the end\n)"+ , -- create view and create ... as: the query laid out under the head.+ lower "create or replace view v (x, y) as select a, b from t where c with local check option" "create or replace view v (x, y) as\nselect\n a\n , b\nfrom t\nwhere c\nwith local check option"+ , upper "create materialized view m as select a from t with no data" "CREATE MATERIALIZED VIEW m AS\nSELECT a\nFROM t\nWITH NO DATA"+ , lower "create temp table t on commit drop as select 1" "create temp table t on commit drop as\nselect 1"+ , -- create index: on and where on lines of their own, using only if+ -- written; a long where breaks at its ands and ors.+ lower "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS i ON s.t(a, (lower(b)) desc nulls last) WHERE c" "create unique index concurrently if not exists i\n on s.t (a, (lower(b)) desc nulls last)\n where c"+ , upper "create index i on t using gin (name gin_trgm_ops)" "CREATE INDEX i\n ON t USING gin (name gin_trgm_ops)"+ , lower "create index i -- why\n on t (a) where (status = 'pre_flight_check' or status = 'initializing' or status = 'waiting_for_payment') and kind = 'x'" "create index i -- why\n on t (a)\n where\n (\n status = 'pre_flight_check'\n or status = 'initializing'\n or status = 'waiting_for_payment'\n )\n and kind = 'x'"+ , -- create function: the arguments on the first line if they fit; each+ -- clause before the body on a line of its own, the last ending in as;+ -- the body from the start of the next line; the clauses after it on+ -- its last line.+ lower "create or replace function f(a bigint, b text default null) returns trigger as $$ begin return new; end $$ language plpgsql security definer" "create or replace function f(a bigint, b text default null)\n returns trigger as\n$$ begin return new; end $$ language plpgsql security definer"+ , lower "CREATE FUNCTION s.f(market text, content jsonb, description text default null, rating numeric(4,2) = null, out total int) RETURNS SETOF jsonb LANGUAGE sql STABLE SET search_path = public, pg_temp AS 'select 1'" "create function s.f(\n market text,\n content jsonb,\n description text default null,\n rating numeric(4, 2) = null,\n out total int\n)\n returns setof jsonb\n language sql\n stable\n set search_path = public, pg_temp as\n'select 1'"+ , lower "create function f() returns table (id bigint, item jsonb) as $$ select 1, null::jsonb $$ language sql" "create function f()\n returns table (id bigint, item jsonb) as\n$$ select 1, null::jsonb $$ language sql"+ , lower "create procedure p(inout x int) language plpgsql as $$ begin x := 1; end $$" "create procedure p(inout x int)\n language plpgsql as\n$$ begin x := 1; end $$"+ , -- Comments on arguments; a comment among the clauses after the body+ -- puts each after the first on a line of its own.+ lower "create function f(\n a int, -- the a\n b int -- the b\n) returns int as $$ select a + b $$ language sql\n -- why\n immutable" "create function f(\n a int, -- the a\n b int -- the b\n)\n returns int as\n$$ select a + b $$ language sql\n -- why\n immutable"+ , -- The opening quote lines up with the closing one on its own line.+ lower "create function f() returns int as $$\n select 1\n $$ language sql" "create function f()\n returns int as\n $$\n select 1\n $$ language sql"+ , -- A SQL-standard body: its statements laid out under begin atomic.+ upper "create function f(x int) returns bigint language sql begin atomic; select count(*) from t where a = x; end" "CREATE FUNCTION f(x INT)\n RETURNS BIGINT\n LANGUAGE SQL\nBEGIN ATOMIC;\n SELECT count(*)\n FROM t\n WHERE a = x;\nEND"+ , lower "create function f(x int) returns int language sql immutable return x + 1" "create function f(x int)\n returns int\n language sql\n immutable\nreturn x + 1"+ , -- alter table: one action per line, trailing commas.+ lower "alter table t add column a int not null default 0" "alter table t\n add column a int not null default 0"+ , lower "alter table t drop column if exists a cascade, drop constraint c, add constraint fk foreign key (b) references u(id) not valid, validate constraint d" "alter table t\n drop column if exists a cascade,\n drop constraint c,\n add constraint fk foreign key (b) references u(id) not valid,\n validate constraint d"+ , upper "alter table t alter column a type numeric(10,2) using a::numeric, alter column b set default now(), alter column c drop not null, enable row level security, set (fillfactor = 70)" "ALTER TABLE t\n ALTER COLUMN a TYPE NUMERIC(10, 2) USING a::NUMERIC,\n ALTER COLUMN b SET DEFAULT now(),\n ALTER COLUMN c DROP NOT NULL,\n ENABLE ROW LEVEL SECURITY,\n SET (fillfactor = 70)"+ , -- create trigger: each clause on a line of its own, not indented.+ lower "create trigger t after insert or update of a, b on s.t referencing new table as changed for each statement execute function s.f('x', 1)" "create trigger t\nafter insert or update of a, b\non s.t\nreferencing new table as changed\nfor each statement\nexecute function s.f('x', 1)"+ , upper "create constraint trigger t after insert on t from u deferrable initially deferred for each row when (NEW.a <> OLD.a) execute procedure f()" "CREATE CONSTRAINT TRIGGER t\nAFTER INSERT\nON t\nFROM u\nDEFERRABLE INITIALLY DEFERRED\nFOR EACH ROW\nWHEN (new.a <> old.a)\nEXECUTE PROCEDURE f()"+ , -- A comment between clauses; a long condition broken at its ands.+ lower "create trigger t before update on t -- the table\nfor each row when (new.aaaaaaaaaaaaaaaa is not null and new.bbbbbbbbbbbbbbbbbbbb is null and new.cccccccccccccccc is null) execute function f()" "create trigger t\nbefore update\non t -- the table\nfor each row\nwhen (\n new.aaaaaaaaaaaaaaaa is not null\n and new.bbbbbbbbbbbbbbbbbbbb is null\n and new.cccccccccccccccc is null\n)\nexecute function f()"+ , -- grant and revoke: one line if short, else on and to on lines of+ -- their own.+ lower "grant select\n on table t\n to a" "grant select on table t to a"+ , upper "grant select, insert, update on table tenant.apple_pay_config to cde_admin, merchant, customer" "GRANT SELECT, INSERT, UPDATE\n ON TABLE tenant.apple_pay_config\n TO cde_admin, merchant, customer"+ , lower "revoke all on function f(bigint, text) from public cascade" "revoke all on function f(bigint, text) from public cascade"+ , lower "grant select (a, b) on t -- why\nto x with grant option" "grant select (a, b)\n on t -- why\n to x with grant option"+ , lower "grant data_worker_ro to \"kronor-worker-read-csv\"" "grant data_worker_ro to \"kronor-worker-read-csv\""+ , -- An index's include and storage options, on its on line.+ lower "create unique index i on t using gin (a gin_trgm_ops) include (b, c) nulls not distinct with (fastupdate = off) where a > 0" "create unique index i\n on t using gin (a gin_trgm_ops) include (b, c) nulls not distinct with (fastupdate = off)\n where a > 0"+ , upper "alter table t alter constraint fk deferrable initially deferred, add constraint k primary key using index i" "ALTER TABLE t\n ALTER CONSTRAINT fk DEFERRABLE INITIALLY DEFERRED,\n ADD CONSTRAINT k PRIMARY KEY USING INDEX i"+ , -- A long key using an index breaks before using.+ lower "alter table t add constraint uq_amex_file_summary_file_payee unique using index uq_amex_file_summary_file_payee" "alter table t\n add constraint uq_amex_file_summary_file_payee unique\n using index uq_amex_file_summary_file_payee"+ , -- A partition: each clause on a line of its own.+ lower "create table if not exists s.t_p0 partition of s.t for values from (0) to (250000000)" "create table if not exists s.t_p0\npartition of s.t\nfor values from (0) to (250000000)"+ , upper "create table p_a partition of p for values in ('a', 'b')" "CREATE TABLE p_a\nPARTITION OF p\nFOR VALUES IN ('a', 'b')"+ ]+++-- | Statements the renderer leaves to the caller.+refused :: [Text]+refused =+ [ "create sequence s"+ , "create index i on t (a) tablespace fast"+ , "alter table t attach partition p for values from (1) to (2)"+ , "create table t (a int, exclude using gist (a with =))"+ , "create table t (a int) with (fillfactor = 70)"+ , "create table p partition of t (a primary key) for values from (1) to (2)"+ , "create recursive view v (n) as select 1 union all select n + 1 from v"+ , "grant select on t to a -- why\nwith grant option"+ , "select x from t where a similar to 'b'"+ , "select 1; select 2"+ , -- No line break where the comment is.+ "select a + -- inside\n b from t"+ , "select 'a' -- between the parts of a string\n 'b'"+ ]+++main :: IO ()+main = do+ same <- forM sameAsRender \sql -> do+ laid <- Layout.formatStatement False (TE.encodeUtf8 sql)+ let old = Render.formatStatement PlainSql sql+ case (laid, old) of+ (Right new, Right o) | new == o -> pure True+ _ -> do+ TIO.putStrLn ("FAIL (same as Render): " <> sql <> "\n layout: " <> T.pack (show laid) <> "\n render: " <> T.pack (show old))+ pure False+ exact <- forM expected \Expected{upperKeywords, sql, want} -> do+ laid <- Layout.formatStatement upperKeywords (TE.encodeUtf8 sql)+ if laid == Right want+ then pure True+ else do+ TIO.putStrLn ("FAIL (expected): " <> sql <> "\n got: " <> T.pack (show laid) <> "\n want: " <> T.pack (show want))+ pure False+ refusals <- forM refused \sql -> do+ laid <- Layout.formatStatement False (TE.encodeUtf8 sql)+ unless (isLeft laid) (TIO.putStrLn ("FAIL (refused): " <> sql <> "\n got: " <> T.pack (show laid)))+ pure (isLeft laid)+ let results = same ++ exact ++ refusals+ putStrLn (show (length (filter id results)) <> " of " <> show (length results) <> " passed")+ unless (and results) exitFailure
+ test/RenderSpec.hs view
@@ -0,0 +1,1356 @@+{-# LANGUAGE CPP #-}++module Main where++import Data.String.Interpolate (__i)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import PgStyle.Render (formatSql)+import PostgresqlSyntax qualified as Ast+import System.Exit (ExitCode (..), exitWith)+import Prelude+++-- | Parse a SQL snippet, ignoring surrounding whitespace. Returns 'Nothing' if+-- the parser rejects the input. Used to compare the AST of input/expected/actual+-- as a semantic-equivalence guard on top of string equality.+parseAst :: Text -> Maybe Ast.PreparableStmt+parseAst t = either (const Nothing) Just (Ast.parse settings (T.strip t))+ where+ settings = Ast.nullabilityMarkers True <> kronorSettings+++-- | Kronor's extensions to hasql-th's syntax, in a build with them.+kronorSettings :: Ast.Settings+#ifdef KRONOR_SYNTAX+kronorSettings = Ast.haskellTargets True <> Ast.haskellParamFields True+#else+kronorSettings = mempty+#endif+++-- | The fixtures this build can parse: all of them with the @kronor-syntax@+-- flag, the rest without.+runnable :: [TestCase]+#ifdef KRONOR_SYNTAX+runnable = tests+#else+runnable = filter (\t -> t.syntax == PlainSyntax) tests+#endif+++data TestCase = TestCase+ { name :: Text+ , qqCol :: Int+ , input :: Text+ , expected :: Text+ , syntax :: FixtureSyntax+ }+++-- | Whether a fixture uses the extensions only Kronor's fork of+-- postgresql-syntax parses: Haskell targets (@$Record {..}@, @$f (a, b)@) and+-- param fields (@$1.$field@).+data FixtureSyntax = PlainSyntax | KronorSyntax+ deriving stock (Eq)+++-- | Prepend @n@ spaces to each non-blank line.+indent :: Int -> Text -> Text+indent n = T.intercalate "\n" . map addPrefix . T.lines+ where+ prefix = T.replicate n " "+ addPrefix line+ | T.null (T.strip line) = line+ | otherwise = prefix <> line+++-- | Build a test case. @rawInput@ and @rawExpected@ are dedented SQL snippets;+-- the input is indented to column @qqCol@ (simulating the real quasiquote+-- context), and the expected output is indented to @qqCol + 4@ (the formatter+-- indents content one level deeper than the opening bracket). Both are given a+-- leading newline, matching what a quasiquote block contains.+mkCase :: Text -> Int -> Text -> Text -> TestCase+mkCase nm col rawInput rawExpected =+ TestCase+ { name = nm+ , qqCol = col+ , input = "\n" <> indent col rawInput+ , expected = "\n" <> indent (col + 4) rawExpected+ , syntax = PlainSyntax+ }+++-- | 'mkCase' for a fixture in Kronor's syntax.+mkKronorCase :: Text -> Int -> Text -> Text -> TestCase+mkKronorCase nm col rawInput rawExpected = (mkCase nm col rawInput rawExpected){syntax = KronorSyntax}+++tests :: [TestCase]+tests =+ [ TestCase+ { name = "[01] single-line query (no newlines) is left untouched"+ , qqCol = 4+ , input = " update deployer.config set is_frozen = $1::bool where id = 42 "+ , expected = " update deployer.config set is_frozen = $1::bool where id = 42 "+ , syntax = PlainSyntax+ }+ , mkCase+ "[02] SELECT ... WHERE: inlined FROM is split out, trailing LIMIT moves to its own line, ANDs are indented under WHERE"+ 4+ [__i|+ select response_body::jsonb from runtime.idempotency+ where merchant_id = $1::bigint+ and namespace = $2::text+ and idempotency_key = $3::text+ and request_params = $4::jsonb limit 1+ |]+ [__i|+ select response_body::jsonb+ from runtime.idempotency+ where merchant_id = $1::bigint+ and namespace = $2::text+ and idempotency_key = $3::text+ and request_params = $4::jsonb+ limit 1+ |]+ , mkCase+ "[03] INSERT with 4+ columns and a VALUES tuple: both are split into leading-comma lists"+ 4+ [__i|+ insert into runtime.idempotency (merchant_id, namespace, idempotency_key, request_params)+ values ($1::bigint, $2::text, $3::text, $4::jsonb)+ |]+ [__i|+ insert into runtime.idempotency+ ( merchant_id+ , namespace+ , idempotency_key+ , request_params+ )+ values+ ( $1::bigint+ , $2::text+ , $3::text+ , $4::jsonb+ )+ |]+ , mkCase+ "[04] UPDATE ... WHERE normalizes inconsistent AND indentation (2 spaces -> 4) under the WHERE keyword"+ 4+ [__i|+ update runtime.idempotency+ set response_body = $4::jsonb+ where merchant_id = $1::bigint+ and namespace = $2::text+ and idempotency_key = $3::text+ |]+ [__i|+ update runtime.idempotency+ set response_body = $4::jsonb+ where merchant_id = $1::bigint+ and namespace = $2::text+ and idempotency_key = $3::text+ |]+ , mkCase+ "[05] JOIN with multi-condition ON: the AND continuation sits at the same indent as ON, not nested further"+ 4+ [__i|+ select payment.id::bigint,+ payment.reepay_handle::text?+ from payment_gateway.transaction_release+ join tenant.reepay_setting+ on reepay_setting.merchant_id = transaction_release.merchant_id+ join payment_gateway.payment+ on payment.id = transaction_release.payment_id+ and payment.merchant_id = transaction_release.merchant_id+ where transaction_release.merchant_id = $1::bigint+ and transaction_release.id = $2::bigint+ |]+ [__i|+ select+ payment.id::bigint+ , payment.reepay_handle::text?+ from payment_gateway.transaction_release+ join tenant.reepay_setting+ on reepay_setting.merchant_id = transaction_release.merchant_id+ join payment_gateway.payment+ on payment.id = transaction_release.payment_id+ and payment.merchant_id = transaction_release.merchant_id+ where transaction_release.merchant_id = $1::bigint+ and transaction_release.id = $2::bigint+ |]+ , mkKronorCase+ "[06] hasql-th $CanBeEncrypted(...) splice is preserved verbatim in a select list"+ 4+ [__i|+ select+ $CanBeEncrypted (api_key::text, 'tenant.t'::text, 'api_key'::text),+ $CanBeEncrypted (private_key::text, 'tenant.t'::text, 'private_key'::text)+ from tenant.clearhaus_acquirer_setting+ where merchant_id = $1::bigint+ and id = $2::bigint+ |]+ [__i|+ select+ $CanBeEncrypted (api_key::text, 'tenant.t'::text, 'api_key'::text)+ , $CanBeEncrypted (private_key::text, 'tenant.t'::text, 'private_key'::text)+ from tenant.clearhaus_acquirer_setting+ where merchant_id = $1::bigint+ and id = $2::bigint+ |]+ , mkKronorCase+ "[07] hasql-th $Name{...} record syntax: inlined braces are reformatted to Haskell-style leading-comma record"+ 8+ [__i|+ select $AuthTdsData{ isCardSame = x::bool?,+ tdsServer = tse.tds_server::text,+ country = ae.country::text }+ from cde.tds_details+ where id = $1::uuid+ |]+ [__i|+ select+ $AuthTdsData+ { isCardSame = x::bool?+ , tdsServer = tse.tds_server::text+ , country = ae.country::text+ }+ from cde.tds_details+ where id = $1::uuid+ |]+ , mkKronorCase+ "[08] hasql-th $1.$field record access survives inside BETWEEN x AND y and coalesce() args"+ 8+ [__i|+ select 1+ from t ext+ where ext.org = $1.$orgId::bigint+ and ext.d between $1.$start::date and $1.$end::date+ and ext.acq = coalesce($1.$acq::text?, ext.acq)+ |]+ [__i|+ select 1+ from t ext+ where ext.org = $1.$orgId::bigint+ and ext.d between $1.$start::date and $1.$end::date+ and ext.acq = coalesce($1.$acq::text?, ext.acq)+ |]+ , mkCase+ "[09] INSERT ... ON CONFLICT DO UPDATE SET puts the updated column assignment on its own indented line"+ 4+ [__i|+ insert into t (org_id, batch_id, data)+ select $1::bigint, $2::text, unnest($3::jsonb[])+ on conflict (batch_id, md5(data::text))+ do update set data = excluded.data+ |]+ [__i|+ insert into t+ (org_id, batch_id, data)+ select+ $1::bigint+ , $2::text+ , unnest($3::jsonb[])+ on conflict (batch_id, md5(data::text))+ do update set+ data = excluded.data+ |]+ , mkCase+ "[10] WITH CTE + LEFT JOIN LATERAL fn(...): CTE body is multi-lined, last CTE closes with ')' not '),', ::text? survives inside the lateral function"+ 8+ [__i|+ with details as (+ select * from cde.tds_details+ where id = $1::uuid )+ select details.id::uuid+ from details+ left join lateral fsm.notify ( shard := details.mid, event := $2::text, data := jsonb_build_object( 'error', $3::text? ) )+ on true+ |]+ [__i|+ with details as (+ select *+ from cde.tds_details+ where id = $1::uuid+ )+ select details.id::uuid+ from details+ left join lateral fsm.notify(+ shard := details.mid+ , event := $2::text+ , data := jsonb_build_object('error', $3::text?)+ )+ on true+ |]+ , mkCase+ "[11] content inside single-quoted string literals ('U', 'Y', 'FM000') is not lowercased or otherwise touched"+ 4+ [__i|+ select (case when x is null then 'U' when x then 'Y' else 'N' end)::text,+ to_char(n, 'FM000')::text+ from t+ where id = $1::uuid+ |]+ [__i|+ select+ (case+ when x is null then 'U'+ when x then 'Y'+ else 'N'+ end)::text+ , to_char(+ n+ , 'FM000'+ )::text+ from t+ where id = $1::uuid+ |]+ , mkCase+ "[12] chained typecasts like ::text?::uuid? preserve both nullability markers (not just the last)"+ 4+ [__i|+ select (x->>'a')::text?,+ (x->>'b')::text?::uuid?,+ (x->>'c')::text?+ from t+ where id = $1::uuid+ |]+ [__i|+ select+ (x->>'a')::text?+ , (x->>'b')::text?::uuid?+ , (x->>'c')::text?+ from t+ where id = $1::uuid+ |]+ , mkCase+ "[13] UPDATE ... SET: assigned expressions keep nullability chains like ::text?::uuid on the right-hand side"+ 4+ [__i|+ update cde.tds_details+ set auth_response = $2::jsonb,+ ds_trans_id = $3::text?::uuid+ where id = $1::uuid+ |]+ [__i|+ update cde.tds_details+ set+ auth_response = $2::jsonb+ , ds_trans_id = $3::text?::uuid+ where id = $1::uuid+ |]+ , mkCase+ "[14] UNION ALL: both arms are formatted independently with their own multi-line select layout"+ 4+ [__i|+ select id::bigint, name::text from table_a where active = true+ union all+ select id::bigint, name::text from table_b where active = true+ |]+ [__i|+ select+ id::bigint+ , name::text+ from table_a+ where active = true+ union all+ select+ id::bigint+ , name::text+ from table_b+ where active = true+ |]+ , mkCase+ "[15] GROUP BY / ORDER BY / LIMIT each land on their own line at the base clause indent after WHERE"+ 4+ [__i|+ select acquirer::text, count(*)::bigint+ from reconciliation.ext+ where org_id = $1::bigint+ group by acquirer+ order by count(*) desc+ limit 10+ |]+ [__i|+ select+ acquirer::text+ , count(*)::bigint+ from reconciliation.ext+ where org_id = $1::bigint+ group by acquirer+ order by count(*) desc+ limit 10+ |]+ , mkCase+ "[16] DELETE FROM with a multi-predicate WHERE: ANDs are split onto their own indented lines"+ 4+ [__i|+ delete from runtime.some_table+ where merchant_id = $1::bigint+ and id = $2::bigint+ |]+ [__i|+ delete from runtime.some_table+ where merchant_id = $1::bigint+ and id = $2::bigint+ |]+ , mkCase+ "[17] FROM can be a set-returning function call (not just a table name) without losing the FROM keyword"+ 4+ [__i|+ select count(*)::bigint+ from cde.set_role_and_config($1::text, $2::jsonb)+ |]+ [__i|+ select count(*)::bigint+ from cde.set_role_and_config($1::text, $2::jsonb)+ |]+ , mkCase+ "[18] regression: ORDER BY inside an inline subquery is not emitted as 'order by order by' (R.sortClause already includes the keyword)"+ 4+ [__i|+ select id::bigint+ from t+ where id = (select id from u order by created_at desc limit 1)+ |]+ [__i|+ select id::bigint+ from t+ where id = (select id from u order by created_at desc limit 1)+ |]+ , mkCase+ "[19] regression: GROUP BY inside an inline subquery is not emitted as 'group by group by' (R.groupClause already includes the keyword)"+ 4+ [__i|+ select id::bigint+ from t+ where id = (select max(id) from u group by org_id)+ |]+ [__i|+ select id::bigint+ from t+ where id = (select max(id) from u group by org_id)+ |]+ , mkCase+ "[20] regression: ORDER BY inside an aggregate's argument list (string_agg(x, ',' order by y)) is not doubled"+ 4+ [__i|+ select string_agg(name, ', ' order by id)::text+ from t+ where org_id = $1::bigint+ |]+ [__i|+ select string_agg(+ name+ , ', '+ order by id+ )::text+ from t+ where org_id = $1::bigint+ |]+ , mkCase+ "[21] x = ANY(array_expr) keeps the parens around the array expression (Postgres requires them when the operand isn't a subquery)"+ 4+ [__i|+ select id::bigint+ from t+ where merchant_id = ANY($1::bigint[])+ |]+ [__i|+ select id::bigint+ from t+ where merchant_id = any($1::bigint[])+ |]+ , mkCase+ "[22] CASE WHEN ... THEN ... ELSE ... END arms preserve hasql-th's ::text? nullable marker (don't fall through to the generic renderer)"+ 4+ [__i|+ update t+ set x = case when $2::text? = 'Y' then $1::jsonb else x end+ where id = $3::uuid+ |]+ [__i|+ update t+ set x = case when $2::text? = 'Y' then $1::jsonb else x end+ where id = $3::uuid+ |]+ , mkCase+ "[23] FROM with multiple tables and no joins stays on a single line (no 'from t1\\nfrom t2' duplication)"+ 4+ [__i|+ select t1.id::bigint+ from t1, t2+ where t1.id = t2.id+ |]+ [__i|+ select t1.id::bigint+ from t1, t2+ where t1.id = t2.id+ |]+ , mkCase+ "[24] nullable array typecast ::text[]? keeps the trailing ? (the second Bool in the array-dims tuple must be rendered)"+ 4+ [__i|+ update t+ set statuses = $1::text[]?+ where id = $2::uuid+ |]+ [__i|+ update t+ set statuses = $1::text[]?+ where id = $2::uuid+ |]+ , mkKronorCase+ "[25] array[...] literal preserves hasql-th $1.$field access inside its element expressions"+ 4+ [__i|+ select enqueue(array[mk_payload(organization_id => $1.$organizationId::bigint, frequency => $2::text)])::text+ |]+ [__i|+ select enqueue(array[mk_payload(organization_id => $1.$organizationId::bigint, frequency => $2::text)])::text+ |]+ , mkCase+ "[26] ROW(...) constructor preserves $1.$field access and ::text? nullability on its elements"+ 4+ [__i|+ select create_payment(capture_input := ROW($2::bigint, $3::bigint::currency_unit, $4::text?)::capture_input, created_by := $5::text?)+ |]+ [__i|+ select create_payment(+ capture_input := row($2::bigint, $3::bigint::currency_unit, $4::text?)::capture_input+ , created_by := $5::text?+ )+ |]+ , mkKronorCase+ "[27] inline subquery's FROM function-call (inside EXISTS (...)) preserves $1.$field in its argument list"+ 4+ [__i|+ select exists (select 1::int from gen($1.$orgId::bigint, $1.$cursor::text?))::bool+ |]+ [__i|+ select exists (select 1::int from gen($1.$orgId::bigint, $1.$cursor::text?))::bool+ |]+ , mkKronorCase+ "[28] UNION ALL inside EXISTS (...) wraps when the inline form gets long; each arm preserves $1.$field"+ 4+ [__i|+ select exists (select 1::int from gen1($1.$orgId::bigint, $1.$cursor::text?) union all select 1::int from gen2($1.$orgId::bigint, $1.$cursor::text?))::bool+ |]+ [__i|+ select exists (+ select 1::int+ from gen1($1.$orgId::bigint, $1.$cursor::text?)+ union all+ select 1::int+ from gen2($1.$orgId::bigint, $1.$cursor::text?)+ )::bool+ |]+ , mkKronorCase+ "[29] EXTRACT(field FROM $1.$field::type) preserves the hasql-th field access inside the extracted expression"+ 4+ [__i|+ select extract(epoch from ($2.$expiresAt::timestamptz - now()))+ |]+ [__i|+ select extract(epoch from ($2.$expiresAt::timestamptz - now()))+ |]+ , mkCase+ "[30] multi-row VALUES emits the 'values' keyword once with comma-separated row tuples (not 'values (...) values (...)')"+ 4+ [__i|+ insert into t (a, b, c, d)+ values+ ($1::bigint, 'A', null, 'x'),+ ($1::bigint, 'B', null, 'y')+ |]+ [__i|+ insert into t+ ( a+ , b+ , c+ , d+ )+ values+ ( $1::bigint+ , 'A'+ , null+ , 'x'+ ),+ ( $1::bigint+ , 'B'+ , null+ , 'y'+ )+ |]+ , mkCase+ "[31] LEFT JOIN with multi-condition ON: AND continuations under the ON clause"+ 4+ [__i|+ select t1.id::bigint+ from t1+ left join t2 on t1.id = t2.t1_id and t1.kind = t2.kind and t1.org = t2.org+ where t1.id = $1::bigint+ |]+ [__i|+ select t1.id::bigint+ from t1+ left join t2+ on t1.id = t2.t1_id+ and t1.kind = t2.kind+ and t1.org = t2.org+ where t1.id = $1::bigint+ |]+ , mkCase+ "[32] WITH chains multiple CTEs separated by '),' and ends the last with ')'"+ 4+ [__i|+ with parsed (parsed_cursor) as (+ select coalesce($1::jsonb, '{}'::jsonb)+ ),+ data as (select 1::int from parsed)+ select 1::int from data+ |]+ [__i|+ with parsed (parsed_cursor) as (+ select coalesce($1::jsonb, '{}'::jsonb)+ ),+ data as (+ select 1::int+ from parsed+ )+ select 1::int+ from data+ |]+ , mkCase+ "[33] CTE with explicit column list: 'with name (col1, col2) as (...)' preserves the column list parens"+ 4+ [__i|+ with rolled (a, b) as (+ select 1::int, 2::int+ )+ select rolled.a::int from rolled+ |]+ [__i|+ with rolled (a, b) as (+ select+ 1::int+ , 2::int+ )+ select rolled.a::int+ from rolled+ |]+ , mkCase+ "[34] CROSS JOIN renders on its own line with no ON/USING qualifier"+ 4+ [__i|+ select t1.id::bigint+ from t1+ cross join t2+ where t1.id = $1::bigint+ |]+ [__i|+ select t1.id::bigint+ from t1+ cross join t2+ where t1.id = $1::bigint+ |]+ , mkCase+ "[35] INSERT ... ON CONFLICT DO NOTHING: 'on conflict' and 'do nothing' each go on their own line"+ 4+ [__i|+ insert into t (a, b, c)+ values ($1::bigint, $2::text, $3::text)+ on conflict+ do nothing+ |]+ [__i|+ insert into t+ (a, b, c)+ values+ ( $1::bigint+ , $2::text+ , $3::text+ )+ on conflict+ do nothing+ |]+ , mkCase+ "[36] UPDATE ... FROM: the FROM clause goes on its own line between SET and WHERE"+ 4+ [__i|+ update t1 set x = t2.y from t2 where t1.id = t2.id and t1.id = $1::bigint+ |]+ [__i|+ update t1+ set x = t2.y+ from t2+ where t1.id = t2.id+ and t1.id = $1::bigint+ |]+ , mkCase+ "[37] DELETE ... USING: the USING clause goes on its own line between DELETE and WHERE"+ 4+ [__i|+ delete from t1 using t2 where t1.id = t2.id and t1.id = $1::bigint+ |]+ [__i|+ delete from t1+ using t2+ where t1.id = t2.id+ and t1.id = $1::bigint+ |]+ , mkCase+ "[38] Function call with multiple arguments wraps each argument onto its own line, with closing paren back at the function's column"+ 4+ [__i|+ select cde.save_td_secure_pre_auth($2::text, $1::jsonb, $3::jsonb, $4::bytea, $5::jsonb)::uuid+ |]+ [__i|+ select cde.save_td_secure_pre_auth(+ $2::text+ , $1::jsonb+ , $3::jsonb+ , $4::bytea+ , $5::jsonb+ )::uuid+ |]+ , mkCase+ "[39] LEFT JOIN LATERAL with a function call that has multiple named args wraps the call onto multiple lines"+ 4+ [__i|+ select 1::int+ from t+ left join lateral fsm.notify_state_machine(shard := $1::bigint, machine := $2::bigint, event := 'foo', data := jsonb_build_object('a', $3::text)) on true+ |]+ [__i|+ select 1::int+ from t+ left join lateral fsm.notify_state_machine(+ shard := $1::bigint+ , machine := $2::bigint+ , event := 'foo'+ , data := jsonb_build_object('a', $3::text)+ )+ on true+ |]+ , mkCase+ "[40] Single-argument function call stays inline (no wrap when args < threshold)"+ 4+ [__i|+ select md5($1::text)::text+ |]+ [__i|+ select md5($1::text)::text+ |]+ , mkCase+ "[41] Two-argument function call wraps onto multiple lines (threshold is 2)"+ 4+ [__i|+ select to_char(n, 'FM000')::text from t+ |]+ [__i|+ select to_char(+ n+ , 'FM000'+ )::text+ from t+ |]+ , mkCase+ "[42] string literal containing ' and ' is not split as a boolean AND"+ 4+ [__i|+ select id::bigint from t+ where label = 'apple and orange'+ and other = $1::text+ |]+ [__i|+ select id::bigint+ from t+ where label = 'apple and orange'+ and other = $1::text+ |]+ , mkCase+ "[43] string literal containing ' :: ' is preserved verbatim"+ 4+ [__i|+ select id::bigint from t+ where note = 'see x :: y for details'+ |]+ [__i|+ select id::bigint+ from t+ where note = 'see x :: y for details'+ |]+ , mkCase+ "[44] FOR UPDATE inside an inline subquery is preserved"+ 4+ [__i|+ select id::bigint from t+ where exists (select 1 from u where u.t_id = t.id for update)+ |]+ [__i|+ select id::bigint+ from t+ where exists (select 1 from u where u.t_id = t.id for update)+ |]+ , mkCase+ "[45] Chained typecasts on a function-call select target keep every cast"+ 4+ [__i|+ select jsonb_build_object($1::text, $2::text)::text::bytea from t+ |]+ [__i|+ select jsonb_build_object(+ $1::text+ , $2::text+ )::text::bytea+ from t+ |]+ , mkCase+ "[46] Top-level WINDOW clause is preserved on its own line"+ 4+ [__i|+ select row_number() over w::bigint from t window w as (partition by x order by y)+ |]+ [__i|+ select row_number() over w::bigint+ from t+ window w as (partition by x order by y)+ |]+ , mkCase+ "[47] CTE materialization hint (MATERIALIZED) is preserved"+ 4+ [__i|+ with cte as materialized (select 1::bigint as x)+ select x::bigint from cte+ |]+ [__i|+ with cte as materialized (+ select 1::bigint as x+ )+ select x::bigint+ from cte+ |]+ , mkCase+ "[48] INSERT ... OVERRIDING SYSTEM VALUE is preserved on its own line"+ 4+ [__i|+ insert into t (id, name, kind, source) overriding system value+ select x.id::bigint, x.name::text, x.kind::text, x.source::text from src x+ |]+ [__i|+ insert into t+ ( id+ , name+ , kind+ , source+ )+ overriding system value+ select+ x.id::bigint+ , x.name::text+ , x.kind::text+ , x.source::text+ from src x+ |]+ , mkCase+ "[49] Nested function calls wrap recursively; jsonb_build_object groups (key, value) pairs onto one line when wrapped; trailing args after a wrapped sub-call line up with the leading-comma column"+ 4+ [__i|+ select job_queue.enqueue_payload(+ array_agg(+ job_queue.mk_payload(+ caller => 'Kronor.Valitor.FetchSettlements',+ acquirer => 'Valitor',+ payload => jsonb_build_object(+ 'tag', 'FetchValitorBatchesTag',+ 'contents', jsonb_build_object(+ 'organizationId', inserted.organization_id,+ 'valitorSettlementId', inserted.id,+ 'stateMachineId', $4::bigint+ )+ ),+ run_at => now(),+ timeout => '1 day'::interval+ )+ )::jsonb[],+ priority_ := 100+ )::text+ from inserted+ |]+ [__i|+ select job_queue.enqueue_payload(+ array_agg(+ job_queue.mk_payload(+ caller => 'Kronor.Valitor.FetchSettlements'+ , acquirer => 'Valitor'+ , payload => jsonb_build_object(+ 'tag', 'FetchValitorBatchesTag'+ , 'contents', jsonb_build_object(+ 'organizationId', inserted.organization_id+ , 'valitorSettlementId', inserted.id+ , 'stateMachineId', $4::bigint+ )+ )+ , run_at => now()+ , timeout => '1 day'::interval+ )+ )::jsonb[]+ , priority_ := 100+ )::text+ from inserted+ |]+ , mkCase+ "[50] EXISTS subquery in a CTE wraps multi-line when the inline form gets too long"+ 4+ [__i|+ with customer_card as (+ select exists (select * from payment_gateway.customer_card where merchant_id = current_setting('cde.merchant_id')::bigint and customer_reference = current_setting('cde.customer_reference')::text and fingerprint = $2::uuid) card_exists+ )+ select (save_card_details and not customer_card.card_exists)::boolean+ from cde.tds_details, customer_card+ where tds_details.merchant_id = current_setting('cde.merchant_id')::bigint+ and tds_details.id = $1::uuid+ |]+ [__i|+ with customer_card as (+ select exists (+ select *+ from payment_gateway.customer_card+ where merchant_id = current_setting('cde.merchant_id')::bigint+ and customer_reference = current_setting('cde.customer_reference')::text+ and fingerprint = $2::uuid+ ) card_exists+ )+ select (save_card_details and not customer_card.card_exists)::boolean+ from cde.tds_details, customer_card+ where tds_details.merchant_id = current_setting('cde.merchant_id')::bigint+ and tds_details.id = $1::uuid+ |]+ , mkCase+ "[51] SQL keyword-form functions (position / substring / trim / overlay) emit no space before '('"+ 4+ [__i|+ select position(' ' in name)::int+ , substring(s from 1 for 5)::text+ , substring(s, 1, 5)::text+ , trim(both ' ' from name)::text+ , overlay(name placing 'x' from 1 for 1)::text+ from t+ where id = $1::bigint+ |]+ [__i|+ select+ position(' ' in name)::int+ , substring(s from 1 for 5)::text+ , substring(s, 1, 5)::text+ , trim(both ' ' from name)::text+ , overlay(name placing 'x' from 1 for 1)::text+ from t+ where id = $1::bigint+ |]+ , mkCase+ "[52] array[fn(...)] literal whose element is a wrap-eligible call expands the inner call across multiple lines"+ 4+ [__i|+ select job_queue.enqueue_payload(+ array[job_queue.mk_payload(caller => 'X', acquirer => 'MobilePay', payload => jsonb_build_object('tag', 'FetchTag', 'contents', jsonb_build_object('organizationId', $1::bigint, 'ledgerId', $2::bigint, 'cursor', $3::text)))]+ , priority_ := 5000+ )::text+ |]+ [__i|+ select job_queue.enqueue_payload(+ array[+ job_queue.mk_payload(+ caller => 'X'+ , acquirer => 'MobilePay'+ , payload => jsonb_build_object(+ 'tag', 'FetchTag'+ , 'contents', jsonb_build_object(+ 'organizationId', $1::bigint+ , 'ledgerId', $2::bigint+ , 'cursor', $3::text+ )+ )+ )+ ]+ , priority_ := 5000+ )::text+ |]+ , mkCase+ "[53] FROM-list `from fn(args)` wraps when the function call has multiple args"+ 4+ [__i|+ select count(*)::bigint+ from job_queue.enqueue_payload(array[job_queue.mk_payload(merchant_id => $1::bigint, caller => 'Foo', payload => jsonb_build_object('tag', 'X', 'contents', jsonb_build_object('orgId', $2::bigint, 'cursor', $3::text)))]::jsonb[], priority_ := 5000)+ |]+ [__i|+ select count(*)::bigint+ from job_queue.enqueue_payload(+ array[+ job_queue.mk_payload(+ merchant_id => $1::bigint+ , caller => 'Foo'+ , payload => jsonb_build_object(+ 'tag', 'X'+ , 'contents', jsonb_build_object(+ 'orgId', $2::bigint+ , 'cursor', $3::text+ )+ )+ )+ ]::jsonb[]+ , priority_ := 5000+ )+ |]+ , mkCase+ "[54] Single-arg outer call (e.g. unnest) with a long array arg wraps via the select-target length gate"+ 4+ [__i|+ select unnest(array[format('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $1::text), format('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', $2::text)])::text+ from t+ |]+ [__i|+ select unnest(+ array[+ format(+ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+ , $1::text+ )+ , format(+ 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'+ , $2::text+ )+ ]+ )::text+ from t+ |]+ , mkCase+ "[55] (expr)::type — parenthesized wrap-eligible expression with a typecast wraps when too long"+ 4+ [__i|+ select (json_build_object('https://hasura.io/jwt/claims', $2::jsonb?, 'iat', extract(epoch from now()), 'exp', extract(epoch from now() + interval '1 hour'), 'tid', $4::text?, 'ttype', $3::text?, 'tname', null, 'associated_email', $1::text?)::jsonb)::json+ |]+ [__i|+ select (+ json_build_object(+ 'https://hasura.io/jwt/claims', $2::jsonb?+ , 'iat', extract(epoch from now())+ , 'exp', extract(epoch from now() + interval '1 hour')+ , 'tid', $4::text?+ , 'ttype', $3::text?+ , 'tname', null+ , 'associated_email', $1::text?+ )::jsonb+ )::json+ |]+ , mkCase+ "[56] FROM unnest(...) AS alias (col1, col2, ..., colN) wraps the column list when it has more than 3 columns"+ 4+ [__i|+ select count(*)::bigint from unnest($1::int[]) as txn_row (entry_reference, external_status, currency, amount, transaction_type, name, booking_date, value_date)+ |]+ [__i|+ select count(*)::bigint+ from unnest($1::int[]) as txn_row+ ( entry_reference+ , external_status+ , currency+ , amount+ , transaction_type+ , name+ , booking_date+ , value_date+ )+ |]+ , mkKronorCase+ "[57] hasql-th nested $Record{...} fields expand multi-line when an inner record's inline form is long"+ 8+ [__i|+ select $PaymentSource{ paypal = $PayPal{ experienceContext = $ExperienceContext{ brandName = merchant.name::text, returnUrl = paypal_payment.return_url::text, cancelUrl = paypal_payment.return_url::text } } }+ from t+ where id = $1::uuid+ |]+ [__i|+ select+ $PaymentSource+ { paypal = $PayPal+ { experienceContext = $ExperienceContext+ { brandName = merchant.name::text+ , returnUrl = paypal_payment.return_url::text+ , cancelUrl = paypal_payment.return_url::text+ }+ }+ }+ from t+ where id = $1::uuid+ |]+ , mkCase+ "[58] CROSS JOIN (VALUES ...) with many tuples wraps multi-line; each tuple > 3 cols also expands to bracket-list"+ 4+ [__i|+ select m.id::bigint, payment_method.column1::text, payment_method.column2::int+ from tenant.merchant m+ cross join (values ('SUCCESSFUL_SWISH_PAYMENTS', 64, 500, 'SEK', 'Swish transaction fee'), ('SUCCESSFUL_DIRECT_DEBIT_PAYMENTS', 65, 200, 'SEK', 'Direct Debit (Open Banking)'), ('SUCCESSFUL_CREDIT_CARD_PAYMENTS', 80, 30, 'SEK', 'Credit card fee')) as payment_method+ |]+ [__i|+ select+ m.id::bigint+ , payment_method.column1::text+ , payment_method.column2::int+ from tenant.merchant m+ cross join (+ values+ ( 'SUCCESSFUL_SWISH_PAYMENTS'+ , 64+ , 500+ , 'SEK'+ , 'Swish transaction fee'+ ),+ ( 'SUCCESSFUL_DIRECT_DEBIT_PAYMENTS'+ , 65+ , 200+ , 'SEK'+ , 'Direct Debit (Open Banking)'+ ),+ ( 'SUCCESSFUL_CREDIT_CARD_PAYMENTS'+ , 80+ , 30+ , 'SEK'+ , 'Credit card fee'+ )+ ) as payment_method+ |]+ , mkCase+ "[59] CASE expressions in SET RHS expand multi-line when the inline form gets long; body aligns under the CASE keyword"+ 4+ [__i|+ update cde.tds_details+ set+ challenge_response = case when $3::text? = 'Y' then $2::jsonb else challenge_response end+ , post_auth_response = case when $3::text? = 'Y' then $2::jsonb else post_auth_response end+ , error_response = case when $3::text? != 'Y' or $3::text? is null then $2::jsonb else error_response end+ where id = $1::uuid+ |]+ [__i|+ update cde.tds_details+ set+ challenge_response = case+ when $3::text? = 'Y' then $2::jsonb+ else challenge_response+ end+ , post_auth_response = case+ when $3::text? = 'Y' then $2::jsonb+ else post_auth_response+ end+ , error_response = case+ when $3::text? != 'Y' or $3::text? is null then $2::jsonb+ else error_response+ end+ where id = $1::uuid+ |]+ , mkKronorCase+ "[60] hasql-th $Foo (...) splice wraps multi-line when inline form is long; SQL inside its args (CASE, parens, casts) wraps the same way it would at the top-level SELECT-target position"+ 4+ [__i|+ select+ swish_payment.id::uuid+ , $CanBeEncrypted ((case swish_payment.payment_category when 'StandAlone' then (select client_certificate_public from merchant_as_target) else (select client_certificate_public from kronor_as_target) end)::text, 'tenant.swish_setting'::text, 'client_certificate_public'::text)+ from runtime.swish_payment+ |]+ [__i|+ select+ swish_payment.id::uuid+ , $CanBeEncrypted (+ (case swish_payment.payment_category+ when 'StandAlone' then (+ select client_certificate_public+ from merchant_as_target+ )+ else (+ select client_certificate_public+ from kronor_as_target+ )+ end)::text+ , 'tenant.swish_setting'::text+ , 'client_certificate_public'::text+ )+ from runtime.swish_payment+ |]+ , mkCase+ "[61] CASE expression in a top-level SELECT target always wraps multi-line, even when its inline form would fit under the length threshold"+ 4+ [__i|+ select+ pma.country::text+ , (case when tds_details.tds_method_invoked then 'Y' else 'N' end)::text+ , tds_details.tds_trans_id::uuid+ from cde.tds_details+ join tenant.payment_method_acquirer pma on pma.id = tds_details.pma_id+ where tds_details.id = $1::uuid+ |]+ [__i|+ select+ pma.country::text+ , (case+ when tds_details.tds_method_invoked then 'Y'+ else 'N'+ end)::text+ , tds_details.tds_trans_id::uuid+ from cde.tds_details+ join tenant.payment_method_acquirer pma+ on pma.id = tds_details.pma_id+ where tds_details.id = $1::uuid+ |]+ , mkCase+ "[62] bare CASE in SELECT target (no surrounding parens, optional trailing typecast on @end@) wraps with body indented relative to the @case@ keyword's column, not the outer block's nest level"+ 4+ [__i|+ select+ id::text+ , currency::text+ , case transaction_type when 'CAPTURE' then 'Purchase' when 'REFUND' then 'Refund' end::text+ , amount::int+ from payment_gateway.ledger+ where merchant_id = $1::bigint+ |]+ [__i|+ select+ id::text+ , currency::text+ , case transaction_type+ when 'CAPTURE' then 'Purchase'+ when 'REFUND' then 'Refund'+ end::text+ , amount::int+ from payment_gateway.ledger+ where merchant_id = $1::bigint+ |]+ , mkCase+ "[63] single-target SELECT whose target is a top-level CASE forces block-list layout (`select` ends the line, `case` starts at item-content column) so @end@ lines up under @case@ — instead of @case@ landing mid-line after `select ` and the body / @end@ being pushed far right by 'align'"+ 4+ [__i|+ select case when status = 'won' then fsm.notify_state_machine(shard := organization_id, machine := state_machine_id, event := 'dispute.won') when status = 'lost' then fsm.notify_state_machine(shard := organization_id, machine := state_machine_id, event := 'dispute.lost') end::text+ from reconciliation.acquirer_dispute dispute+ where organization_id = $1::bigint+ and dispute.id = $2::uuid+ |]+ [__i|+ select+ case+ when status = 'won' then fsm.notify_state_machine(+ shard := organization_id+ , machine := state_machine_id+ , event := 'dispute.won'+ )+ when status = 'lost' then fsm.notify_state_machine(+ shard := organization_id+ , machine := state_machine_id+ , event := 'dispute.lost'+ )+ end::text+ from reconciliation.acquirer_dispute dispute+ where organization_id = $1::bigint+ and dispute.id = $2::uuid+ |]+ , mkCase+ "[64] inline subquery `SELECT DISTINCT ON (...)` keeps the `ON (...)` clause — regression guard for the Shift4 card-bin job (PR #5324)"+ 4+ [__i|+ insert into reference.card_bins (start_bin, end_bin, bin_length)+ select (row_data->>'start_bin')::numeric, (row_data->>'end_bin')::numeric, (row_data->>'bin_length')::bigint+ from (select distinct on (row_data->>'start_bin', row_data->>'end_bin') row_data from jsonb_array_elements($1::jsonb) as row_data) s+ on conflict (start_bin, end_bin) do nothing+ |]+ [__i|+ insert into reference.card_bins+ (start_bin, end_bin, bin_length)+ select+ (row_data->>'start_bin')::numeric+ , (row_data->>'end_bin')::numeric+ , (row_data->>'bin_length')::bigint+ from (+ select distinct on (row_data ->> 'start_bin', row_data ->> 'end_bin') row_data+ from jsonb_array_elements($1::jsonb) as row_data+ ) s+ on conflict (start_bin, end_bin)+ do nothing+ |]+ ]+++main :: IO ()+main = do+ let results = map runTest runnable+ failures = filter (not . fst) results+ skipped = length tests - length runnable+ if skipped > 0+ then putStrLn (show skipped <> " fixtures need the kronor-syntax flag; skipped.")+ else pure ()+ mapM_+ ( \(_, msg) -> do+ TIO.putStrLn "---"+ TIO.putStrLn msg+ )+ failures+ if null failures+ then do+ putStrLn $ "All " <> show (length runnable) <> " tests passed."+ else do+ putStrLn $ "\n" <> show (length failures) <> " of " <> show (length runnable) <> " tests FAILED."+ exitWith (ExitFailure 1)+++runTest :: TestCase -> (Bool, Text)+runTest TestCase{name, qqCol, input, expected} =+ -- 'formatSql' returns 'Left' on AST mismatch; treating that as a+ -- failure is the whole point of this test suite — if the formatter ever+ -- emits semantically-different SQL, the test reports it as such.+ let result = formatSql qqCol (T.stripEnd input)+ actual = either ("ERROR: " <>) id result+ stringEq = either (const False) (\a -> T.stripEnd a == T.stripEnd expected) result+ -- Semantic guard on the test fixture itself: the hand-written+ -- `expected` must parse to the same AST as `input`. Catches a+ -- fixture-authoring mistake even before the formatter runs.+ astFixtureEq = case (parseAst input, parseAst expected) of+ (Just a, Just b) -> a == b+ _ -> True -- can't parse one side; defer to string check+ -- Semantic guard on the formatter output: parsing `actual` must+ -- yield the same AST as `input`. Catches a renderer that drops+ -- or alters a clause but still emits valid SQL (the+ -- `DISTINCT ON (...)` regression that motivated this guard).+ astFormatterEq = case (parseAst input, parseAst <$> result) of+ (Just a, Right (Just b)) -> a == b+ _ -> True+ pass = stringEq && astFixtureEq && astFormatterEq+ reason+ | Left _ <- result = "the formatter refused it"+ | not stringEq = "string mismatch"+ | not astFixtureEq = "AST mismatch: expected fixture is not semantically equivalent to input"+ | not astFormatterEq = "AST mismatch: formatter output is not semantically equivalent to input"+ | otherwise = ""+ msg =+ if pass+ then "PASS: " <> name+ else+ "FAIL ("+ <> reason+ <> "): "+ <> name+ <> "\n=== INPUT ===\n"+ <> showWhitespace input+ <> "\n=== EXPECTED ===\n"+ <> showWhitespace expected+ <> "\n=== ACTUAL ===\n"+ <> showWhitespace actual+ in (pass, msg)+++-- | Show whitespace characters for debugging+showWhitespace :: Text -> Text+showWhitespace = T.pack . concatMap showC . T.unpack+ where+ showC '\n' = "\\n\n"+ showC c = [c]