pg-ast 2.4.10 → 17.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +156 -85
  3. package/package.json +16 -21
package/LICENSE CHANGED
@@ -1,8 +1,6 @@
1
1
  The MIT License (MIT)
2
2
 
3
- Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
- Copyright (c) 2025 Constructive <developers@constructive.io>
5
- Copyright (c) 2020-present, Interweb, Inc.
3
+ Copyright (c) 2020 Dan Lynch <pyramation@gmail.com>
6
4
 
7
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
8
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,127 +1,198 @@
1
1
  # pg-ast
2
2
 
3
3
  <p align="center" width="100%">
4
- <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
4
+ <img height="120" src="https://github.com/constructive-io/pgsql-parser/assets/545047/6440fa7d-918b-4a3b-8d1b-755d85de8bea" />
5
5
  </p>
6
6
 
7
7
  <p align="center" width="100%">
8
- <a href="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml">
9
- <img height="20" src="https://github.com/constructive-io/constructive/actions/workflows/run-tests.yaml/badge.svg" />
8
+ <a href="https://github.com/constructive-io/pgsql-parser/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/pgsql-parser/actions/workflows/run-tests.yaml/badge.svg" />
10
10
  </a>
11
- <a href="https://github.com/constructive-io/constructive/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
- <a href="https://www.npmjs.com/package/pg-ast"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/constructive?filename=packages%2Fpg-ast%2Fpackage.json"/></a>
11
+ <a href="https://github.com/constructive-io/pgsql-parser/blob/main/LICENSE-MIT"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/pg-ast"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/pgsql-parser?filename=packages%2Fpg-ast%2Fpackage.json"/></a>
13
13
  </p>
14
14
 
15
- Create PostgreSQL ASTs with JavaScript
15
+ `pg-ast` is a utility library for `@pgsql/types`, offering convenient functions to work with PostgreSQL Abstract Syntax Tree (AST) nodes in a type-safe manner. This library facilitates the creation of AST nodes for building SQL queries or statements programmatically.
16
16
 
17
- ## Installation
17
+ > **Note**: If you need the runtime schema for AST introspection, use [`@pgsql/utils`](https://www.npmjs.com/package/@pgsql/utils) instead.
18
18
 
19
- ```sh
20
- npm install pg-ast
21
- ```
19
+ # Table of Contents
22
20
 
23
- ## Usage
21
+ 1. [pg-ast](#pg-ast)
22
+ - [Features](#features)
23
+ 2. [Installation](#installation)
24
+ 3. [Usage](#usage)
25
+ - [AST Node Creation](#ast-node-creation)
26
+ - [JSON AST](#json-ast)
27
+ - [Select Statement](#select-statement)
28
+ - [Creating Table Schemas Dynamically](#creating-table-schemas-dynamically)
29
+ 4. [Related Projects](#related)
30
+ 5. [Disclaimer](#disclaimer)
24
31
 
25
- ```js
26
- import * as ast from 'pg-ast';
27
- const node = ast.A_Expr({
28
- kind: 0,
29
- name: [ast.String({ str: '=' })],
30
- lexpr: ast.Integer({ ival: 0 }),
31
- rexpr: ast.Integer({ ival: 0 })
32
- });
33
- ```
32
+ ## Features
34
33
 
35
- ## Pairs well with `pgsql-deparser`
34
+ - **AST Node Creation**: Simplifies the process of constructing PostgreSQL AST nodes, allowing for easy assembly of SQL queries or statements programmatically.
35
+ - **Comprehensive Coverage**: Supports all node types defined in the PostgreSQL AST.
36
+ - **Seamless Integration**: Designed to be used alongside the `@pgsql/types` package for a complete AST handling solution.
36
37
 
37
- https://github.com/constructive-io/pgsql-parser
38
+ ## Installation
38
39
 
39
- You can create ASTs manually, and then generate your SQL:
40
+ To add `pg-ast` to your project, use the following npm command:
40
41
 
41
- ```js
42
- import * as ast from '../src';
43
- import { deparse } from 'pgsql-deparser';
44
-
45
- const node = ast.A_Expr({
46
- kind: 0,
47
- name: [ast.String({ str: '=' })],
48
- lexpr: ast.Integer({ ival: 0 }),
49
- rexpr: ast.Integer({ ival: 0 })
50
- });
51
- const sqlCode = deparse([node]);
42
+ ```bash
43
+ npm install pg-ast
52
44
  ```
53
45
 
54
- ---
55
-
56
- ## Education and Tutorials
57
-
58
- 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
59
- Get started with modular databases in minutes. Install prerequisites and deploy your first module.
46
+ ## Usage
60
47
 
61
- 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
62
- Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
48
+ ### AST Node Creation
63
49
 
64
- 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
65
- Master the workflow for adding, organizing, and managing database changes with pgpm.
50
+ With the AST helper methods, creating complex SQL ASTs becomes straightforward and intuitive.
66
51
 
67
- 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
68
- Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
52
+ #### JSON AST
69
53
 
70
- 5. [Supabase Testing](https://constructive.io/learn/supabase)
71
- Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
54
+ Explore the PostgreSQL Abstract Syntax Tree (AST) as JSON objects with ease using `pg-ast`. Below is an example of how you can generate a JSON AST using TypeScript:
72
55
 
73
- 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
74
- Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
75
-
76
- 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
77
- Common issues and solutions for pgpm, PostgreSQL, and testing.
56
+ ```ts
57
+ import * as t from 'pg-ast';
58
+ import { SelectStmt } from '@pgsql/types';
59
+ import { deparse } from 'pgsql-deparser';
78
60
 
79
- ## Related Constructive Tooling
61
+ const selectStmt: { SelectStmt: SelectStmt } = t.nodes.selectStmt({
62
+ targetList: [
63
+ t.nodes.resTarget({
64
+ val: t.nodes.columnRef({
65
+ fields: [t.nodes.aStar()]
66
+ })
67
+ })
68
+ ],
69
+ fromClause: [
70
+ t.nodes.rangeVar({
71
+ relname: 'some_amazing_table',
72
+ inh: true,
73
+ relpersistence: 'p'
74
+ })
75
+ ],
76
+ limitOption: 'LIMIT_OPTION_DEFAULT',
77
+ op: 'SETOP_NONE'
78
+ });
79
+ console.log(selectStmt);
80
+ // Output: { "SelectStmt": { "targetList": [ { "ResTarget": { "val": { "ColumnRef": { "fields": [ { "A_Star": {} } ] } } } } ], "fromClause": [ { "RangeVar": { "relname": "some_amazing_table", "inh": true, "relpersistence": "p" } } ], "limitOption": "LIMIT_OPTION_DEFAULT", "op": "SETOP_NONE" } }
81
+ console.log(await deparse(stmt))
82
+ // Output: SELECT * FROM some_amazing_table
83
+ ```
80
84
 
81
- ### 🧪 Testing
85
+ #### Select Statement
82
86
 
83
- * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
84
- * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
85
- * [graphile-test](https://github.com/constructive-io/constructive/tree/main/graphile/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
86
- * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/postgres/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
87
+ ```ts
88
+ import * as t from 'pg-ast';
89
+ import { SelectStmt } from '@pgsql/types';
90
+ import { deparse } from 'pgsql-deparser';
87
91
 
88
- ### 🧠 Parsing & AST
92
+ const query: { SelectStmt: SelectStmt } = t.nodes.selectStmt({
93
+ targetList: [
94
+ t.nodes.resTarget({
95
+ val: t.nodes.columnRef({
96
+ fields: [t.nodes.string({ sval: 'name' })]
97
+ })
98
+ }),
99
+ t.nodes.resTarget({
100
+ val: t.nodes.columnRef({
101
+ fields: [t.nodes.string({ sval: 'email' })]
102
+ })
103
+ })
104
+ ],
105
+ fromClause: [
106
+ t.nodes.rangeVar({
107
+ relname: 'users',
108
+ inh: true,
109
+ relpersistence: 'p'
110
+ })
111
+ ],
112
+ whereClause: t.nodes.aExpr({
113
+ kind: 'AEXPR_OP',
114
+ name: [t.nodes.string({ sval: '>' })],
115
+ lexpr: t.nodes.columnRef({
116
+ fields: [t.nodes.string({ sval: 'age' })]
117
+ }),
118
+ rexpr: t.nodes.aConst({
119
+ ival: t.ast.integer({ ival: 18 })
120
+ })
121
+ }),
122
+ limitOption: 'LIMIT_OPTION_DEFAULT',
123
+ op: 'SETOP_NONE'
124
+ });
89
125
 
90
- * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
91
- * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
92
- * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
93
- * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
94
- * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
95
- * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
126
+ await deparse(createStmt);
127
+ // SELECT name, email FROM users WHERE age > 18
128
+ ```
96
129
 
97
- ### 🚀 API & Dev Tools
130
+ #### Creating Table Schemas Dynamically
131
+
132
+ ```ts
133
+ // Example JSON schema
134
+ const schema = {
135
+ "tableName": "users",
136
+ "columns": [
137
+ { "name": "id", "type": "int", "constraints": ["PRIMARY KEY"] },
138
+ { "name": "username", "type": "text" },
139
+ { "name": "email", "type": "text", "constraints": ["UNIQUE"] },
140
+ { "name": "created_at", "type": "timestamp", "constraints": ["NOT NULL"] }
141
+ ]
142
+ };
143
+
144
+ // Construct the CREATE TABLE statement
145
+ const createStmt = t.nodes.createStmt({
146
+ relation: t.ast.rangeVar({
147
+ relname: schema.tableName,
148
+ inh: true,
149
+ relpersistence: 'p'
150
+ }),
151
+ tableElts: schema.columns.map(column => t.nodes.columnDef({
152
+ colname: column.name,
153
+ typeName: t.ast.typeName({
154
+ names: [t.nodes.string({ sval: column.type })]
155
+ }),
156
+ constraints: column.constraints?.map(constraint =>
157
+ t.nodes.constraint({
158
+ contype: constraint === "PRIMARY KEY" ? "CONSTR_PRIMARY" : constraint === "UNIQUE" ? "CONSTR_UNIQUE" : "CONSTR_NOTNULL"
159
+ })
160
+ )
161
+ }))
162
+ });
98
163
 
99
- * [@constructive-io/graphql-server](https://github.com/constructive-io/constructive/tree/main/graphql/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
100
- * [@constructive-io/graphql-explorer](https://github.com/constructive-io/constructive/tree/main/graphql/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
164
+ // `deparse` function converts AST to SQL string
165
+ const sql = await deparse(createStmt, { pretty: true });
101
166
 
102
- ### 🔁 Streaming & Uploads
167
+ console.log(sql);
168
+ // OUTPUT:
103
169
 
104
- * [etag-hash](https://github.com/constructive-io/constructive/tree/main/streaming/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
105
- * [etag-stream](https://github.com/constructive-io/constructive/tree/main/streaming/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
106
- * [uuid-hash](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
107
- * [uuid-stream](https://github.com/constructive-io/constructive/tree/main/streaming/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
108
- * [@constructive-io/s3-streamer](https://github.com/constructive-io/constructive/tree/main/streaming/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
109
- * [@constructive-io/upload-names](https://github.com/constructive-io/constructive/tree/main/streaming/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
170
+ // CREATE TABLE users (
171
+ // id int PRIMARY KEY,
172
+ // username text,
173
+ // email text UNIQUE,
174
+ // created_at timestamp NOT NULL
175
+ // )
176
+ ```
110
177
 
111
- ### 🧰 CLI & Codegen
178
+ ---
112
179
 
113
- * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
114
- * [@constructive-io/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
115
- * [@constructive-io/graphql-codegen](https://github.com/constructive-io/constructive/tree/main/graphql/codegen): **✨ GraphQL code generation** (types, operations, SDK) from schema/endpoint introspection.
116
- * [@constructive-io/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
117
- * [@constructive-io/graphql-query](https://github.com/constructive-io/constructive/tree/main/graphql/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
180
+ **🛠 Built by the [Constructive](https://constructive.io) team creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
118
181
 
119
- ## Credits
182
+ ## Related
120
183
 
121
- **🛠 Built by the [Constructive](https://constructive.io) team creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
184
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): The real PostgreSQL parser for Node.js, providing symmetric parsing and deparsing of SQL statements with actual PostgreSQL parser integration.
185
+ * [pgsql-deparser](https://www.npmjs.com/package/pgsql-deparser): A streamlined tool designed for converting PostgreSQL ASTs back into SQL queries, focusing solely on deparser functionality to complement `pgsql-parser`.
186
+ * [@pgsql/parser](https://www.npmjs.com/package/@pgsql/parser): Multi-version PostgreSQL parser with dynamic version selection at runtime, supporting PostgreSQL 15, 16, and 17 in a single package.
187
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): Offers TypeScript type definitions for PostgreSQL AST nodes, facilitating type-safe construction, analysis, and manipulation of ASTs.
188
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): Provides TypeScript enum definitions for PostgreSQL constants, enabling type-safe usage of PostgreSQL enums and constants in your applications.
189
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): A comprehensive utility library for PostgreSQL, offering type-safe AST node creation and enum value conversions, simplifying the construction and manipulation of PostgreSQL ASTs.
190
+ * [@pgsql/traverse](https://www.npmjs.com/package/@pgsql/traverse): PostgreSQL AST traversal utilities for pgsql-parser, providing a visitor pattern for traversing PostgreSQL Abstract Syntax Tree nodes, similar to Babel's traverse functionality but specifically designed for PostgreSQL AST structures.
191
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): A TypeScript tool that parses PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
192
+ * [libpg-query](https://github.com/constructive-io/libpg-query-node): The real PostgreSQL parser exposed for Node.js, used primarily in `pgsql-parser` for parsing and deparsing SQL queries.
122
193
 
123
194
  ## Disclaimer
124
195
 
125
196
  AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
126
197
 
127
- No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
198
+ No developer or entity involved in creating Software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the Software code or Software CLI, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pg-ast",
3
- "version": "2.4.10",
3
+ "version": "17.9.0",
4
4
  "author": "Constructive <developers@constructive.io>",
5
- "description": "PostgreSQL ASTs in JS",
5
+ "description": "PostgreSQL AST helpers for building AST nodes",
6
6
  "main": "index.js",
7
7
  "module": "esm/index.js",
8
8
  "types": "index.d.ts",
9
- "homepage": "https://github.com/constructive-io/constructive",
9
+ "homepage": "https://github.com/constructive-io/pgsql-parser",
10
10
  "license": "MIT",
11
11
  "publishConfig": {
12
12
  "access": "public",
@@ -14,36 +14,31 @@
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "https://github.com/constructive-io/constructive"
17
+ "url": "https://github.com/constructive-io/pgsql-parser"
18
18
  },
19
19
  "bugs": {
20
- "url": "https://github.com/constructive-io/constructive/issues"
20
+ "url": "https://github.com/constructive-io/pgsql-parser/issues"
21
21
  },
22
22
  "scripts": {
23
- "clean": "makage clean",
24
23
  "copy": "makage assets",
25
- "prepack": "npm run build",
26
- "build": "npm run build:proto && makage build",
27
- "build:dev": "makage build --dev",
24
+ "clean": "makage clean dist",
25
+ "prepublishOnly": "npm run build",
26
+ "build": "npm run build:proto && npm run clean && tsc && tsc -p tsconfig.esm.json && npm run copy",
27
+ "build:dev": "npm run clean && tsc --declarationMap && tsc -p tsconfig.esm.json && npm run copy",
28
28
  "build:proto": "ts-node scripts/pg-proto-parser",
29
29
  "lint": "eslint . --fix",
30
- "test": "jest --passWithNoTests",
30
+ "test": "jest",
31
31
  "test:watch": "jest --watch"
32
32
  },
33
- "keywords": [
34
- "postgres",
35
- "ast",
36
- "parser",
37
- "parse"
38
- ],
39
33
  "devDependencies": {
40
- "makage": "^0.1.9",
41
- "pg-proto-parser": "^1.30.2",
42
- "pgsql-deparser": "^17.15.0"
34
+ "makage": "^0.1.8",
35
+ "pg-proto-parser": "1.30.2",
36
+ "pgsql-deparser": "17.15.0"
43
37
  },
44
38
  "dependencies": {
45
39
  "@pgsql/types": "^17.6.2",
46
- "nested-obj": "0.1.7"
40
+ "nested-obj": "0.1.5"
47
41
  },
48
- "gitHead": "e3d01915223e3d87d263606bc4086e3e88183cab"
42
+ "keywords": [],
43
+ "gitHead": "67bd9027fdff2b957009cf5051e2c5e94ff77e24"
49
44
  }