PostgreSQL Syntax Reference
БесплатноБез исполняемых скриптовНе проверенConsult PostgreSQL's parser and grammar (gram.y) to understand SQL syntax, DDL statement structure, and parsing rules when implementing pgschema features
Об этом скилле
PostgreSQL Syntax Reference
Use this skill when you need to understand PostgreSQL's SQL syntax, DDL statement structure, or how PostgreSQL parses specific SQL constructs. This is essential for correctly parsing SQL files and generating valid DDL in pgschema.
When to Use This Skill
Invoke this skill when:
- Implementing new SQL statement parsing in
ir/parser.go - Debugging SQL parsing issues with pg_query_go
- Understanding complex SQL syntax (CREATE TABLE, CREATE TRIGGER, etc.)
- Generating DDL statements in
internal/diff/*.go - Validating SQL statement structure
- Understanding precedence and grammar rules
- Learning about PostgreSQL-specific syntax extensions
Source Code Locations
Main parser directory: https://github.com/postgres/postgres/blob/master/src/backend/parser/
Key files to reference:
Grammar and Lexer
gram.y- Main grammar file - Yacc/Bison grammar defining PostgreSQL SQL syntaxscan.l- Lexical scanner (Flex/Lex) - tokenization ruleskeywords.c- Reserved and non-reserved keywords
Parser Implementation
parse_clause.c- Parsing of clauses (WHERE, GROUP BY, ORDER BY, etc.)parse_expr.c- Expression parsing (operators, function calls, etc.)parse_type.c- Type name parsing and resolutionparse_relation.c- Table and relation parsingparse_target.c- Target list parsing (SELECT list, etc.)parse_func.c- Function call parsingparse_utilcmd.c- Utility commands (DDL statements like CREATE, ALTER, DROP)
Analysis and Transformation
analyze.c- Post-parse analysisparse_node.c- Parse node creation utilities
Step-by-Step Workflow
1. Identify the SQL Statement Type
Determine what kind of SQL you're working with:
| Statement Type | gram.y Section | parse_utilcmd.c Function |
|---|---|---|
| CREATE TABLE | CreateStmt |
transformCreateStmt() |
| ALTER TABLE | AlterTableStmt |
transformAlterTableStmt() |
| CREATE INDEX | IndexStmt |
transformIndexStmt() |
| CREATE TRIGGER | CreateTrigStmt |
transformCreateTrigStmt() |
| CREATE FUNCTION | CreateFunctionStmt |
transformCreateFunctionStmt() |
| CREATE PROCEDURE | CreateFunctionStmt |
(procedures are functions) |
| CREATE VIEW | ViewStmt |
transformViewStmt() |
| CREATE MATERIALIZED VIEW | CreateMatViewStmt |
- |
| CREATE SEQUENCE | CreateSeqStmt |
transformCreateSeqStmt() |
| CREATE TYPE | CreateEnumStmt, CreateDomainStmt, CompositeTypeStmt |
- |
| CREATE POLICY | CreatePolicyStmt |
transformCreatePolicyStmt() |
| COMMENT ON | CommentStmt |
- |
2. Locate the Grammar Rule in gram.y
Search gram.y for the statement's production rule:
Example - Finding CREATE TRIGGER syntax:
# In the postgres repository
grep -n "CreateTrigStmt:" src/backend/parser/gram.y
What to look for:
- The production rule name (e.g.,
CreateTrigStmt:) - Alternative syntaxes (multiple
|branches) - Optional elements (
opt_*rules) - List constructs (
*_listrules) - Terminal tokens (keywords, literals)
3. Understand the Grammar Structure
gram.y uses Yacc/Bison syntax:
CreateTrigStmt:
CREATE opt_or_replace TRIGGER name TriggerActionTime TriggerEvents ON
qualified_name TriggerReferencing TriggerForSpec TriggerWhen
EXECUTE FUNCTION_or_PROCEDURE func_name '(' TriggerFuncArgs ')'
{
CreateTrigStmt *n = makeNode(CreateTrigStmt);
n->trigname = $4;
n->relation = $8;
n->funcname = $13;
/* ... */
$$ = (Node *)n;
}
Key elements:
- Terminals (uppercase): Keywords like
CREATE,TRIGGER,ON - Non-terminals (lowercase): Other grammar rules like
name,qualified_name - Actions (
{ ... }): C code that builds the parse tree - Alternatives (
|): Different ways to write the same statement - Optional elements: Rules prefixed with
opt_
4. Trace Through Related Rules
Follow the grammar rules to understand the complete syntax:
Example - Understanding trigger events:
TriggerEvents:
TriggerOneEvent
| TriggerEvents OR TriggerOneEvent
TriggerOneEvent:
INSERT
| DELETE
| UPDATE
| UPDATE OF columnList
| TRUNCATE
This shows:
- Triggers can have multiple events combined with OR
- UPDATE can optionally specify columns with
OF columnList
5. Cross-Reference with parse_utilcmd.c
After understanding the grammar, check how PostgreSQL transforms the parsed statement:
Example - How CREATE TRIGGER is processed:
// In parse_utilcmd.c
static void
transformCreateTrigStmt(CreateTrigStmt *stmt, const char *queryString)
{
// Validation and transformation logic
// - Check trigger name conflicts
// - Validate trigger function exists
// - Process WHEN condition
// - Handle constraint triggers
}
6. Apply to pgschema
Use this understanding in pgschema:
For parsing (ir/parser.go):
- pgs
Установить PostgreSQL Syntax Reference в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл PostgreSQL Syntax Reference?
Consult PostgreSQL's parser and grammar (gram.y) to understand SQL syntax, DDL statement structure, and parsing rules when implementing pgschema features
Как установить скилл PostgreSQL Syntax Reference?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл PostgreSQL Syntax Reference запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic