-
Notifications
You must be signed in to change notification settings - Fork 4
/
combinable-logic.js
60 lines (54 loc) · 1.64 KB
/
combinable-logic.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
const sqlString = require(`sqlstring`)
const { build } = require(`./build-logic.js`)
const combinableType = {
text: `text`,
clauses: `clauses`,
}
const buildCombinable = (combinableArray, joinedBy = `\n`) => combinableArray.map(({ type, clauses, text }) => {
if (type === combinableType.text) {
return { sql: text, values: [] }
} else if (type === combinableType.clauses) {
return build(clauses, joinedBy)
}
throw new Error(`TehShrike messed up and somehow referenced a combinable type that isn't supported: "${type}"`)
}).reduce((combined, { sql, values }) => {
if (combined) {
return {
sql: combined.sql + joinedBy + sql,
values: [
...combined.values,
...values,
],
}
} else {
return {
sql,
values,
}
}
}, null)
const makeCombinableQueries = combinableArray => ({
union: ({ getClauses }) => makeCombinableQueries([
...combinableArray,
{ text: `UNION`, type: combinableType.text },
{ clauses: getClauses(), type: combinableType.clauses },
]),
unionAll: ({ getClauses }) => makeCombinableQueries([
...combinableArray,
{ text: `UNION ALL`, type: combinableType.text },
{ clauses: getClauses(), type: combinableType.clauses },
]),
build: joinedBy => buildCombinable(combinableArray, joinedBy),
toString: joinedBy => {
const { sql, values } = buildCombinable(combinableArray, joinedBy)
return sqlString.format(sql, values)
},
})
const combineClauses = (clausesA, combineText, clausesB) => makeCombinableQueries([
{ clauses: clausesA, type: combinableType.clauses },
{ text: combineText, type: combinableType.text },
{ clauses: clausesB, type: combinableType.clauses },
])
module.exports = {
combineClauses,
}