{"id":44700255,"url":"https://github.com/valkdb/postgresparser","last_synced_at":"2026-02-21T09:03:13.960Z","repository":{"id":337478463,"uuid":"1147050014","full_name":"ValkDB/postgresparser","owner":"ValkDB","description":"ANTLR-based PostgreSQL query parser for Go. Extracts tables, columns, joins, CTEs, parameters, DDL actions, and full column-usage metadata    from SQL into a structured IR.","archived":false,"fork":false,"pushed_at":"2026-02-15T08:19:43.000Z","size":1018,"stargazers_count":181,"open_issues_count":8,"forks_count":7,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-15T13:47:08.138Z","etag":null,"topics":["antlr","database","developer-tools","go","postgres","postgresql","sql-parser"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ValkDB.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-01T05:22:33.000Z","updated_at":"2026-02-15T07:47:38.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ValkDB/postgresparser","commit_stats":null,"previous_names":["valkdb/postgresparser"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/ValkDB/postgresparser","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValkDB%2Fpostgresparser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValkDB%2Fpostgresparser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValkDB%2Fpostgresparser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValkDB%2Fpostgresparser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ValkDB","download_url":"https://codeload.github.com/ValkDB/postgresparser/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValkDB%2Fpostgresparser/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29573392,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-18T07:57:19.261Z","status":"ssl_error","status_checked_at":"2026-02-18T07:57:18.820Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["antlr","database","developer-tools","go","postgres","postgresql","sql-parser"],"created_at":"2026-02-15T09:45:19.548Z","updated_at":"2026-02-18T08:00:34.311Z","avatar_url":"https://github.com/ValkDB.png","language":"Go","readme":"# postgresparser\r\n\r\n[![CI](https://github.com/valkdb/postgresparser/actions/workflows/ci.yml/badge.svg)](https://github.com/valkdb/postgresparser/actions/workflows/ci.yml)\r\n[![Go Reference](https://pkg.go.dev/badge/github.com/valkdb/postgresparser.svg)](https://pkg.go.dev/github.com/valkdb/postgresparser)\r\n[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)\r\n\r\nA pure-Go PostgreSQL parser. No cgo, no C toolchain — just `go build`.\r\n\r\n## Why postgresparser?\r\n\r\nNeed to parse PostgreSQL SQL in Go but can't use cgo? Deploying to Alpine containers, Lambda, ARM, scratch images, or anywhere that requires `CGO_ENABLED=0`?\r\n\r\n`postgresparser` works everywhere `go build` works. It parses SQL into a structured intermediate representation (IR) that gives you tables, columns, joins, filters, CTEs, subqueries, and more — without executing anything.\r\n\r\n```go\r\nresult, err := postgresparser.ParseSQL(`\r\n    SELECT u.name, COUNT(o.id) AS order_count\r\n    FROM users u\r\n    LEFT JOIN orders o ON o.user_id = u.id\r\n    WHERE u.active = true\r\n    GROUP BY u.name\r\n    ORDER BY order_count DESC\r\n`)\r\n\r\nfmt.Println(result.Command)       // \"SELECT\"\r\nfmt.Println(result.Tables)        // users, orders with aliases\r\nfmt.Println(result.Columns)       // u.name, COUNT(o.id) AS order_count\r\nfmt.Println(result.Where)         // [\"u.active=true\"]\r\nfmt.Println(result.JoinConditions) // [\"o.user_id=u.id\"]\r\nfmt.Println(result.GroupBy)       // [\"u.name\"]\r\nfmt.Println(result.ColumnUsage)   // each column with its role: filter, join, projection, group, order\r\n```\r\n\r\n**Performance:** With [SLL prediction mode](docs/performance.md), most queries parse in **70–350 µs**.\r\n\r\n## Installation\r\n\r\n```bash\r\ngo get github.com/valkdb/postgresparser\r\n```\r\n\r\n## What you can build with it\r\n\r\n- **Query linting** — detect missing WHERE on DELETEs, flag SELECT *, enforce naming conventions\r\n- **Dependency extraction** — map which tables and columns a query touches, build lineage graphs\r\n- **Migration tooling** — parse DDL to understand schema changes, diff CREATE statements\r\n- **Audit logging** — tag log entries with structured metadata (tables, operation type, filtered columns)\r\n- **Query rewriting** — inject tenant filters, add audit columns, transform SQL before execution\r\n- **Index advisors** — analyze column usage patterns to suggest optimal indexes\r\n\r\n## Parsing\r\n\r\nHandles the SQL you actually write in production:\r\n\r\n- **DML**: SELECT, INSERT, UPDATE, DELETE, MERGE\r\n- **DDL**: CREATE TABLE (columns/type/nullability/default), CREATE INDEX, DROP TABLE/INDEX, ALTER TABLE, TRUNCATE\r\n- **CTEs**: `WITH ... AS` including `RECURSIVE`, materialization hints\r\n- **JOINs**: INNER, LEFT, RIGHT, FULL, CROSS, NATURAL, LATERAL\r\n- **Subqueries**: in SELECT, FROM, WHERE, and HAVING\r\n- **Set operations**: UNION, INTERSECT, EXCEPT (ALL/DISTINCT)\r\n- **Upsert**: INSERT ... ON CONFLICT DO UPDATE/DO NOTHING\r\n- **JSONB**: `-\u003e`, `-\u003e\u003e`, `@\u003e`, `?`, `?|`, `?\u0026`\r\n- **Window functions**: OVER, PARTITION BY\r\n- **Type casts**: `::type`\r\n- **Parameters**: `$1`, `$2`, ...\r\n\r\nIR field reference: [ParsedQuery IR Reference](docs/parsed-query.md)\r\n\r\n## Supported SQL Statements\r\n\r\nSee [docs/supported-statements.md](./docs/supported-statements.md) for full details on parsed commands, graceful handling (e.g. SET/SHOW/RESET), and what's currently UNKNOWN or unsupported.\r\n\r\n| Category | Statements | Status |\r\n|----------|-----------|--------|\r\n| **DML** | SELECT, INSERT, UPDATE, DELETE, MERGE | Full IR extraction |\r\n| **DDL** | CREATE TABLE, ALTER TABLE, DROP TABLE/INDEX, CREATE INDEX, TRUNCATE | Full IR extraction |\r\n| **Utility** | SET, SHOW, RESET | Graceful — returns `UNKNOWN`, no error |\r\n| **Other** | GRANT, REVOKE, CREATE VIEW/FUNCTION/TRIGGER, COPY, EXPLAIN, VACUUM, BEGIN/COMMIT/ROLLBACK, etc. | Not yet supported — may error or return `UNKNOWN` |\r\n\r\n## Analysis\r\n\r\nThe `analysis` subpackage provides higher-level intelligence on top of the IR:\r\n\r\n### Column usage analysis\r\n\r\nKnow exactly how every column is used — filtering, joining, projection, grouping, ordering:\r\n\r\n```go\r\nresult, err := analysis.AnalyzeSQL(\"SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.status = 'active'\")\r\n\r\nfor _, cu := range result.ColumnUsage {\r\n    fmt.Printf(\"%s.%s → %s\\n\", cu.TableAlias, cu.Column, cu.UsageType)\r\n}\r\n// o.id → projection\r\n// c.name → projection\r\n// o.customer_id → join\r\n// c.id → join\r\n// o.status → filter\r\n```\r\n\r\n### WHERE condition extraction\r\n\r\nPull structured conditions with operators and values:\r\n\r\n```go\r\nconditions, _ := analysis.ExtractWhereConditions(\"SELECT * FROM orders WHERE status = 'active' AND total \u003e 100\")\r\n\r\nfor _, c := range conditions {\r\n    fmt.Printf(\"%s %s %v\\n\", c.Column, c.Operator, c.Value)\r\n}\r\n// status = active\r\n// total \u003e 100\r\n```\r\n\r\n### Schema-aware JOIN relationship detection\r\n\r\nPass in your schema metadata and get back foreign key relationships — no heuristic guessing:\r\n\r\n```go\r\nschema := map[string][]analysis.ColumnSchema{\r\n    \"customers\": {\r\n        {Name: \"id\", PGType: \"bigint\", IsPrimaryKey: true},\r\n        {Name: \"name\", PGType: \"text\"},\r\n    },\r\n    \"orders\": {\r\n        {Name: \"id\", PGType: \"bigint\", IsPrimaryKey: true},\r\n        {Name: \"customer_id\", PGType: \"bigint\"},\r\n    },\r\n}\r\n\r\njoins, _ := analysis.ExtractJoinRelationshipsWithSchema(\r\n    \"SELECT * FROM orders o JOIN customers c ON o.customer_id = c.id\",\r\n    schema,\r\n)\r\n// orders.customer_id → customers.id\r\n```\r\n\r\n### DDL extraction\r\n\r\nFor `CREATE TABLE` parsing, see [`examples/ddl/`](examples/ddl/).\r\n\r\n## Performance\r\n\r\nWith SLL prediction mode, `postgresparser` parses most queries in **70–350 µs** with minimal allocations. The IR extraction layer accounts for only ~3% of CPU — the rest is ANTLR's grammar engine, which SLL mode keeps fast.\r\n\r\nSee the [Performance Guide](docs/performance.md) for benchmarks, profiling results, and optimization details.\r\n\r\n## Examples\r\n\r\nSee the [`examples/`](examples/) directory:\r\n\r\n- [`basic/`](examples/basic/) — Parse SQL and inspect the IR\r\n- [`analysis/`](examples/analysis/) — Column usage, WHERE conditions, JOIN relationships\r\n- [`ddl/`](examples/ddl/) — Parse CREATE TABLE / ALTER TABLE plus DELETE command metadata\r\n- [`sll_mode/`](examples/sll_mode/) — SLL prediction mode for maximum throughput\r\n\r\n## Grammar\r\n\r\nBuilt on ANTLR4 grammar files in `grammar/`. To regenerate after modifying:\r\n\r\n```bash\r\nantlr4 -Dlanguage=Go -visitor -listener -package gen -o gen grammar/PostgreSQLLexer.g4 grammar/PostgreSQLParser.g4\r\n```\r\n\r\n## Compatibility\r\n\r\nThis is an ANTLR4-based grammar, not PostgreSQL's internal server parser. Some edge-case syntax may differ across PostgreSQL versions. If you find a query that parses in PostgreSQL but fails here, please [open an issue](https://github.com/valkdb/postgresparser/issues) with a minimal repro.\r\n\r\n`ParseSQL` processes the first SQL statement. Multi-statement strings (separated by `;`) will have subsequent statements silently ignored.\r\n\r\n## License\r\n\r\nApache License 2.0 — see [LICENSE](LICENSE) for details.\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalkdb%2Fpostgresparser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvalkdb%2Fpostgresparser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvalkdb%2Fpostgresparser/lists"}