forked from taozhi8833998/node-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.js
More file actions
55 lines (51 loc) · 1.67 KB
/
insert.js
File metadata and controls
55 lines (51 loc) · 1.67 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
import { tablesToSQL } from './tables'
import { exprToSQL } from './expr'
import { identifierToSql, commonOptionConnector, hasVal, toUpper, returningToSQL } from './util'
import { selectToSQL } from './select'
import { setToSQL } from './update'
/**
* @param {Array} values
* @return {string}
*/
function valuesToSQL(values) {
if (values.type === 'select') return selectToSQL(values)
const clauses = values.map(exprToSQL)
return `(${clauses.join('), (')})`
}
function partitionToSQL(partition) {
if (!partition) return ''
const partitionArr = ['PARTITION', '(']
if (Array.isArray(partition)) {
partitionArr.push(partition.map(identifierToSql).join(', '))
} else {
const { value } = partition
partitionArr.push(value.map(exprToSQL).join(', '))
}
partitionArr.push(')')
return partitionArr.filter(hasVal).join('')
}
function insertToSQL(stmt) {
const {
table,
prefix = 'into',
columns,
values,
where,
on_duplicate_update: onDuplicateUpdate,
partition,
returning,
set,
} = stmt
const { keyword, set: duplicateSet } = onDuplicateUpdate || {}
const clauses = ['INSERT', toUpper(prefix), tablesToSQL(table), partitionToSQL(partition)]
if (Array.isArray(columns)) clauses.push(`(${columns.map(identifierToSql).join(', ')})`)
clauses.push(commonOptionConnector(Array.isArray(values) ? 'VALUES' : '', valuesToSQL, values))
clauses.push(commonOptionConnector('SET', setToSQL, set))
clauses.push(commonOptionConnector('WHERE', exprToSQL, where))
clauses.push(returningToSQL(returning))
clauses.push(commonOptionConnector(keyword, setToSQL, duplicateSet))
return clauses.filter(hasVal).join(' ')
}
export {
insertToSQL,
}