Full Code of godmodelabs/flora-sql-parser for AI

main 41c468e37923 cached
44 files
158.1 KB
39.2k tokens
31 symbols
1 requests
Download .txt
Repository: godmodelabs/flora-sql-parser
Branch: main
Commit: 41c468e37923
Files: 44
Total size: 158.1 KB

Directory structure:
gitextract_u9__4di5/

├── .editorconfig
├── .githooks/
│   └── pre-commit
├── .github/
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── eslint.config.js
├── index.js
├── lib/
│   ├── parser.js
│   ├── sql.js
│   └── util.js
├── package.json
├── sql.pegjs
└── test/
    ├── ast2sql/
    │   ├── column.spec.js
    │   ├── cte.spec.js
    │   ├── expr.spec.js
    │   ├── from.spec.js
    │   ├── groupby.spec.js
    │   ├── having.spec.js
    │   ├── join.spec.js
    │   ├── limit.spec.js
    │   ├── literal.spec.js
    │   ├── mysql.spec.js
    │   ├── order.spec.js
    │   ├── select.spec.js
    │   ├── util.js
    │   └── where.spec.js
    └── sql2ast/
        ├── column.spec.js
        ├── cte.spec.js
        ├── expr.spec.js
        ├── from.spec.js
        ├── groupby.spec.js
        ├── having.spec.js
        ├── join.spec.js
        ├── limit.spec.js
        ├── literal.spec.js
        ├── mysql.spec.js
        ├── orderby.spec.js
        ├── placeholder.spec.js
        ├── row-value-constructor.spec.js
        ├── select.spec.js
        └── where.spec.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[{package.json}]
indent_style = space
indent_size = 2


================================================
FILE: .githooks/pre-commit
================================================
#!/bin/sh
npm run test && npm run lint-fix


================================================
FILE: .github/workflows/ci.yml
================================================
name: ci

on:
  push:
    branches:
      - main
    paths-ignore:
      - 'docs/**'
      - '*.md'

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node: ['20', '22', '24']
    steps:
      - uses: actions/checkout@v6
      - name: Setup node ${{ matrix.node }}
        uses: actions/setup-node@v6
        with:
          node-version: ${{ matrix.node }}
      - run: npm install
      - run: npm test


================================================
FILE: .gitignore
================================================
.DS_Store
.vscode
node_modules
dist
package-lock.json


================================================
FILE: .prettierrc
================================================
{
    "printWidth": 120,
    "tabWidth": 4,
    "singleQuote": true,
    "trailingComma": "none"
}


================================================
FILE: CHANGELOG.md
================================================
# Changelog

## [4.0.0]
### Breaking Changes
- Replaced PEG.js by Peggy
- Removed support for Node.js 18
- `DECIMAL` is parsed in a structured way now:

  `DECIMAL(10)`
  ```json
  {
    "dataType": "DECIMAL",
    "precision": 10
  }
  ```
  `DECIMAL(10, 2)`
  ```json
  {
    "dataType": "DECIMAL",
    "precision": 10,
    "scale": 2
  }
  ```
### Added
- Support for JSON_TABLE (new keywords `COLUMNS`, `JSON_TABLE` and `PATH`)
- Support for BIGINT


================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.

    c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

NO WARRANTY

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS


================================================
FILE: README.md
================================================
# @florajs/sql-parser

![](https://github.com/florajs/sql-parser/workflows/ci/badge.svg)
[![NPM version](https://img.shields.io/npm/v/@florajs/sql-parser.svg?style=flat)](https://www.npmjs.com/package/@florajs/sql-parser)
[![NPM downloads](https://img.shields.io/npm/dm/@florajs/sql-parser.svg?style=flat)](https://www.npmjs.com/package/@florajs/sql-parser)

Parse simple SQL statements into an abstract syntax tree (AST) and convert it back to SQL.

## Usage

### Create AST for SQL statement

```javascript
const { Parser } = require('@florajs/sql-parser');
const parser = new Parser();
const ast = parser.parse('SELECT * FROM t');

console.log(ast);
```

### Convert AST back to SQL

```javascript
const { Parser } = require('@florajs/sql-parser');
const ast = (new Parser()).parse('SELECT * FROM t');
const toSQL = require('@florajs/sql-parser').util.astToSQL;

console.log(toSQL(ast));
```

The generated SQL is ANSI SQL compliant. To run those queries on MySQL, make sure you set correct SQL mode

```sql
SET SESSION sql_mode = 'ANSI';
```

before running any query.

## Acknowledgement

This project is based on the SQL parser extracted from Alibaba's [nquery](https://github.com/alibaba/nquery) module.  

## License

[GPL-2.0](LICENSE)


================================================
FILE: eslint.config.js
================================================
const js = require('@eslint/js');
const eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');

module.exports = [
    {
        files: ['index.js', 'lib/*.js', 'test/**/*.spec.js', 'eslint.config.js']
    },
    {
        ignores: ['node_modules/', 'dist/']
    },
    js.configs.recommended,
    eslintPluginPrettierRecommended,
    {
        languageOptions: {
            sourceType: 'commonjs',
            ecmaVersion: 2018
        },
        rules: {
            'no-console': 'warn',
            'no-unused-vars': 'off',
            'require-atomic-updates': 'off',
            'no-prototype-builtins': 'off'
        }
    }
];


================================================
FILE: index.js
================================================
'use strict';

const Parser = require('./lib/parser');
const util = require('./lib/util');

module.exports = { Parser, util };


================================================
FILE: lib/parser.js
================================================
'use strict';

const parseFn = require('./../dist/parser').parse;

class Parser {
    parse(sql) {
        return parseFn(sql);
    }
}

module.exports = Parser;


================================================
FILE: lib/sql.js
================================================
'use strict';

const escapeMap = {
    '\0': '\\0',
    "'": "\\'",
    '"': '\\"',
    '\b': '\\b',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t',
    '\x1a': '\\Z', // EOF
    '\\': '\\\\'
};

function escape(str) {
    return str
        .split('')
        .map((char) => (!Object.hasOwn(escapeMap, char) ? char : escapeMap[char]))
        .join('');
}

function identifierToSql(ident) {
    return `"${ident}"`;
}

function literalToSQL(literal) {
    const { type } = literal;
    let { value } = literal;

    if (type === 'number') {
        /* nothing */
    } else if (type === 'string') value = "'" + escape(value) + "'";
    else if (type === 'bool') value = value ? 'TRUE' : 'FALSE';
    else if (type === 'null') value = 'NULL';
    else if (type === 'star') value = '*';
    else if (['time', 'date', 'timestamp'].includes(type)) value = `${type.toUpperCase()} '${value}'`;
    else if (type === 'param') value = ':' + value;
    else if (type === 'interval') {
        const sign = literal.sign ? literal.sign + ' ' : '';
        value = `INTERVAL ${sign}'${escape(value)}' ${literal.qualifier}`;
    }

    return !literal.parentheses ? value : '(' + value + ')';
}

function aggrToSQL({ name: fnName, quantifier, args }) {
    return fnName + '(' + (quantifier ? quantifier + ' ' : '') + exprToSQL(args.expr) + ')';
}

function binaryToSQL(expr) {
    let operator = expr.operator;
    let rstr = exprToSQL(expr.right);

    if (Array.isArray(rstr)) {
        if (operator === '=') operator = 'IN';
        if (operator === '!=') operator = 'NOT IN';
        if (operator === 'BETWEEN' || operator === 'NOT BETWEEN') rstr = rstr[0] + ' AND ' + rstr[1];
        else rstr = '(' + rstr.join(', ') + ')';
    }

    const str = exprToSQL(expr.left) + ' ' + operator + ' ' + rstr;

    return !expr.parentheses ? str : '(' + str + ')';
}

function caseToSQL(expr) {
    const res = ['CASE'];
    const conditions = expr.args;

    if (expr.expr) res.push(exprToSQL(expr.expr));

    for (let i = 0, l = conditions.length; i < l; ++i) {
        res.push(conditions[i].type.toUpperCase()); // when/else
        if (conditions[i].cond) {
            res.push(exprToSQL(conditions[i].cond));
            res.push('THEN');
        }
        res.push(exprToSQL(conditions[i].result));
    }

    res.push('END');

    return res.join(' ');
}

function dataTypeToSQL(type) {
    const { dataType } = type;
    if (type.length > 0) return `${dataType}(${type.length})`;
    if (type.precision && type.scale) return `${dataType}(${type.precision}, ${type.scale})`;
    if (type.precision) return `${dataType}(${type.precision})`;
    return dataType;
}

function castToSQL(expr) {
    return 'CAST(' + exprToSQL(expr.expr) + ' AS ' + dataTypeToSQL(expr.target) + ')';
}

function columnRefToSQL(expr) {
    let str = expr.column !== '*' ? identifierToSql(expr.column) : '*';
    if (Object.hasOwn(expr, 'table') && expr.table !== null) str = identifierToSql(expr.table) + '.' + str;
    return !expr.parentheses ? str : '(' + str + ')';
}

function getExprListSQL(exprList) {
    return exprList.map(exprToSQL);
}

function funcToSQL(expr) {
    const str = expr.name + '(' + exprToSQL(expr.args).join(', ') + ')';
    return !expr.parentheses ? str : '(' + str + ')';
}

/**
 * Stringify column expressions
 *
 * @param {Array} columns
 * @return {string}
 */
function columnsToSQL(columns) {
    return columns
        .map((column) => {
            let str = exprToSQL(column.expr);

            if (column.as !== null) {
                str += ' AS ';
                if (column.as.match(/^[a-z_][0-9a-z_]*$/i)) str += identifierToSql(column.as);
                else str += '"' + column.as + '"';
            }

            return str;
        })
        .join(', ');
}

/**
 * @param {Array} tables
 * @return {string}
 */
function tablesToSQL(tables) {
    return tables
        .map((node, index) => {
            if (node.join) return joinToSQL(node);
            if (node.table) return (index > 0 ? ', ' : '') + tableToSQL(node);
            if (node.type === 'json_table') return (index > 0 ? ', ' : '') + jsonTableToSQL(node, index);
            if (node.expr) return tableExprToSQL(node);
            if (node.type === 'dual') return 'DUAL';

            throw new Error('Failed to convert node to SQL', { cause: { node } });
        })
        .join('');
}

function tableToSQL(node) {
    let str = node.db ? `${node.db}.` : '';

    str += identifierToSql(node.table);
    if (node.as) str += ' AS ' + identifierToSql(node.as);

    return str;
}

function joinToSQL(node) {
    let str = node.join ? ' ' + node.join + (node.lateral ? ' LATERAL' : '') + ' ' : ', ';

    if (node.table) str += tableToSQL(node);
    else if (node.type === 'json_table') str += jsonTableToSQL(node);
    else str += exprToSQL(node.expr) + (node.as !== null ? ' AS ' + identifierToSql(node.as) : '');

    if (node.type !== 'json_table' && Array.isArray(node.columns) && node.columns.length) {
        str += ' (' + node.columns.map(identifierToSql).join(', ') + ')';
    }

    if (node.on) str += ' ON ' + exprToSQL(node.on);
    if (node.using) str += ' USING (' + node.using.map(identifierToSql).join(', ') + ')';

    return str;
}

function tableExprToSQL(node) {
    const { expr, columns } = node;
    let str = expr.type === 'select' ? `(${toSQL(expr)})` : exprToSQL(expr);

    if (node.as) str += ' AS ' + identifierToSql(node.as);
    if (Array.isArray(columns) && columns.length) {
        str += ' (' + columns.map(identifierToSql).join(', ') + ')';
    }

    return str;
}

function jsonColumnToSQL(column) {
    if (column.nested) {
        let str = 'NESTED PATH ' + exprToSQL(column.path);
        return str + ' COLUMNS (' + column.columns.map(jsonColumnToSQL).join(', ') + ')';
    }

    let str = identifierToSql(column.name);
    if (column.ordinality) {
        str += ' FOR ORDINALITY';
        return str;
    }

    let onEmpty = '';
    if (column.onEmpty) {
        if (column.onEmpty.expr) {
            onEmpty = column.onEmpty.default ? ' DEFAULT' : '';
            onEmpty += column.onEmpty.expr ? ' ' + literalToSQL(column.onEmpty.expr) : '';
        } else if (column.onEmpty.error) onEmpty = ' ERROR';
        else throw new Error('Unknown onEmpty behavior');

        onEmpty += ' ON EMPTY';
    }

    let onError = '';
    if (column.onError) {
        if (column.onError.expr) {
            onError = column.onError.default ? ' DEFAULT' : '';
            onError += column.onError.expr ? ' ' + literalToSQL(column.onError.expr) : '';
        } else if (column.onError.error) onError = ' ERROR';
        else throw new Error('Unknown onError behavior');

        onError += ' ON ERROR';
    }

    return (
        str +
        ' ' +
        dataTypeToSQL(column.dataType) +
        (column.exists ? ' EXISTS' : '') +
        ' PATH ' +
        literalToSQL(column.path) +
        onEmpty +
        onError
    );
}

function jsonTableToSQL(node) {
    let str = exprToSQL(node.expr) + ', ' + literalToSQL(node.path);
    const columns = node.columns.map(jsonColumnToSQL).join(', ');

    str += ` COLUMNS (${columns})`;
    str = `JSON_TABLE(${str})`;

    return str + (node.as ? ' AS ' + identifierToSql(node.as) : '');
}

/**
 * @param {Object} withExpr
 */
function withToSql(withExpr) {
    return (
        'WITH ' +
        (withExpr.recursive ? 'RECURSIVE ' : '') +
        withExpr.value
            .map((cte) => {
                const name = `"${cte.name}"`;
                const columns = Array.isArray(cte.columns) ? '(' + cte.columns.join(', ') + ')' : '';

                return name + columns + ' AS (' + exprToSQL(cte.stmt) + ')';
            })
            .join(', ')
    );
}

/**
 * @param {Object}          stmt
 * @param {?Array}          stmt.with
 * @param {?Array}          stmt.options
 * @param {string|null}     stmt.distinct
 * @param {?Array|string}   stmt.columns
 * @param {?Array}          stmt.from
 * @param {?Object}         stmt.where
 * @param {?Array}          stmt.groupby
 * @param {?Object}         stmt.having
 * @param {?Array}          stmt.orderby
 * @param {?Array}          stmt.limit
 * @return {string}
 */
function selectToSQL(stmt) {
    const clauses = ['SELECT'];

    if (Object.hasOwn(stmt, 'with') && stmt.with !== null) clauses.unshift(withToSql(stmt.with));
    if (Object.hasOwn(stmt, 'options') && Array.isArray(stmt.options)) clauses.push(stmt.options.join(' '));
    if (Object.hasOwn(stmt, 'distinct') && stmt.distinct !== null) clauses.push(stmt.distinct);

    clauses.push(stmt.columns !== '*' ? columnsToSQL(stmt.columns) : '*');

    // FROM + joins
    if (Array.isArray(stmt.from)) clauses.push('FROM', tablesToSQL(stmt.from));

    if (Object.hasOwn(stmt, 'where') && stmt.where !== null) clauses.push('WHERE ' + exprToSQL(stmt.where));
    if (Array.isArray(stmt.groupby) && stmt.groupby.length > 0)
        clauses.push('GROUP BY', getExprListSQL(stmt.groupby).join(', '));
    if (Object.hasOwn(stmt, 'having') && stmt.having !== null) clauses.push('HAVING ' + exprToSQL(stmt.having));

    if (Array.isArray(stmt.orderby) && stmt.orderby.length > 0) {
        const orderExpressions = stmt.orderby.map((expr) => exprToSQL(expr.expr) + ' ' + expr.type);
        clauses.push('ORDER BY', orderExpressions.join(', '));
    }

    if (Array.isArray(stmt.limit)) clauses.push('LIMIT', stmt.limit.map(exprToSQL));

    return clauses.join(' ');
}

function unaryToSQL(expr) {
    const str = expr.operator + ' ' + exprToSQL(expr.expr);
    return !expr.parentheses ? str : '(' + str + ')';
}

function rowValueToSQL(expr) {
    const needsKeyword = expr.keyword === true;
    return (needsKeyword ? 'ROW' : '') + '(' + expr.value.map(exprToSQL) + ')';
}

function valuesToSQL(expr) {
    const str = 'VALUES ' + expr.value.map(exprToSQL).join(', ');
    return `(${str})`;
}

function unionToSQL(stmt) {
    const res = [selectToSQL(stmt)];

    while (stmt._next) {
        res.push('UNION', selectToSQL(stmt._next));
        stmt = stmt._next;
    }

    return res.join(' ');
}

const exprToSQLConvertFn = {
    aggr_func: aggrToSQL,
    binary_expr: binaryToSQL,
    case: caseToSQL,
    cast: castToSQL,
    column_ref: columnRefToSQL,
    expr_list: (expr) => {
        const str = getExprListSQL(expr.value);
        return !expr.parentheses ? str : `(${str})`;
    },
    function: funcToSQL,
    select: (expr) => {
        const str = typeof expr._next !== 'object' ? selectToSQL(expr) : unionToSQL(expr);
        return !expr.parentheses ? str : `(${str})`;
    },
    unary_expr: unaryToSQL,
    values: valuesToSQL,
    row_value: rowValueToSQL
};

function exprToSQL(expr) {
    return exprToSQLConvertFn[expr.type] ? exprToSQLConvertFn[expr.type](expr) : literalToSQL(expr);
}

function toSQL(ast) {
    if (ast.type !== 'select') throw new Error('Only SELECT statements supported at the moment');
    return unionToSQL(ast);
}

module.exports = toSQL;


================================================
FILE: lib/util.js
================================================
'use strict';

const { ImplementationError } = require('@florajs/errors');

const astToSQL = require('./sql');

/**
 * @param {(Array|boolean|string|number|null)} value
 * @return {Object}
 */
function createValueExpr(value) {
    const type = typeof value;

    if (Array.isArray(value)) return { type: 'expr_list', value: value.map(createValueExpr) };
    if (type === 'boolean') return { type: 'bool', value };
    if (type === 'string') return { type: 'string', value };
    if (type === 'number') return { type: 'number', value };
    if (value === null) return { type: 'null', value };

    throw new ImplementationError(`Cannot convert value "${value}" to SQL`);
}

/**
 * @param operator
 * @param left
 * @param right
 * @return {Object}
 */
function createBinaryExpr(operator, left, right) {
    const expr = {
        operator,
        type: 'binary_expr',
        left: left && left.type ? left : createValueExpr(left)
    };

    if (operator === 'BETWEEN' || operator === 'NOT BETWEEN') {
        expr.right = {
            type: 'expr_list',
            value: [createValueExpr(right[0]), createValueExpr(right[1])]
        };
    } else {
        expr.right = right && right.type ? right : createValueExpr(right);
    }

    return expr;
}

/**
 * Replace param expressions
 *
 * @param {Object} ast      - AST object
 * @param {Object} data     - Keys = parameter names, values = parameter values
 * @return {Object}         - Newly created AST object
 */
function replaceParams(ast, data) {
    Object.keys(ast)
        .filter((key) => {
            const value = ast[key];
            return Array.isArray(value) || (typeof value === 'object' && value !== null);
        })
        .forEach((key) => {
            const expr = ast[key];

            if (!(typeof expr === 'object' && expr.type === 'param')) return replaceParams(expr, data);

            if (data[expr.value] === undefined) throw new Error(`no value for parameter :${expr.value} found`);
            ast[key] = createValueExpr(data[expr.value]);
            return null;
        });

    return ast;
}

module.exports = {
    createBinaryExpr,
    createValueExpr,
    replaceParams: (ast, params) => replaceParams(JSON.parse(JSON.stringify(ast)), params),
    astToSQL
};


================================================
FILE: package.json
================================================
{
  "name": "@florajs/sql-parser",
  "version": "4.0.0",
  "description": "Parse SQL (select) statements into abstract syntax tree (AST) and convert ASTs back to SQL.",
  "main": "index.js",
  "scripts": {
    "prepare": "git config --local core.hooksPath .githooks",
    "build": "mkdir -p dist && peggy -o dist/parser.js sql.pegjs",
    "pretest": "npm run build",
    "test": "node --test test/**/*.spec.js",
    "lint": "eslint .",
    "lint-fix": "eslint --fix .",
    "prepack": "npm run build"
  },
  "keywords": [
    "florajs",
    "sql",
    "parser",
    "ast"
  ],
  "author": {
    "name": "stock3 AG",
    "email": "it@stock3.com"
  },
  "contributors": [
    {
      "name": "Marco Baumgartl",
      "email": "marco.baumgartl@stock3.com"
    },
    {
      "name": "Nico Kaiser",
      "email": "nico.kaiser@stock3.com"
    },
    {
      "name": "Mark Plomer",
      "email": "mark.plomer@stock3.com"
    }
  ],
  "files": [
    "index.js",
    "lib/",
    "dist/parser.js"
  ],
  "license": "GPL-2.0",
  "repository": "florajs/sql-parser",
  "homepage": "https://github.com/florajs/sql-parser",
  "engines": {
    "node": ">=20"
  },
  "dependencies": {
    "@florajs/errors": "^4.0.0"
  },
  "devDependencies": {
    "@eslint/js": "^10.0.1",
    "eslint": "^10.1.0",
    "eslint-config-prettier": "^10.1.8",
    "eslint-plugin-prettier": "^5.5.5",
    "peggy": "^5.1.0",
    "prettier": "^3.8.1"
  }
}


================================================
FILE: sql.pegjs
================================================
{
  var reservedMap = {
    'ALL': true,
    'AND': true,
    'AS': true,
    'ASC': true,

    'BETWEEN': true,
    'BIGINT': true,
    'BY': true,

    'CASE': true,
    'CREATE': true,
    'CONTAINS': true,
    'COLUMNS': true,
    'CURRENT_DATE': true,
    'CURRENT_TIME': true,
    'CURRENT_TIMESTAMP': true,
    'CURRENT_USER': true,

    'DAY': true,
    'DELETE': true,
    'DESC': true,
    'DISTINCT': true,
    'DROP': true,

    'ELSE': true,
    'END': true,
    'EXISTS': true,
    'EXPLAIN': true,

    'FALSE': true,
    'FROM': true,
    'FULL': true,

    'GROUP': true,

    'HAVING': true,
    'HOUR': true,

    'IN': true,
    'INDEX': true,
    'INNER': true,
    'INSERT': true,
    'INTO': true,
    'INTERVAL': true,
    'IS': true,

    'JOIN': true,
    'JSON': true,
    'JSON_TABLE': true,

    'LEFT': true,
    'LIKE': true,
    'LIMIT': true,

    'MICROSECOND': true,
    'MINUTE': true,
    'MONTH': true,

    'NOT': true,
    'NULL': true,

    'ON': true,
    'OR': true,
    'ORDER': true,
    'OUTER': true,

    'PATH': true,

    'QUARTER': true,

    'RECURSIVE': true,
    'REPLACE': true,
    'RIGHT': true,

    'SECOND': true,
    'SELECT': true,
    'SESSION_USER': true,
    'SET': true,
    'SHOW': true,
    'STATUS': true, // reserved (MySQL)
    'SYSTEM_USER': true,

    'TABLE': true,
    'THEN': true,
    'TRUE': true,
    'TYPE': true,   // reserved (MySQL)

    'UNION': true,
    'UPDATE': true,
    'USER': true,
    'USING': true,

    'VALUES': true,

    'WITH': true,
    'WEEK': true,
    'WHEN': true,
    'WHERE': true,

    'YEAR': true
  };

  function createUnaryExpr(operator, expr) {
    return { type: 'unary_expr', operator, expr };
  }

  function createBinaryExpr(operator, left, right) {
    return { type: 'binary_expr', operator, left, right };
  }

  function createList(head, tail) {
    return [head, ...tail.map(item => item[3])];
  }

  function createBinaryExprChain(head, tail) {
    return tail.reduce((result, item) => createBinaryExpr(item[1], result, item[3]), head);
  }

  var cmpPrefixMap = {
    '+': true,
    '-': true,
    '*': true,
    '/': true,
    '>': true,
    '<': true,
    '!': true,
    '=': true,

    //between
    'B': true,
    'b': true,
    //for is or in
    'I': true,
    'i': true,
    //for like
    'L': true,
    'l': true,
    //for not
    'N': true,
    'n': true
  };

  // used for dependency analysis
  var varList = [];
}

start
  = union_stmt
  / update_stmt
  / replace_insert_stmt
  / proc_stmts

union_stmt
  = head:select_stmt tail:(__ KW_UNION __ select_stmt)* {
      var cur = head;
      for (var i = 0; i < tail.length; i++) {
        cur._next = tail[i][3];
        cur = cur._next
      }
      return head;
    }

select_stmt
  = select_stmt_nake
  / s:('(' __ select_stmt __ ')') {
      return s[2];
    }

with_clause "WITH clause"
  = KW_WITH __ recursive:KW_RECURSIVE? __ list:with_list {
      return { type: 'with', recursive: recursive !== null, value: list };
    }

with_list
  = head:with_list_element tail:(__ COMMA __ with_list_element)* {
      return createList(head, tail);
    }

with_list_element
  = name:ident_name __ columns:with_column_list? __ KW_AS __ LPAREN __ stmt:union_stmt __ RPAREN {
      return { name, stmt, columns };
    }

with_column_list
  = LPAREN __ head:column tail:(__ COMMA __ column)* __ RPAREN {
      return createList(head, tail);
    }

select_stmt_nake "SELECT statement"
  = cte:with_clause? __ KW_SELECT __
    opts:option_clause? __
    d:KW_DISTINCT?      __
    c:column_clause     __
    f:from_clause?      __
    w:where_clause?     __
    g:group_by_clause?  __
    h:having_clause?    __
    o:order_by_clause?  __
    l:limit_clause? {
      return {
        with: cte,
        type: 'select',
        options: opts,
        distinct: d,
        columns: c,
        from: f,
        where: w,
        groupby: g,
        having: h,
        orderby: o,
        limit: l
      };
  }

// MySQL extensions to standard SQL
option_clause
  = head:query_option tail:(__ query_option)* {
    return [head, ...tail.map(item => item[1])];
  }

query_option
  = option:(
        OPT_SQL_CALC_FOUND_ROWS
        / (OPT_SQL_CACHE / OPT_SQL_NO_CACHE)
        / OPT_SQL_BIG_RESULT
        / OPT_SQL_SMALL_RESULT
        / OPT_SQL_BUFFER_RESULT
    ) { return option; }

column_clause "columns"
  = (KW_ALL / (STAR !ident_start)) { return '*'; }
  / head:column_list_item tail:(__ COMMA __ column_list_item)* {
      return createList(head, tail);
    }

column_list_item
  = table:ident __ DOT __ STAR {
      return {
        expr: {
          type: 'column_ref',
          table,
          column: '*'
        },
        as: null
      };
    }
  / e:expr __ alias:alias_clause? {
      return { expr: e, as: alias };
    }

alias_clause
  = KW_AS? __ i:ident { return i; }

from_clause "FROM clause"
  = KW_FROM __ l:table_ref_list { return l; }

table_ref_list "table reference list"
  = head:table_ref tail:(__ COMMA? __ table_ref)* {
      return createList(head, tail);
    }

table_ref "table reference"
  = t:table_primary { return t; }
  / op:join_op __ t:table_ref __ spec:join_spec {
      return { ...t, join: op, ...spec };
    }

table_primary
  = KW_DUAL {
      return { type: 'dual' };
    }
  / LPAREN __ KW_VALUES __ l:table_row_value_expr_list __ RPAREN __ KW_AS? __ alias:ident __ cols:derived_col_list? {
      return {
        expr: {
            type: 'values',
            value: l
        },
        as: alias,
        columns: cols
      };
    }
  / lateral:KW_LATERAL? __ sub:sub_query __ KW_AS? __ alias:ident __ cols:derived_col_list? {
      return {
        expr: { ...sub },
        as: alias,
        lateral: lateral !== null,
        columns: cols
      };
    }
  / json_table
  / t:table_name __ KW_AS? __ as:ident? {
      return { ...t, as };
    }

join_op
  = KW_LEFT __ KW_OUTER? __ KW_JOIN { return 'LEFT JOIN'; }
  / KW_RIGHT __ KW_OUTER? __ KW_JOIN { return 'RIGHT JOIN'; }
  / KW_FULL __ KW_OUTER? __ KW_JOIN { return 'FULL JOIN'; }
  / (KW_INNER __)? KW_JOIN { return 'INNER JOIN'; }

join_spec "join specification"
  = KW_ON __ e:expr {
      return { on: e };
    }
  / KW_USING __ LPAREN __ head:ident_name tail:(__ COMMA __ ident_name)* __ RPAREN {
      return { using: createList(head, tail) };
    }

table_name
  = dt:ident tail:(__ DOT __ ident)? {
      var obj = { db: null, table: dt };
      if (tail !== null) {
        obj.db = dt;
        obj.table = tail[3];
      }
      return obj;
    }
  / v:var_decl {
      v.db = null;
      v.table = v.name;
      return v;
    }

table_row_value_expr_list
  = head:row_value_constructor tail:(__ COMMA __ row_value_constructor)* {
      return createList(head, tail);
    }

row_value_constructor
  = rowkw:KW_ROW? __ LPAREN __ head:literal __ tail:(__ COMMA __ literal)* __ RPAREN {
      return {
        type: 'row_value',
        keyword: rowkw !== null,
        value: createList(head, tail),
      };
    }

on_clause
  = KW_ON __ e:expr { return e; }

sub_query
  = LPAREN __ stmt:union_stmt __ RPAREN {
      return { ...stmt, parentheses: true };
    }

json_table = KW_JSON_TABLE __ LPAREN __ expr:expr __ COMMA __ path:literal_string __ KW_COLUMNS __ LPAREN __ columns:json_table_column_list __ RPAREN __ RPAREN __ KW_AS? __ as:ident {
    return {
      type: 'json_table',
      expr,
      path,
      columns,
      as
    };
  }

json_table_column_list
  = head:json_table_column tail:(__ COMMA? __ json_table_column)* {
     return createList(head, tail);
  }

json_table_column = name:ident_name __ KW_FOR __ KW_ORDINALITY {
    return { type: 'json_table_column', name, ordinality: true };
  }
  / name:ident_name __ dataType:data_type __ KW_PATH __ path:literal_string __ onEmpty:json_column_on_empty? __ onError:json_column_on_error? {
     return {
       type: 'json_table_column',
       name,
       dataType,
       path,
       ...(onEmpty ? { onEmpty: onEmpty } : {}),
       ...(onError ? { onError: onError } : {}),
     };
  }
  / name:ident_name __ dataType:data_type __ exists:KW_EXISTS __ KW_PATH __ path:literal_string {
     return {
       type: 'json_table_column',
       name,
       dataType,
       path,
       exists: true,
     };
   }
   / KW_NESTED __ KW_PATH? __ path:literal_string __ KW_COLUMNS __ LPAREN __ columns:json_table_column_list __ RPAREN {
     return {
       type: 'json_table_column',
       nested: true,
       path,
       columns
     };
   }

json_column_on_empty
  = expr:literal_null __ KW_ON __ KW_EMPTY {
    return { expr };
  }
  / KW_DEFAULT __ expr:literal_string __ KW_ON __ KW_EMPTY {
    return { default: true, expr };
  }
  / KW_ERROR __ KW_ON __ KW_EMPTY {
    return { error: true };
  }

json_column_on_error
  = expr:literal_null __ KW_ON __ KW_ERROR {
    return { expr };
  }
  / KW_DEFAULT __ expr:literal_string __ KW_ON __ KW_ERROR {
    return { default: true, expr };
  }
  / KW_ERROR __ KW_ON __ KW_ERROR {
    return { error: true };
  }

derived_col_list "derived column list"
  = LPAREN __ head:ident __ tail:(__ COMMA __ ident)* __ RPAREN {
      return createList(head, tail);
    }

where_clause "WHERE clause"
  = KW_WHERE __ e:expr { return e; }

group_by_clause "GROUP BY clause"
  = KW_GROUP __ KW_BY __ l:column_ref_list { return l; }

column_ref_list
  = head:column_ref tail:(__ COMMA __ column_ref)* {
      return createList(head, tail);
    }

having_clause "HAVING clause"
  = KW_HAVING __ e:expr { return e; }

order_by_clause "ORDER BY clause"
  = KW_ORDER __ KW_BY __ l:order_by_list { return l; }

order_by_list
  = head:order_by_element tail:(__ COMMA __ order_by_element)* {
      return createList(head, tail);
    }

order_by_element
  = e:expr __ d:(KW_DESC / KW_ASC)? {
    return { expr: e, type: d === 'DESC' ? 'DESC' : 'ASC' };
  }

number_or_param
  = literal_numeric
  / param

limit_clause "LIMIT clause"
  = KW_LIMIT __ i1:(number_or_param) __ tail:(COMMA __ number_or_param)? {
      var res = [i1];
      if (tail === null) res.unshift({ type: 'number', value: 0 });
      else res.push(tail[2]);
      return res;
    }

update_stmt
  = KW_UPDATE    __
    t:table_name __
    KW_SET       __
    l:set_list   __
    w:where_clause {
      return {
        type: 'update',
        db: t.db,
        table: t.table,
        set: l,
        where: w
      };
    }

set_list
  = head:set_item tail:(__ COMMA __ set_item)* {
      return createList(head, tail);
    }

/**
 * here only use `additive_expr` to support 'col1 = col1+2'
 * if you want to use lower operator, please use '()' like below
 * 'col1 = (col2 > 3)'
 */
set_item
  = c:column_name __ '=' __ v:additive_expr {
      return { column: c, value: v };
    }

replace_insert_stmt
  = ri:replace_insert       __
    KW_INTO                 __
    t:table_name  __ LPAREN __
    c:column_list  __ RPAREN __
    v:value_clause {
      return {
        type: ri,
        db: t.db,
        table: t.table,
        columns: c,
        values: v
      };
    }

replace_insert
  = KW_INSERT   { return 'insert'; }
  / KW_REPLACE  { return 'replace'; }

value_clause
  = KW_VALUES __ l:value_list  { return l; }

value_list
  = head:value_item tail:(__ COMMA __ value_item)* {
      return createList(head, tail);
    }

value_item
  = LPAREN __ l:expr_list  __ RPAREN {
      return l;
    }

expr_list
  = head:expr tail:(__ COMMA __ expr)* {
      return { type: 'expr_list', value: createList(head, tail) };
    }

case_expr "CASE expression"
  = KW_CASE                         __
    expr:expr?                      __
    condition_list:case_when_then+  __
    otherwise:case_else?            __
    KW_END __ KW_CASE? {
      if (otherwise) condition_list.push(otherwise);
      return {
        type: 'case',
        expr: expr || null,
        args: condition_list
      };
    }

case_when_then
  = KW_WHEN __ condition:expr __ KW_THEN __ result:expr __ {
    return {
      type: 'when',
      cond: condition,
      result: result
    };
  }

case_else = KW_ELSE __ result:expr {
    return { type: 'else', result: result };
  }

/**
 * Borrowed from PL/SQL ,the priority of below list IS ORDER BY DESC
 * ---------------------------------------------------------------------------------------------------
 * | +, -                                                     | identity, negation                   |
 * | *, /                                                     | multiplication, division             |
 * | +, -                                                     | addition, subtraction, concatenation |
 * | =, <, >, <=, >=, <>, !=, IS, LIKE, BETWEEN, IN           | comparion                            |
 * | !, NOT                                                   | logical negation                     |
 * | AND                                                      | conjunction                          |
 * | OR                                                       | inclusion                            |
 * ---------------------------------------------------------------------------------------------------
 */

expr
  = or_expr
  / select_stmt

or_expr
  = head:and_expr tail:(__ KW_OR __ and_expr)* {
      return createBinaryExprChain(head, tail);
    }

and_expr
  = head:not_expr tail:(__ KW_AND __ not_expr)* {
      return createBinaryExprChain(head, tail);
    }

//here we should use `NOT` instead of `comparision_expr` to support chain-expr
not_expr
  = comparison_expr
  / exists_expr
  / (KW_NOT / "!" !"=") __ expr:not_expr {
      return createUnaryExpr('NOT', expr);
    }

comparison_expr
  = left:additive_expr __ rh:comparison_op_right? {
      if (rh === null) return left;
      else if (rh.type === 'arithmetic') return createBinaryExprChain(left, rh.tail);
      else return createBinaryExpr(rh.op, left, rh.right);
    }

exists_expr
  = op:exists_op __ sub:sub_query {
    return createUnaryExpr(op, { ...sub });
  }

exists_op
  = nk:(KW_NOT __ KW_EXISTS) { return nk[0] + ' ' + nk[2]; }
  / KW_EXISTS

comparison_op_right
  = arithmetic_op_right
  / in_op_right
  / between_op_right
  / is_op_right
  / like_op_right

arithmetic_op_right
  = l:(__ arithmetic_comparison_operator __ additive_expr)+ {
      return { type: 'arithmetic', tail: l };
    }

arithmetic_comparison_operator
  = ">=" / ">" / "<=" / "<>" / "<" / "=" / "!="

is_op_right
  = KW_IS __ right:additive_expr {
      return { op: 'IS', right };
    }
  / (KW_IS __ KW_NOT) __ right:additive_expr {
      return { op: 'IS NOT', right };
  }

between_op_right
  = op:between_or_not_between_op __  begin:additive_expr __ KW_AND __ end:additive_expr {
      return {
        op,
        right: {
          type: 'expr_list',
          value: [begin, end]
        }
      };
    }

between_or_not_between_op
  = nk:(KW_NOT __ KW_BETWEEN) { return nk[0] + ' ' + nk[2]; }
  / KW_BETWEEN

like_op
  = nk:(KW_NOT __ KW_LIKE) { return nk[0] + ' ' + nk[2]; }
  / KW_LIKE

in_op
  = nk:(KW_NOT __ KW_IN) { return nk[0] + ' ' + nk[2]; }
  / KW_IN

like_op_right
  = op:like_op __ right:comparison_expr {
      return { op, right: right };
    }

in_op_right
  = op:in_op __ LPAREN  __ l:expr_list __ RPAREN {
      return { op, right: l };
    }
  / op:in_op __ e:var_decl {
      return { op, right: e };
    }

additive_expr
  = head:multiplicative_expr
    tail:(__ additive_operator  __ multiplicative_expr)* {
      return createBinaryExprChain(head, tail);
    }

additive_operator
  = "+" / "-"

multiplicative_expr
  = head:primary
    tail:(__ multiplicative_operator  __ primary)* {
      return createBinaryExprChain(head, tail);
    }

multiplicative_operator
  = "*" / "/" / "%"

primary
  = literal
  / cast_expr
  / aggr_func
  / func_call
  / case_expr
  / column_ref
  / param
  / LPAREN __ e:expr __ RPAREN {
      return { ...e, parentheses: true };
    }
  / LPAREN __ list:expr_list __ RPAREN {
        return { ...list, parentheses: true };
    }
  / var_decl
  / interval_expr

column_ref
  = tbl:ident __ DOT __ col:column {
      return {
        type: 'column_ref',
        table: tbl,
        column: col
      };
    }
  / col:column {
      return {
        type: 'column_ref',
        table: null,
        column: col
      };
    }

column_list
  = head:column tail:(__ COMMA __ column)* {
      return createList(head, tail);
    }

ident
  = name:ident_name !{ return reservedMap[name.toUpperCase()] === true; } {
      return name;
    }
  / name:quoted_ident {
      return name;
    }

quoted_ident
  = double_quoted_ident
  / single_quoted_ident
  / backticks_quoted_ident

double_quoted_ident
  = '"' chars:[^"]+ '"' { return chars.join(''); }

single_quoted_ident
  = "'" chars:[^']+ "'" { return chars.join(''); }

backticks_quoted_ident
  = "`" chars:[^`]+ "`" { return chars.join(''); }

column
  = name:column_name !{ return reservedMap[name.toUpperCase()] === true; } { return name; }
  / quoted_ident

column_name
  =  start:ident_start parts:column_part* { return start + parts.join(''); }

ident_name
  =  start:ident_start parts:ident_part* { return start + parts.join(''); }

ident_start = [A-Za-z_]

ident_part  = [A-Za-z0-9_]

// to support column name like `cf1:name` in hbase
column_part  = [A-Za-z0-9_:]

param
  = l:(':' ident_name) {
      return { type: 'param', value: l[1] };
    }

aggr_func
  = name:KW_COUNT __ LPAREN __ expr:star_expr __ RPAREN {
      return { type: 'aggr_func', name, args: { expr } };
    }
  / name:set_function_type  __ LPAREN __ quantifier:set_quantifier? __ expr:column_ref __ RPAREN {
      return { type: 'aggr_func', name, quantifier, args: { expr } };
    }

set_function_type
  = KW_AVG / KW_MAX / KW_MIN / KW_SUM
  / KW_COUNT
  / 'group_concat'i { return 'GROUP_CONCAT'; } /* MySQL doesn't support listagg */

set_quantifier = KW_DISTINCT / KW_ALL

star_expr
  = STAR { return { type: 'star', value: '*' }; }

func_call
  = name:ident __ LPAREN __ l:expr_list? __ RPAREN {
      return { type: 'function', name, args: l ? l : { type: 'expr_list', value: [] } };
    }
  / name:(KW_YEAR / KW_MONTH / KW_DAY / KW_HOUR / KW_MINUTE) __ LPAREN __ l:expr_list? __ RPAREN {
      return { type: 'function', name, args: l ? l : { type: 'expr_list', value: [] } };
    }
  / name:scalar_func {
      return { type: 'function', name, args: { type: 'expr_list', value: [] } };
    }

scalar_func
  = KW_CURRENT_DATE
  / KW_CURRENT_TIME
  / KW_CURRENT_TIMESTAMP
  / KW_CURRENT_USER
  / KW_USER
  / KW_SESSION_USER
  / KW_SYSTEM_USER

cast_expr "CAST expression"
  = KW_CAST __ LPAREN __ expr:expr __ KW_AS __ target:data_type __ RPAREN {
    return { type: 'cast', expr, target };
  }
  / KW_CAST __ LPAREN __ e:expr __ KW_AS __ s:signedness __ t:KW_INTEGER? __ RPAREN { /* MySQL cast to un-/signed integer */
    return {
      type: 'cast',
      expr: e,
      target: {
        dataType: s + (t ? ' ' + t: '')
      }
    };
  }

interval_expr "INTERVAL expression"
  = KW_INTERVAL __  sign:("+" / "-")? __ "'"? __ value:int "'"? __ qualifier:interval_unit {
    return { type: 'interval', sign, value, qualifier };
  }

interval_unit
  = KW_MINUTE
  / KW_HOUR
  / KW_DAY
  / KW_MONTH
  / KW_YEAR

signedness
  = KW_SIGNED
  / KW_UNSIGNED

literal
  = literal_string
  / literal_numeric
  / literal_bool
  / literal_null
  / literal_datetime

literal_list
  = head:literal tail:(__ COMMA __ literal)* {
      return createList(head, tail);
    }

literal_null
  = KW_NULL {
      return { type: 'null', value: null };
    }

literal_bool
  = KW_TRUE {
      return { type: 'bool', value: true };
    }
  / KW_FALSE {
      return { type: 'bool', value: false };
    }

literal_string
  = ca:("'" single_char* "'") {
      return {
        type: 'string',
        value: ca[1].join('')
      };
    }

literal_datetime
  = type:(KW_TIME / KW_DATE / KW_TIMESTAMP) __ ca:("'" single_char* "'") {
      return {
        type: type.toLowerCase(),
        value: ca[1].join('')
      };
    }

single_char
  = [^'\\\0-\x1F\x7f]
  / escape_char

escape_char
  = "\\'"  { return "'";  }
  / '\\"'  { return '"';  }
  / "\\\\" { return "\\"; }
  / "\\/"  { return "/";  }
  / "\\b"  { return "\b"; }
  / "\\f"  { return "\f"; }
  / "\\n"  { return "\n"; }
  / "\\r"  { return "\r"; }
  / "\\t"  { return "\t"; }
  / "''"   { return "\'"; }
  / "\\u" h1:hexDigit h2:hexDigit h3:hexDigit h4:hexDigit {
      return String.fromCharCode(parseInt("0x" + h1 + h2 + h3 + h4));
    }

line_terminator
  = [\n\r]

literal_numeric
  = value:number {
      return { type: 'number', value };
    }

number
  = int_:int frac:frac exp:exp __ { return parseFloat(int_ + frac + exp); }
  / int_:int frac:frac __         { return parseFloat(int_ + frac); }
  / int_:int exp:exp __           { return parseFloat(int_ + exp); }
  / int_:int __                   { return parseFloat(int_); }
  / frac:frac __                  { return parseFloat(frac); }
  / op:("-" / "+" ) frac:frac __  { return parseFloat(op + frac); }

int
  = digits
  / digit:digit
  / op:("-" / "+" ) digits:digits { return op + digits; }
  / op:("-" / "+" ) digit:digit { return op + digit; }

frac
  = "." digits:digits { return "." + digits; }

exp
  = e:e digits:digits { return e + digits; }

digits
  = digits:digit+ { return digits.join(""); }

digit   = [0-9]

hexDigit
  = [0-9a-fA-F]

e
  = e:[eE] sign:[+-]? { return e + (sign !== null ? sign: ''); }


KW_NULL     = "NULL"i       !ident_start
KW_TRUE     = "TRUE"i       !ident_start
KW_FALSE    = "FALSE"i      !ident_start

KW_SHOW     = "SHOW"i       !ident_start
KW_DROP     = "DROP"i       !ident_start
KW_SELECT   = "SELECT"i     !ident_start
KW_UPDATE   = "UPDATE"i     !ident_start
KW_CREATE   = "CREATE"i     !ident_start
KW_DELETE   = "DELETE"i     !ident_start
KW_INSERT   = "INSERT"i     !ident_start
KW_RECURSIVE= "RECURSIVE"   !ident_start
KW_REPLACE  = "REPLACE"i    !ident_start
KW_EXPLAIN  = "EXPLAIN"i    !ident_start

KW_INTO     = "INTO"i       !ident_start
KW_FROM     = "FROM"i       !ident_start
KW_SET      = "SET"i        !ident_start

KW_AS       = "AS"i         !ident_start
KW_TABLE    = "TABLE"i      !ident_start

KW_ON       = "ON"i       !ident_start
KW_LEFT     = "LEFT"i     !ident_start
KW_RIGHT    = "RIGHT"i    !ident_start
KW_FULL     = "FULL"i     !ident_start
KW_INNER    = "INNER"i    !ident_start
KW_JOIN     = "JOIN"i     !ident_start
KW_OUTER    = "OUTER"i    !ident_start
KW_UNION    = "UNION"i    !ident_start
KW_VALUES   = "VALUES"i   !ident_start
KW_USING    = "USING"i    !ident_start
KW_LATERAL  = "LATERAL"i  !ident_start

KW_WHERE    = "WHERE"i      !ident_start
KW_WITH     = "WITH"i       !ident_start

KW_GROUP    = "GROUP"i      !ident_start
KW_BY       = "BY"i         !ident_start
KW_ORDER    = "ORDER"i      !ident_start
KW_HAVING   = "HAVING"i     !ident_start

KW_LIMIT    = "LIMIT"i      !ident_start

KW_ASC      = "ASC"i        !ident_start { return 'ASC'; }
KW_DESC     = "DESC"i       !ident_start { return 'DESC'; }

KW_ALL      = "ALL"i        !ident_start { return 'ALL'; }
KW_DISTINCT = "DISTINCT"i   !ident_start { return 'DISTINCT';}

KW_BETWEEN  = "BETWEEN"i    !ident_start { return 'BETWEEN'; }
KW_IN       = "IN"i         !ident_start { return 'IN'; }
KW_IS       = "IS"i         !ident_start { return 'IS'; }
KW_LIKE     = "LIKE"i       !ident_start { return 'LIKE'; }
KW_EXISTS   = "EXISTS"i     !ident_start { return 'EXISTS'; }

KW_NOT      = "NOT"i        !ident_start { return 'NOT'; }
KW_AND      = "AND"i        !ident_start { return 'AND'; }
KW_OR       = "OR"i         !ident_start { return 'OR'; }

KW_COLUMNS  = "COLUMNS"i    !ident_start { return 'COLUMNS'; }
KW_DEFAULT  = "DEFAULT"i    !ident_start
KW_EMPTY    = "EMPTY"i      !ident_start
KW_ERROR    = "ERROR"i      !ident_start
KW_FOR      = "FOR"i        !ident_start
KW_JSON_TABLE = "JSON_TABLE" !ident_start
KW_NESTED   = "NESTED"i     !ident_start
KW_ORDINALITY = "ORDINALITY" !ident_start
KW_PATH     = "PATH"i       !ident_start { return 'PATH'; }

KW_COUNT    = "COUNT"i      !ident_start { return 'COUNT'; }
KW_MAX      = "MAX"i        !ident_start { return 'MAX'; }
KW_MIN      = "MIN"i        !ident_start { return 'MIN'; }
KW_SUM      = "SUM"i        !ident_start { return 'SUM'; }
KW_AVG      = "AVG"i        !ident_start { return 'AVG'; }

KW_CASE     = "CASE"i       !ident_start
KW_WHEN     = "WHEN"i       !ident_start
KW_THEN     = "THEN"i       !ident_start
KW_ELSE     = "ELSE"i       !ident_start
KW_END      = "END"i        !ident_start

KW_CAST     = "CAST"i       !ident_start

KW_BIGINT   = "BIGINT"i     !ident_start { return 'BIGINT'; };
KW_BOOL     = "BOOL"i       !ident_start { return 'BOOL'; };
KW_CHAR     = "CHAR"i     !ident_start { return 'CHAR'; }
KW_VARCHAR  = "VARCHAR"i  !ident_start { return 'VARCHAR';}
KW_NUMERIC  = "NUMERIC"i  !ident_start { return 'NUMERIC'; }
KW_DECIMAL  = "DECIMAL"i  !ident_start { return 'DECIMAL'; }
KW_SIGNED   = "SIGNED"i   !ident_start { return 'SIGNED'; }
KW_UNSIGNED = "UNSIGNED"i !ident_start { return 'UNSIGNED'; }
KW_INT      = "INT"i      !ident_start { return 'INT'; }
KW_INTEGER  = "INTEGER"i  !ident_start { return 'INTEGER'; }
KW_JSON     = "JSON"i     !ident_start { return 'JSON'; }
KW_SMALLINT = "SMALLINT"i !ident_start { return 'SMALLINT'; }
KW_DATE     = "DATE"i     !ident_start { return 'DATE'; }
KW_TIME     = "TIME"i     !ident_start { return 'TIME'; }
KW_TIMESTAMP= "TIMESTAMP"i!ident_start { return 'TIMESTAMP'; }
KW_USER     = "USER"i     !ident_start { return 'USER'; }

KW_INTERVAL     = "INTERVAL"i !ident_start { return 'INTERVAL'; }
KW_MINUTE       = "MINUTE"i !ident_start { return 'MINUTE'; }
KW_HOUR         = "HOUR"i !ident_start { return 'HOUR'; }
KW_DAY          = "DAY"i !ident_start { return 'DAY'; }
KW_MONTH        = "MONTH"i !ident_start { return 'MONTH'; }
KW_YEAR         = "YEAR"i !ident_start { return 'YEAR'; }

KW_CURRENT_DATE     = "CURRENT_DATE"i !ident_start { return 'CURRENT_DATE'; }
KW_CURRENT_TIME     = "CURRENT_TIME"i !ident_start { return 'CURRENT_TIME'; }
KW_CURRENT_TIMESTAMP= "CURRENT_TIMESTAMP"i !ident_start { return 'CURRENT_TIMESTAMP'; }
KW_CURRENT_USER     = "CURRENT_USER"i !ident_start { return 'CURRENT_USER'; }
KW_SESSION_USER     = "SESSION_USER"i !ident_start { return 'SESSION_USER'; }
KW_SYSTEM_USER      = "SYSTEM_USER"i !ident_start { return 'SYSTEM_USER'; }

KW_VAR_PRE = '$'
KW_RETURN = 'return'i
KW_ASSIGN = ':='

KW_DUAL = "DUAL"
KW_ROW  = "ROW"i !ident_start { return 'ROW'; }

// MySQL extensions to SQL
OPT_SQL_CALC_FOUND_ROWS = "SQL_CALC_FOUND_ROWS"i
OPT_SQL_CACHE           = "SQL_CACHE"i
OPT_SQL_NO_CACHE        = "SQL_NO_CACHE"i
OPT_SQL_SMALL_RESULT    = "SQL_SMALL_RESULT"i
OPT_SQL_BIG_RESULT      = "SQL_BIG_RESULT"i
OPT_SQL_BUFFER_RESULT   = "SQL_BUFFER_RESULT"i

//special character
DOT       = '.'
COMMA     = ','
STAR      = '*'
LPAREN    = '('
RPAREN    = ')'

LBRAKE    = '['
RBRAKE    = ']'

// separator
__
  = (whitespace / comment)*

comment
  = block_comment
  / line_comment

block_comment
  = "/*" (!"*/" char)* "*/"

line_comment
  = "--" (!EOL char)*

char = .

whitespace =
  [ \t\n\r]

EOL
  = EOF
  / [\n\r]+

EOF = !.

//begin procedure extension
proc_stmts
  = proc_stmt*

proc_stmt
  = &{ varList = []; return true; } __ s:(assign_stmt / return_stmt) {
      return { stmt: s, vars: varList };
    }

assign_stmt
  = va:var_decl __ KW_ASSIGN __ e:proc_expr {
    return {
      type: 'assign',
      left: va,
      right: e
    };
  }

return_stmt
  = KW_RETURN __ e:proc_expr {
      return { type: 'return', expr: e };
    }

proc_expr
  = select_stmt
  / proc_join
  / proc_additive_expr
  / proc_array

proc_additive_expr
  = head:proc_multiplicative_expr
    tail:(__ additive_operator  __ proc_multiplicative_expr)* {
      return createBinaryExprChain(head, tail);
    }

proc_multiplicative_expr
  = head:proc_primary
    tail:(__ multiplicative_operator  __ proc_primary)* {
      return createBinaryExprChain(head, tail);
    }

proc_join
  = lt:var_decl __ op:join_op  __ rt:var_decl __ expr:on_clause {
      return {
        type: 'join',
        ltable: lt,
        rtable: rt,
        op: op,
        on: expr
      };
    }

proc_primary
  = literal
  / var_decl
  / proc_func_call
  / param
  / LPAREN __ e:proc_additive_expr __ RPAREN {
      e.parentheses = true;
      return e;
    }

proc_func_call
  = name:ident __ LPAREN __ l:proc_primary_list __ RPAREN {
      //compatible with original func_call
      return {
        type: 'function',
        name: name,
        args: {
          type: 'expr_list',
          value: l
        }
      };
    }

proc_primary_list
  = head:proc_primary tail:(__ COMMA __ proc_primary)* {
      return createList(head, tail);
    }

proc_array =
  LBRAKE __ l:proc_primary_list __ RBRAKE {
    return { type: 'array', value: l };
  }

var_decl
  = KW_VAR_PRE name:ident_name members:mem_chain {
    //push for analysis
    varList.push(name);
    return { type: 'var', name,  members };
  }

mem_chain
  = l:('.' ident_name)* {
    return l.map(item => item[1]);
  }

data_type
  = character_string_type
  / numeric_type
  / datetime_type
  / boolean_type
  / json_type

character_string_type
  = t:(KW_CHAR / KW_VARCHAR) __ LPAREN __ l:[0-9]+ __ RPAREN __ {
    return { dataType: t, length: parseInt(l.join(''), 10) };
  }
  / t:KW_CHAR { return { dataType: t }; }
  / t:KW_VARCHAR { return { dataType: t }; }

numeric_type
  = t:KW_DECIMAL __ LPAREN __ precision:int __ COMMA __ scale:int __ RPAREN {
    return { dataType: t, precision, scale };
  }
  / t:KW_DECIMAL __ LPAREN __ precision:int __ RPAREN {
    return { dataType: t, precision };
  }
  / t:(KW_NUMERIC / KW_DECIMAL / KW_BIGINT / KW_INT / KW_INTEGER / KW_SMALLINT) { return { dataType: t }; }

datetime_type
  = t:(KW_DATE / KW_TIME / KW_TIMESTAMP) { return { dataType: t }; }

boolean_type
  = t:KW_BOOL { return { dataType: t }; }

json_type
  = t:KW_JSON { return { dataType: t }; }


================================================
FILE: test/ast2sql/column.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('column clause', () => {
    it('should support asterisk', () => {
        assert.equal(getParsedSql('SELECT * FROM t'), 'SELECT * FROM "t"');
    });

    it('should support asterisk prefixed by table', () => {
        assert.equal(getParsedSql('SELECT t.* FROM t'), 'SELECT "t".* FROM "t"');
    });

    it('should parse multiple expressions', () => {
        const sql = 'SELECT col1 AS a, col2 AS b FROM t';
        assert.equal(getParsedSql(sql), 'SELECT "col1" AS "a", "col2" AS "b" FROM "t"');
    });

    it('should escape reserved keywords', () => {
        assert.equal(getParsedSql('SELECT col."select" FROM t'), 'SELECT "col"."select" FROM "t"');
    });

    it('should escape reserved keywords in aliases', () => {
        assert.equal(getParsedSql('SELECT col AS "index" FROM t'), 'SELECT "col" AS "index" FROM "t"');
    });

    it('should escape aliases with non-identifier chars (/a-z0-9_/i)', () => {
        assert.equal(getParsedSql(`SELECT col AS "foo bar" FROM t`), `SELECT "col" AS "foo bar" FROM "t"`);
    });

    it('should support subselects', () => {
        assert.equal(
            getParsedSql(`SELECT 'string', (SELECT col FROM t2) subSelect FROM t1`),
            `SELECT 'string', (SELECT "col" FROM "t2") AS "subSelect" FROM "t1"`
        );
    });
});


================================================
FILE: test/ast2sql/cte.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('common table expressions', () => {
    it('should support single CTE', () => {
        const sql = `
            WITH cte AS (SELECT 1)
            SELECT * FROM cte
        `.trim();

        assert.equal(getParsedSql(sql), 'WITH "cte" AS (SELECT 1) SELECT * FROM "cte"');
    });

    it('should support multiple CTE', () => {
        const expected =
            'WITH "cte1" AS (SELECT 1), "cte2" AS (SELECT 2) ' + 'SELECT * FROM "cte1" UNION SELECT * FROM "cte2"';
        const sql = `
            WITH cte1 AS (SELECT 1), cte2 AS (SELECT 2)
            SELECT * FROM cte1 UNION SELECT * FROM cte2
        `.trim();

        assert.equal(getParsedSql(sql), expected);
    });

    it('should support CTE with column', () => {
        const sql = `
            WITH cte (col1) AS (SELECT 1)
            SELECT * FROM cte
        `.trim();

        assert.ok(getParsedSql(sql).includes('(col1)'));
    });

    it('should support CTE with multiple columns', () => {
        const sql = `
            WITH cte (col1, col2) AS (SELECT 1, 2)
            SELECT * FROM cte
        `.trim();

        assert.ok(getParsedSql(sql).includes('(col1, col2)'));
    });

    it('should support recursive CTE', () => {
        const sql = `
            WITH RECURSIVE cte(n) AS
            (
                SELECT 1
                UNION
                SELECT n + 1 FROM cte WHERE n < 5
            )
            SELECT * FROM cte
        `.trim();

        assert.match(getParsedSql(sql), /^WITH RECURSIVE/);
    });
});


================================================
FILE: test/ast2sql/expr.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { util } = require('../../');
const { getParsedSql } = require('./util');

describe('expressions', () => {
    ["'", '"', 'n', 't', '\\'].forEach((char) => {
        it(`should escape char ${char} "`, () => {
            const sql = `SELECT ' escape \\${char}'`;
            assert.equal(getParsedSql(sql), sql);
        });
    });

    it('should support boolean values', () => {
        const sql = 'SELECT false, true';
        assert.equal(getParsedSql(sql), 'SELECT FALSE, TRUE');
    });

    it('should support parentheses', () => {
        const sql = 'SELECT (2 + 3) * 4';
        assert.equal(getParsedSql(sql), sql);
    });

    it('should support unary operators', () => {
        const sql = 'SELECT (not true), !t.foo as foo FROM t';
        assert.equal(getParsedSql(sql), 'SELECT (NOT TRUE), NOT "t"."foo" AS "foo" FROM "t"');
    });

    ['distinct', 'all'].forEach((quantifier) => {
        it(`should support "${quantifier}" quantifier in aggregate functions`, () => {
            const sql = `SELECT COUNT(${quantifier} t.id) FROM t`;
            assert.equal(getParsedSql(sql), `SELECT COUNT(${quantifier.toUpperCase()} "t"."id") FROM "t"`);
        });
    });

    it('should throw an exception for undefined values', () => {
        // @florajs/datasource-mysql uses plain values instead of equivalent expressions, so expressions
        // have to be created by SQL parser
        assert.throws(() => util.createBinaryExpr('=', { type: 'column_ref', table: null, column: 'id' }, undefined), {
            name: 'ImplementationError'
        });
    });

    describe('case', () => {
        it('should support case-when', () => {
            const sql = `select case when 1 then 'one' when 2 then 'two' END`;
            assert.equal(getParsedSql(sql), `SELECT CASE WHEN 1 THEN 'one' WHEN 2 THEN 'two' END`);
        });

        it('should support case-when-else', () => {
            const sql = `select case FUNC(a) when 1 then 'one' when 2 then 'two' else 'more' END FROM t`;
            assert.equal(
                getParsedSql(sql),
                `SELECT CASE FUNC("a") WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'more' END FROM "t"`
            );
        });
    });

    describe('casts', () => {
        Object.entries({
            'simple casts': ['SELECT CAST(col AS CHAR) FROM t', 'SELECT CAST("col" AS CHAR) FROM "t"'],
            'signed integer casts': [
                'SELECT CAST(col as unsigned integer) FROM t',
                'SELECT CAST("col" AS UNSIGNED INTEGER) FROM "t"'
            ],
            'simple decimal casts': ['SELECT CAST(col AS DECIMAL) FROM t', 'SELECT CAST("col" AS DECIMAL) FROM "t"'],
            'decimal casts with precision': [
                'SELECT CAST(col AS DECIMAL(4)) FROM t',
                'SELECT CAST("col" AS DECIMAL(4)) FROM "t"'
            ],
            'decimal casts with precision and scale': [
                'SELECT CAST(col AS DECIMAL(6, 2)) FROM t',
                'SELECT CAST("col" AS DECIMAL(6, 2)) FROM "t"'
            ],
            'json casts': [
                `SELECT CAST('{"foo":"bar"}' AS JSON) FROM dual`,
                `SELECT CAST('{\\"foo\\":\\"bar\\"}' AS JSON) FROM "dual"`
            ]
        }).forEach(([cast, [inputQuery, expectedQuery]]) => {
            it(`should support ${cast}`, () => {
                assert.equal(getParsedSql(inputQuery), expectedQuery);
            });
        });
    });

    describe('functions', () => {
        it('should support functions', () => {
            const sql = `SELECT md5('foo')`;
            assert.equal(getParsedSql(sql), sql);
        });

        it('should support if function', () => {
            assert.equal(
                getParsedSql(`SELECT IF(col1 = 'xyz', 'foo', 'bar') FROM t`),
                `SELECT IF("col1" = 'xyz', 'foo', 'bar') FROM "t"`
            );
        });
    });
});


================================================
FILE: test/ast2sql/from.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('from clause', () => {
    it('should support subselects in FROM clause', () => {
        assert.equal(
            getParsedSql('SELECT * FROM (SELECT id FROM t1) AS someAlias'),
            'SELECT * FROM (SELECT "id" FROM "t1") AS "someAlias"'
        );
    });

    it('should parse DUAL table', () => {
        const sql = `SELECT "id" FROM DUAL`;
        assert.equal(getParsedSql(sql), sql);
    });

    describe('table value expressions', () => {
        it('should support expressions with single values', () => {
            assert.equal(
                getParsedSql('SELECT id FROM (VALUES (1), (2)) t(id)'),
                'SELECT "id" FROM (VALUES (1), (2)) AS "t" ("id")'
            );
        });

        it('should support expressions with multiple values', () => {
            assert.equal(
                getParsedSql('SELECT id FROM (VALUES (1, 2), (3, 4)) t(id)'),
                'SELECT "id" FROM (VALUES (1,2), (3,4)) AS "t" ("id")'
            );
        });

        it('should support expressions with ROW keyword', () => {
            assert.equal(
                getParsedSql('SELECT id1, id2 FROM (VALUES ROW(1, 2), ROW(3, 4)) t(id1, id2)'),
                'SELECT "id1", "id2" FROM (VALUES ROW(1,2), ROW(3,4)) AS "t" ("id1", "id2")'
            );
        });
    });

    describe('JSON_TABLE', () => {
        it('should support JSON_TABLE in FROM clause', () => {
            assert.equal(
                getParsedSql(`SELECT jt.id FROM JSON_TABLE('[{"id":1}]', '$[*]' COLUMNS (id INT PATH '$.id')) AS jt`),
                `SELECT "jt"."id" FROM JSON_TABLE('[{\\"id\\":1}]', '$[*]' COLUMNS ("id" INT PATH '$.id')) AS "jt"`
            );
        });

        it('should support implicit joins', () => {
            assert.equal(
                getParsedSql(`SELECT jt.id FROM t, JSON_TABLE(t.data, '$[*]' COLUMNS (id INT PATH '$.id')) AS jt`),
                `SELECT "jt"."id" FROM "t", JSON_TABLE("t"."data", '$[*]' COLUMNS ("id" INT PATH '$.id')) AS "jt"`
            );
        });

        it('should support JSON_TABLE in joins', () => {
            assert.equal(
                getParsedSql(
                    `SELECT jt.id FROM t JOIN JSON_TABLE('[{"id":1}]', '$[*]' COLUMNS (id INT PATH '$.id')) AS jt ON t.id = jt.id`
                ),
                `SELECT "jt"."id" FROM "t" INNER JOIN JSON_TABLE('[{\\"id\\":1}]', '$[*]' COLUMNS ("id" INT PATH '$.id')) AS "jt" ON "t"."id" = "jt"."id"`
            );
        });

        describe('columns', () => {
            it('should support multiple columns', () => {
                assert.equal(
                    getParsedSql(
                        `SELECT jt.id, jt.foo FROM JSON_TABLE('[{"id":1,"foo":"bar"}]', '$[*]' COLUMNS (id INT PATH '$.id', foo VARCHAR(5) PATH '$.foo')) AS jt`
                    ),
                    `SELECT "jt"."id", "jt"."foo" FROM JSON_TABLE('[{\\"id\\":1,\\"foo\\":\\"bar\\"}]', '$[*]' COLUMNS ("id" INT PATH '$.id', "foo" VARCHAR(5) PATH '$.foo')) AS "jt"`
                );
            });

            it('should support ordinality column', () => {
                assert.equal(
                    getParsedSql(
                        `SELECT jt.id, jt.foo FROM JSON_TABLE('[{"foo":"bar"}]', '$[*]' COLUMNS (id FOR ORDINALITY, foo VARCHAR(5) PATH '$.foo')) AS jt`
                    ),
                    `SELECT "jt"."id", "jt"."foo" FROM JSON_TABLE('[{\\"foo\\":\\"bar\\"}]', '$[*]' COLUMNS ("id" FOR ORDINALITY, "foo" VARCHAR(5) PATH '$.foo')) AS "jt"`
                );
            });

            it('should support EXISTS keyword for paths', () => {
                assert.equal(
                    getParsedSql(
                        `SELECT jt.foo, jt.bar FROM JSON_TABLE('[{"foo":"bar"}]', '$[*]' COLUMNS (foo VARCHAR(5) PATH '$.foo', bar INT EXISTS PATH '$.bar')) AS jt`
                    ),
                    `SELECT "jt"."foo", "jt"."bar" FROM JSON_TABLE('[{\\"foo\\":\\"bar\\"}]', '$[*]' COLUMNS ("foo" VARCHAR(5) PATH '$.foo', "bar" INT EXISTS PATH '$.bar')) AS "jt"`
                );
            });

            it('should support nested columns', () => {
                assert.equal(
                    getParsedSql(`
                        SELECT *
                        FROM JSON_TABLE(
                            '[{"id":1,"name":"Alice","projects":[{"title":"Project A"}]}]',
                            '$[*]' COLUMNS (
                                user_id INT PATH '$.id',
                                user_name VARCHAR(100) PATH '$.name',
                                NESTED PATH '$.projects[*]' COLUMNS (
                                    project_title VARCHAR(100) PATH '$.title'
                                )
                            )
                        ) AS jt
                    `),
                    `SELECT * FROM JSON_TABLE('[{\\"id\\":1,\\"name\\":\\"Alice\\",\\"projects\\":[{\\"title\\":\\"Project A\\"}]}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_name" VARCHAR(100) PATH '$.name', NESTED PATH '$.projects[*]' COLUMNS ("project_title" VARCHAR(100) PATH '$.title'))) AS "jt"`
                );
            });

            it('should support deeply nested columns', () => {
                assert.equal(
                    getParsedSql(`
                        SELECT *
                        FROM JSON_TABLE(
                            '[{"id":1,"name":"Alice","projects":[{"title":"Project A","tasks":[{"description":"Design","status":"done"},{"description":"Build","status":"in progress"}]}]}]',
                            '$[*]' COLUMNS (
                                user_id INT PATH '$.id',
                                user_name VARCHAR(100) PATH '$.name',
                                NESTED PATH '$.projects[*]' COLUMNS (
                                    project_title VARCHAR(100) PATH '$.title',
                                    NESTED PATH '$.tasks[*]' COLUMNS (
                                        task_desc VARCHAR(100) PATH '$.description',
                                        task_status VARCHAR(50) PATH '$.status'
                                    )
                                )
                            )
                       ) AS jt
                    `),
                    `SELECT * FROM JSON_TABLE('[{\\"id\\":1,\\"name\\":\\"Alice\\",\\"projects\\":[{\\"title\\":\\"Project A\\",\\"tasks\\":[{\\"description\\":\\"Design\\",\\"status\\":\\"done\\"},{\\"description\\":\\"Build\\",\\"status\\":\\"in progress\\"}]}]}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_name" VARCHAR(100) PATH '$.name', NESTED PATH '$.projects[*]' COLUMNS ("project_title" VARCHAR(100) PATH '$.title', NESTED PATH '$.tasks[*]' COLUMNS ("task_desc" VARCHAR(100) PATH '$.description', "task_status" VARCHAR(50) PATH '$.status')))) AS "jt"`
                );
            });

            describe('ON EMPTY', () => {
                it('should handle NULL', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_name VARCHAR(100) PATH '$.name' NULL ON EMPTY
                                )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_name" VARCHAR(100) PATH '$.name' NULL ON EMPTY)) AS "jt"`
                    );
                });

                it('should handle DEFAULT', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_name VARCHAR(100) PATH '$.name' DEFAULT '"not available"' ON EMPTY
                                )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_name" VARCHAR(100) PATH '$.name' DEFAULT '\\"not available\\"' ON EMPTY)) AS "jt"`
                    );
                });

                it('should handle ERROR', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_name VARCHAR(100) PATH '$.name' ERROR ON EMPTY
                                )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_name" VARCHAR(100) PATH '$.name' ERROR ON EMPTY)) AS "jt"`
                    );
                });
            });

            describe('ON ERROR', () => {
                it('should handle NULL', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1,"age":"abc"}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_age INT PATH '$.age' NULL ON ERROR
                               )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1,\\"age\\":\\"abc\\"}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_age" INT PATH '$.age' NULL ON ERROR)) AS "jt"`
                    );
                });

                it('should handle DEFAULT', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1,"age":"abc"}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_age INT PATH '$.age' DEFAULT '99' ON ERROR
                                )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1,\\"age\\":\\"abc\\"}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_age" INT PATH '$.age' DEFAULT '99' ON ERROR)) AS "jt"`
                    );
                });

                it('should handle ERROR', () => {
                    assert.equal(
                        getParsedSql(`
                            SELECT *
                            FROM JSON_TABLE(
                                '[{"id":1,"age":"abc"}]',
                                '$[*]' COLUMNS (
                                    user_id INT PATH '$.id',
                                    user_age INT PATH '$.age' ERROR ON ERROR
                                )
                           ) AS jt
                        `),
                        `SELECT * FROM JSON_TABLE('[{\\"id\\":1,\\"age\\":\\"abc\\"}]', '$[*]' COLUMNS ("user_id" INT PATH '$.id', "user_age" INT PATH '$.age' ERROR ON ERROR)) AS "jt"`
                    );
                });
            });
        });
    });
});


================================================
FILE: test/ast2sql/groupby.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser, util } = require('../../');
const { getParsedSql } = require('./util');

describe('group clause', () => {
    it('should support single expressions', () => {
        assert.equal(getParsedSql('SELECT a FROM t group by t.b'), 'SELECT "a" FROM "t" GROUP BY "t"."b"');
    });

    it('should support multiple expressions', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t GROUP BY t.b, t.c'),
            'SELECT "a" FROM "t" GROUP BY "t"."b", "t"."c"'
        );
    });

    it('should not generate an empty GROUP BY clause on empty arrays', () => {
        const ast = new Parser().parse('SELECT a FROM t');
        ast.groupby = [];
        assert.equal(util.astToSQL(ast), 'SELECT "a" FROM "t"');
    });
});


================================================
FILE: test/ast2sql/having.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('having clause', () => {
    it('should support simple expressions', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t GROUP BY t.b having COUNT(*) > 1'),
            'SELECT "a" FROM "t" GROUP BY "t"."b" HAVING COUNT(*) > 1'
        );
    });

    it('should support complex expressions', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t GROUP BY t.b HAVING COUNT(*) > (SELECT 10)'),
            'SELECT "a" FROM "t" GROUP BY "t"."b" HAVING COUNT(*) > (SELECT 10)'
        );
    });
});


================================================
FILE: test/ast2sql/join.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('joins', () => {
    it('should support implicit joins', () => {
        assert.equal(getParsedSql('SELECT a.col , b.c FROM a ,b'), 'SELECT "a"."col", "b"."c" FROM "a", "b"');
    });

    it('should support (INNER) JOINs', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t1 join t2 on t1.t2id = t2.t1id'),
            'SELECT "a" FROM "t1" INNER JOIN "t2" ON "t1"."t2id" = "t2"."t1id"'
        );
    });

    it('should support LEFT JOINs', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t1 left join t2 on t1.t2id = t2.t1id'),
            'SELECT "a" FROM "t1" LEFT JOIN "t2" ON "t1"."t2id" = "t2"."t1id"'
        );
    });

    it('should support RIGHT JOINs', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t1 right join t2 on t1.t2id = t2.t1id'),
            'SELECT "a" FROM "t1" RIGHT JOIN "t2" ON "t1"."t2id" = "t2"."t1id"'
        );
    });

    it('should support FULL JOINs', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t1 full join t2 on t1.t2id = t2.t1id'),
            'SELECT "a" FROM "t1" FULL JOIN "t2" ON "t1"."t2id" = "t2"."t1id"'
        );
    });

    it('should support multiple joins', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t1 LEFT JOIN t2 ON t1.t2id = t2.t1id INNER JOIN t3 ON t1.t3id = t3.t1id'),
            'SELECT "a" FROM "t1" LEFT JOIN "t2" ON "t1"."t2id" = "t2"."t1id" INNER JOIN "t3" ON "t1"."t3id" = "t3"."t1id"'
        );
    });

    it('should support alias for base table', () => {
        assert.equal(getParsedSql('SELECT col1 FROM awesome_table t'), 'SELECT "col1" FROM "awesome_table" AS "t"');
    });

    it('should support joins with tables from other databases', () => {
        assert.equal(
            getParsedSql('SELECT col1 FROM t JOIN otherdb.awesome_table at ON t.id = at.tid'),
            'SELECT "col1" FROM "t" INNER JOIN otherdb."awesome_table" AS "at" ON "t"."id" = "at"."tid"'
        );
    });

    it('should support aliases in joins', () => {
        assert.equal(
            getParsedSql('SELECT col1 FROM t1 LEFT JOIN awesome_table AS t2 ON t1.id = t2.t1id'),
            'SELECT "col1" FROM "t1" LEFT JOIN "awesome_table" AS "t2" ON "t1"."id" = "t2"."t1id"'
        );
    });

    it('should support joined subquery', () => {
        assert.equal(
            getParsedSql('SELECT * FROM t1 LEFT JOIN (SELECT id, col1 FROM t2) AS someAlias ON t1.id = someAlias.id'),
            'SELECT * FROM "t1" LEFT JOIN (SELECT "id", "col1" FROM "t2") AS "someAlias" ON "t1"."id" = "someAlias"."id"'
        );
    });

    it('should support USING keyword (single column)', () => {
        assert.equal(
            getParsedSql('SELECT * FROM t1 JOIN t2 USING (id)'),
            'SELECT * FROM "t1" INNER JOIN "t2" USING ("id")'
        );
    });

    it('should support USING keyword (multiple columns)', () => {
        assert.equal(
            getParsedSql('SELECT * FROM t1 JOIN t2 USING (id1, id2)'),
            'SELECT * FROM "t1" INNER JOIN "t2" USING ("id1", "id2")'
        );
    });

    it('should support LATERAL joins', () => {
        assert.equal(
            getParsedSql('SELECT * FROM t1 join lateral (SELECT id FROM t2 WHERE t1.id = t2.t1id) alias ON true'),
            'SELECT * FROM "t1" INNER JOIN LATERAL (SELECT "id" FROM "t2" WHERE "t1"."id" = "t2"."t1id") AS "alias" ON TRUE'
        );
    });

    describe('derived table columns', () => {
        it('should support single column in "base table"', () => {
            assert.equal(getParsedSql('SELECT id FROM (SELECT 1) t (id)'), 'SELECT "id" FROM (SELECT 1) AS "t" ("id")');
        });

        it('should parse multiple columns in "base table"', () => {
            assert.equal(
                getParsedSql('SELECT id1, id2 FROM (SELECT 1, 2) t (id1, id2)'),
                'SELECT "id1", "id2" FROM (SELECT 1, 2) AS "t" ("id1", "id2")'
            );
        });

        it('should support single column in joins', () => {
            assert.equal(
                getParsedSql('SELECT id FROM t1 JOIN (SELECT 1) t2 (id) ON TRUE'),
                'SELECT "id" FROM "t1" INNER JOIN (SELECT 1) AS "t2" ("id") ON TRUE'
            );
        });

        it('should support multiple columns in joins', () => {
            assert.equal(
                getParsedSql('SELECT id1, id2 FROM t1 JOIN (SELECT 1, 2) t2 (id1, id2) ON TRUE'),
                'SELECT "id1", "id2" FROM "t1" INNER JOIN (SELECT 1, 2) AS "t2" ("id1", "id2") ON TRUE'
            );
        });
    });
});


================================================
FILE: test/ast2sql/limit.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('limit clause', () => {
    it('should work w/o offset', () => {
        assert.equal(getParsedSql('SELECT a FROM t limit 10'), 'SELECT "a" FROM "t" LIMIT 0,10');
    });

    it('should work w/ offset', () => {
        assert.equal(getParsedSql('SELECT a FROM t limit 10, 10'), 'SELECT "a" FROM "t" LIMIT 10,10');
    });
});


================================================
FILE: test/ast2sql/literal.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('literals', () => {
    it('should support string values', () => {
        const sql = `SELECT 'foo'`;
        assert.equal(getParsedSql(sql), `SELECT 'foo'`);
    });

    it('should support null values', () => {
        const sql = 'SELECT null';
        assert.equal(getParsedSql(sql), 'SELECT NULL');
    });

    it('should support trailing zeros', () => {
        assert.equal(getParsedSql('SELECT 042'), 'SELECT 42');
        assert.equal(getParsedSql('SELECT -042'), 'SELECT -42');
    });

    describe('datetime', () => {
        Object.entries({
            time: '08:23:16',
            date: '1999-12-25',
            timestamp: '1999-12-25 08:23:16'
        }).forEach(([type, value]) => {
            it(type, () => {
                const sql = `SELECT ${type} '${value}'`;
                assert.equal(getParsedSql(sql), `SELECT ${type.toUpperCase()} '${value}'`);
            });
        });
    });

    describe('interval', () => {
        it('should parse simple INTERVAL', () => {
            const sql = 'SELECT NOW() + INTERVAL 1 DAY FROM DUAL';
            assert.equal(getParsedSql(sql), `SELECT NOW() + INTERVAL '1' DAY FROM DUAL`);
        });

        it('should parse string INTERVAL', () => {
            const sql = `SELECT NOW() + INTERVAL '1' DAY FROM DUAL`;
            assert.equal(getParsedSql(sql), sql);
        });

        it('should parse signed INTERVAL', () => {
            const sql = `SELECT NOW() + INTERVAL - '1' DAY FROM DUAL`;
            assert.equal(getParsedSql(sql), sql);
        });
    });
});


================================================
FILE: test/ast2sql/mysql.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('MySQL', () => {
    it('should support query options', () => {
        assert.equal(
            getParsedSql('SELECT SQL_CALC_FOUND_ROWS SQL_BUFFER_RESULT col1 FROM t'),
            'SELECT SQL_CALC_FOUND_ROWS SQL_BUFFER_RESULT "col1" FROM "t"'
        );
    });
});


================================================
FILE: test/ast2sql/order.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser, util } = require('../../');
const { getParsedSql } = require('./util');

describe('order clause', () => {
    it('should support implicit sort order', () => {
        assert.equal(getParsedSql('SELECT a FROM t order by id'), 'SELECT "a" FROM "t" ORDER BY "id" ASC');
    });

    it('should support explicit sort order', () => {
        assert.equal(getParsedSql('SELECT a FROM t order by id desc'), 'SELECT "a" FROM "t" ORDER BY "id" DESC');
    });

    it('should support multiple expressions', () => {
        assert.equal(
            getParsedSql('SELECT a FROM t order by id desc, name asc'),
            'SELECT "a" FROM "t" ORDER BY "id" DESC, "name" ASC'
        );
    });

    it('should support complex expressions', () => {
        assert.equal(getParsedSql('SELECT a FROM t ORDER BY rand() ASC'), 'SELECT "a" FROM "t" ORDER BY rand() ASC');
    });

    it('should not generate an empty ORDER BY clause on empty arrays', () => {
        const ast = new Parser().parse('SELECT a FROM t');
        ast.orderby = [];
        assert.equal(util.astToSQL(ast), 'SELECT "a" FROM "t"');
    });
});


================================================
FILE: test/ast2sql/select.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { getParsedSql } = require('./util');

describe('select', () => {
    it('should parse ANSI SQL compliant statements', () => {
        const sql = `SELECT "id", 'foo' AS "type" FROM "table"`;
        assert.equal(getParsedSql(sql), sql);
    });

    describe('union operator', () => {
        it('should combine multiple statements', () => {
            assert.equal(
                getParsedSql(`select 1 union select '1' union select a from t union (select true)`),
                `SELECT 1 UNION SELECT '1' UNION SELECT "a" FROM "t" UNION SELECT TRUE`
            );
        });

        it('should be supported in expressions', () => {
            const sql = `select * from (select 1 union select 2) t`;
            assert.equal(getParsedSql(sql), `SELECT * FROM (SELECT 1 UNION SELECT 2) AS "t"`);
        });
    });

    describe('unsupported statements', () => {
        const unsupportedStatements = {
            insert: 'INSERT INTO t (col1, col2) VALUES (1, 2)',
            update: 'UPDATE t SET col1 = 5 WHERE id = 1337'
        };

        Object.keys(unsupportedStatements).forEach((stmtType) => {
            it(`should throw exception for ${stmtType} statements`, () => {
                assert.throws(() => getParsedSql(unsupportedStatements[stmtType]), {
                    name: 'Error',
                    message: 'Only SELECT statements supported at the moment'
                });
            });
        });
    });
});


================================================
FILE: test/ast2sql/util.js
================================================
'use strict';

const { Parser, util } = require('../../');
const parser = new Parser();

module.exports = {
    getParsedSql: function (sql) {
        const ast = parser.parse(sql);
        return util.astToSQL(ast);
    }
};


================================================
FILE: test/ast2sql/where.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { util } = require('../../');
const { getParsedSql } = require('./util');

describe('where clause', () => {
    ['<', '<=', '=', '!=', '>=', '>'].forEach((operator) => {
        it(`should support simple "${operator}" comparison`, () => {
            const sql = `SELECT a fRom db.t wHERE "type" ${operator} 3`;
            assert.equal(getParsedSql(sql), `SELECT "a" FROM db."t" WHERE "type" ${operator} 3`);
        });
    });

    const operatorMap = { '=': 'IN', '!=': 'NOT IN' };
    Object.keys(operatorMap).forEach((operator) => {
        const sqlOperator = operatorMap[operator];

        it(`should convert "${operator}" to ${sqlOperator} operator for array values`, () => {
            const ast = {
                type: 'select',
                options: null,
                distinct: null,
                columns: [{ expr: { type: 'column_ref', table: null, column: 'a' }, as: null }],
                from: [{ db: null, table: 't', as: null }],
                where: {
                    type: 'binary_expr',
                    operator: operator,
                    left: { type: 'column_ref', table: null, column: 'id' },
                    right: {
                        type: 'expr_list',
                        value: [
                            { type: 'number', value: 1 },
                            { type: 'number', value: 2 }
                        ]
                    }
                },
                groupby: null,
                limit: null
            };

            assert.equal(util.astToSQL(ast), `SELECT "a" FROM "t" WHERE "id" ${sqlOperator} (1, 2)`);
        });
    });

    ['IN', 'NOT IN'].forEach((operator) => {
        it(`should support ${operator} operator`, () => {
            const sql = `SELECT a FROM t WHERE id ${operator.toLowerCase()} (1, 2, 3)`;
            assert.equal(getParsedSql(sql), `SELECT "a" FROM "t" WHERE "id" ${operator} (1, 2, 3)`);
        });
    });

    ['IS', 'IS NOT'].forEach((operator) => {
        it(`should support ${operator} operator`, () => {
            const sql = `SELECT a FROM t WHERE col ${operator.toLowerCase()} NULL`;
            assert.equal(getParsedSql(sql), `SELECT "a" FROM "t" WHERE "col" ${operator} NULL`);
        });
    });

    it('should support query param values', () => {
        const sql = 'SELECT * FROM t where t.a > :my_param';
        assert.equal(getParsedSql(sql), 'SELECT * FROM "t" WHERE "t"."a" > :my_param');
    });

    ['BETWEEN', 'NOT BETWEEN'].forEach((operator) => {
        it(`should support ${operator} operator`, () => {
            const sql = `SELECT a FROM t WHERE id ${operator.toLowerCase()} '1' and 1337`;
            assert.equal(getParsedSql(sql), `SELECT "a" FROM "t" WHERE "id" ${operator} '1' AND 1337`);
        });
    });

    it('should support boolean values', () => {
        const sql = 'SELECT col1 FROM t WHERE col2 = false';
        assert.equal(getParsedSql(sql), 'SELECT "col1" FROM "t" WHERE "col2" = FALSE');
    });

    it('should support string values', () => {
        assert.equal(
            getParsedSql(`SELECT col1 FROM t WHERE col2 = 'foobar'`),
            `SELECT "col1" FROM "t" WHERE "col2" = 'foobar'`
        );
    });

    it('should support null values', () => {
        assert.equal(
            getParsedSql('SELECT col1 FROM t WHERE col2 IS NULL'),
            'SELECT "col1" FROM "t" WHERE "col2" IS NULL'
        );
    });

    it('should support array values', () => {
        assert.equal(
            getParsedSql('SELECT col1 FROM t WHERE col2 IN (1, 3, 5, 7)'),
            'SELECT "col1" FROM "t" WHERE "col2" IN (1, 3, 5, 7)'
        );
    });

    ['EXISTS', 'NOT EXISTS'].forEach((operator) => {
        it(`should support ${operator} operator`, () => {
            assert.equal(
                getParsedSql(`SELECT a FROM t WHERE ${operator} (SELECT 1)`),
                `SELECT "a" FROM "t" WHERE ${operator} (SELECT 1)`
            );
        });
    });

    it('should support row value constructors', () => {
        assert.equal(
            getParsedSql(`SELECT * FROM "user" WHERE (firstname, lastname) = ('John', 'Doe')`),
            `SELECT * FROM "user" WHERE ("firstname","lastname") = ('John','Doe')`
        );
    });
});


================================================
FILE: test/sql2ast/column.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('column clause', () => {
    const parser = new Parser();
    let ast;

    it('should parse "*" shorthand', () => {
        ast = parser.parse('SELECT * FROM t');
        assert.equal(ast.columns, '*');
    });

    it('should parse "table.*" column expressions', () => {
        ast = parser.parse('SELECT t.* FROM t');

        assert.deepEqual(ast.columns, [{ expr: { type: 'column_ref', table: 't', column: '*' }, as: null }]);
    });

    it('should parse aliases w/o "AS" keyword', () => {
        ast = parser.parse('SELECT a aa FROM  t');

        assert.deepEqual(ast.columns, [{ expr: { type: 'column_ref', table: null, column: 'a' }, as: 'aa' }]);
    });

    it('should parse aliases w/ "AS" keyword', () => {
        ast = parser.parse('SELECT b.c as bc FROM t');

        assert.deepEqual(ast.columns, [{ expr: { type: 'column_ref', table: 'b', column: 'c' }, as: 'bc' }]);
    });

    it('should parse multiple columns', () => {
        ast = parser.parse('SELECT b.c as bc, 1+3 FROM t');

        assert.deepEqual(ast.columns, [
            { expr: { type: 'column_ref', table: 'b', column: 'c' }, as: 'bc' },
            {
                expr: {
                    type: 'binary_expr',
                    operator: '+',
                    left: { type: 'number', value: 1 },
                    right: { type: 'number', value: 3 }
                },
                as: null
            }
        ]);
    });

    describe('aggregate functions', () => {
        it('should parse COUNT(*)', () => {
            ast = parser.parse('SELECT COUNT(*) FROM t');

            assert.deepEqual(ast.columns, [
                {
                    expr: {
                        type: 'aggr_func',
                        name: 'COUNT',
                        args: {
                            expr: {
                                type: 'star',
                                value: '*'
                            }
                        }
                    },
                    as: null
                }
            ]);
        });

        ['avg', 'count', 'group_concat', 'max', 'min', 'sum'].forEach((aggrFunction) => {
            it(`should parse ${aggrFunction.toUpperCase()} function`, () => {
                ast = parser.parse(`SELECT ${aggrFunction}(col) FROM t`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'aggr_func',
                            name: aggrFunction.toUpperCase(),
                            quantifier: null,
                            args: {
                                expr: {
                                    type: 'column_ref',
                                    table: null,
                                    column: 'col'
                                }
                            }
                        },
                        as: null
                    }
                ]);
            });
        });

        ['DISTINCT', 'ALL'].forEach((quantifier) => {
            it(`should parse ${quantifier} quantifier`, () => {
                ast = parser.parse(`SELECT GROUP_CONCAT(${quantifier} col) FROM t`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'aggr_func',
                            name: 'GROUP_CONCAT',
                            quantifier,
                            args: {
                                expr: {
                                    type: 'column_ref',
                                    table: null,
                                    column: 'col'
                                }
                            }
                        },
                        as: null
                    }
                ]);
            });
        });
    });
});


================================================
FILE: test/sql2ast/cte.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('common table expressions', () => {
    const parser = new Parser();

    it('should parse single CTE', () => {
        const ast = parser.parse(
            `
            WITH cte AS (SELECT 1)
            SELECT * FROM cte
        `.trim()
        );

        assert.ok(typeof ast.with === 'object');

        const { with: cte } = ast;
        assert.ok(Object.hasOwn(cte, 'type'));
        assert.equal(cte.type, 'with');

        assert.ok(Object.hasOwn(cte, 'value'));
        assert.ok(Array.isArray(cte.value));
        assert.equal(cte.value.length, 1);

        const [withListElement] = cte.value;
        assert.ok(Object.hasOwn(withListElement, 'name'));
        assert.equal(withListElement.name, 'cte');
        assert.ok(Object.hasOwn(withListElement, 'columns'));
        assert.equal(withListElement.columns, null);
        assert.ok(Object.hasOwn(withListElement, 'stmt'));
        assert.ok(typeof withListElement.stmt === 'object');
        assert.ok(Object.hasOwn(withListElement.stmt, 'type'));
        assert.equal(withListElement.stmt.type, 'select');
    });

    it('should parse multiple CTEs', () => {
        const ast = parser.parse(
            `
            WITH cte1 AS (SELECT 1), cte2 AS (SELECT 2)
            SELECT * FROM cte1 UNION SELECT * FROM cte2
        `.trim()
        );

        assert.ok(Object.hasOwn(ast.with, 'value'));
        assert.ok(Array.isArray(ast.with.value));
        assert.equal(ast.with.value.length, 2);

        const [cte1, cte2] = ast.with.value;
        assert.ok(Object.hasOwn(cte1, 'name'));
        assert.equal(cte1.name, 'cte1');
        assert.ok(Object.hasOwn(cte2, 'name'));
        assert.equal(cte2.name, 'cte2');
    });

    it('should parse CTE with column', () => {
        const ast = parser.parse(
            `
            WITH cte (col1) AS (SELECT 1)
            SELECT * FROM cte
        `.trim()
        );

        const [cte] = ast.with.value;
        assert.ok(Object.hasOwn(cte, 'columns'));
        assert.deepEqual(cte.columns, ['col1']);
    });

    it('should parse CTE with multiple columns', () => {
        const ast = parser.parse(
            `
            WITH cte (col1, col2) AS (SELECT 1, 2)
            SELECT * FROM cte
        `.trim()
        );

        const [cte] = ast.with.value;
        assert.deepEqual(cte.columns, ['col1', 'col2']);
    });

    it('should parse recursive CTE', () => {
        const ast = parser.parse(
            `
            WITH RECURSIVE cte(n) AS
            (
                SELECT 1
                UNION
                SELECT n + 1 FROM cte WHERE n < 5
            )
            SELECT * FROM cte
        `.trim()
        );

        assert.ok(Object.hasOwn(ast.with, 'recursive'));
        assert.equal(ast.with.recursive, true);
    });
});


================================================
FILE: test/sql2ast/expr.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('expressions', () => {
    const parser = new Parser();

    describe('function', () => {
        it('should parse functions', () => {
            const ast = parser.parse('SELECT fun(d) FROM t');

            assert.deepEqual(ast.columns, [
                {
                    expr: {
                        type: 'function',
                        name: 'fun',
                        args: {
                            type: 'expr_list',
                            value: [{ type: 'column_ref', table: null, column: 'd' }]
                        }
                    },
                    as: null
                }
            ]);
        });

        ['year', 'month', 'day', 'hour', 'minute'].forEach((fn) => {
            it(`should parse ${fn} date function expression`, () => {
                const ast = parser.parse(`SELECT ${fn}(NOW()) FROM dual`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'function',
                            name: fn.toUpperCase(),
                            args: {
                                type: 'expr_list',
                                value: [
                                    {
                                        type: 'function',
                                        name: 'NOW',
                                        args: { type: 'expr_list', value: [] }
                                    }
                                ]
                            }
                        },
                        as: null
                    }
                ]);
            });
        });

        [
            'CURRENT_DATE',
            'CURRENT_TIME',
            'CURRENT_TIMESTAMP',
            'CURRENT_USER',
            'SESSION_USER',
            'USER',
            'SYSTEM_USER'
        ].forEach((func) => {
            it(`should parse scalar function ${func}`, () => {
                const ast = parser.parse(`SELECT ${func} FROM t`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'function',
                            name: func,
                            args: {
                                type: 'expr_list',
                                value: []
                            }
                        },
                        as: null
                    }
                ]);
            });
        });
    });
});


================================================
FILE: test/sql2ast/from.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('from clause', () => {
    const parser = new Parser();

    it('should parse single table', () => {
        const ast = parser.parse('SELECT * FROM t');
        assert.deepEqual(ast.from, [{ db: null, table: 't', as: null }]);
    });

    it('should parse tables from other databases', () => {
        const ast = parser.parse('SELECT * FROM u.t');
        assert.deepEqual(ast.from, [{ db: 'u', table: 't', as: null }]);
    });

    it('should parse tables from other databases (ANSI identifier)', () => {
        const ast = parser.parse('SELECT * FROM "u"."t"');
        assert.deepEqual(ast.from, [{ db: 'u', table: 't', as: null }]);
    });

    it('should parse subselect', () => {
        const ast = parser.parse('SELECT * FROM (SELECT id FROM t1) someAlias');

        assert.deepEqual(ast.from, [
            {
                expr: {
                    with: null,
                    type: 'select',
                    options: null,
                    distinct: null,
                    from: [{ db: null, table: 't1', as: null }],
                    columns: [{ expr: { type: 'column_ref', table: null, column: 'id' }, as: null }],
                    where: null,
                    groupby: null,
                    having: null,
                    orderby: null,
                    limit: null,
                    parentheses: true
                },
                as: 'someAlias',
                lateral: false,
                columns: null
            }
        ]);
    });

    it('should parse DUAL table', () => {
        const ast = parser.parse('SELECT * FROM DUAL');
        assert.deepEqual(ast.from, [{ type: 'dual' }]);
    });

    describe('values', () => {
        it('should parse table constructors with single value row value constructors', () => {
            const ast = parser.parse('SELECT id FROM (VALUES (1), (2)) t (id)');

            assert.deepEqual(ast.from, [
                {
                    expr: {
                        type: 'values',
                        value: [
                            {
                                type: 'row_value',
                                keyword: false,
                                value: [{ type: 'number', value: 1 }]
                            },
                            {
                                type: 'row_value',
                                keyword: false,
                                value: [{ type: 'number', value: 2 }]
                            }
                        ]
                    },
                    as: 't',
                    columns: ['id']
                }
            ]);
        });

        it('should parse table constructors with multi value row value constructors', () => {
            const ast = parser.parse('SELECT id1, id2 FROM (VALUES (1, 2), (3, 4)) t (id1, id2)');

            assert.deepEqual(ast.from, [
                {
                    expr: {
                        type: 'values',
                        value: [
                            {
                                type: 'row_value',
                                keyword: false,
                                value: [
                                    { type: 'number', value: 1 },
                                    { type: 'number', value: 2 }
                                ]
                            },
                            {
                                type: 'row_value',
                                keyword: false,
                                value: [
                                    { type: 'number', value: 3 },
                                    { type: 'number', value: 4 }
                                ]
                            }
                        ]
                    },
                    as: 't',
                    columns: ['id1', 'id2']
                }
            ]);
        });

        it('should parse table constructors with ROW keyword row value constructors', () => {
            const ast = parser.parse('SELECT * FROM (VALUES ROW(1, 2), ROW(3, 4)) t');

            assert.deepEqual(ast.from, [
                {
                    expr: {
                        type: 'values',
                        value: [
                            {
                                type: 'row_value',
                                keyword: true,
                                value: [
                                    { type: 'number', value: 1 },
                                    { type: 'number', value: 2 }
                                ]
                            },
                            {
                                type: 'row_value',
                                keyword: true,
                                value: [
                                    { type: 'number', value: 3 },
                                    { type: 'number', value: 4 }
                                ]
                            }
                        ]
                    },
                    as: 't',
                    columns: null
                }
            ]);
        });
    });

    describe('JSON_TABLE', () => {
        it('should parse column list w/ one column', () => {
            const ast = parser.parse(
                `SELECT jt.a FROM JSON_TABLE('[{"a":1},{"a":2}]', '$[*]' COLUMNS (a INT PATH '$.a')) jt`
            );

            assert.deepEqual(ast.from, [
                {
                    type: 'json_table',
                    expr: { type: 'string', value: '[{"a":1},{"a":2}]' },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'a',
                            dataType: { dataType: 'INT' },
                            path: { type: 'string', value: '$.a' }
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        it('should parse column list w/ multiple columns', () => {
            const ast = parser.parse(
                `SELECT jt.a FROM t, JSON_TABLE(t.data, '$[*]' COLUMNS (a INT PATH '$.a', b VARCHAR(10) PATH '$.b')) AS jt`
            );

            assert.deepEqual(ast.from, [
                {
                    table: 't',
                    db: null,
                    as: null
                },
                {
                    type: 'json_table',
                    expr: {
                        type: 'column_ref',
                        column: 'data',
                        table: 't'
                    },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'a',
                            dataType: { dataType: 'INT' },
                            path: { type: 'string', value: '$.a' }
                        },
                        {
                            type: 'json_table_column',
                            name: 'b',
                            dataType: { dataType: 'VARCHAR', length: 10 },
                            path: { type: 'string', value: '$.b' }
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        describe('ON EMPTY', () => {
            it('should parse NULL ON EMPTY', () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {}]', '$[*]' COLUMNS (a INT PATH '$.a' NULL ON EMPTY)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onEmpty: { expr: { type: 'null', value: null } }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });

            it('should parse DEFAULT ON EMPTY', () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {}]', '$[*]' COLUMNS (a INT PATH '$.a' DEFAULT '-1' ON EMPTY)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onEmpty: { default: true, expr: { type: 'string', value: '-1' } }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });

            it('should parse ERROR ON EMPTY', () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {}]', '$[*]' COLUMNS (a INT PATH '$.a' ERROR ON EMPTY)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onEmpty: { error: true }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });
        });

        describe('ON ERROR', () => {
            it('should parse NULL ON ERROR', async () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {"a":"foo"}]', '$[*]' COLUMNS (a INT PATH '$.a' NULL ON ERROR)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {"a":"foo"}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onError: { expr: { type: 'null', value: null } }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });

            it('should parse DEFAULT ON ERROR', () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {"a":"foo"}]', '$[*]' COLUMNS (a INT PATH '$.a' DEFAULT '-1' ON ERROR)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {"a":"foo"}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onError: { default: true, expr: { type: 'string', value: '-1' } }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });

            it('should parse ERROR ON ERROR', () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":1}, {"a":"foo"}]', '$[*]' COLUMNS (a INT PATH '$.a' ERROR ON ERROR)) jt`
                );

                assert.deepEqual(ast.from, [
                    {
                        type: 'json_table',
                        expr: { type: 'string', value: '[{"a":1}, {"a":"foo"}]' },
                        path: { type: 'string', value: '$[*]' },
                        columns: [
                            {
                                type: 'json_table_column',
                                name: 'a',
                                dataType: { dataType: 'INT' },
                                path: { type: 'string', value: '$.a' },
                                onError: { error: true }
                            }
                        ],
                        as: 'jt'
                    }
                ]);
            });
        });

        describe('should parse data types', () => {
            describe('strings', () => {
                ['CHAR', 'VARCHAR'].forEach((type) =>
                    it(`should parse ${type} in COLUMNS`, () => {
                        const ast = parser.parse(
                            `SELECT jt.a FROM JSON_TABLE('[{"a":"foo"}]', '$[*]' COLUMNS (a ${type}(5) PATH '$.a')) jt`
                        );

                        assert.ok(ast);
                    })
                );
            });

            describe('numbers', () => {
                ['INT', 'INTEGER', 'DECIMAL(10, 2)', 'BIGINT'].forEach((type) =>
                    it(`should parse ${type} in COLUMNS`, () => {
                        const ast = parser.parse(
                            `SELECT jt.a FROM JSON_TABLE('[{"a":"1"}]', '$[*]' COLUMNS (a ${type} PATH '$.a')) jt`
                        );

                        assert.ok(ast);
                    })
                );
            });

            describe('date/time', () => {
                ['DATE', 'TIME', 'TIMESTAMP'].forEach((type) =>
                    it(`should parse ${type} in COLUMNS`, () => {
                        const ast = parser.parse(
                            `SELECT jt.a FROM JSON_TABLE('[{"a":"1970-01-01"}]', '$[*]' COLUMNS (a ${type} PATH '$.a')) jt`
                        );

                        assert.ok(ast);
                    })
                );
            });

            it(`should parse BOOL in COLUMNS`, () => {
                const ast = parser.parse(
                    `SELECT jt.a FROM JSON_TABLE('[{"a":true}]', '$[*]' COLUMNS (a BOOL PATH '$.a')) jt`
                );

                assert.ok(ast);
            });
        });

        it('should parse column list w/ ordinality column', () => {
            const ast = parser.parse(
                `SELECT jt.a FROM JSON_TABLE('[{"a":1},{"a":2}]', '$[*]' COLUMNS (id FOR ORDINALITY, a INT PATH '$.a')) jt`
            );

            assert.deepEqual(ast.from, [
                {
                    type: 'json_table',
                    expr: { type: 'string', value: '[{"a":1},{"a":2}]' },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'id',
                            ordinality: true
                        },
                        {
                            type: 'json_table_column',
                            name: 'a',
                            dataType: { dataType: 'INT' },
                            path: { type: 'string', value: '$.a' }
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        it('should parse column list w/ EXISTS PATH column', () => {
            const ast = parser.parse(
                `SELECT jt.a FROM JSON_TABLE('[{"a":1},{"a":2}]', '$[*]' COLUMNS (a INT EXISTS PATH '$.a')) jt`
            );

            assert.deepEqual(ast.from, [
                {
                    type: 'json_table',
                    expr: { type: 'string', value: '[{"a":1},{"a":2}]' },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'a',
                            dataType: { dataType: 'INT' },
                            exists: true,
                            path: { type: 'string', value: '$.a' }
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        it('should parse column list w/ nested columns', () => {
            const ast = parser.parse(
                `SELECT jt.a
                 FROM JSON_TABLE(
                      '[{"a":1,"b":["foo","bar"]},{"a":2,"b":["foobar"]}]',
                      '$[*]' COLUMNS (
                          a INT EXISTS PATH '$.a',
                          NESTED PATH '$.b[*]' COLUMNS (b VARCHAR(10) PATH '$')
                      )
                ) jt`
            );

            assert.deepEqual(ast.from, [
                {
                    type: 'json_table',
                    expr: { type: 'string', value: '[{"a":1,"b":["foo","bar"]},{"a":2,"b":["foobar"]}]' },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'a',
                            dataType: { dataType: 'INT' },
                            exists: true,
                            path: { type: 'string', value: '$.a' }
                        },
                        {
                            type: 'json_table_column',
                            nested: true,
                            path: { type: 'string', value: '$.b[*]' },
                            columns: [
                                {
                                    type: 'json_table_column',
                                    name: 'b',
                                    dataType: { dataType: 'VARCHAR', length: 10 },
                                    path: { type: 'string', value: '$' }
                                }
                            ]
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        it('should parse column list w/ deeply nested columns', () => {
            const ast = parser.parse(
                `SELECT jt.id, jt.name, jt.project_title, jt.task_desc, jt.task_status
                 FROM JSON_TABLE(
                    '[{"id":1,"name":"Alice","projects":[{"title":"Project A","tasks":[{"description":"Design","status":"done"},{"description":"Build","status":"in progress"}]}]}]',
                    '$[*]' COLUMNS (
                        id INT PATH '$.id',
                        name VARCHAR(10) PATH '$.name',
                        NESTED PATH '$.projects[*]' COLUMNS (
                             project_title VARCHAR(10) PATH '$.title',
                             NESTED PATH '$.tasks[*]' COLUMNS (
                                 task_desc VARCHAR(100) PATH '$.description',
                                 task_status VARCHAR(100) PATH '$.status'
                             )
                        )
                    )
                ) jt`
            );

            assert.deepEqual(ast.from, [
                {
                    type: 'json_table',
                    expr: {
                        type: 'string',
                        value: '[{"id":1,"name":"Alice","projects":[{"title":"Project A","tasks":[{"description":"Design","status":"done"},{"description":"Build","status":"in progress"}]}]}]'
                    },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 'id',
                            dataType: { dataType: 'INT' },
                            path: { type: 'string', value: '$.id' }
                        },
                        {
                            type: 'json_table_column',
                            name: 'name',
                            dataType: { dataType: 'VARCHAR', length: 10 },
                            path: { type: 'string', value: '$.name' }
                        },
                        {
                            type: 'json_table_column',
                            nested: true,
                            path: { type: 'string', value: '$.projects[*]' },
                            columns: [
                                {
                                    type: 'json_table_column',
                                    name: 'project_title',
                                    dataType: { dataType: 'VARCHAR', length: 10 },
                                    path: { type: 'string', value: '$.title' }
                                },
                                {
                                    type: 'json_table_column',
                                    nested: true,
                                    path: { type: 'string', value: '$.tasks[*]' },
                                    columns: [
                                        {
                                            type: 'json_table_column',
                                            name: 'task_desc',
                                            path: { type: 'string', value: '$.description' },
                                            dataType: { dataType: 'VARCHAR', length: 100 }
                                        },
                                        {
                                            type: 'json_table_column',
                                            name: 'task_status',
                                            path: { type: 'string', value: '$.status' },
                                            dataType: { dataType: 'VARCHAR', length: 100 }
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });

        it('should parse joined JSON tables', () => {
            const ast = parser.parse(
                `SELECT t.id, jt.b
                 FROM t
                 JOIN JSON_TABLE(
                      '[{"id":1,"b":"foo"},{"id":2,"b":"bar"}]',
                      '$[*]' COLUMNS (
                          t_id INT PATH '$.id',
                          b VARCHAR(10) PATH '$.b'
                      )
                ) jt ON t.id = jt.t_id`
            );

            assert.deepEqual(ast.from, [
                { table: 't', db: null, as: null },
                {
                    join: 'INNER JOIN',
                    on: {
                        type: 'binary_expr',
                        operator: '=',
                        left: { type: 'column_ref', column: 'id', table: 't' },
                        right: { type: 'column_ref', column: 't_id', table: 'jt' }
                    },
                    type: 'json_table',
                    expr: {
                        type: 'string',
                        value: '[{"id":1,"b":"foo"},{"id":2,"b":"bar"}]'
                    },
                    path: { type: 'string', value: '$[*]' },
                    columns: [
                        {
                            type: 'json_table_column',
                            name: 't_id',
                            dataType: { dataType: 'INT' },
                            path: { type: 'string', value: '$.id' }
                        },
                        {
                            type: 'json_table_column',
                            name: 'b',
                            dataType: { dataType: 'VARCHAR', length: 10 },
                            path: { type: 'string', value: '$.b' }
                        }
                    ],
                    as: 'jt'
                }
            ]);
        });
    });
});


================================================
FILE: test/sql2ast/groupby.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('group by clause', () => {
    const parser = new Parser();

    it('should parse single columns', () => {
        const ast = parser.parse('SELECT a FROM b WHERE c = 0 GROUP BY d');

        assert.deepEqual(ast.groupby, [{ type: 'column_ref', table: null, column: 'd' }]);
    });

    it('should parse multiple columns', () => {
        const ast = parser.parse('SELECT a FROM b WHERE c = 0 GROUP BY d, t.b, t.c');

        assert.deepEqual(ast.groupby, [
            { type: 'column_ref', table: null, column: 'd' },
            { type: 'column_ref', table: 't', column: 'b' },
            { type: 'column_ref', table: 't', column: 'c' }
        ]);
    });
});


================================================
FILE: test/sql2ast/having.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('having clause', () => {
    const parser = new Parser();

    it('should parse single conditions', () => {
        const ast = parser.parse('SELECT col1 FROM t GROUP BY col2 HAVING COUNT(*) > 1');

        assert.deepEqual(ast.having, {
            type: 'binary_expr',
            operator: '>',
            left: {
                type: 'aggr_func',
                name: 'COUNT',
                args: { expr: { type: 'star', value: '*' } }
            },
            right: { type: 'number', value: 1 }
        });
    });

    it('should parse multiple conditions', () => {
        const ast = parser.parse('SELECT col1 FROM t GROUP BY col2 HAVING SUM(col2) > 10 OR 1 = 1');

        assert.deepEqual(ast.having, {
            type: 'binary_expr',
            operator: 'OR',
            left: {
                type: 'binary_expr',
                operator: '>',
                left: {
                    type: 'aggr_func',
                    name: 'SUM',
                    quantifier: null,
                    args: { expr: { type: 'column_ref', table: null, column: 'col2' } }
                },
                right: { type: 'number', value: 10 }
            },
            right: {
                type: 'binary_expr',
                operator: '=',
                left: { type: 'number', value: 1 },
                right: { type: 'number', value: 1 }
            }
        });
    });

    it('should parse subselects', () => {
        const ast = parser.parse('SELECT col1 FROM t GROUP BY col2 HAVING SUM(col2) > (SELECT 10)');

        assert.deepEqual(ast.having, {
            type: 'binary_expr',
            operator: '>',
            left: {
                type: 'aggr_func',
                name: 'SUM',
                quantifier: null,
                args: { expr: { type: 'column_ref', table: null, column: 'col2' } }
            },
            right: {
                with: null,
                type: 'select',
                options: null,
                distinct: null,
                columns: [{ expr: { type: 'number', value: 10 }, as: null }],
                from: null,
                where: null,
                groupby: null,
                having: null,
                orderby: null,
                limit: null,
                parentheses: true
            }
        });
    });
});


================================================
FILE: test/sql2ast/join.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('joins', () => {
    const parser = new Parser();

    it('should parse implicit joins', () => {
        const ast = parser.parse('SELECT * FROM t, a.b b, c.d as cd');

        assert.deepEqual(ast.from, [
            { db: null, table: 't', as: null },
            { db: 'a', table: 'b', as: 'b' },
            { db: 'c', table: 'd', as: 'cd' }
        ]);
    });

    ['left', 'right', 'full'].forEach((join) => {
        [' ', ' outer '].forEach((outer) => {
            it(`should parse ${join}${outer}joins`, () => {
                const ast = parser.parse(`SELECT * FROM t ${join} ${outer} join d on t.d = d.a`);

                assert.deepEqual(ast.from, [
                    { db: null, table: 't', as: null },
                    {
                        db: null,
                        table: 'd',
                        as: null,
                        join: `${join.toUpperCase()} JOIN`,
                        on: {
                            type: 'binary_expr',
                            operator: '=',
                            left: { type: 'column_ref', table: 't', column: 'd' },
                            right: { type: 'column_ref', table: 'd', column: 'a' }
                        }
                    }
                ]);
            });
        });
    });

    it('should parse joined subselect', () => {
        const ast = parser.parse('SELECT * FROM t1 JOIN (SELECT id, col1 FROM t2) someAlias ON t1.id = someAlias.id');

        assert.deepEqual(ast.from, [
            { db: null, table: 't1', as: null },
            {
                expr: {
                    with: null,
                    type: 'select',
                    options: null,
                    distinct: null,
                    from: [{ db: null, table: 't2', as: null }],
                    columns: [
                        { expr: { type: 'column_ref', table: null, column: 'id' }, as: null },
                        { expr: { type: 'column_ref', table: null, column: 'col1' }, as: null }
                    ],
                    where: null,
                    groupby: null,
                    having: null,
                    orderby: null,
                    limit: null,
                    parentheses: true
                },
                as: 'someAlias',
                join: 'INNER JOIN',
                on: {
                    type: 'binary_expr',
                    operator: '=',
                    left: { type: 'column_ref', table: 't1', column: 'id' },
                    right: { type: 'column_ref', table: 'someAlias', column: 'id' }
                },
                lateral: false,
                columns: null
            }
        ]);
    });

    it('should parse joins with USING (single column)', () => {
        const ast = parser.parse('SELECT * FROM t1 JOIN t2 USING (id)');

        assert.deepEqual(ast.from, [
            { db: null, table: 't1', as: null },
            { db: null, table: 't2', as: null, join: 'INNER JOIN', using: ['id'] }
        ]);
    });

    it('should parse joins with USING (multiple columns)', () => {
        const ast = parser.parse('SELECT * FROM t1 JOIN t2 USING (id1, id2)');

        assert.deepEqual(ast.from, [
            { db: null, table: 't1', as: null },
            { db: null, table: 't2', as: null, join: 'INNER JOIN', using: ['id1', 'id2'] }
        ]);
    });

    it('should parse LATERAL joins', () => {
        const ast = parser.parse(
            'SELECT * FROM t1 JOIN LATERAL (SELECT id FROM t2 WHERE t1.id = t2.t1id) AS subselect ON TRUE'
        );
        const [, lateralJoin] = ast.from;

        assert.ok(Object.hasOwn(lateralJoin, 'lateral'));
        assert.equal(lateralJoin.lateral, true);
    });

    it('should parse derived column list with single column', () => {
        const ast = parser.parse('SELECT id FROM (SELECT 1) t(id)');
        const [subSelect] = ast.from;

        assert.ok(Object.hasOwn(subSelect, 'columns'));
        assert.deepEqual(subSelect.columns, ['id']);
    });

    it('should parse derived column list with multiple columns', () => {
        const ast = parser.parse('SELECT id1, id2 FROM (SELECT 1, 2) t(id1, id2)');
        const [subSelect] = ast.from;

        assert.ok(Object.hasOwn(subSelect, 'columns'));
        assert.deepEqual(subSelect.columns, ['id1', 'id2']);
    });
});


================================================
FILE: test/sql2ast/limit.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('limit clause', () => {
    const parser = new Parser();

    it('should be parsed w/o offset', () => {
        const ast = parser.parse('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 3');

        assert.deepEqual(ast.limit, [
            { type: 'number', value: 0 },
            { type: 'number', value: 3 }
        ]);
    });

    it('should be parsed w/ offset', () => {
        const ast = parser.parse('SELECT DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 0, 3');

        assert.deepEqual(ast.limit, [
            { type: 'number', value: 0 },
            { type: 'number', value: 3 }
        ]);
    });
});


================================================
FILE: test/sql2ast/literal.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('literals', () => {
    const parser = new Parser();

    describe('numbers', () => {
        [
            ['should parse positive number', '1', 1],
            ['should parse (explicit) positive number', '+1', 1],
            ['should parse negative number', '-1', -1],
            ['should parse positive numbers', '10', 10],
            ['should parse (explicit) positive numbers', '+10', 10],
            ['should parse negative numbers', '-10', -10],
            ['should parse positive decimal numbers', '0.5', 0.5],
            ['should parse (explicit) positive decimal numbers', '+0.5', 0.5],
            ['should parse positive decimal numbers w/o integral part', '.5', 0.5],
            ['should parse (explicit) positive decimal numbers w/o integral part', '+.5', 0.5],
            ['should parse negative decimal numbers', '-0.5', -0.5],
            ['should parse negative decimal numbers w/o integral part', '-.5', -0.5]
        ].forEach(([label, expr, expectedValue]) => {
            it(label, () => {
                const ast = parser.parse(`SELECT ${expr}`);
                assert.deepEqual(ast.columns, [{ expr: { type: 'number', value: expectedValue }, as: null }]);
            });
        });
    });

    describe('booleans', () => {
        [true, false].forEach((value) =>
            it('should parse bool', () => {
                const ast = parser.parse(`SELECT ${value.toString()}`);
                assert.deepEqual(ast.columns, [{ expr: { type: 'bool', value }, as: null }]);
            })
        );
    });

    describe('strings', () => {
        it('should parse single quoted strings', () => {
            const ast = parser.parse(`SELECT 'string'`);
            assert.deepEqual(ast.columns, [{ expr: { type: 'string', value: 'string' }, as: null }]);
        });

        it('should parse keywords in single quotes as string', () => {
            const ast = parser.parse(`SELECT 'select'`);
            assert.deepEqual(ast.columns, [{ expr: { type: 'string', value: 'select' }, as: null }]);
        });

        it('should parse double single quotes as escape character', () => {
            const ast = parser.parse(`SELECT 'wendy''s'`);
            assert.deepEqual(ast.columns, [{ expr: { type: 'string', value: "wendy's" }, as: null }]);
        });
    });

    describe('datetime', () => {
        Object.entries({
            time: '08:23:16',
            date: '1999-12-25',
            timestamp: '1999-12-25 08:23:16'
        }).forEach(([type, value]) => {
            [type, type.toUpperCase()].forEach((t) => {
                it(t, () => {
                    const ast = parser.parse(`SELECT ${t} '${value}'`);
                    assert.deepEqual(ast.columns, [{ expr: { type, value }, as: null }]);
                });
            });
        });
    });

    describe('interval', () => {
        describe('qualifiers', () => {
            ['MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR'].forEach((qualifier) => {
                it(`should support ${qualifier}`, () => {
                    const ast = parser.parse(`SELECT CURRENT_DATE + INTERVAL 10 ${qualifier} FROM dual`);

                    assert.deepEqual(ast.columns, [
                        {
                            expr: {
                                type: 'binary_expr',
                                operator: '+',
                                left: {
                                    type: 'function',
                                    name: 'CURRENT_DATE',
                                    args: { type: 'expr_list', value: [] }
                                },
                                right: {
                                    type: 'interval',
                                    sign: null,
                                    value: '10',
                                    qualifier: qualifier
                                }
                            },
                            as: null
                        }
                    ]);
                });
            });
        });

        [
            ['should support intervals with explicit plus sign in interval qualifier', '+10', '+', '10'],
            ['should support negative interval qualifier', '-10', '-', '10']
        ].forEach(([description, interval, sign, expectedResult]) => {
            it(description, () => {
                const ast = parser.parse(`SELECT CURRENT_DATE + INTERVAL ${interval} DAY FROM dual`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'binary_expr',
                            operator: '+',
                            left: {
                                type: 'function',
                                name: 'CURRENT_DATE',
                                args: { type: 'expr_list', value: [] }
                            },
                            right: {
                                type: 'interval',
                                sign: sign,
                                value: expectedResult,
                                qualifier: 'DAY'
                            }
                        },
                        as: null
                    }
                ]);
            });
        });

        it('should support intervals as strings', () => {
            const ast = parser.parse(`SELECT CURRENT_DATE + INTERVAL '10' DAY FROM dual`);

            assert.deepEqual(ast.columns, [
                {
                    expr: {
                        type: 'binary_expr',
                        operator: '+',
                        left: {
                            type: 'function',
                            name: 'CURRENT_DATE',
                            args: { type: 'expr_list', value: [] }
                        },
                        right: {
                            type: 'interval',
                            sign: null,
                            value: '10',
                            qualifier: 'DAY'
                        }
                    },
                    as: null
                }
            ]);
        });

        [
            ['should support positive sign', '+', '-10'],
            ['should support negative sign', '-', '-10']
        ].forEach(([description, sign, expectedResult]) => {
            it(description, () => {
                const ast = parser.parse(`SELECT CURRENT_DATE + INTERVAL ${sign} '-10' DAY FROM dual`);

                assert.deepEqual(ast.columns, [
                    {
                        expr: {
                            type: 'binary_expr',
                            operator: '+',
                            left: {
                                type: 'function',
                                name: 'CURRENT_DATE',
                                args: { type: 'expr_list', value: [] }
                            },
                            right: {
                                type: 'interval',
                                sign: sign,
                                value: expectedResult,
                                qualifier: 'DAY'
                            }
                        },
                        as: null
                    }
                ]);
            });
        });
    });
});


================================================
FILE: test/sql2ast/mysql.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('MySQL SQL extensions', () => {
    const parser = new Parser();

    it('should parse SQL_CALC_FOUND_ROWS', () => {
        const ast = parser.parse('SELECT SQL_CALC_FOUND_ROWS col FROM t');
        assert.deepEqual(ast.options, ['SQL_CALC_FOUND_ROWS']);
    });

    it('should parse SQL_CACHE/SQL_NO_CACHE', () => {
        let ast = parser.parse('SELECT SQL_CACHE col FROM t');
        assert.deepEqual(ast.options, ['SQL_CACHE']);

        ast = parser.parse('SELECT SQL_NO_CACHE col FROM t');
        assert.deepEqual(ast.options, ['SQL_NO_CACHE']);
    });

    it('should parse SQL_SMALL_RESULT/SQL_BIG_RESULT', () => {
        let ast = parser.parse('SELECT SQL_SMALL_RESULT col FROM t');
        assert.deepEqual(ast.options, ['SQL_SMALL_RESULT']);

        ast = parser.parse('SELECT SQL_BIG_RESULT col FROM t');
        assert.deepEqual(ast.options, ['SQL_BIG_RESULT']);
    });

    it('should parse SQL_BUFFER_RESULT', () => {
        const ast = parser.parse('SELECT SQL_BUFFER_RESULT col FROM t');
        assert.deepEqual(ast.options, ['SQL_BUFFER_RESULT']);
    });

    it('should parse multiple options per query', () => {
        const ast = parser.parse('SELECT SQL_CALC_FOUND_ROWS SQL_BIG_RESULT SQL_BUFFER_RESULT col FROM t');
        assert.deepEqual(ast.options, ['SQL_CALC_FOUND_ROWS', 'SQL_BIG_RESULT', 'SQL_BUFFER_RESULT']);
    });
});


================================================
FILE: test/sql2ast/orderby.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('order by clause', () => {
    const parser = new Parser();
    let ast;

    it('should parse single column', () => {
        ast = parser.parse('SELECT a FROM b WHERE c = 0 order BY d');

        assert.deepEqual(ast.orderby, [{ expr: { type: 'column_ref', table: null, column: 'd' }, type: 'ASC' }]);
    });

    it('should parse multiple columns', () => {
        ast = parser.parse('SELECT a FROM b WHERE c = 0 order BY d, t.b dEsc, t.c');

        assert.deepEqual(ast.orderby, [
            { expr: { type: 'column_ref', table: null, column: 'd' }, type: 'ASC' },
            { expr: { type: 'column_ref', table: 't', column: 'b' }, type: 'DESC' },
            { expr: { type: 'column_ref', table: 't', column: 'c' }, type: 'ASC' }
        ]);
    });

    it('should parse expressions', () => {
        ast = parser.parse('SELECT a FROM b WHERE c = 0 order BY d, SuM(e)');

        assert.deepEqual(ast.orderby, [
            { expr: { type: 'column_ref', table: null, column: 'd' }, type: 'ASC' },
            {
                expr: {
                    type: 'aggr_func',
                    name: 'SUM',
                    quantifier: null,
                    args: { expr: { type: 'column_ref', table: null, column: 'e' } }
                },
                type: 'ASC'
            }
        ]);
    });
});


================================================
FILE: test/sql2ast/placeholder.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser, util } = require('../../');

describe('placeholder', () => {
    const parser = new Parser();
    let ast;

    it('should replace single parameter', () => {
        ast = parser.parse('SELECT col FROM t WHERE id = :id');
        ast = util.replaceParams(ast, { id: 1 });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: null, column: 'id' },
            right: { type: 'number', value: 1 }
        });
    });

    it('should replace multiple parameters', () => {
        ast = parser.parse('SELECT col FROM t WHERE id = :id AND "type" = :type');
        ast = util.replaceParams(ast, { id: 1, type: 'foobar' });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: 'AND',
            left: {
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'id' },
                right: { type: 'number', value: 1 }
            },
            right: {
                type: 'binary_expr',
                operator: '=',
                left: { type: 'column_ref', table: null, column: 'type' },
                right: { type: 'string', value: 'foobar' }
            }
        });
    });

    it('should set parameter with string', () => {
        ast = parser.parse('SELECT col1 FROM t WHERE col2 = :name');
        ast = util.replaceParams(ast, { name: 'John Doe' });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: null, column: 'col2' },
            right: { type: 'string', value: 'John Doe' }
        });
    });

    it('should set parameter with boolean value', () => {
        ast = parser.parse('SELECT col1 FROM t WHERE isMain = :main');
        ast = util.replaceParams(ast, { main: true });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: null, column: 'isMain' },
            right: { type: 'bool', value: true }
        });
    });

    it('should set parameter with null value', () => {
        ast = parser.parse('SELECT col1 FROM t WHERE col2 = :param');
        ast = util.replaceParams(ast, { param: null });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: null, column: 'col2' },
            right: { type: 'null', value: null }
        });
    });

    it('should set parameter with array as value', () => {
        ast = parser.parse('SELECT col1 FROM t WHERE id = :ids');
        ast = util.replaceParams(ast, { ids: [1, 3, 5, 7] });

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: null, column: 'id' },
            right: {
                type: 'expr_list',
                value: [
                    { type: 'number', value: 1 },
                    { type: 'number', value: 3 },
                    { type: 'number', value: 5 },
                    { type: 'number', value: 7 }
                ]
            }
        });
    });

    it('should throw an exception if no value for parameter is available', () => {
        ast = parser.parse('SELECT col FROM t WHERE id = :id');

        assert.throws(() => util.replaceParams(ast, { foo: 'bar' }), {
            name: 'Error',
            message: 'no value for parameter :id found'
        });
    });

    it('should return new AST object', () => {
        ast = parser.parse('SELECT col FROM t WHERE id = :id');
        const resolvedParamAST = util.replaceParams(ast, { id: 1 });

        assert.notDeepEqual(ast, resolvedParamAST);
    });
});


================================================
FILE: test/sql2ast/row-value-constructor.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('row value constructor', () => {
    const parser = new Parser();

    it('should parse simple values', () => {
        const ast = parser.parse(`SELECT * FROM "user" WHERE (firstname, lastname) = ('John', 'Doe')`);

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: {
                type: 'expr_list',
                value: [
                    { column: 'firstname', table: null, type: 'column_ref' },
                    { column: 'lastname', table: null, type: 'column_ref' }
                ],
                parentheses: true
            },
            right: {
                type: 'expr_list',
                value: [
                    { type: 'string', value: 'John' },
                    { type: 'string', value: 'Doe' }
                ],
                parentheses: true
            }
        });
    });
});


================================================
FILE: test/sql2ast/select.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../index');

describe('select', () => {
    const parser = new Parser();

    it('should be null if empty', () => {
        const ast = parser.parse('SELECT a');

        assert.equal(ast.options, null);
        assert.equal(ast.distinct, null);
        assert.equal(ast.from, null);
        assert.equal(ast.where, null);
        assert.equal(ast.groupby, null);
        assert.equal(ast.orderby, null);
        assert.equal(ast.limit, null);
    });

    it('should have appropriate types', () => {
        const ast = parser.parse('SELECT SQL_NO_CACHE DISTINCT a FROM b WHERE c = 0 GROUP BY d ORDER BY e limit 3');

        assert.ok(Array.isArray(ast.options));
        assert.equal(ast.distinct, 'DISTINCT');
        assert.ok(Array.isArray(ast.from));
        assert.ok(typeof ast.where === 'object');
        assert.ok(Array.isArray(ast.groupby));
        assert.ok(Array.isArray(ast.orderby));
        assert.ok(Array.isArray(ast.limit));
    });
});


================================================
FILE: test/sql2ast/where.spec.js
================================================
'use strict';

const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const { Parser } = require('../../');

describe('where clause', () => {
    const parser = new Parser();
    let ast;

    it('should parse single condition', () => {
        ast = parser.parse('SELECT * FROM t where t.a > 0');

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '>',
            left: { type: 'column_ref', table: 't', column: 'a' },
            right: { type: 'number', value: 0 }
        });
    });

    it('should parse parameters', () => {
        ast = parser.parse('SELECT * FROM t where t.a > :my_param');

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '>',
            left: { type: 'column_ref', table: 't', column: 'a' },
            right: { type: 'param', value: 'my_param' }
        });
    });

    it('should parse multiple conditions', () => {
        ast = parser.parse(`SELECT * FROM t where t.c between 1 and 't' AND Not true`);

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: 'AND',
            left: {
                type: 'binary_expr',
                operator: 'BETWEEN',
                left: { type: 'column_ref', table: 't', column: 'c' },
                right: {
                    type: 'expr_list',
                    value: [
                        { type: 'number', value: 1 },
                        { type: 'string', value: 't' }
                    ]
                }
            },
            right: {
                type: 'unary_expr',
                operator: 'NOT',
                expr: { type: 'bool', value: true }
            }
        });
    });

    it('should parse single condition with boolean', () => {
        ast = parser.parse('SELECT * FROM t where t.a = TRUE');

        assert.deepEqual(ast.where, {
            type: 'binary_expr',
            operator: '=',
            left: { type: 'column_ref', table: 't', column: 'a' },
            right: { type: 'bool', value: true }
        });
    });

    ['is', 'is not'].forEach((operator) => {
        it(`should parse ${operator} condition`, () => {
            ast = parser.parse(`SELECT * FROM t WHERE "col" ${operator} NULL`);

            assert.deepEqual(ast.where, {
                type: 'binary_expr',
                operator: operator.toUpperCase(),
                left: { type: 'column_ref', table: null, column: 'col' },
                right: { type: 'null', value: null }
            });
        });
    });

    ['exists', 'not exists'].forEach((operator) => {
        it('should parse ' + operator.toUpperCase() + ' condition', () => {
            ast = parser.parse(`SELECT * FROM t WHERE ${operator} (SELECT 1)`);

            assert.deepEqual(ast.where, {
                type: 'unary_expr',
                operator: operator.toUpperCase(),
                expr: {
                    with: null,
                    type: 'select',
                    options: null,
                    distinct: null,
                    columns: [{ expr: { type: 'number', value: 1 }, as: null }],
                    from: null,
                    where: null,
                    groupby: null,
                    having: null,
                    orderby: null,
                    limit: null,
                    parentheses: true
                }
            });
        });
    });
});
Download .txt
gitextract_u9__4di5/

├── .editorconfig
├── .githooks/
│   └── pre-commit
├── .github/
│   └── workflows/
│       └── ci.yml
├── .gitignore
├── .prettierrc
├── CHANGELOG.md
├── LICENSE
├── README.md
├── eslint.config.js
├── index.js
├── lib/
│   ├── parser.js
│   ├── sql.js
│   └── util.js
├── package.json
├── sql.pegjs
└── test/
    ├── ast2sql/
    │   ├── column.spec.js
    │   ├── cte.spec.js
    │   ├── expr.spec.js
    │   ├── from.spec.js
    │   ├── groupby.spec.js
    │   ├── having.spec.js
    │   ├── join.spec.js
    │   ├── limit.spec.js
    │   ├── literal.spec.js
    │   ├── mysql.spec.js
    │   ├── order.spec.js
    │   ├── select.spec.js
    │   ├── util.js
    │   └── where.spec.js
    └── sql2ast/
        ├── column.spec.js
        ├── cte.spec.js
        ├── expr.spec.js
        ├── from.spec.js
        ├── groupby.spec.js
        ├── having.spec.js
        ├── join.spec.js
        ├── limit.spec.js
        ├── literal.spec.js
        ├── mysql.spec.js
        ├── orderby.spec.js
        ├── placeholder.spec.js
        ├── row-value-constructor.spec.js
        ├── select.spec.js
        └── where.spec.js
Download .txt
SYMBOL INDEX (31 symbols across 3 files)

FILE: lib/parser.js
  class Parser (line 5) | class Parser {
    method parse (line 6) | parse(sql) {

FILE: lib/sql.js
  function escape (line 15) | function escape(str) {
  function identifierToSql (line 22) | function identifierToSql(ident) {
  function literalToSQL (line 26) | function literalToSQL(literal) {
  function aggrToSQL (line 46) | function aggrToSQL({ name: fnName, quantifier, args }) {
  function binaryToSQL (line 50) | function binaryToSQL(expr) {
  function caseToSQL (line 66) | function caseToSQL(expr) {
  function dataTypeToSQL (line 86) | function dataTypeToSQL(type) {
  function castToSQL (line 94) | function castToSQL(expr) {
  function columnRefToSQL (line 98) | function columnRefToSQL(expr) {
  function getExprListSQL (line 104) | function getExprListSQL(exprList) {
  function funcToSQL (line 108) | function funcToSQL(expr) {
  function columnsToSQL (line 119) | function columnsToSQL(columns) {
  function tablesToSQL (line 139) | function tablesToSQL(tables) {
  function tableToSQL (line 153) | function tableToSQL(node) {
  function joinToSQL (line 162) | function joinToSQL(node) {
  function tableExprToSQL (line 179) | function tableExprToSQL(node) {
  function jsonColumnToSQL (line 191) | function jsonColumnToSQL(column) {
  function jsonTableToSQL (line 237) | function jsonTableToSQL(node) {
  function withToSql (line 250) | function withToSql(withExpr) {
  function selectToSQL (line 279) | function selectToSQL(stmt) {
  function unaryToSQL (line 306) | function unaryToSQL(expr) {
  function rowValueToSQL (line 311) | function rowValueToSQL(expr) {
  function valuesToSQL (line 316) | function valuesToSQL(expr) {
  function unionToSQL (line 321) | function unionToSQL(stmt) {
  function exprToSQL (line 352) | function exprToSQL(expr) {
  function toSQL (line 356) | function toSQL(ast) {

FILE: lib/util.js
  function createValueExpr (line 11) | function createValueExpr(value) {
  function createBinaryExpr (line 29) | function createBinaryExpr(operator, left, right) {
  function replaceParams (line 55) | function replaceParams(ast, data) {
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (171K chars).
[
  {
    "path": ".editorconfig",
    "chars": 202,
    "preview": "root = true\n\n[*]\nindent_style = space\nindent_size = 4\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ni"
  },
  {
    "path": ".githooks/pre-commit",
    "chars": 43,
    "preview": "#!/bin/sh\nnpm run test && npm run lint-fix\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 432,
    "preview": "name: ci\n\non:\n  push:\n    branches:\n      - main\n    paths-ignore:\n      - 'docs/**'\n      - '*.md'\n\njobs:\n  test:\n    r"
  },
  {
    "path": ".gitignore",
    "chars": 54,
    "preview": ".DS_Store\n.vscode\nnode_modules\ndist\npackage-lock.json\n"
  },
  {
    "path": ".prettierrc",
    "chars": 99,
    "preview": "{\n    \"printWidth\": 120,\n    \"tabWidth\": 4,\n    \"singleQuote\": true,\n    \"trailingComma\": \"none\"\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 452,
    "preview": "# Changelog\n\n## [4.0.0]\n### Breaking Changes\n- Replaced PEG.js by Peggy\n- Removed support for Node.js 18\n- `DECIMAL` is "
  },
  {
    "path": "LICENSE",
    "chars": 14872,
    "preview": "GNU GENERAL PUBLIC LICENSE\nVersion 2, June 1991\n\nCopyright (C) 1989, 1991 Free Software Foundation, Inc.\n51 Franklin Str"
  },
  {
    "path": "README.md",
    "chars": 1245,
    "preview": "# @florajs/sql-parser\n\n![](https://github.com/florajs/sql-parser/workflows/ci/badge.svg)\n[![NPM version](https://img.shi"
  },
  {
    "path": "eslint.config.js",
    "chars": 662,
    "preview": "const js = require('@eslint/js');\nconst eslintPluginPrettierRecommended = require('eslint-plugin-prettier/recommended');"
  },
  {
    "path": "index.js",
    "chars": 127,
    "preview": "'use strict';\n\nconst Parser = require('./lib/parser');\nconst util = require('./lib/util');\n\nmodule.exports = { Parser, u"
  },
  {
    "path": "lib/parser.js",
    "chars": 162,
    "preview": "'use strict';\n\nconst parseFn = require('./../dist/parser').parse;\n\nclass Parser {\n    parse(sql) {\n        return parseF"
  },
  {
    "path": "lib/sql.js",
    "chars": 10989,
    "preview": "'use strict';\n\nconst escapeMap = {\n    '\\0': '\\\\0',\n    \"'\": \"\\\\'\",\n    '\"': '\\\\\"',\n    '\\b': '\\\\b',\n    '\\n': '\\\\n',\n  "
  },
  {
    "path": "lib/util.js",
    "chars": 2260,
    "preview": "'use strict';\n\nconst { ImplementationError } = require('@florajs/errors');\n\nconst astToSQL = require('./sql');\n\n/**\n * @"
  },
  {
    "path": "package.json",
    "chars": 1420,
    "preview": "{\n  \"name\": \"@florajs/sql-parser\",\n  \"version\": \"4.0.0\",\n  \"description\": \"Parse SQL (select) statements into abstract s"
  },
  {
    "path": "sql.pegjs",
    "chars": 29929,
    "preview": "{\n  var reservedMap = {\n    'ALL': true,\n    'AND': true,\n    'AS': true,\n    'ASC': true,\n\n    'BETWEEN': true,\n    'BI"
  },
  {
    "path": "test/ast2sql/column.spec.js",
    "chars": 1457,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/cte.spec.js",
    "chars": 1679,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/expr.spec.js",
    "chars": 4001,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { util"
  },
  {
    "path": "test/ast2sql/from.spec.js",
    "chars": 11844,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/groupby.spec.js",
    "chars": 859,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/ast2sql/having.spec.js",
    "chars": 697,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/join.spec.js",
    "chars": 4724,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/limit.spec.js",
    "chars": 489,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/literal.spec.js",
    "chars": 1714,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/mysql.spec.js",
    "chars": 432,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/order.spec.js",
    "chars": 1230,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/ast2sql/select.spec.js",
    "chars": 1566,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { getP"
  },
  {
    "path": "test/ast2sql/util.js",
    "chars": 226,
    "preview": "'use strict';\n\nconst { Parser, util } = require('../../');\nconst parser = new Parser();\n\nmodule.exports = {\n    getParse"
  },
  {
    "path": "test/ast2sql/where.spec.js",
    "chars": 4368,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { util"
  },
  {
    "path": "test/sql2ast/column.spec.js",
    "chars": 4028,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/cte.spec.js",
    "chars": 2952,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/expr.spec.js",
    "chars": 2668,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/from.spec.js",
    "chars": 25250,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/groupby.spec.js",
    "chars": 822,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/having.spec.js",
    "chars": 2495,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/join.spec.js",
    "chars": 4520,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/limit.spec.js",
    "chars": 805,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/literal.spec.js",
    "chars": 7501,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/mysql.spec.js",
    "chars": 1522,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/orderby.spec.js",
    "chars": 1482,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/placeholder.spec.js",
    "chars": 3954,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/row-value-constructor.spec.js",
    "chars": 1053,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/select.spec.js",
    "chars": 1098,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  },
  {
    "path": "test/sql2ast/where.spec.js",
    "chars": 3481,
    "preview": "'use strict';\n\nconst { describe, it } = require('node:test');\nconst assert = require('node:assert/strict');\nconst { Pars"
  }
]

About this extraction

This page contains the full source code of the godmodelabs/flora-sql-parser GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (158.1 KB), approximately 39.2k tokens, and a symbol index with 31 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!