Skip to content

Declaring Postgres Objects

llms.txt lists every page for an agent
Optional: hand this page to your coding agentThe steps work by hand too.
Show the whole prompt
Read https://intentius.io/chant/lexicons/sql/postgres-ddl/.
Declare the Postgres schemas, tables, indexes, views, types or functions I describe as tagged templates from `@intentius/chant-lexicon-sql/postgres`, with every column reference written as `${table.columns.name}`, and a rename written with `-- previously:`.
Run `npx chant build src --lexicon sql -o dist/schema.json` and `npx chant lint src` until both are clean, and open a pull request with the declarations.
Never deploy to a real cloud account or shared environment (with `chant run`, `chant components` or a platform's own CLI), approve (a pull request review, `chant approve` or `chant run approve`), override a policy denial (`chant approve policy-override`), or merge; never cut or publish a release (`chant release cut --yes` or `chant release publish`), push or delete a `ci/*` tag (`chant ci tick` pushes them), or change the value of an existing flag; never touch `.chant/allowed_signers` or `chant/lifecycle`.

A Postgres object is declared as its own DDL, inside a tagged template from @intentius/chant-lexicon-sql/postgres:

import { schema, sequence, table, index } from "@intentius/chant-lexicon-sql/postgres";
export const app = schema`CREATE SCHEMA app`;
export const ticketSeq = sequence`CREATE SEQUENCE ${app}.ticket_seq AS bigint START WITH 1000`;
export const tickets = table`
CREATE TABLE ${app}.tickets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
no bigint NOT NULL DEFAULT nextval(${ticketSeq}),
title text NOT NULL,
priority int NOT NULL DEFAULT 3,
CONSTRAINT tickets_priority_ck CHECK (priority BETWEEN 1 AND 5)
);
COMMENT ON TABLE ${app}.tickets IS 'Support tickets';
COMMENT ON CONSTRAINT tickets_priority_ck ON ${app}.tickets IS 'One to five'`;
export const ticketsTitle = index`
CREATE INDEX CONCURRENTLY tickets_title_idx ON ${tickets} (${tickets.columns.title})`;

chant build parses each template when it folds the file, without running it, into one entity. The export name (tickets) is the object’s identity in chant; the name in the SQL (app.tickets) is its name in the database. An unquoted name folds to lower case, as Postgres folds it, so CREATE TABLE Tickets is tickets, and .columns is keyed by the folded name. An object whose name has no schema is in the environment’s default schema, public unless the profile’s defaultSchema says otherwise.

TagStatementEntity type
schemaCREATE SCHEMAPostgres::Schema
tableCREATE TABLE, including PARTITION OFPostgres::Table
indexCREATE [UNIQUE] INDEX [CONCURRENTLY] name ON ...Postgres::Index
viewCREATE VIEW or CREATE MATERIALIZED VIEWPostgres::View, Postgres::MaterializedView
sequenceCREATE SEQUENCEPostgres::Sequence
typeCREATE TYPE name AS ENUM (...), AS (...) or AS RANGE (...)Postgres::Enum, Postgres::CompositeType, Postgres::RangeType
domainCREATE DOMAINPostgres::Domain
extensionCREATE EXTENSIONPostgres::Extension
funcCREATE [OR REPLACE] FUNCTIONPostgres::Function
procedureCREATE [OR REPLACE] PROCEDUREPostgres::Procedure
aggregateCREATE [OR REPLACE] AGGREGATEPostgres::Aggregate
triggerCREATE [OR REPLACE] [CONSTRAINT] TRIGGERPostgres::Trigger
eventTriggerCREATE EVENT TRIGGERPostgres::EventTrigger
operatorCREATE OPERATORPostgres::Operator
operatorClassCREATE OPERATOR CLASSPostgres::OperatorClass
operatorFamilyCREATE OPERATOR FAMILYPostgres::OperatorFamily
foreignTableCREATE FOREIGN TABLEPostgres::ForeignTable
textSearchConfigurationCREATE TEXT SEARCH CONFIGURATION, then ALTER TEXT SEARCH CONFIGURATION ... ADD MAPPINGPostgres::TextSearchConfiguration
textSearchDictionaryCREATE TEXT SEARCH DICTIONARYPostgres::TextSearchDictionary
statisticsCREATE STATISTICSPostgres::Statistics
foreignDataWrapperCREATE FOREIGN DATA WRAPPERPostgres::ForeignDataWrapper
foreignServerCREATE SERVERPostgres::ForeignServer
publicationCREATE PUBLICATIONPostgres::Publication
collationCREATE COLLATIONPostgres::Collation
castCREATE CASTPostgres::Cast
policyCREATE POLICYPostgres::Policy
roleCREATE ROLE, without a password or membershipsPostgres::Role
grantGRANT, REVOKE, ALTER DEFAULT PRIVILEGESPostgres::Grant, Postgres::DefaultPrivileges

A template holds one CREATE, of its tag’s kind, followed by any COMMENT ON statements for that object (and, in a textSearchConfiguration, its ADD MAPPING statements). A different statement, a second CREATE, or DDL that does not parse is SQLPG001, reported at the token as a line and column of the .ts file. A clause chant’s parser does not know yet, after a table’s column list, on a column, after an index’s elements or before a view’s AS, is kept and sent as written with a build warning, and a plan classes a change to it as one to review (SQLPG299); Plain .sql Files says where the line falls. The type tag declares enum, composite and range types; a base type (CREATE TYPE name (INPUT = ...)), whose functions are C code, and a shell type are refused. Object Coverage lists every CREATE command and whether a tag declares it.

A table’s template may also turn row-level security on after its CREATE TABLE (ALTER TABLE ... ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY). Policies, roles, grants and row-level security are planned and applied only where the profile manages access; see Access.

A table’s declaration records every column (type, NOT NULL, default, GENERATED ... AS IDENTITY, GENERATED ALWAYS AS (...) STORED or VIRTUAL, collation, compression, storage) and every constraint: the primary key, unique constraints (with NULLS NOT DISTINCT, INCLUDE, WITH), checks (with NO INHERIT, NOT VALID, NOT ENFORCED), foreign keys (with MATCH, actions and deferral) and exclusion constraints. A constraint written on a column’s line is filed with the table’s, as Postgres files it. It also records PARTITION BY, PARTITION OF ... FOR VALUES, OF type, LIKE, INHERITS, USING, storage parameters in WITH (...), ON COMMIT and a tablespace.

A partition is a table of its own that names its parent by reference:

events.ts
import { index, schema, table } from "@intentius/chant-lexicon-sql/postgres";
export const telemetry = schema`CREATE SCHEMA telemetry`;
// A partitioned table's primary key has to include the partition key, so
// the key is (id, occurred_at). Rows route to the partition whose range holds
// occurred_at; a row outside every range goes to the default partition
// instead of failing the insert.
export const events = table`
CREATE TABLE ${telemetry}.events (
id bigint GENERATED ALWAYS AS IDENTITY,
occurred_at timestamptz NOT NULL,
device_id bigint NOT NULL,
kind text NOT NULL,
payload jsonb NOT NULL DEFAULT '{}',
PRIMARY KEY (id, occurred_at)
) PARTITION BY RANGE (occurred_at)`;
// One partition per month, created ahead of time. Ranges are half-open: the
// upper bound belongs to the next month.
export const eventsOct = table`
CREATE TABLE ${telemetry}.events_2026_10 PARTITION OF ${events} FOR VALUES FROM ('2026-10-01') TO ('2026-11-01')`;
export const eventsNov = table`
CREATE TABLE ${telemetry}.events_2026_11 PARTITION OF ${events} FOR VALUES FROM ('2026-11-01') TO ('2026-12-01')`;
export const eventsDec = table`
CREATE TABLE ${telemetry}.events_2026_12 PARTITION OF ${events} FOR VALUES FROM ('2026-12-01') TO ('2027-01-01')`;
export const eventsDefault = table`
CREATE TABLE ${telemetry}.events_default PARTITION OF ${events} DEFAULT`;
// An index on the parent exists on every partition, present and future.
export const eventsByDevice = index`
CREATE INDEX events_by_device_idx ON ${events} (${events.columns.device_id}, ${events.columns.occurred_at} DESC)`;

REFERENCES ${users} (${users.columns.id}) makes the referenced table a dependency, so the build creates it first. A foreign key to a table the project does not declare can name it as text, REFERENCES billing.accounts (id); the build then cannot order the two.

What the build checks about a column: its type against the target major’s catalog in any spelling Postgres accepts, or against the types the project declares (SQLPG119), the type’s modifiers (SQLPG120), an identity column’s type (SQLPG121), that no column is declared twice (SQLPG122), the functions its DEFAULT or generated expression calls (SQLPG126), and, for a foreign key to a ${} table, that the referenced column exists and its type compares (SQLPG124). Column names in key, index and grant lists are checked against the table (SQLPG123); column names inside expressions are left to the server.

Name the constraints you expect to change. A constraint left unnamed gets a name from the server (orders_amount_check); a plan matches it by what it says rather than by that name, so it is not reported as changed, but a COMMENT ON CONSTRAINT needs the name in the declaration.

An index needs a name, and the name is unqualified: an index lives in its table’s schema, and its name is its identity on the server. An unnamed index is SQLPG001.

export const ticketsOpen = index`
CREATE INDEX CONCURRENTLY tickets_open_idx ON ${tickets} USING btree (${tickets.columns.priority})
INCLUDE (${tickets.columns.title})
WHERE ${tickets.columns.priority} > 3`;

The index records CONCURRENTLY, its method, its elements (with the column when an element is a plain column), INCLUDE and WHERE. Declare CONCURRENTLY on any index you add to a table that already holds rows: without it the build blocks every write to the table until it ends, and the plan reports SQLPG241. An index on a table the same plan creates is part of the create (SQLPG200), since an empty table has no writes to block; if it is declared CONCURRENTLY, the applier still builds it outside a transaction, once the table’s transaction has committed.

The view tag takes both. A view records its query, the objects its FROM and JOIN read (by reference), and the column lineage of its select list; see References and Lineage.

export const openTickets = view`
CREATE VIEW ${app}.open_tickets WITH (security_invoker = true) AS
SELECT t.${tickets.columns.id}, t.${tickets.columns.title}
FROM ${tickets} t
WHERE t.${tickets.columns.priority} > 3`;

In a join or with a table alias, qualify each column reference with the alias, t.${tickets.columns.id}: the reference renders as the column’s bare name.

Set security_invoker = true (Postgres 15 and later) unless the view should run with its owner’s privileges; SQLPG117 reports a view without it. A materialized view can end in WITH NO DATA, and needs a unique index over plain columns before REFRESH MATERIALIZED VIEW CONCURRENTLY works, which SQLPG111 checks; the RefreshedView composite declares both.

nextval(${seq}), currval(${seq}) and setval(${seq}, ...) render the sequence as a regclass literal, nextval('app.ticket_seq'::regclass), which is how pg_get_expr prints the default back. The declaration and the server’s catalog then read the same, and the table depends on the sequence. Any declared object followed by ::regclass renders the same way: pg_relation_size(${tickets}::regclass) reads pg_relation_size('app.tickets'::regclass).

A name typed in a string, nextval('app.ticket_seq'), records no reference, so the build may create the table before the sequence. SQLPG003 warns about it.

A sequence OWNED BY a column whose default calls nextval on that same sequence is a cycle, and the build fails naming it. An identity column, GENERATED ALWAYS AS IDENTITY, is the form to use there; it owns its sequence without declaring one, and SQLPG103 suggests it over serial.

import { domain, extension, type } from "@intentius/chant-lexicon-sql/postgres";
export const ticketStatus = type`CREATE TYPE ${app}.ticket_status AS ENUM ('open', 'closed')`;
export const email = domain`CREATE DOMAIN ${app}.email AS text CHECK (VALUE ~ '@')`;
export const trgm = extension`CREATE EXTENSION pg_trgm WITH SCHEMA ${app}`;

A column of an enum type or a domain names it by reference, status ${ticketStatus} NOT NULL DEFAULT 'open', so the build creates the type first. Labels are added to an enum in place (SQLPG260); removing or reordering them is expand and contract (SQLPG261).

An extension is checked against the configured managed provider’s list (SQLPG004, see Managed Providers) and against the target major’s catalog (SQLPG116 for one the major no longer ships). The objects an extension creates are its own, and chant neither declares nor imports them.

import { func, procedure, trigger } from "@intentius/chant-lexicon-sql/postgres";
export const touch = func`
CREATE FUNCTION ${app}.touch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END
$$`;
export const openCount = func`
CREATE FUNCTION ${app}.open_count(min_priority int DEFAULT 1) RETURNS bigint
LANGUAGE sql STABLE PARALLEL SAFE
AS $$ SELECT count(*) FROM ${tickets} WHERE ${tickets.columns.priority} >= min_priority $$`;
export const closeOld = procedure`
CREATE PROCEDURE ${app}.close_old(before timestamptz) LANGUAGE plpgsql AS $$
BEGIN UPDATE ${tickets} SET status = 'closed' WHERE created_at < before; END
$$`;
export const ticketsTouch = trigger`
CREATE TRIGGER tickets_touch BEFORE UPDATE ON ${tickets}
FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) EXECUTE FUNCTION ${touch}()`;

function is a JavaScript key word, so the tag is func. The body is a string constant (AS $$ ... $$ or AS '...'), kept as written: Postgres stores it verbatim and prints it back unchanged, so it is compared exactly. An interpolation inside the body renders as text, an object as its schema-qualified name and a column reference as the column’s name, and is recorded as a reference, so the build creates the routine after the table its body reads. A SQL-standard body (RETURN expr, BEGIN ATOMIC ... END) is refused, since the server keeps it parsed and prints it back rewritten; so is SET ... FROM CURRENT, which takes the value of whichever session runs the CREATE.

A routine’s identity on the server is its name and its input parameter types, so overloads are separate objects, and COMMENT ON FUNCTION ${app}.touch() IS '...' names it the same way. A trigger belongs to its table and its name is unqualified. A trigger’s arguments are stored as strings, and its WHEN condition is compared as the server prints it, its casts included.

import { type } from "@intentius/chant-lexicon-sql/postgres";
export const money = type`
CREATE TYPE ${app}.money_amount AS (amount numeric(12,2), currency char(3) COLLATE "C");
COMMENT ON TYPE ${app}.money_amount IS 'An amount and its currency'`;
export const priceRange = type`CREATE TYPE ${app}.price_range AS RANGE (SUBTYPE = numeric, SUBTYPE_DIFF = numeric_sub)`;

A composite type’s attributes are compared by name, type and collation, in order. A range type records its options; one left out is the one Postgres chooses (the subtype’s default btree operator class and collation), and its multirange type is named as Postgres names it (price_multirange here) unless MULTIRANGE_TYPE_NAME says otherwise. A column may use either type, or the multirange, by reference or by name. Neither type has an ALTER for its definition: a changed one is dropped and created when nothing on the server uses it (SQLPG300), and refused while a column, a function or a cast does (SQLPG301).

import { aggregate, func } from "@intentius/chant-lexicon-sql/postgres";
export const add2 = func`CREATE FUNCTION ${app}.add2(a integer, b integer) RETURNS integer LANGUAGE sql IMMUTABLE AS $$ SELECT a + b $$`;
export const total = aggregate`
CREATE AGGREGATE ${app}.total(integer) (SFUNC = ${add2}, STYPE = integer, INITCOND = '0', PARALLEL = SAFE);
COMMENT ON AGGREGATE ${app}.total(integer) IS 'A sum'`;

An aggregate is identified, as a function is, by its name and argument types: (integer), (*) for none, (text ORDER BY integer) for an ordered-set aggregate. Its options are compared by name, each function by its qualified name (a built-in one bare), each type canonical, and an option at the value Postgres would choose (SSPACE = 0, PARALLEL = UNSAFE, FINALFUNC_MODIFY = READ_ONLY for a plain aggregate) as if it were not written. A change keeps the aggregate with CREATE OR REPLACE AGGREGATE (SQLPG302), unless it changes the state type or the final function, which can change its result: then it is dropped and created, or refused while a view uses it. The old form, CREATE AGGREGATE name (BASETYPE = ...), is refused.

import { cast, collation, eventTrigger } from "@intentius/chant-lexicon-sql/postgres";
export const ci = collation`CREATE COLLATION ${app}.ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false)`;
export const moneyText = cast`CREATE CAST (${money} AS text) WITH FUNCTION ${moneyToText}(${money}) AS ASSIGNMENT`;
export const ddlAudit = eventTrigger`
CREATE EVENT TRIGGER ddl_audit ON ddl_command_end WHEN TAG IN ('CREATE TABLE', 'ALTER TABLE')
EXECUTE FUNCTION ${auditDdl}()`;

A collation records its provider (libc unless written), its locales and whether it is deterministic; VERSION is the provider library’s and is not compared. CREATE COLLATION ... FROM is refused: write the settings, which are what the server keeps. Write an ICU locale as the BCP 47 tag the server stores (und-u-ks-level2).

A cast lives in no schema and is named by its two types, (app.money_amount AS text), which is also how COMMENT ON CAST names it; its function is compared by name. Creating a cast takes owning its source or target type. An event trigger belongs to the database, its name unqualified; its tags are compared as a set. Creating one takes a superuser, and it fires for DDL anywhere in the database, so keep its function cheap. Whether it is enabled (ALTER EVENT TRIGGER ... DISABLE) is not declared or compared.

None of the three has an ALTER for its definition: a change is a drop and a create in one transaction (SQLPG300), refused while a column uses the collation (SQLPG301).

Operators, statistics, foreign servers and publications

Section titled “Operators, statistics, foreign servers and publications”
import { foreignDataWrapper, foreignServer, operator, publication, statistics } from "@intentius/chant-lexicon-sql/postgres";
export const sameValue = operator`
CREATE OPERATOR ${app}.=== (FUNCTION = ${intSame}, LEFTARG = integer, RIGHTARG = integer, COMMUTATOR = ===, HASHES)`;
export const ordersStats = statistics`
CREATE STATISTICS ${app}.orders_stats (dependencies, ndistinct) ON user_id, status FROM ${orders}`;
export const remoteFdw = foreignDataWrapper`CREATE FOREIGN DATA WRAPPER remote_fdw HANDLER ${remoteHandler} OPTIONS (debug 'true')`;
export const replica = foreignServer`
CREATE SERVER replica TYPE 'pg' FOREIGN DATA WRAPPER ${remoteFdw} OPTIONS (host 'db.internal', port '5432')`;
export const orderEvents = publication`
CREATE PUBLICATION order_events FOR TABLE ${orders} (id, status) WHERE (status <> 'draft'), TABLES IN SCHEMA ${audit}
WITH (publish = 'insert, update')`;

An operator is identified, as an aggregate is, by its name and operand types, app.===(integer,integer), with NONE for a missing side. Its function, restrict and join estimators are compared by qualified name (a built-in one bare), and a COMMUTATOR or NEGATOR as schema.symbol: written bare, it is in the operator’s own schema. HASHES and MERGES count only when set. ALTER OPERATOR ... SET changes what the server lets it change, so those edits are made in place (SQLPG304): RESTRICT and JOIN on every supported major, set, changed or removed (NONE); and from 17 a COMMUTATOR or NEGATOR the operator does not have yet, and HASHES or MERGES turned on. The Postgres 18 page says a commutator and a negator “can only be changed if the operator does not have an existing” one and the two flags “can only be enabled and not disabled”, and setting a commutator or negator also sets the other operator’s. Everything else is a drop and a create (SQLPG300), refused while an operator class, an index or a view depends on it (SQLPG301): the function, the operands, a commutator or negator that is already set, a flag turned off, and on 14 to 16 every attribute but RESTRICT and JOIN (those majors’ ALTER OPERATOR has no other). The rule is operatorAlterable in src/postgres/plan/diff.ts, and the major is sql.postgresMajor.

Extended statistics are a schema’s, named in the table’s schema when you qualify them. Their kinds are compared as a set, and a list that names all three (ndistinct, dependencies, mcv) is the same as none, which is what the server prints. A column and an expression are compared in the order the server keeps them, so ON b, a and ON a, b are one declaration. A change is a drop and a create (SQLPG300), and the new statistics hold nothing until the next ANALYZE.

A foreign data wrapper, a foreign server and a publication belong to the database, with unqualified names; creating a wrapper takes a superuser. A wrapper’s handler and validator are compared by function name, a server’s type and wrapper by name, and options by name. A wrapper’s change is ALTER FOREIGN DATA WRAPPER, a server’s version and options are ALTER SERVER, and a publication’s options, tables and schemas are ALTER PUBLICATION (SQLPG303), so none of them is dropped for an edit. The exceptions are a server’s type or wrapper and a publication’s FOR ALL TABLES, which have no ALTER: they are dropped and created (SQLPG300), or refused while something depends on the object (SQLPG301). A publication that is dropped stops its subscribers until it exists again, so prefer the edit that keeps it.

An option named like a credential (password, sslpassword, secret, token, api_key) is refused in a wrapper or a server. The user mapping that carries the remote user and password is the environment’s: CREATE USER MAPPING is not declared, and neither is CREATE SUBSCRIPTION, whose connection string holds a credential. Import reads a server without such an option and says it left it out.

Section titled “Foreign tables, operator classes and families, and text search”
import { foreignTable, operatorClass, operatorFamily, textSearchConfiguration, textSearchDictionary } from "@intentius/chant-lexicon-sql/postgres";
export const remoteOrders = foreignTable`
CREATE FOREIGN TABLE ${app}.remote_orders (
id integer OPTIONS (column_name 'order_id') NOT NULL,
status text DEFAULT 'placed',
CONSTRAINT status_known CHECK (status IS NOT NULL)
) SERVER ${replica} OPTIONS (table_name 'orders')`;
export const intOps = operatorClass`
CREATE OPERATOR CLASS ${app}.int_hash_ops FOR TYPE integer USING hash AS
OPERATOR 1 =,
FUNCTION 1 hashint4(integer)`;
export const shopStop = textSearchDictionary`
CREATE TEXT SEARCH DICTIONARY ${app}.shop_stop (TEMPLATE = simple, StopWords = english)`;
export const shopSearch = textSearchConfiguration`
CREATE TEXT SEARCH CONFIGURATION ${app}.shop (PARSER = pg_catalog."default");
ALTER TEXT SEARCH CONFIGURATION ${app}.shop ADD MAPPING FOR asciiword, word WITH ${shopStop}, english_stem`;

A foreign table has its own tag, and table refuses CREATE FOREIGN TABLE. It is another kind of relation, with its own CREATE and ALTER FOREIGN TABLE (ALTER TABLE refuses it). It takes no key, index, identity, partitioning, storage or tablespace clause, and it names a server that no ALTER can change. Folding it into table would put a branch for each of those in the parser, the classifier and the statements of every table. It shares the relation namespace with tables, views and sequences, as on the server. The tag declares its columns (type, collation, default, NOT NULL, and a column’s OPTIONS), CHECK and NOT NULL constraints, SERVER and OPTIONS. INHERITS, PARTITION OF, LIKE, a key, a generated column and ENFORCED or NOT ENFORCED are refused when you write them; import reads a foreign table with any of them as unsupported and says why. Columns, constraints and options change with ALTER FOREIGN TABLE (SQLPG306), which reads nothing from the remote side. A change of server is a drop and a create (SQLPG300), refused while a view uses the table (SQLPG301). An option named like a credential is refused, here and in a column’s options.

An operator class is identified by its name and index method, app.int_hash_ops USING hash, so one name for two methods is two classes. Its members are written as CREATE OPERATOR CLASS writes them. Operand types left out are the class’s type, and a support function’s are what the server gives it (a B-tree comparison function’s and a hash function’s are the function’s own input types), so a declaration compares equal to what the catalog prints. A class with no FAMILY is in a family of its own name, which the server makes for it; that family is the class’s, and import does not read it as a family of its own, so an operatorFamily named as a class of the same method is that class’s family and is not declared. ALTER OPERATOR CLASS renames, changes the owner and moves; it does not touch the members. So any change to a class is a drop and a create (SQLPG300), refused while an index uses it (SQLPG301). An operator family is its name and method, with the members its classes bring; members added to a family with ALTER OPERATOR FAMILY ... ADD are loose, and import leaves them out with a warning. Creating either takes a superuser.

A dictionary’s options are compared as the server keeps them, as strings by name, so StopWords = english and stopwords = 'english' are one option. A configuration is its parser and its mappings, one ADD MAPPING per group of token types; COPY = other is refused, since it copies mappings chant does not read, and a token type mapped twice is an error. Mappings and options change in place (SQLPG305): ADD, ALTER and DROP MAPPING for a configuration, one ALTER TEXT SEARCH DICTIONARY for a dictionary, in which an option named without a value is removed. A tsvector already stored keeps the tokens it was built with, so rebuild the columns and indexes that hold one when an edit changes what a word becomes. A configuration’s parser and a dictionary’s template have no ALTER and are dropped and created (SQLPG300), refused while an index or a configuration uses the object (SQLPG301). The parsers and templates themselves are C code an extension installs and are not declared.

Across the supported majors 14 to 18 the grammar of an operator class, a family and the two text search kinds is the same: the pinned catalogs (src/spec/postgres-catalog-14.snapshot.json to -18) list the same access methods, the same 177 operator classes and the same key words (CLASS, FAMILY, MAPPING, PARSER, TEMPLATE, DICTIONARY). A foreign table differs in two key words only 18 has, ENFORCED and VIRTUAL, and neither is declared. The one difference that matters is ALTER OPERATOR, above.

Postgres has no inline comment clause, so a template follows its CREATE with COMMENT ON statements. They may name the object itself, one of its columns, or one of its named constraints, and nothing else:

COMMENT ON TABLE ${app}.tickets IS 'Support tickets';
COMMENT ON COLUMN ${app}.tickets.title IS 'What the reporter typed';
COMMENT ON CONSTRAINT tickets_priority_ck ON ${app}.tickets IS 'One to five'

They fold into the entity’s comment, each column’s and each constraint’s, and stay in the DDL the build writes. The applier sets the object’s own comment with chant’s ownership marker after it; see Applying to a Postgres Server. SQLPG112 asks for a comment on a column named like a secret or personal data (password, token, email, phone and similar), or on its table.

What an interpolation means is decided by its value:

ValueRenders asRecords
a Postgres entity (${tickets})its schema-qualified name, app.tickets; a schema as its namea reference
a column (${tickets.columns.title})the column’s name, titlea reference to the column
a sequence in nextval, currval, setval, or any entity before ::regclassa regclass literal, 'app.ticket_seq'::regclassa reference
a stringSQL text, spliced in before the statement is parsednothing
a number or biginta numeric literalnothing
true, false, nulltrue, false, NULLnothing
literal(value)a quoted string literalnothing

${tickets.title} is not a column. An entity’s own fields (kind, lexicon, entityType, props, sqlName, dependsOn) would splice their value in as SQL text, so ${tickets.kind} where a column is called kind builds into a different statement. SQLPG002 reports it for an entity the file declares or imports from a project file. Write ${tickets.columns.kind}.

A plain string is spliced into the statement as SQL, the way a composite’s columns prop is:

const auditColumns = "created_at timestamptz NOT NULL DEFAULT now(), created_by text";
export const notes = table`
CREATE TABLE ${app}.notes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
${auditColumns}
)`;

When the string is a value, wrap it in literal(): DEFAULT ${literal("it's")} renders DEFAULT 'it''s'. literal() doubles a single quote and leaves a backslash as an ordinary character, as Postgres reads a string with standard_conforming_strings on, the default since 9.1.

The export name is the identity, so changing the name in the SQL under the same export is a rename of the object, which the plan treats as expand and contract (SQLPG228). A renamed column says so on its own line, and a renamed object before its CREATE:

-- previously: tickets
CREATE TABLE ${app}.issues (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL -- previously: subject
)

See Postgres Locks and the Change Classifier for how a plan reads the hint, and Migrating a Column for running a column rename.

A project’s build holds one dialect. Declaring a Postgres object and a ClickHouse object in the same project fails the build, naming one of each. Two databases of different dialects are two projects. sql.dialect: "postgres" in chant.config.ts marks a project as Postgres when nothing declared says so yet, such as before an import.

Inside a template whose tag is imported from /postgres, chant serve lsp completes type names, index and table access methods after USING, storage parameters inside WITH ( for the object’s kind, extensions after CREATE EXTENSION, function names in expressions and key words, and offers the file’s declared objects after ${ and their columns after ${t.columns.. Hover shows what the catalog says about the name. Both read the catalog of the project’s major, sql.postgresMajor, so a name that major lacks is not offered; see The Postgres Pin and Supported Majors.

Each entity’s parsed definition, its references and its lineage are in the build output; see Serialization. Lint Rules and Checks lists SQLPG001 to SQLPG005, which run over the source, and SQLPG101 to SQLPG126, which run over the build.

chant