formatter.js
5.1 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import QueryBuilder from './query/builder';
import Raw from './raw';
import { transform } from 'lodash'
// Valid values for the `order by` clause generation.
const orderBys = ['asc', 'desc'];
// Turn this into a lookup map
const operators = transform([
'=', '<', '>', '<=', '>=', '<>', '!=', 'like',
'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp', '~', '~*', '!~', '!~*',
'#', '&&', '@>', '<@', '||'
], (result, key) => {
result[key] = true
}, {});
export default class Formatter {
constructor(client) {
this.client = client
this.bindings = []
}
// Accepts a string or array of columns to wrap as appropriate.
columnize(target) {
const columns = typeof target === 'string' ? [target] : target
let str = '', i = -1;
while (++i < columns.length) {
if (i > 0) str += ', '
str += this.wrap(columns[i])
}
return str
}
// Turns a list of values into a list of ?'s, joining them with commas unless
// a "joining" value is specified (e.g. ' and ')
parameterize(values, notSetValue) {
if (typeof values === 'function') return this.parameter(values);
values = Array.isArray(values) ? values : [values];
let str = '', i = -1;
while (++i < values.length) {
if (i > 0) str += ', '
str += this.parameter(values[i] === undefined ? notSetValue : values[i])
}
return str;
}
// Checks whether a value is a function... if it is, we compile it
// otherwise we check whether it's a raw
parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
}
unwrapRaw(value, isParameter) {
let query;
if (value instanceof QueryBuilder) {
query = this.client.queryCompiler(value).toSQL()
if (query.bindings) {
this.bindings = this.bindings.concat(query.bindings);
}
return this.outputQuery(query, isParameter);
}
if (value instanceof Raw) {
value.client = this.client;
query = value.toSQL()
if (query.bindings) {
this.bindings = this.bindings.concat(query.bindings);
}
return query.sql
}
if (isParameter) {
this.bindings.push(value);
}
}
rawOrFn(value, method) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value, method));
}
return this.unwrapRaw(value) || '';
}
// Puts the appropriate wrapper around a value depending on the database
// engine, unless it's a knex.raw value, in which case it's left alone.
wrap(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (typeof value === 'number') return value;
return this._wrapString(value + '');
}
wrapAsIdentifier(value) {
return this.client.wrapIdentifier((value || '').trim());
}
alias(first, second) {
return first + ' as ' + second;
}
// The operator method takes a value and returns something or other.
operator(value) {
const raw = this.unwrapRaw(value);
if (raw) return raw;
if (operators[(value || '').toLowerCase()] !== true) {
throw new TypeError(`The operator "${value}" is not permitted`);
}
return value;
}
// Specify the direction of the ordering.
direction(value) {
const raw = this.unwrapRaw(value);
if (raw) return raw;
return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc';
}
// Compiles a callback using the query builder.
compileCallback(callback, method) {
const { client } = this;
// Build the callback
const builder = client.queryBuilder();
callback.call(builder, builder);
// Compile the callback, using the current formatter (to track all bindings).
const compiler = client.queryCompiler(builder);
compiler.formatter = this;
// Return the compiled & parameterized sql.
return compiler.toSQL(method || 'select');
}
// Ensures the query is aliased if necessary.
outputQuery(compiled, isParameter) {
let sql = compiled.sql || '';
if (sql) {
if (
(compiled.method === 'select' || compiled.method === 'first') &&
(isParameter || compiled.as)
) {
sql = `(${sql})`;
if (compiled.as) return this.alias(sql, this.wrap(compiled.as))
}
}
return sql;
}
// Coerce to string to prevent strange errors when it's not a string.
_wrapString(value) {
const asIndex = value.toLowerCase().indexOf(' as ');
if (asIndex !== -1) {
const first = value.slice(0, asIndex)
const second = value.slice(asIndex + 4)
return this.alias(this.wrap(first), this.wrapAsIdentifier(second))
}
const wrapped = [];
let i = -1;
const segments = value.split('.');
while (++i < segments.length) {
value = segments[i];
if (i === 0 && segments.length > 1) {
wrapped.push(this.wrap((value || '').trim()));
} else {
wrapped.push(this.client.wrapIdentifier((value || '').trim()));
}
}
return wrapped.join('.');
}
}