forked from taozhi8833998/node-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtables.js
More file actions
56 lines (51 loc) · 1.79 KB
/
Copy pathtables.js
File metadata and controls
56 lines (51 loc) · 1.79 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
import { identifierToSql, hasVal, commonOptionConnector, toUpper } from './util'
import { exprToSQL } from './expr'
function tableToSQL(tableInfo) {
const { table, db, as, expr } = tableInfo
const database = identifierToSql(db)
const tableName = table ? identifierToSql(table) : exprToSQL(expr)
const str = database ? `${database}.${tableName}` : tableName
if (as) return `${str} AS ${identifierToSql(as)}`
return str
}
function unnestToSQL(unnestExpr) {
const { type, as, expr, with_offset: withOffset } = unnestExpr
const result = [toUpper(type), `(${expr && exprToSQL(expr) || ' '})`, commonOptionConnector('AS', identifierToSql, as), commonOptionConnector(toUpper(withOffset && withOffset.keyword), identifierToSql, withOffset && withOffset.as)]
return result.filter(hasVal).join(' ')
}
/**
* @param {Array} tables
* @return {string}
*/
function tablesToSQL(tables) {
const { type } = tables
if (toUpper(type) === 'UNNEST') return unnestToSQL(tables)
const baseTable = tables[0]
const clauses = []
if (baseTable.type === 'dual') return 'DUAL'
clauses.push(tableToSQL(baseTable))
for (let i = 1; i < tables.length; ++i) {
const joinExpr = tables[i]
const { on, using, join } = joinExpr
const str = []
str.push(join ? ` ${join}` : ',')
str.push(tableToSQL(joinExpr))
str.push(commonOptionConnector('ON', exprToSQL, on))
if (using) str.push(`USING (${using.map(identifierToSql).join(', ')})`)
clauses.push(str.filter(hasVal).join(' '))
}
return clauses.filter(hasVal).join('')
}
function tableOptionToSQL(tableOption) {
const { keyword, symbol, value } = tableOption
const sql = [keyword.toUpperCase()]
if (symbol) sql.push(symbol)
sql.push(value)
return sql.join(' ')
}
export {
tablesToSQL,
tableOptionToSQL,
tableToSQL,
unnestToSQL,
}