parser Package
Theparser package parses SQL files containing schema definitions into schema.Database objects.
Parser
Main type for SQL parsing.Options
Parse Methods
Parse String
Parse a SQL string:Parse File
Parse a single SQL file:Parse Directory
Parse all.sql files in a directory:
ParseResult
Example Usage
Supported Statements
CREATE TABLE
- Columns with types, defaults, constraints
- Primary keys, foreign keys, unique, check constraints
- Table partitioning (HASH, RANGE, LIST)
CREATE INDEX
- Index name and table
- Columns and expressions
- Index type (btree, hash, gin, etc.)
- INCLUDE columns
- WHERE clause for partial indexes
CREATE VIEW
CREATE FUNCTION
- All PostgreSQL languages (plpgsql, sql, c, etc.)
- Dollar-quoted bodies
- Function attributes (VOLATILE, STABLE, IMMUTABLE, etc.)
CREATE TRIGGER
CREATE TYPE
CREATE EXTENSION
TimescaleDB Functions
Lexer
The lexer tokenizes SQL into tokens:Lexer Features
- PostgreSQL keywords recognition
- Dollar-quoted strings (
$$,$body$, etc.) - Quoted identifiers (
"TableName") - Single and double-quoted strings
- Line and block comments
- Numeric literals
Statement Splitter
Splits multiple statements from a single SQL file:- Semicolon-separated statements
- Dollar-quoted function bodies
- Nested parentheses
- Comments
Identifier Normalization
- Unquoted identifiers are lowercased
- Quoted identifiers preserve case
- Schema-qualified names are split and normalized
Users→users"Users"→Userspublic.users→public.users
Error Handling
ParseError
Common Errors
| Error | Cause |
|---|---|
| ”unexpected end of input” | Unclosed parenthesis or quote |
| ”unknown statement type” | Unrecognized SQL statement |
| ”invalid column definition” | Malformed column syntax |
| ”duplicate constraint name” | Same constraint name twice |
See Also
- schema Package - Parsed data structures
- Declarative Migrations - SQL file format