node-pgparser

16.1.3 • Public • Published

node-pgparser

node-pgparser - Node.js wrapper for libpg_query C library.

It parses the query and returns the parse tree or error object.

Installation

If you use a corporate certificate to internet access please add it to node first:

# linux and macos
export NODE_EXTRA_CA_CERTS=/path/to/cert

# windows
set NODE_EXTRA_CA_CERTS=/path/to/cert

then run the command

npm install node-pgparser

Uses node-pre-gyp to download prebuild binaries from S3 Amazon.

Currently supports Nodejs v16,v18,v20 for Linux, Macos (x64 and arm64) and Windows.

Example

Parse SQL query

const pgparser = require('node-pgparser');

let tree = pgparser('select 1');
if (tree instanceof Error) {
  console.log('Error parsing: ', tree);
} else {
  console.dir(tree, {depth: null});
}

Result

{
  version: 160001,
    stmts: [
    {
      stmt: {
        SelectStmt: {
          targetList: [
            {
              ResTarget: {
                val: { A_Const: { ival: { ival: 1 }, location: 7 } },
                location: 7
              }
            }
          ],
          limitOption: 'LIMIT_OPTION_DEFAULT',
          op: 'SETOP_NONE'
        }
      }
    }
  ]
}

Parse PL/pgSQL

const pgparser = require('node-pgparser');

let tree = pgparser('DO $$ BEGIN SELECT 1; END$$;', true);
if (tree instanceof Error) {
  console.log('Error parsing PL/pgSQL: ', tree);
} else {
  console.dir(tree, {depth: null});
}

Result

[
  {
    PLpgSQL_function: {
      datums: [
        {
          PLpgSQL_var: {
            refname: 'found',
            datatype: { PLpgSQL_type: { typname: 'UNKNOWN' } }
          }
        }
      ],
      action: {
        PLpgSQL_stmt_block: {
          lineno: 1,
          body: [
            {
              PLpgSQL_stmt_execsql: {
                lineno: 1,
                sqlstmt: { PLpgSQL_expr: { query: 'SELECT 1', parseMode: 0 } }
              }
            },
            { PLpgSQL_stmt_return: {} }
          ]
        }
      }
    }
  }
]

Versions

PG Major Version libpg_query Branch npm
16 16-latest pg16 node-pgparser@16
15 15-latest pg15 node-pgparser@15
14 14-latest pg14 node-pgparser@14
13 13-latest pg13 node-pgparser@13

Package Sidebar

Install

npm i node-pgparser

Weekly Downloads

18

Version

16.1.3

License

MIT

Unpacked Size

9.41 kB

Total Files

7

Last publish

Collaborators

  • mgorkov