This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (106 loc) · 2.04 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
function placeholderGenerator() {
let queryValues = []
return {
gen(value) {
queryValues.push(value)
return `$${queryValues.length}`
},
getValues() {
return queryValues
}
}
}
// for tagged template see
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
function sql(strings) {
const $ = placeholderGenerator()
let fillers = Array.from(arguments)
fillers.shift()
let result = [strings[0]]
fillers.forEach((filler, index) => {
result.push(filler($.gen), strings[index + 1])
})
return [result.join(''), $.getValues()]
}
function q($, unit) {
if(typeof unit === 'string') {
return unit
}
else if(Array.isArray(unit)) {
let value = unit[1]
if(value !== undefined) {
if(Array.isArray(value)) {
return [unit[0], `( ${value.map(avalue => $(avalue)).join(', ')} )`].join(' ')
}
else {
return [unit[0], $(value)].join(' ')
}
}
return undefined
}
else if (typeof unit === 'function') {
return unit($)
}
}
function and() {
const args = Array.from(arguments)
return ($) => {
const query = args
.map(item => {
return q($, item)
})
.filter(item => !!item)
.join(' AND ')
if(query) {
return `( ${query} )`
}
}
}
function or() {
const args = Array.from(arguments)
return ($) => {
const query = args
.map(item => {
return q($, item)
})
.filter(item => !!item)
.join(' OR ')
if(query) {
return `( ${query} )`
}
}
}
function where(orAnd) {
return ($) => {
const partialQuery = orAnd($)
if (partialQuery) {
return 'WHERE ' + partialQuery
}
return ''
}
}
function limit(value) {
return function ($) {
if(value) {
return `LIMIT ${$(value)}`
}
return ''
}
}
function offset(value) {
return function ($) {
if(value) {
return `OFFSET ${$(value)}`
}
return ''
}
}
module.exports = {
placeholderGenerator,
sql,
where,
limit,
offset,
and,
or
}