Quick Start
Get sqldoc running in 5 minutes. This guide walks through creating a schema, adding tags, generating migrations, and generating typed code.
1. Install
brew install elliots/sqldoc/sqldocor download the latest release from GitHub Releases for your platform.
2. Initialise in your project
sqldoc init3. Create a schema
Create a schema.sql file:
-- @import '@sqldoc/ns-validate'
-- @import '@sqldoc/ns-comment'
-- @comment('User accounts')
CREATE TABLE users (
id SERIAL PRIMARY KEY,
-- @comment('Login email address')
-- @validate.notEmpty
email VARCHAR(255) NOT NULL UNIQUE,
-- @validate.length(min: 2, max: 100)
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT now()
);
-- @comment('Blog posts')
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES users(id),
-- @validate.notEmpty
title VARCHAR(200) NOT NULL,
body TEXT,
published BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT now()
);4. Update the config
Update sqldoc.config.ts:
export default {
dialect: 'postgres',
schema: ['./schema.sql'],
codegen: [
{
template: 'typescript',
output: './generated/types.ts',
},
],
migrations: {
dir: 'migrations',
},
}4. Validate
Check your tags are correct:
sqldoc validateYou should see no errors. If a tag has invalid arguments or targets the wrong SQL object, you'll get a clear error message with line numbers.
5. Generate code
sqldoc codegenThis creates ./generated/types.ts with typed interfaces matching your schema, plus the SQL output with COMMENT ON statements and CHECK constraints compiled from your tags.
6. Create a migration
sqldoc migrateAnd check for your migration in ./migrations. By default it only saves up migrations, not down.
Then make a change to your schema (e.g. add a column), run migrate again, and check for the second migration file.
7. Explore more
- Add
@auditfor audit trails -- see @audit - Add
@rlsfor row-level security -- see @rls - Run
sqldoc lintto catch common issues - Run
sqldoc schema inspectto view the full compiled schema - See all namespace plugins and templates
What just happened?
sqldoc read your SQL file, parsed the tags in comments, and:
- Validated that all tags have correct syntax, arguments, and targets
- Compiled the tags into additional SQL (COMMENT ON statements, CHECK constraints)
- Verified the compiled sql was run in an embedded Postgres (PGLite), as well as the migrations, and then diffed.
- Generated TypeScript interfaces from your schema via Atlas
The input SQL stayed unchanged -- tags are comments, so the file is always valid SQL.
For more on how the compiler works, see Compilation.