Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,20 +97,21 @@ The `pgsql-deparser` module serializes ASTs to SQL in pure TypeScript, avoiding
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`:

```ts
import ast from '@pgsql/utils';
import { deparse } from 'pgsql-deparser';
import * as t from '@pgsql/utils';
import { RangeVar, SelectStmt } from '@pgsql/types';
import { deparseSync as deparse } from 'pgsql-deparser';

// This could have been obtained from any JSON or AST, not necessarily @pgsql/utils
const stmt = ast.selectStmt({
const stmt: { SelectStmt: SelectStmt } = t.nodes.selectStmt({
targetList: [
ast.resTarget({
val: ast.columnRef({
fields: [ast.aStar()]
t.nodes.resTarget({
val: t.nodes.columnRef({
fields: [t.nodes.aStar()]
})
})
],
fromClause: [
ast.rangeVar({
t.nodes.rangeVar({
relname: 'some_table',
inh: true,
relpersistence: 'p'
Expand All @@ -120,11 +121,11 @@ const stmt = ast.selectStmt({
op: 'SETOP_NONE'
});

// Modify the AST if needed
stmt.SelectStmt.fromClause[0].RangeVar.relname = 'another_table';
// Modify the AST if needed
(stmt.SelectStmt.fromClause[0] as {RangeVar: RangeVar}).RangeVar.relname = 'another_table';

// Deparse the modified AST back to a SQL string
console.log(deparse(stmts));
console.log(deparse(stmt));

// Output: SELECT * FROM another_table
```
Expand Down
80 changes: 40 additions & 40 deletions packages/deparser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,20 @@
<a href="https://www.npmjs.com/package/pgsql-deparser"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/pgsql-parser?filename=packages%2Fdeparser%2Fpackage.json"/></a>
</p>

`pgsql-deparser` is a streamlined tool designed to convert PostgreSQL Abstract Syntax Trees (AST) back into SQL queries. It is a companion module to [`pgsql-parser`](https://github.com/launchql/pgsql-parser), which is capable of both parsing SQL queries into ASTs and deparsing these ASTs back into SQL. However, unlike `pgsql-parser`, which incorporates the full PostgreSQL parser, `pgsql-deparser` focuses solely on the deparser functionality. This makes it an excellent choice for scenarios where only AST-to-SQL conversion is needed, avoiding the extra overhead associated with the full parsing capabilities.
`pgsql-deparser` is the lightning-fast, pure TypeScript solution for converting PostgreSQL ASTs back into SQL queries. Perfect companion to [`pgsql-parser`](https://github.com/launchql/pgsql-parser), this focused tool delivers SQL generation without any native dependencies or WebAssembly overhead.

## Installation

```sh
npm install pgsql-deparser
```

## Key Features
## Features

- **Lightweight and Pure TypeScript**: Built entirely in TypeScript, `pgsql-deparser` is lightweight and doesn't rely on native dependencies, facilitating easier integration and deployment across various environments.
- **Focused Functionality**: By concentrating on decompiling ASTs to SQL, `pgsql-deparser` offers a specialized, efficient solution for those who need to generate SQL statements from ASTs without the full parsing mechanism.
- **Compatibility**: Ideal for use cases where the AST is already obtained from another source or process, allowing for seamless SQL generation from AST representations.
* ⚡ **Pure TypeScript Performance** – Zero dependencies, no WASM, no compilation - just blazing fast SQL generation
* 🪶 **Ultra Lightweight** – Minimal footprint with laser-focused functionality for AST-to-SQL conversion only
* 🧪 **Battle-Tested Reliability** – Validated against 23,000+ SQL statements ensuring production-grade stability
* 🌍 **Universal Compatibility** – Runs anywhere JavaScript does - browsers, Node.js, edge functions, you name it

## Deparser Example

Expand All @@ -35,20 +36,21 @@ The `pgsql-deparser` module serializes ASTs to SQL in pure TypeScript, avoiding
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`:

```ts
import ast, { SelectStmt } from '@pgsql/utils';
import { deparse } from 'pgsql-deparser';
import * as t from '@pgsql/utils';
import { RangeVar, SelectStmt } from '@pgsql/types';
import { deparseSync as deparse } from 'pgsql-deparser';

// This could have been obtained from any JSON or AST, not necessarily @pgsql/utils
const stmt: SelectStmt = ast.selectStmt({
const stmt: { SelectStmt: SelectStmt } = t.nodes.selectStmt({
targetList: [
ast.resTarget({
val: ast.columnRef({
fields: [ast.aStar()]
t.nodes.resTarget({
val: t.nodes.columnRef({
fields: [t.nodes.aStar()]
})
})
],
fromClause: [
ast.rangeVar({
t.nodes.rangeVar({
relname: 'some_table',
inh: true,
relpersistence: 'p'
Expand All @@ -58,11 +60,11 @@ const stmt: SelectStmt = ast.selectStmt({
op: 'SETOP_NONE'
});

// Modify the AST if needed
stmt.SelectStmt.fromClause[0].RangeVar.relname = 'another_table';
// Modify the AST if needed
(stmt.SelectStmt.fromClause[0] as {RangeVar: RangeVar}).RangeVar.relname = 'another_table';

// Deparse the modified AST back to a SQL string
console.log(deparse(stmts));
console.log(deparse(stmt));

// Output: SELECT * FROM another_table
```
Expand All @@ -75,43 +77,41 @@ console.log(deparse(stmts));

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.

Our latest is built with `13-latest` branch from libpg_query
Our latest is built with `17-latest` branch from libpg_query

| PostgreSQL Major Version | libpg_query | Status | npm
| PostgreSQL Major Version | libpg_query | Status | npm tag |
|--------------------------|-------------|---------------------|---------|
| 13 | 13-latest | Active development | `latest`
| 17 | 17-latest | Active Development | `latest` |
| 16 | (n/a) | Not supported |
| 15 | (n/a) | Not supported |
| 14 | (n/a) | Not supported |
| 13 | 13-latest | Only Critical Fixes | `13.16.0` |
| 12 | (n/a) | Not supported |
| 11 | (n/a) | Not supported |
| 10 | 10-latest | Not supported | `@1.3.1` ([tree](https://github.com/launchql/pgsql-parser/tree/39b7b1adc8914253226e286a48105785219a81ca)) |

## Credits

## Related

* [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.
* [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`.
* [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`
* [@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.
* [@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.
* [@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.
* [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.
* [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.

Thanks [@lfittl](https://github.com/lfittl) for building the core `libpg_query` suite:

* [libpg_query](https://github.com/pganalyze/libpg_query)
* [pg_query](https://github.com/lfittl/pg_query)
* [pg_query.go](https://github.com/lfittl/pg_query.go)
Built on the excellent work of several contributors:

## Credits
* **[Dan Lynch](https://github.com/pyramation)** — official maintainer since 2018 and architect of the current implementation
* **[Lukas Fittl](https://github.com/lfittl)** for [libpg_query](https://github.com/pganalyze/libpg_query) — the core PostgreSQL parser that powers this project
* **[Greg Richardson](https://github.com/gregnr)** for AST guidance and pushing the transition to WASM for better interoperability
* **[Ethan Resnick](https://github.com/ethanresnick)** for the original Node.js N-API bindings
* **[Zac McCormick](https://github.com/zhm)** for the foundational [node-pg-query-native](https://github.com/zhm/node-pg-query-native) parser

Thanks to [@zhm](https://github.com/zhm) for the OG parser that started it all:
## Related

* [pg-query-parser](https://github.com/zhm/pg-query-parser)
* [pg-query-native](https://github.com/zhm/node-pg-query-native)
* [Original LICENSE](https://github.com/zhm/pg-query-parser/blob/master/LICENSE.md)
* [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.
* [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`.
* [@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.
* [@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.
* [@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.
* [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.
* [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.

## Disclaimer

AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED AS IS, AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.

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.
4 changes: 2 additions & 2 deletions packages/deparser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@
"database"
],
"devDependencies": {
"libpg-query": "17.3.3"
"libpg-query": "17.5.2"
},
"dependencies": {
"@pgsql/types": "^17.5.3"
"@pgsql/types": "^17.6.1"
}
}
13 changes: 11 additions & 2 deletions packages/deparser/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { Deparser, DeparserOptions } from "./deparser";

const deparse = Deparser.deparse;
export { deparse, Deparser, DeparserOptions };
const deparseMethod = Deparser.deparse;

// Export the original sync version as deparseSync
export const deparseSync = deparseMethod;

// Create an async wrapper for deparse
export const deparse = async (...args: Parameters<typeof deparseMethod>): Promise<ReturnType<typeof deparseMethod>> => {
return deparseMethod(...args);
};

export { Deparser, DeparserOptions };
4 changes: 2 additions & 2 deletions packages/deparser/test-utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { parse } from 'libpg-query';
import { deparse } from '../src';
import { deparseSync as deparse } from '../src';
import { cleanTree } from '../src/utils';
import { readFileSync } from 'fs';
import * as path from 'path';
import { expect } from '@jest/globals';
import {diff} from 'jest-diff'
import { diff } from 'jest-diff'

type ParseErrorType =
| 'PARSE_FAILED'
Expand Down
Loading