百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

dt-sql-parser

> 数据库
开源

用 antlr4 构建的大数据 SQL 解析器。

392 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

用 antlr4 构建的大数据 SQL 解析器。

dt-sql-parser

NPM version NPM downloads Chat

English | 简体中文

dt-sql-parser is a SQL Parser project built with ANTLR4, and it's mainly for the BigData field. The ANTLR4 generated the basic Parser, Visitor, and Listener, so it's easy to complete the Lexer, Parser, traverse the AST, and so on features.

Additionally, it provides advanced features such as SQL Validation, Code Completion and Collecting Table and Columns in SQL.

Supported SQL:

  • MySQL
  • Flink
  • Spark
  • Hive
  • PostgreSQL
  • Trino
  • Impala
  • GenericSQL

[!TIP] This project is the default for Typescript target, also you can try to compile it to other languages if you need.

Integrating SQL Parser with Monaco Editor

We also have provided monaco-sql-languages to easily to integrate dt-sql-parser with monaco-editor.

Installation

bash
# use npm
npm i dt-sql-parser --save

# use yarn
yarn add dt-sql-parser

Usage

We recommend learning the fundamentals usage before continuing. The dt-sql-parser library provides SQL classes for different types of SQL.

javascript
import { MySQL, FlinkSQL, SparkSQL, HiveSQL, PostgreSQL, TrinoSQL, ImpalaSQL, GenericSQL } from 'dt-sql-parser';

Before using syntax validation, code completion, and other features, it is necessary to instantiate the Parser of the relevant SQL type. For instance, one can consider using MySQL as an example:

javascript
const mysql = new MySQL();

The following usage examples will utilize the MySQL, and the Parser for other SQL types will be used in a similar manner as MySQL.

Syntax Validation

First instanced a Parser object, then call the validate method on the SQL instance to validate the sql content, if failed returns an array includes error message.

javascript
import { MySQL } from 'dt-sql-parser';

const mysql = new MySQL();
const incorrectSql = 'selec id,name from user1;';
const errors = mysql.validate(incorrectSql);

console.log(errors); 

output:

javascript
/*
[
  {
    endCol: 5,
    endLine: 1,
    startCol: 0,
    startLine: 1,
    message: "..."
  }
]
*/

Tokenizer

Call the getAllTokens method on the SQL instance:

javascript
import { MySQL } from 'dt-sql-parser';

const mysql = new MySQL()
const sql = 'select id,name,sex from user1;'
const tokens = mysql.getAllTokens(sql)

console.log(tokens)

output:

javascript
/*
[
  {
    channel: 0
    column: 0
    line: 1
    source: [SqlLexer, InputStream]
    start: 0
    stop: 5
    tokenIndex: -1
    type: 137
    _text: null
  },
  ...
]
*/

Visitor

Traverse the tree node by the Visitor:

…

output:

javascript
/*
user1
*/

Listener

Access the specified node in the AST by the Listener

typescript
import { MySQL, MySqlParserListener } from 'dt-sql-parser';

const mysql = new MySQL();
const sql = 'select id, name from user1;';
const parseTree = mysql.parse(sql);

class MyListener extends MySqlParserListener {
    result = '';
    enterTableName = (ctx): void => {
        this.result = ctx.getText();
    };
}

const listener = new MyListener();
mysql.listen(listener, parseTree);

console.log(listener.result)

output:

javascript
/*
user1
*/

Splitting SQL statements

Take FlinkSQL as an example, call the splitSQLByStatement method on the SQL instance:

javascript
import { FlinkSQL } from 'dt-sql-parser';

const flink = new FlinkSQL();
const sql = 'SHOW TABLES;\nSELECT * FROM tb;';
const sqlSlices = flink.splitSQLByStatement(sql);

console.log(sqlSlices)

output:

javascript
/*
[
  {
    startIndex: 0,
    endIndex: 11,
    startLine: 1,
    endLine: 1,
    startColumn: 1,
    endColumn: 12,
    text: 'SHOW TABLES;'
  },
  {
    startIndex: 13,
    endIndex: 29,
    startLine: 2,
    endLine: 2,
    startColumn: 1,
    endColumn: 17,
    text: 'SELECT * FROM tb;'
  }
]
*/

Code Completion

Obtaining code completion information at a specified position in SQL.

Call the getAllEntities method on the SQL instance, pass the SQL content and the row and column numbers indicating the position where code completion is desired. The following are some additional explanations about CaretPosition.

  • keyword candidates list

    javascript
    import { FlinkSQL } from 'dt-sql-parser';
    
    const flink = new FlinkSQL();
    const sql = 'CREATE ';
    const pos = { lineNumber: 1, column: 16 }; // the end position
    const keywords = flink.getSuggestionAtCaretPosition(sql, pos)?.keywords;
    
    console.log(keywords);

    output:

    javascript
    /*
    [ 'CATALOG', 'FUNCTION', 'TEMPORARY', 'VIEW', 'DATABASE', 'TABLE' ] 
    */

    Use the optional keywordFilter to remove unwanted keyword candidates. Return true to keep a keyword and false to remove it.

    typescript
    const sql = 'SELECT * FROM tb ';
    const pos = { lineNumber: 1, column: sql.length + 1 };
    const excludedKeywords = new Set(['WHERE', 'ORDER BY']);
    const keywords = flink.getSuggestionAtCaretPosition(sql, pos, {
        keywordFilter: (keyword) => !excludedKeywords.has(keyword),
    })?.keywords;
  • Obtaining information related to grammar completion

    javascript
    import { FlinkSQL } from 'dt-sql-parser';
    
    const flink = new FlinkSQL();
    const sql = 'SELECT * FROM tb';
    const pos = { lineNumber: 1, column: 16 }; // after 'tb'
    const syntaxSuggestions = flink.getSuggestionAtCaretPosition(sql, pos)?.syntax;
    
    console.log(syntaxSuggestions);

    output:

    javascript
    /*
    [
      {
        syntaxContextType: 'table',
        wordRanges: [
          {
            text: 'tb',
            startIndex: 14,
            stopIndex: 15,
            line: 1,
            startColumn: 15,
            stopColumn: 16
          }
        ]
      },
      {
        syntaxContextType: 'view',
        wordRanges: [
          {
            text: 'tb',
            startIndex: 14,
            stopIndex: 15,
            line: 1,
            startColumn: 15,
            stopColumn: 16
          }
        ]
      }
    ]
    */

The grammar-related code completion information returns an array, where each item represents what grammar can be filled in at that position. For example, the output in the above example represents that the position can be filled with either a table name or a view name. In this case, syntaxContextType represents the type of grammar that can be completed, and wordRanges represents the content that has already been filled.

Get all entities in SQL (e.g. table, column)

Call the getAllEntities method on the SQL instance, and pass in the sql text and the row and column numbers at the specified location to easily get them.

typescript
  import { FlinkSQL } from 'dt-sql-parser';

  const flink = new FlinkSQL();
  const sql = 'SELECT * FROM tb;';
  const pos = { lineNumber: 1, column: 16 }; // tb 的后面
  const entities = flink.getAllEntities(sql, pos);

  console.log(entities);

output

typescript
/*
  [
    {
      entityContextType: 'table',
      text: 'tb',
      position: {
        line: 1,
        startIndex: 14,
        endIndex: 15,
        startColumn: 15,
        endColumn: 17
      },
      belongStmt: {
        stmtContextType: 'selectStmt',
        position: [Object],
        rootStmt: [Object],
        parentStmt: [Object],
        isContainCaret: true
      },
      relatedEntities: null,
      columns: null,
      _alias: null,
      _comment: null
    }
  ]
*/

Position is not required, if the position is passed, then in the collected entities, if the entity is located under the statement where the corresponding position is located, then the statement object to which the entity belongs will be marked with isContainCaret, which can help you quickly filter out the required entities when combined with the code completion function.

In nested subquery scenarios, isContainCaret may not be sufficient to filter out the required entities. For example, for SQL: SELECT id FROM t1 LEFT JOIN (SELECT id, name FROM t2) AS t3 ON t1.id = t3.id, when our cursor is inside the inner query t3 derived table, we expect to provide field completion for the t2 table, but since both t1 and t2 have isContainCaret as true, we cannot distinguish available table entities in more detail.

Therefore, for entity types with entityContextType as table, collected entities will have an isAccessible flag to indicate whether the entity is accessible. isAccessible uses scope depth internally to determine accessibility. When the entity's statement scope depth equals the cursor's statement scope depth and isContainCaret is true, the entity is considered accessible (though this determination method is not absolute, it can exclude most irrelevant entities).

Additional Entity Information

Alias Information

When an entity has an alias, the entity object will contain the _alias field:

  • _alias: Detailed alias information, including text content and position information
typescript
// Example: SELECT u.name FROM users AS u
{
  entityContextType: 'table',
  text: 'users',
  _alias: {        // Table alias information
    text: 'u',
    startIndex: 29,
    endIndex: 29,
    startColumn: 30,
    endColumn: 31,
    line: 1
  }
}

// Example: SELECT name AS username FROM users
{
  entityContextType: 'column',
  text: 'name',
  _alias: {        // Column alias information
    text: 'username',
    startIndex: 15,
    endIndex: 22,
    startColumn: 16,
    endColumn: 24,
    line: 1
  }
}

Declaration Type (DeclareType)

The declareType field identifies how an entity is declared, with different entity types having different declaration types:

Table Entity Declaration Types (TableDeclareType):

  • LITERAL: Literal table name, e.g., SELECT * FROM users
  • EXPRESSION: Table defined by expression, e.g., subquery SELECT * FROM (SELECT * FROM users) AS t

Column Entity Declaration Types (ColumnDeclareType):

  • LITERAL: Literal column name, e.g., SELECT id, name FROM users
  • ALL: Wildcard syntax, e.g., SELECT users.* FROM users
  • EXPRESSION: Complex expressions like subqueries, CASE statements, function calls, etc.
typescript
// Examples of different declareType values
// 1. Literal column
{
  entityContextType: 'column',
  text: 'name',
  declareType: ColumnDeclareType.LITERAL,
}

// 2. Wildcard column
{
  entityContextType: 'column', 
  text: 'users.*',
  declareType: ColumnDeclareType.ALL,
}

// 3. Expression column
{
  entityContextType: 'column',
  text: 'CASE WHEN age > 18 THEN "adult" ELSE "minor" END',
  declareType: ColumnDeclareType.EXPRESSION,
}

Other Metadata Fields

Comment Information

  • _comment: Entity comment information, mainly used for column or table comments in CREATE statements
typescript
// Example: CREATE TABLE users (id INT COMMENT 'USERID', name VARCHAR(50) COMMENT 'USERNAME')
{
  entityContextType: 'column',
  text: 'id',
  _comment: {
    text: "'USERID'",
    startIndex: 35,
    endIndex: 42,
    startColumn: 36,
    endColumn: 44,
    line: 1
  },
  _colType: {
    text: 'INT',
    startIndex: 23,
    endIndex: 42,
    startColumn: 24,
    endColumn: 44,
    line:

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptantlr4autocompletionbigdataflink

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库