-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathindex.js
89 lines (80 loc) · 2.02 KB
/
index.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict'
class SQLStatement {
/**
* @param {string[]} strings
* @param {any[]} values
*/
constructor(strings, values) {
this.strings = strings
this.values = values
}
/** Returns the SQL Statement for Sequelize */
get query() {
return this.bind ? this.text : this.sql
}
/** Returns the SQL Statement for node-postgres */
get text() {
return this.strings.reduce((prev, curr, i) => prev + '$' + i + curr)
}
/**
* @param {SQLStatement|string} statement
* @returns {this}
*/
append(statement) {
if (statement instanceof SQLStatement) {
this.strings[this.strings.length - 1] += statement.strings[0]
this.strings.push.apply(this.strings, statement.strings.slice(1))
const list = this.values || this.bind
list.push.apply(list, statement.values)
} else {
this.strings[this.strings.length - 1] += statement
}
return this
}
/**
* Use a prepared statement with Sequelize.
* Makes `query` return a query with `$n` syntax instead of `?` and switches the `values` key name to `bind`
* @param {boolean} [value=true] value If omitted, defaults to `true`
* @returns this
*/
useBind(value) {
if (value === undefined) {
value = true
}
if (value && !this.bind) {
this.bind = this.values
delete this.values
} else if (!value && this.bind) {
this.values = this.bind
delete this.bind
}
return this
}
/**
* @param {string} name
* @returns {this}
*/
setName(name) {
this.name = name
return this
}
}
/** Returns the SQL Statement for mysql */
Object.defineProperty(SQLStatement.prototype, 'sql', {
enumerable: true,
get() {
return this.strings.join('?')
},
})
/**
* @param {string[]} strings
* @param {...any} values
* @returns {SQLStatement}
*/
function SQL(strings) {
return new SQLStatement(strings.slice(0), Array.from(arguments).slice(1))
}
module.exports = SQL
module.exports.SQL = SQL
module.exports.default = SQL
module.exports.SQLStatement = SQLStatement