forked from taozhi8833998/node-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
76 lines (69 loc) · 2.2 KB
/
parser.js
File metadata and controls
76 lines (69 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { parse as bigquery } from '../build/bigquery'
import { parse as db2 } from '../build/db2'
import { parse as hive } from '../build/hive'
import { parse as mysql } from '../build/mysql'
import { parse as mariadb } from '../build/mariadb'
import { parse as postgresql } from '../build/postgresql'
import { parse as transactsql } from '../build/transactsql'
import astToSQL from './sql'
import { DEFAULT_OPT, setParserOpt } from './util'
const parser = {
bigquery,
db2,
hive,
mysql,
mariadb,
postgresql,
transactsql,
}
class Parser {
astify(sql, opt = DEFAULT_OPT) {
const astInfo = this.parse(sql, opt)
return astInfo && astInfo.ast
}
sqlify(ast, opt = DEFAULT_OPT) {
setParserOpt(opt)
return astToSQL(ast, opt)
}
parse(sql, opt = DEFAULT_OPT) {
const { database = 'mysql' } = opt
setParserOpt(opt)
const typeCase = database.toLowerCase()
if (parser[typeCase]) return parser[typeCase](sql.trim())
throw new Error(`${database} is not supported currently`)
}
whiteListCheck(sql, whiteList, opt = DEFAULT_OPT) {
if (!whiteList || whiteList.length === 0) return
const { type = 'table' } = opt
if (!this[`${type}List`] || typeof this[`${type}List`] !== 'function') throw new Error(`${type} is not valid check mode`)
const checkFun = this[`${type}List`].bind(this)
const authorityList = checkFun(sql, opt)
let hasAuthority = true
let denyInfo = ''
for (const authority of authorityList) {
let hasCorrespondingAuthority = false
for (const whiteAuthority of whiteList) {
const regex = new RegExp(whiteAuthority, 'i')
if (regex.test(authority)) {
hasCorrespondingAuthority = true
break
}
}
if (!hasCorrespondingAuthority) {
denyInfo = authority
hasAuthority = false
break
}
}
if (!hasAuthority) throw new Error(`authority = '${denyInfo}' is required in ${type} whiteList to execute SQL = '${sql}'`)
}
tableList(sql, opt) {
const astInfo = this.parse(sql, opt)
return astInfo && astInfo.tableList
}
columnList(sql, opt) {
const astInfo = this.parse(sql, opt)
return astInfo && astInfo.columnList
}
}
export default Parser