Plain .sql Files
Show the whole prompt
Read https://intentius.io/chant/lexicons/sql/sql-files/.
Move the `.sql` files of CREATE statements I name into the source directory, so the build reads them beside the tagged templates, and take out any statement that is not schema.
Run `npx chant build src --lexicon sql -o dist/schema.json` and `npx chant lint src`, fix every error the build names by file and line, and report each warning about a clause chant does not read.
Open a pull request with the files.
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`.Optional: hand this page to your coding agent
Read https://intentius.io/chant/lexicons/sql/sql-files/.Move the `.sql` files of CREATE statements I name into the source directory, so the build reads them beside the tagged templates, and take out any statement that is not schema.Run `npx chant build src --lexicon sql -o dist/schema.json` and `npx chant lint src`, fix every error the build names by file and line, and report each warning about a clause chant does not read.Open a pull request with the files.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 project can keep its schema, or part of it, in plain .sql files of CREATE statements. chant build reads every .sql file in the source directory and turns each object into the declaration chant import would write for it, so a file and the tagged templates can sit side by side and reference each other.
Put the file in the source directory
Section titled “Put the file in the source directory”-- src/users.sqlCREATE TABLE app.users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL);COMMENT ON TABLE app.users IS 'People who can sign in';CREATE INDEX users_email_idx ON app.users (lower(email));import { schema, view } from "@intentius/chant-lexicon-sql/postgres";
export const app = schema`CREATE SCHEMA app`;export const activeUsers = view`CREATE VIEW app.active_users AS SELECT id, email FROM app.users`;The build finds the file the way it finds .ts source: dist, git-ignored paths, child projects and the project’s exclude globs are left out. The dialect is the templates’ (here Postgres, from the schema tag). A project with no templates reads its files as sql.dialect, which defaults to ClickHouse, so a Postgres project of .sql files alone sets sql: { dialect: "postgres" } in chant.config.ts.
Each object gets an export name, as an import would name it: users and usersEmailIdx above, <name>Schema for a schema, <name>Db for a ClickHouse database. The names show up in the build output, in dependsOn, and in plan and lint messages. A file’s object whose export name a template already uses is a build error; rename the template’s export.
What a file can hold
Section titled “What a file can hold”Postgres reads each CREATE statement chant declares (schema, table, index, view, materialized view, sequence, enum type, domain, extension, function, procedure, trigger, policy, role), each GRANT and REVOKE, and each ALTER DEFAULT PRIVILEGES as one object. Three kinds of statement are folded into the object they finish:
COMMENT ONjoins the object it comments on, wherever in the file it is.ALTER TABLE ... ENABLE | DISABLE | FORCE ROW LEVEL SECURITYjoins its table.ALTER TABLE <t> ADD [CONSTRAINT <c>] FOREIGN KEY | UNIQUE | PRIMARY KEY | CHECK | EXCLUDE ...becomes a table constraint in<t>’sCREATE TABLE.pg_dumpand most ORMs print foreign keys this way.
BEGIN and COMMIT are skipped.
ClickHouse reads CREATE DATABASE, CREATE TABLE, CREATE VIEW, CREATE MATERIALIZED VIEW, CREATE DICTIONARY and CREATE FUNCTION, and the access statements CREATE USER, CREATE ROLE, CREATE ROW POLICY and GRANT (Access Control). Each access statement is read by its tag, so what the tag refuses is refused in its words: a password (IDENTIFIED BY), or a REVOKE.
Anything else fails the build: an INSERT, a DROP, a SET, a CREATE of a kind chant does not declare, a COMMENT ON for an object the file does not create, or a statement that does not parse. The error names the file and every statement it could not read, so the whole file is reported at once:
src/users.sql: a statement chant cannot read as declarations: - not a statement that declares an object: DROP TABLE app.old_usersA statement chant reads except for a clause its parser does not know builds, with a warning. See the next section.
Clauses chant does not read
Section titled “Clauses chant does not read”The SQL is the server’s, so a clause the server accepts belongs in the statement even when chant’s parser does not know it yet, such as a clause a new ClickHouse or Postgres release adds. The build keeps the statement as written, sends it as written, and warns naming the file, the line and the clause:
src/events.sql:7: analytics.events has a clause chant does not read, PARTITION_STRATEGY. It is sent as written and the server checks it; a plan reads the rest of the object, and classes any change to the clause as one to reviewA template gets the same warning, naming its .ts file, its export and the line within the statement. The post-synth checks still run over what chant does read (column types, codecs, settings it knows), and the server decides on the clause when the statement runs.
What chant does not read stays opaque, and nothing that depends on it is guessed:
- The rest of the object is read as usual: its name, its columns, its keys and its references, so dependency order and lineage hold. The build output lists the clauses under
unparsed, each with its text and line. - A column that carries such a clause keeps its type in Typed Columns, but its nullability and its key comparison are
never, so it fits every slot instead of a guessed one. - A plan compares the clause as text. A change to it is classed as one to review, SQLCH290 or SQLPG299, which the plan and the applier refuse rather than guess what
ALTERit takes (Planning ClickHouse Changes, Postgres Locks and the Change Classifier). A clause only the server prints is a hint, not a change.
Where the line falls between a clause chant does not know and SQL that is wrong:
- A clause is kept only where a clause can start: after a table’s column list and its storage clauses, among a column’s or a dictionary attribute’s clauses, before a view’s
AS, among a database’s, a dictionary’s, an index’s or a sequence’s clauses, and at the end of a statement. It starts with a key word of three letters or more, runs to the next clause chant knows, and its parentheses balance. - These still fail: a statement that is not schema (above), a
CREATEof a kind chant does not declare, a key word one letter from a clause chant knows (ORDR BY,TABLESPAC), a clause chant knows written where it cannot go, punctuation, a string or a number where a clause should start, unbalanced parentheses, and what chant refuses on purpose (a password,SET ... FROM CURRENT, a SQL-standard function body). - An unknown word inside an expression (a default, a check, a view’s query) is the expression’s, and the server reads it. In ClickHouse, a key word right after a complete key, default or setting value (
ORDER BY ts PARTITION_STRATEGY = 'hourly') starts a new clause. In Postgres, such a word in a default or a sequence option is an error, as before. - Roles, users, grants and policies are read strictly: an option chant does not know there is an error, because access control is not something to send unread.
SQL that is not schema
Section titled “SQL that is not schema”The build reads every .sql file under the directory it builds. chant build src builds src/. chant lifecycle diff, and the Plan phase of an ApplyOp, build sourceDir from chant.config.ts, or the project root when it is unset. A project that keeps other SQL beside its schema sets sourceDir, so those builds read the schema and nothing else:
export default { lexicons: ["sql"], sourceDir: "src", sql: { dialect: "postgres", profiles: { /* ... */ } },};Wherever the build walks, these files are left out:
- A file under a directory named
migrations, at any depth: versioned migrations (migrations/<id>/migration.sql) and an ORM’s generated ones (prisma/migrations/...). They holdALTERstatements, andCREATEs of objects declared elsewhere. - A file whose first lines carry
-- chant-discovery-skip, for seed data or queries. - A file an
excludeglob inchant.config.tsmatches.
Any other .sql file in the walk is read as schema. A DDL dump that another tool turns into declarations (an ORM’s schema, read into src/ by a generator) is a duplicate of those declarations, and the build fails naming both. Keep it outside sourceDir, or mark it.
References and order
Section titled “References and order”A name in a file’s statement is a reference to another object, in a file or in a template, when:
- it is qualified,
app.users, and an object has that schema and name; - it is bare, where SQL names an object (after
FROM,JOINorREFERENCES, an index’s, trigger’s or policy’s table, a trigger’s function, a column’s or a domain’s type), and an object declared without a schema has that name.
The reference becomes an interpolation, as in the import’s output, so it carries into dependsOn and the build orders the objects by it. A template cannot import a file’s object, so it names it in its text; a qualified or bare name of a file’s object in a template’s statement counts as a reference the same way. Above, users comes after app, and activeUsers after users.
Two files’ objects that reference each other in a cycle are a build error, as two templates would be. An object declared in a file and again in a template (the same type and qualified name) is an error naming both.
Turn a file into templates
Section titled “Turn a file into templates”chant import <file>.sql --lexicon sql writes the file’s objects as one schema.ts of tagged templates, the same declarations the build reads from the file. The dialect is read off the statements: an ENGINE = clause, a CREATE DATABASE, a CREATE DICTIONARY, a CREATE ROW POLICY or a lambda CREATE FUNCTION f AS (x) -> ... is ClickHouse, and a statement only Postgres has (CREATE SCHEMA, CREATE INDEX, COMMENT ON, ALTER TABLE, GRANT) or a CREATE TABLE with no engine is Postgres. --parser-option dialect=postgres names it. A statement the import cannot read stops it, named, as on a build. A CREATE of a kind chant cannot declare (an aggregate, a cast, a quota; see Object Coverage) is named with its kind and why; --parser-option skipUndeclarable imports the rest of the file and lists those statements as warnings, and does the same for a statement that declares nothing at all (COPY, INSERT, UPDATE, DELETE, SELECT, SET, TRUNCATE), naming each with its line. Without the option such a statement stops the import. A Postgres CREATE INDEX with no name is declared under the name Postgres gives it, <table>_<columns>_idx (a number after idx when the schema already has the name, expr for an operator expression, the function’s name for a call), with a warning naming the index and the name; an index on a cast or a CASE still stops the import and has to be named in the DDL.
From code
Section titled “From code”The same reading is exported from the package root (and from @intentius/chant-lexicon-sql/sql-files), for a tool that turns DDL it gets elsewhere into declarations:
import { readSqlFile, sqlFileDeclarations, sqlFileEntities, SqlFileError } from "@intentius/chant-lexicon-sql";
// The objects, each with its export name, type, qualified name and statements.const objects = readSqlFile("postgres", ddl, { origin: "prisma migrate diff" });
// The TypeScript chant import would write, with comment lines at the top.const { content } = sqlFileDeclarations("postgres", ddl, { origin: "db/legacy.sql", schema: "app", header: "Generated from db/legacy.sql" });
// The declarations themselves, references to `known` entities interpolated.const entities = sqlFileEntities("postgres", [{ origin: "db/legacy.sql", ddl }], { known });schema qualifies the names the DDL leaves unqualified, as an ORM does when the schema comes from its connection: an object’s own name, an index’s, trigger’s or policy’s table, a foreign key’s table, a comment’s target and a column type naming an enum or domain the file creates. On ClickHouse it is the database for an object’s unqualified name. Each function throws a SqlFileError, whose problems list the statements it could not read.