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
51 lines (44 loc) · 1.35 KB
/
Copy pathparser.js
File metadata and controls
51 lines (44 loc) · 1.35 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
'use strict'
const parseFn = require('../build/pegjs-parser').parse
class Parser {
sqlToAst(sql) {
const astInfo = this.parse(sql)
return astInfo && astInfo.ast
}
parse(sql) {
return parseFn(sql)
}
whiteListCheck(sql, whiteList, type = 'table') {
if (!whiteList || whiteList.length === 0) return
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)
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) {
const astInfo = this.parse(sql)
return astInfo && astInfo.tableList
}
columnList(sql) {
const astInfo = this.parse(sql)
return astInfo && astInfo.columnList
}
}
module.exports = Parser