pgsql-parser 13.17.0 โ†’ 13.19.1

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.
package/README.md CHANGED
@@ -1,20 +1,20 @@
1
1
  # pgsql-parser
2
2
 
3
3
  <p align="center" width="100%">
4
- <img height="120" src="https://github.com/launchql/pgsql-parser/assets/545047/6440fa7d-918b-4a3b-8d1b-755d85de8bea" />
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/launchql/pgsql-parser/actions/workflows/run-tests.yaml">
9
- <img height="20" src="https://github.com/launchql/pgsql-parser/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
11
  <a href="https://www.npmjs.com/package/pgsql-parser"><img height="20" src="https://img.shields.io/npm/dt/pgsql-parser"></a>
12
12
  <a href="https://www.npmjs.com/package/pgsql-parser"><img height="20" src="https://img.shields.io/npm/dw/pgsql-parser"/></a>
13
- <a href="https://github.com/launchql/pgsql-parser/blob/main/LICENSE-MIT"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
14
- <a href="https://www.npmjs.com/package/pgsql-parser"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/pgsql-parser?filename=packages%2Fparser%2Fpackage.json"/></a>
13
+ <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>
14
+ <a href="https://www.npmjs.com/package/pgsql-parser"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/pgsql-parser?filename=packages%2Fparser%2Fpackage.json"/></a>
15
15
  </p>
16
16
 
17
- The real PostgreSQL parser for Node.js, `pgsql-parser` provides symmetric parsing and deparsing of SQL statements using the actual [PostgreSQL parser](https://github.com/pganalyze/libpg_query). It allows you to parse SQL queries into AST and modify or reconstruct SQL queries from the AST.
17
+ The real PostgreSQL parser for Node.js. Built with the actual [PostgreSQL parser](https://github.com/pganalyze/libpg_query), `pgsql-parser` delivers true-to-spec SQL parsing and reconstruction. Transform SQL queries into ASTs, modify them programmatically, and convert them back to SQL with complete fidelity.
18
18
 
19
19
  ## Installation
20
20
 
@@ -22,11 +22,48 @@ The real PostgreSQL parser for Node.js, `pgsql-parser` provides symmetric parsin
22
22
  npm install pgsql-parser
23
23
  ```
24
24
 
25
- ## Key Features
25
+ ## Features
26
26
 
27
- - **True PostgreSQL Parsing:** Utilizes the real PostgreSQL source code for accurate parsing.
28
- - **Symmetric Parsing and Deparsing:** Convert SQL to AST and back, enabling query manipulation.
29
- - **AST Manipulation:** Easily modify parts of a SQL statement through the AST.
27
+ * ๐Ÿ”„ **Symmetric Parsing & Deparsing** โ€“ Parse SQL to AST and reconstruct it back to SQL with perfect round-trip accuracy
28
+ * ๐Ÿงช **Battle-Tested Reliability** โ€“ Validated against 23,000+ SQL statements ensuring production-grade stability
29
+ * ๐Ÿ”ง **Direct from PostgreSQL** โ€“ Uses the official Postgres C parser compiled to WebAssembly for 100% spec compliance
30
+ * ๐Ÿš€ **WebAssembly Powered:** - Cross-platform compatibility without native dependencies.
31
+ * ๐Ÿ› ๏ธ **AST Manipulation:** - Easily modify parts of a SQL statement through the AST.
32
+
33
+ ## API
34
+
35
+ The package exports both async and sync methods. Async methods handle initialization automatically, while sync methods require explicit initialization.
36
+
37
+ โš ๏ธ If you don't need the parser functionality, consider using the TS-only (no WASM, zero runtime dependencies) [`pgsql-deparser`](https://github.com/constructive-io/pgsql-parser/tree/main/packages/deparser) for a super fast, lightweight deparser. Battle-tested with 23,000+ SQL statements ๐Ÿš€
38
+
39
+ ### Async Methods (Recommended)
40
+
41
+ ```typescript
42
+ import { parse, deparse } from 'pgsql-parser';
43
+
44
+ // Parse SQL to AST
45
+ const stmts = await parse('SELECT * FROM test_table');
46
+
47
+ // Deparse AST back to SQL
48
+ const sql = await deparse(stmts);
49
+ ```
50
+
51
+ ### Sync Methods
52
+
53
+ Sync methods require explicit initialization using `loadModule()`:
54
+
55
+ ```typescript
56
+ import { loadModule, parseSync, deparseSync } from 'pgsql-parser';
57
+
58
+ // Initialize first (required for sync methods)
59
+ await loadModule();
60
+
61
+ // Now safe to use sync methods
62
+ const stmts = parseSync('SELECT * FROM test_table');
63
+ const sql = deparseSync(stmts);
64
+ ```
65
+
66
+ **Note:** We recommend using async methods as they handle initialization automatically. Use sync methods only when necessary, and always call `loadModule()` first.
30
67
 
31
68
  ## Parser Example
32
69
 
@@ -35,12 +72,12 @@ Rewrite part of a SQL query:
35
72
  ```js
36
73
  import { parse, deparse } from 'pgsql-parser';
37
74
 
38
- const stmts = parse('SELECT * FROM test_table');
75
+ const stmts = await parse('SELECT * FROM test_table');
39
76
 
40
77
  // Assuming the structure of stmts is known and matches the expected type
41
78
  stmts[0].RawStmt.stmt.SelectStmt.fromClause[0].RangeVar.relname = 'another_table';
42
79
 
43
- console.log(deparse(stmts));
80
+ console.log(await deparse(stmts));
44
81
 
45
82
  // SELECT * FROM "another_table"
46
83
  ```
@@ -49,23 +86,24 @@ console.log(deparse(stmts));
49
86
 
50
87
  The `pgsql-deparser` module serializes ASTs to SQL in pure TypeScript, avoiding the full parser's native dependencies. It's useful when only SQL string conversion from ASTs is needed, and is written in pure TypeScript for easy cross-environment deployment.
51
88
 
52
- Here's how you can use the deparser in your TypeScript code, using [`@pgsql/utils`](https://github.com/launchql/pgsql-parser/tree/main/packages/utils) to create an AST for `deparse`:
89
+ Here's how you can use the deparser in your TypeScript code, using [`@pgsql/utils`](https://github.com/constructive-io/pgsql-parser/tree/main/packages/utils) to create an AST for `deparse`:
53
90
 
54
91
  ```ts
55
- import ast, { SelectStmt } from '@pgsql/utils';
92
+ import * as t from '@pgsql/utils';
93
+ import { RangeVar, SelectStmt } from '@pgsql/types';
56
94
  import { deparse } from 'pgsql-deparser';
57
95
 
58
96
  // This could have been obtained from any JSON or AST, not necessarily @pgsql/utils
59
- const stmt: SelectStmt = ast.selectStmt({
97
+ const stmt: { SelectStmt: SelectStmt } = t.nodes.selectStmt({
60
98
  targetList: [
61
- ast.resTarget({
62
- val: ast.columnRef({
63
- fields: [ast.aStar()]
99
+ t.nodes.resTarget({
100
+ val: t.nodes.columnRef({
101
+ fields: [t.nodes.aStar()]
64
102
  })
65
103
  })
66
104
  ],
67
105
  fromClause: [
68
- ast.rangeVar({
106
+ t.nodes.rangeVar({
69
107
  relname: 'some_table',
70
108
  inh: true,
71
109
  relpersistence: 'p'
@@ -75,104 +113,41 @@ const stmt: SelectStmt = ast.selectStmt({
75
113
  op: 'SETOP_NONE'
76
114
  });
77
115
 
78
- // Modify the AST if needed
79
- stmt.SelectStmt.fromClause[0].RangeVar.relname = 'another_table';
116
+ // Modify the AST if needed
117
+ (stmt.SelectStmt.fromClause[0] as {RangeVar: RangeVar}).RangeVar.relname = 'another_table';
80
118
 
81
119
  // Deparse the modified AST back to a SQL string
82
- console.log(deparse(stmts));
120
+ console.log(await deparse(stmt));
83
121
 
84
122
  // Output: SELECT * FROM another_table
85
123
  ```
86
124
 
87
- ## CLI
88
-
89
- ```
90
- npm install -g pgsql-parser
91
- ```
92
-
93
- ### usage
94
-
95
- ```sh
96
- pgsql-parser <sqlfile>
97
- ```
98
-
99
- ### Documentation
100
-
101
- ### `parser.parse(sql)`
102
-
103
- Parses the query and returns a parse object.
104
-
105
- ### Parameters
106
-
107
- | parameter | type | description |
108
- | -------------------- | ------------------ | --------------------------------------------------------- |
109
- | `query` | String | SQL query |
110
-
111
- Returns an object in the format:
112
-
113
- ```
114
- { query: <query|Object>,
115
- error: { message: <message|String>,
116
- fileName: <fileName|String>,
117
- lineNumber: <line|Number>,
118
- cursorPosition: <cursor|Number> }
119
- ```
120
-
121
- ### `parser.deparse(query)`
122
-
123
- Deparses the query tree and returns a formatted SQL statement. This function takes as input a query AST
124
- in the same format as the `query` property of on the result of the `parse` method. This is the primary
125
- functionality of this module.
126
-
127
- ### Parameters
128
-
129
- | parameter | type | description |
130
- | -------------------- | ------------------ | --------------------------------------------------------- |
131
- | `query` | Object | Query tree obtained from `parse` |
132
-
133
- Returns a normalized formatted SQL string.
134
-
135
- ## Versions
136
-
137
- As of PG 13, PG majors versions maintained will have a matching dedicated major npm version. Only the latest Postgres stable release receives active updates.
125
+ ## Credits
138
126
 
139
- Our latest is built with `13-latest` branch from libpg_query
127
+ Built on the excellent work of several contributors:
140
128
 
141
- | PostgreSQL Major Version | libpg_query | Status | npm
142
- |--------------------------|-------------|---------------------|---------|
143
- | 13 | 13-latest | Active development | `latest`
144
- | 12 | (n/a) | Not supported |
145
- | 11 | (n/a) | Not supported |
146
- | 10 | 10-latest | Not supported | `@1.3.1` ([tree](https://github.com/launchql/pgsql-parser/tree/39b7b1adc8914253226e286a48105785219a81ca)) |
129
+ * **[Dan Lynch](https://github.com/pyramation)** โ€” official maintainer since 2018 and architect of the current implementation
130
+ * **[Lukas Fittl](https://github.com/lfittl)** for [libpg_query](https://github.com/pganalyze/libpg_query) โ€” the core PostgreSQL parser that powers this project
131
+ * **[Greg Richardson](https://github.com/gregnr)** for AST guidance and pushing the transition to WASM and multiple PG runtimes for better interoperability
132
+ * **[Ethan Resnick](https://github.com/ethanresnick)** for the original Node.js N-API bindings
133
+ * **[Zac McCormick](https://github.com/zhm)** for the foundational [node-pg-query-native](https://github.com/zhm/node-pg-query-native) parser
147
134
 
135
+ **๐Ÿ›  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).**
148
136
 
149
137
  ## Related
150
138
 
151
- * [pgsql-parser](https://github.com/launchql/pgsql-parser): The real PostgreSQL parser for Node.js, providing symmetric parsing and deparsing of SQL statements with actual PostgreSQL parser integration.
152
- * [pgsql-deparser](https://github.com/launchql/pgsql-parser/tree/main/packages/deparser): A streamlined tool designed for converting PostgreSQL ASTs back into SQL queries, focusing solely on deparser functionality to complement `pgsql-parser`.
153
- * [pgsql-enums](https://github.com/launchql/pgsql-parser/tree/main/packages/pgsql-enums): A utility package offering easy access to PostgreSQL enumeration types in JSON format, aiding in string and integer conversions of enums used within ASTs to compliment `pgsql-parser`
154
- * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): Provides PostgreSQL AST enums in TypeScript, enhancing type safety and usability in projects interacting with PostgreSQL AST nodes.
155
- * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): Offers TypeScript type definitions for PostgreSQL AST nodes, facilitating type-safe construction, analysis, and manipulation of ASTs.
156
- * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/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.
157
- * [pg-proto-parser](https://github.com/launchql/pg-proto-parser): A TypeScript tool that parses PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
158
- * [libpg-query](https://github.com/launchql/libpg-query-node): The real PostgreSQL parser exposed for Node.js, used primarily in `pgsql-parser` for parsing and deparsing SQL queries.
159
-
160
- Thanks [@lfittl](https://github.com/lfittl) for building the core `libpg_query` suite:
161
-
162
- * [libpg_query](https://github.com/pganalyze/libpg_query)
163
- * [pg_query](https://github.com/lfittl/pg_query)
164
- * [pg_query.go](https://github.com/lfittl/pg_query.go)
165
-
166
- ## Credits
167
-
168
- Thanks to [@zhm](https://github.com/zhm) for the OG parser that started it all:
169
-
170
- * [pg-query-parser](https://github.com/zhm/pg-query-parser)
171
- * [pg-query-native](https://github.com/zhm/node-pg-query-native)
172
- * [Original LICENSE](https://github.com/zhm/pg-query-parser/blob/master/LICENSE.md)
139
+ * [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.
140
+ * [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`.
141
+ * [@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.
142
+ * [@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.
143
+ * [@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.
144
+ * [@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.
145
+ * [@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.
146
+ * [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.
147
+ * [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.
173
148
 
174
149
  ## Disclaimer
175
150
 
176
- AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED โ€œAS ISโ€, AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
151
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
177
152
 
178
153
  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/esm/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { parse as parse, parseSync as parseSync, loadModule as loadModule } from 'libpg-query';
2
+ export { deparse, deparseSync, } from 'pgsql-deparser';
3
+ export * from '@pgsql/types';
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { parse as parse, parseSync as parseSync, loadModule as loadModule } from 'libpg-query';
2
+ export { deparse, deparseSync, } from 'pgsql-deparser';
3
+ export * from '@pgsql/types';
package/index.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.deparseSync = exports.deparse = exports.loadModule = exports.parseSync = exports.parse = void 0;
18
+ var libpg_query_1 = require("libpg-query");
19
+ Object.defineProperty(exports, "parse", { enumerable: true, get: function () { return libpg_query_1.parse; } });
20
+ Object.defineProperty(exports, "parseSync", { enumerable: true, get: function () { return libpg_query_1.parseSync; } });
21
+ Object.defineProperty(exports, "loadModule", { enumerable: true, get: function () { return libpg_query_1.loadModule; } });
22
+ var pgsql_deparser_1 = require("pgsql-deparser");
23
+ Object.defineProperty(exports, "deparse", { enumerable: true, get: function () { return pgsql_deparser_1.deparse; } });
24
+ Object.defineProperty(exports, "deparseSync", { enumerable: true, get: function () { return pgsql_deparser_1.deparseSync; } });
25
+ __exportStar(require("@pgsql/types"), exports);
package/package.json CHANGED
@@ -1,28 +1,29 @@
1
1
  {
2
2
  "name": "pgsql-parser",
3
- "version": "13.17.0",
3
+ "version": "13.19.1",
4
+ "author": "Constructive <developers@constructive.io>",
4
5
  "description": "The real PostgreSQL query parser",
5
- "author": "Dan Lynch <pyramation@gmail.com>",
6
- "homepage": "https://github.com/launchql/pgsql-parser",
7
- "license": "SEE LICENSE IN LICENSE",
8
- "main": "main/index.js",
9
- "module": "module/index.js",
10
- "typings": "types/index.d.ts",
11
- "directories": {
12
- "lib": "src",
13
- "test": "__tests__"
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/pgsql-parser",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
14
  },
15
- "files": [
16
- "types",
17
- "module",
18
- "src",
19
- "main"
20
- ],
21
- "bin": {
22
- "pgsql-parser": "main/cli.js"
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/pgsql-parser"
23
18
  },
24
- "publishConfig": {
25
- "access": "public"
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/pgsql-parser/issues"
21
+ },
22
+ "scripts": {
23
+ "copy": "copyfiles -f ../../../../LICENSE README.md package.json dist",
24
+ "clean": "rimraf dist",
25
+ "build": "npm run clean && tsc && tsc -p tsconfig.esm.json && npm run copy",
26
+ "publish:pkg": "npm publish --tag pg13"
26
27
  },
27
28
  "keywords": [
28
29
  "sql",
@@ -33,61 +34,9 @@
33
34
  "query",
34
35
  "database"
35
36
  ],
36
- "repository": {
37
- "type": "git",
38
- "url": "https://github.com/launchql/pgsql-parser"
39
- },
40
- "scripts": {
41
- "build:main": "yarn tsc -p tsconfig.json --outDir main --module commonjs",
42
- "build:module": "yarn tsc -p tsconfig.json --outDir module --module es2022",
43
- "build": "npm run build:module && npm run build:main",
44
- "buidl": "npm run build",
45
- "buidl:clean": "npm run clean && npm run buidl",
46
- "clean": "rimraf ./types",
47
- "prepare": "npm run build",
48
- "lint": "eslint .",
49
- "format": "eslint . --fix",
50
- "test": "jest",
51
- "test:watch": "jest --watch",
52
- "test:debug": "node --inspect node_modules/.bin/jest --runInBand"
53
- },
54
- "bugs": {
55
- "url": "https://github.com/launchql/pgsql-parser/issues"
56
- },
57
- "jest": {
58
- "preset": "ts-jest",
59
- "testEnvironment": "node",
60
- "transform": {
61
- "^.+\\.ts?$": "ts-jest"
62
- },
63
- "transformIgnorePatterns": [
64
- "<rootDir>/node_modules/"
65
- ],
66
- "testPathIgnorePatterns": [
67
- "main/",
68
- "module/",
69
- "types/"
70
- ]
71
- },
72
- "devDependencies": {
73
- "@types/jest": "^29.5.0",
74
- "eslint": "8.38.0",
75
- "eslint-config-prettier": "^8.8.0",
76
- "eslint-plugin-prettier": "^4.0.0",
77
- "esprima": "4.0.1",
78
- "glob": "8.0.3",
79
- "jest": "^29.5.0",
80
- "prettier": "^2.8.7",
81
- "rimraf": "5.0.5",
82
- "ts-jest": "^29.1.0",
83
- "ts-node": "10.9.2",
84
- "typescript": "^5.0.4"
85
- },
86
37
  "dependencies": {
87
- "libpg-query": "13.3.2",
88
- "minimist": "^1.2.6",
89
- "pgsql-deparser": "^13.16.0",
90
- "pgsql-enums": "^13.11.0"
91
- },
92
- "gitHead": "85346892e652a57e570562fdac7a768545113619"
93
- }
38
+ "@pgsql/types": "13.11.1",
39
+ "libpg-query": "13.6.0",
40
+ "pgsql-deparser": "13.19.1"
41
+ }
42
+ }
package/main/cli.js DELETED
@@ -1,27 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const path_1 = require("path");
5
- const fs_1 = require("fs");
6
- const index_1 = require("./index");
7
- const utils_1 = require("./utils");
8
- const argv = require('minimist')(process.argv.slice(2));
9
- const args = argv._;
10
- if (args.length !== 1) {
11
- console.log(argv);
12
- console.warn('Usage: pgsql-parser <sqlfile>');
13
- process.exit(1);
14
- }
15
- const pth = args[0].startsWith('/')
16
- ? args[0]
17
- : (0, path_1.resolve)((0, path_1.join)(process.cwd(), args[0]));
18
- const content = (0, fs_1.readFileSync)(pth, 'utf-8');
19
- let query;
20
- if (argv.pl) {
21
- // plpgsql ONLY
22
- query = (0, index_1.parseFunction)(content);
23
- }
24
- else {
25
- query = (0, index_1.parse)(content);
26
- }
27
- process.stdout.write(JSON.stringify((0, utils_1.cleanTreeWithStmt)(query), null, 2));
package/main/index.js DELETED
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseFunction = exports.Deparser = exports.deparse = exports.parseAsync = exports.parse = void 0;
4
- const pgsql_deparser_1 = require("pgsql-deparser");
5
- Object.defineProperty(exports, "Deparser", { enumerable: true, get: function () { return pgsql_deparser_1.Deparser; } });
6
- Object.defineProperty(exports, "deparse", { enumerable: true, get: function () { return pgsql_deparser_1.deparse; } });
7
- const libpg_query_1 = require("libpg-query");
8
- Object.defineProperty(exports, "parseFunction", { enumerable: true, get: function () { return libpg_query_1.parsePlPgSQLSync; } });
9
- function mapStmt({ stmt, stmt_len, stmt_location }) {
10
- return {
11
- RawStmt: {
12
- stmt,
13
- stmt_len,
14
- stmt_location: stmt_location || 0
15
- }
16
- };
17
- }
18
- const parse = (sql) => {
19
- if (!sql)
20
- throw new Error('no SQL provided to parser');
21
- const result = (0, libpg_query_1.parseQuerySync)(sql);
22
- return result.stmts.map(mapStmt);
23
- };
24
- exports.parse = parse;
25
- const parseAsync = async (sql) => {
26
- if (!sql)
27
- throw new Error('no SQL provided to parser');
28
- const result = await (0, libpg_query_1.parseQuery)(sql);
29
- return result.stmts.map(mapStmt);
30
- };
31
- exports.parseAsync = parseAsync;
@@ -1,97 +0,0 @@
1
- "use strict";
2
- /* eslint-disable no-restricted-syntax */
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.cleanTreeWithStmt = exports.cleanTree = exports.transform = exports.cleanLines = void 0;
5
- const cleanLines = (sql) => {
6
- return sql
7
- .split('\n')
8
- .map((l) => l.trim())
9
- .filter((a) => a)
10
- .join('\n');
11
- };
12
- exports.cleanLines = cleanLines;
13
- const transform = (obj, props) => {
14
- let copy = null;
15
- // Handle the 3 simple types, and null or undefined
16
- if (obj == null || typeof obj !== 'object') {
17
- return obj;
18
- }
19
- // Handle Date
20
- if (obj instanceof Date) {
21
- copy = new Date();
22
- copy.setTime(obj.getTime());
23
- return copy;
24
- }
25
- // Handle Array
26
- if (obj instanceof Array) {
27
- copy = [];
28
- for (let i = 0, len = obj.length; i < len; i++) {
29
- copy[i] = (0, exports.transform)(obj[i], props);
30
- }
31
- return copy;
32
- }
33
- // Handle Object
34
- if (obj instanceof Object || typeof obj === 'object') {
35
- copy = {};
36
- for (const attr in obj) {
37
- if (obj.hasOwnProperty(attr)) {
38
- if (props.hasOwnProperty(attr)) {
39
- if (typeof props[attr] === 'function') {
40
- copy[attr] = props[attr](obj[attr]);
41
- }
42
- else if (props[attr].hasOwnProperty(obj[attr])) {
43
- copy[attr] = props[attr][obj[attr]];
44
- }
45
- else {
46
- copy[attr] = (0, exports.transform)(obj[attr], props);
47
- }
48
- }
49
- else {
50
- copy[attr] = (0, exports.transform)(obj[attr], props);
51
- }
52
- }
53
- else {
54
- copy[attr] = (0, exports.transform)(obj[attr], props);
55
- }
56
- }
57
- return copy;
58
- }
59
- throw new Error("Unable to copy obj! Its type isn't supported.");
60
- };
61
- exports.transform = transform;
62
- const noop = () => undefined;
63
- const cleanTree = (tree) => {
64
- return (0, exports.transform)(tree, {
65
- stmt_len: noop,
66
- stmt_location: noop,
67
- location: noop,
68
- DefElem: (obj) => {
69
- if (obj.defname === 'as') {
70
- if (Array.isArray(obj.arg) && obj.arg.length) {
71
- // function
72
- obj.arg[0].String.str = obj.arg[0].String.str.trim();
73
- }
74
- else if (obj.arg.List && obj.arg.List.items) {
75
- // function
76
- obj.arg.List.items[0].String.str = obj.arg.List.items[0].String.str.trim();
77
- }
78
- else {
79
- // do stmt
80
- obj.arg.String.str = obj.arg.String.str.trim();
81
- }
82
- return (0, exports.cleanTree)(obj);
83
- }
84
- else {
85
- return (0, exports.cleanTree)(obj);
86
- }
87
- }
88
- });
89
- };
90
- exports.cleanTree = cleanTree;
91
- const cleanTreeWithStmt = (tree) => {
92
- return (0, exports.transform)(tree, {
93
- stmt_location: noop,
94
- location: noop
95
- });
96
- };
97
- exports.cleanTreeWithStmt = cleanTreeWithStmt;
package/module/cli.js DELETED
@@ -1,25 +0,0 @@
1
- #!/usr/bin/env node
2
- import { resolve, join } from 'path';
3
- import { readFileSync } from 'fs';
4
- import { parse, parseFunction } from './index';
5
- import { cleanTreeWithStmt } from './utils';
6
- const argv = require('minimist')(process.argv.slice(2));
7
- const args = argv._;
8
- if (args.length !== 1) {
9
- console.log(argv);
10
- console.warn('Usage: pgsql-parser <sqlfile>');
11
- process.exit(1);
12
- }
13
- const pth = args[0].startsWith('/')
14
- ? args[0]
15
- : resolve(join(process.cwd(), args[0]));
16
- const content = readFileSync(pth, 'utf-8');
17
- let query;
18
- if (argv.pl) {
19
- // plpgsql ONLY
20
- query = parseFunction(content);
21
- }
22
- else {
23
- query = parse(content);
24
- }
25
- process.stdout.write(JSON.stringify(cleanTreeWithStmt(query), null, 2));
package/module/index.js DELETED
@@ -1,24 +0,0 @@
1
- import { Deparser, deparse } from 'pgsql-deparser';
2
- import { parseQuery, parseQuerySync, parsePlPgSQLSync as parseFunction } from 'libpg-query';
3
- function mapStmt({ stmt, stmt_len, stmt_location }) {
4
- return {
5
- RawStmt: {
6
- stmt,
7
- stmt_len,
8
- stmt_location: stmt_location || 0
9
- }
10
- };
11
- }
12
- export const parse = (sql) => {
13
- if (!sql)
14
- throw new Error('no SQL provided to parser');
15
- const result = parseQuerySync(sql);
16
- return result.stmts.map(mapStmt);
17
- };
18
- export const parseAsync = async (sql) => {
19
- if (!sql)
20
- throw new Error('no SQL provided to parser');
21
- const result = await parseQuery(sql);
22
- return result.stmts.map(mapStmt);
23
- };
24
- export { deparse, Deparser, parseFunction };
@@ -1,90 +0,0 @@
1
- /* eslint-disable no-restricted-syntax */
2
- export const cleanLines = (sql) => {
3
- return sql
4
- .split('\n')
5
- .map((l) => l.trim())
6
- .filter((a) => a)
7
- .join('\n');
8
- };
9
- export const transform = (obj, props) => {
10
- let copy = null;
11
- // Handle the 3 simple types, and null or undefined
12
- if (obj == null || typeof obj !== 'object') {
13
- return obj;
14
- }
15
- // Handle Date
16
- if (obj instanceof Date) {
17
- copy = new Date();
18
- copy.setTime(obj.getTime());
19
- return copy;
20
- }
21
- // Handle Array
22
- if (obj instanceof Array) {
23
- copy = [];
24
- for (let i = 0, len = obj.length; i < len; i++) {
25
- copy[i] = transform(obj[i], props);
26
- }
27
- return copy;
28
- }
29
- // Handle Object
30
- if (obj instanceof Object || typeof obj === 'object') {
31
- copy = {};
32
- for (const attr in obj) {
33
- if (obj.hasOwnProperty(attr)) {
34
- if (props.hasOwnProperty(attr)) {
35
- if (typeof props[attr] === 'function') {
36
- copy[attr] = props[attr](obj[attr]);
37
- }
38
- else if (props[attr].hasOwnProperty(obj[attr])) {
39
- copy[attr] = props[attr][obj[attr]];
40
- }
41
- else {
42
- copy[attr] = transform(obj[attr], props);
43
- }
44
- }
45
- else {
46
- copy[attr] = transform(obj[attr], props);
47
- }
48
- }
49
- else {
50
- copy[attr] = transform(obj[attr], props);
51
- }
52
- }
53
- return copy;
54
- }
55
- throw new Error("Unable to copy obj! Its type isn't supported.");
56
- };
57
- const noop = () => undefined;
58
- export const cleanTree = (tree) => {
59
- return transform(tree, {
60
- stmt_len: noop,
61
- stmt_location: noop,
62
- location: noop,
63
- DefElem: (obj) => {
64
- if (obj.defname === 'as') {
65
- if (Array.isArray(obj.arg) && obj.arg.length) {
66
- // function
67
- obj.arg[0].String.str = obj.arg[0].String.str.trim();
68
- }
69
- else if (obj.arg.List && obj.arg.List.items) {
70
- // function
71
- obj.arg.List.items[0].String.str = obj.arg.List.items[0].String.str.trim();
72
- }
73
- else {
74
- // do stmt
75
- obj.arg.String.str = obj.arg.String.str.trim();
76
- }
77
- return cleanTree(obj);
78
- }
79
- else {
80
- return cleanTree(obj);
81
- }
82
- }
83
- });
84
- };
85
- export const cleanTreeWithStmt = (tree) => {
86
- return transform(tree, {
87
- stmt_location: noop,
88
- location: noop
89
- });
90
- };
package/src/cli.js DELETED
@@ -1,25 +0,0 @@
1
- #!/usr/bin/env node
2
- import { resolve, join } from 'path';
3
- import { readFileSync } from 'fs';
4
- import { parse, parseFunction } from './index';
5
- import { cleanTreeWithStmt } from './utils';
6
- const argv = require('minimist')(process.argv.slice(2));
7
- const args = argv._;
8
- if (args.length !== 1) {
9
- console.log(argv);
10
- console.warn('Usage: pgsql-parser <sqlfile>');
11
- process.exit(1);
12
- }
13
- const pth = args[0].startsWith('/')
14
- ? args[0]
15
- : resolve(join(process.cwd(), args[0]));
16
- const content = readFileSync(pth, 'utf-8');
17
- let query;
18
- if (argv.pl) {
19
- // plpgsql ONLY
20
- query = parseFunction(content);
21
- } else {
22
- query = parse(content);
23
- }
24
-
25
- process.stdout.write(JSON.stringify(cleanTreeWithStmt(query), null, 2));
package/src/index.ts DELETED
@@ -1,30 +0,0 @@
1
- import { Deparser, deparse } from 'pgsql-deparser';
2
- import {
3
- parseQuery,
4
- parseQuerySync,
5
- parsePlPgSQLSync as parseFunction
6
- } from 'libpg-query';
7
-
8
- function mapStmt({ stmt, stmt_len, stmt_location }) {
9
- return {
10
- RawStmt: {
11
- stmt,
12
- stmt_len,
13
- stmt_location: stmt_location || 0
14
- }
15
- };
16
- }
17
-
18
- export const parse = (sql) => {
19
- if (!sql) throw new Error('no SQL provided to parser');
20
- const result = parseQuerySync(sql);
21
- return result.stmts.map(mapStmt);
22
- };
23
-
24
- export const parseAsync = async (sql) => {
25
- if (!sql) throw new Error('no SQL provided to parser');
26
- const result = await parseQuery(sql);
27
- return result.stmts.map(mapStmt);
28
- };
29
-
30
- export { deparse, Deparser, parseFunction };
@@ -1,92 +0,0 @@
1
- /* eslint-disable no-restricted-syntax */
2
-
3
- export const cleanLines = (sql) => {
4
- return sql
5
- .split('\n')
6
- .map((l) => l.trim())
7
- .filter((a) => a)
8
- .join('\n');
9
- };
10
-
11
- export const transform = (obj, props) => {
12
- let copy = null;
13
- // Handle the 3 simple types, and null or undefined
14
- if (obj == null || typeof obj !== 'object') {
15
- return obj;
16
- }
17
-
18
- // Handle Date
19
- if (obj instanceof Date) {
20
- copy = new Date();
21
- copy.setTime(obj.getTime());
22
- return copy;
23
- }
24
-
25
- // Handle Array
26
- if (obj instanceof Array) {
27
- copy = [];
28
- for (let i = 0, len = obj.length; i < len; i++) {
29
- copy[i] = transform(obj[i], props);
30
- }
31
- return copy;
32
- }
33
-
34
- // Handle Object
35
- if (obj instanceof Object || typeof obj === 'object') {
36
- copy = {};
37
- for (const attr in obj) {
38
- if (obj.hasOwnProperty(attr)) {
39
- if (props.hasOwnProperty(attr)) {
40
- if (typeof props[attr] === 'function') {
41
- copy[attr] = props[attr](obj[attr]);
42
- } else if (props[attr].hasOwnProperty(obj[attr])) {
43
- copy[attr] = props[attr][obj[attr]];
44
- } else {
45
- copy[attr] = transform(obj[attr], props);
46
- }
47
- } else {
48
- copy[attr] = transform(obj[attr], props);
49
- }
50
- } else {
51
- copy[attr] = transform(obj[attr], props);
52
- }
53
- }
54
- return copy;
55
- }
56
-
57
- throw new Error("Unable to copy obj! Its type isn't supported.");
58
- };
59
-
60
- const noop = () => undefined;
61
-
62
- export const cleanTree = (tree) => {
63
- return transform(tree, {
64
- stmt_len: noop,
65
- stmt_location: noop,
66
- location: noop,
67
- DefElem: (obj) => {
68
- if (obj.defname === 'as') {
69
- if (Array.isArray(obj.arg) && obj.arg.length) {
70
- // function
71
- obj.arg[0].String.str = obj.arg[0].String.str.trim();
72
- } else if (obj.arg.List && obj.arg.List.items) {
73
- // function
74
- obj.arg.List.items[0].String.str = obj.arg.List.items[0].String.str.trim();
75
- } else {
76
- // do stmt
77
- obj.arg.String.str = obj.arg.String.str.trim();
78
- }
79
- return cleanTree(obj);
80
- } else {
81
- return cleanTree(obj);
82
- }
83
- }
84
- });
85
- };
86
-
87
- export const cleanTreeWithStmt = (tree) => {
88
- return transform(tree, {
89
- stmt_location: noop,
90
- location: noop
91
- });
92
- };
package/types/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/types/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- import { Deparser, deparse } from 'pgsql-deparser';
2
- import { parsePlPgSQLSync as parseFunction } from 'libpg-query';
3
- export declare const parse: (sql: any) => any;
4
- export declare const parseAsync: (sql: any) => Promise<any>;
5
- export { deparse, Deparser, parseFunction };
@@ -1,4 +0,0 @@
1
- export declare const cleanLines: (sql: any) => any;
2
- export declare const transform: (obj: any, props: any) => any;
3
- export declare const cleanTree: (tree: any) => any;
4
- export declare const cleanTreeWithStmt: (tree: any) => any;