lava-dt-sql-parser-semantic.../README.md

96 lines
2.3 KiB
Markdown
Raw Normal View History

2024-04-07 19:10:38 +08:00
# dt-sql-parser-semantic-analyse-plugin
2024-05-15 19:35:40 +08:00
A [dt-sql-parser](https://github.com/DTStack/dt-sql-parser) plugin with semantic result. [Theory(zh-CN)](https://github.com/Kijin-Seija/dt-sql-parser-analyse-demo).
2024-04-07 19:10:38 +08:00
## Installation
```
npm install dt-sql-parser-semantic-analyse-plugin
```
## Quick Usage
```typescript
const myPlugin = new DtSqlParserSemAnalysePlugin()
const sql = 'SELECT a| FROM t'
const caretColumn = sql.indexOf('|') + 1
const result = myPlugin.parse(sql.replace('|', ''), { lineNumber: 1, columnNumber: caretColumn })
console.log(result)
```
This will use a postgresql Parser and build-in rules/preprocessors
## Add a Rule Chain
```typescript
import { PostgresSQL } from 'dt-sql-parser'
import { PostgreSQLParser } from 'dt-sql-parser/dist/lib/pgsql/PostgreSQLParser'
const myPlugin = new DtSqlParserSemAnalysePlugin({
parse: {
parser: new PostgresSQL()
2024-05-15 19:35:40 +08:00
alias: {
selectstmt: 'selectStatement',
target_el: 'target_label'
}
2024-04-07 19:10:38 +08:00
stmts: [
'selectstmt'
],
entities: [
'column_name'
],
rules: {
'select_columns': [
PostgreSQLParser.RULE_insertstmt,
PostgreSQLParser.RULE_column_name
]
}
}
})
const sql = 'SELECT a| FROM t'
const caretColumn = sql.indexOf('|') + 1
const result = myPlugin.parse(sql.replace('|', ''), { lineNumber: 1, columnNumber: caretColumn })
console.log(result)
```
**Notice: A rule must start with a/an statement/entity and stop with an entity. You should add a node keywords(keyword is in your parser with format: `RULE_[keyword]`) into stmts/entities before using it.**
2024-06-05 16:01:24 +08:00
## Rule Chain Operator
2024-05-15 19:35:40 +08:00
You can set a negative number whose abs equals to a ruleIndex. That means exclude this rule.
Example:
```typescript
select_target_alias: [
PostgreSqlParser.RULE_target_el,
-PostgreSqlParser.RULE_attr_name,
PostgreSqlParser.RULE_collabel
]
```
🚧 I will later work on `Operator.AND` and `Operator.OR`.
## Alias
2024-05-15 19:57:04 +08:00
Some node names in dt-sql-parser code are different from their antlr4's definition.
2024-05-15 19:35:40 +08:00
Example:
2024-05-16 09:51:17 +08:00
2024-05-15 19:35:40 +08:00
![alt text](./assets/alias-example.png)
2024-05-17 16:48:51 +08:00
You can find possible alias in https://github.com/DTStack/dt-sql-parser/blob/main/src/grammar/postgresql/PostgreSqlParser.g4, then add it into `alias` option.
2024-05-15 19:35:40 +08:00
2024-04-07 19:10:38 +08:00
## Add a preprocessor
```typescript
const myPlugin = new DtSqlParserSemAnalysePlugin({
preprocessor: [
2024-05-16 09:51:17 +08:00
(sql) => sql.toUpperCase(),
...
]
2024-04-07 19:10:38 +08:00
})
```