forked from thomas4019/mongo-query-to-postgres-jsonb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
303 lines (291 loc) · 11.8 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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
const util = require('./util.js')
// These are the simple operators.
// Note that "is distinct from" needs to be used to ensure nulls are returned as expected, see https://modern-sql.com/feature/is-distinct-from
const OPS = {
$eq: '=',
$gt: '>',
$gte: '>=',
$lt: '<',
$lte: '<=',
$ne: ' IS DISTINCT FROM ',
}
const OTHER_OPS = {
$all: true, $in: true, $nin: true, $not: true, $or: true, $and: true, $elemMatch: true, $regex: true, $type: true, $size: true, $exists: true, $mod: true, $text: true
}
function getMatchingArrayPath(op, arrayPaths) {
if (arrayPaths === true) {
// always assume array path if true is passed
return true
}
if (!arrayPaths || !Array.isArray(arrayPaths)) {
return false
}
return arrayPaths.find(path => op.startsWith(path))
}
/**
* @param path array path current key
* @param op current key, might be a dotted path
* @param value
* @param parent
* @param arrayPathStr
* @returns {string|string|*}
*/
function createElementOrArrayQuery(path, op, value, parent, arrayPathStr, options) {
const arrayPath = arrayPathStr.split('.')
const deeperPath = op.split('.').slice(arrayPath.length)
const innerPath = ['value', ...deeperPath]
const pathToMaybeArray = path.concat(arrayPath)
// TODO: nested array paths are not yet supported.
const singleElementQuery = convertOp(path, op, value, parent, [], options)
const text = util.pathToText(pathToMaybeArray, false)
const safeArray = `jsonb_typeof(${text})='array' AND`
let arrayQuery = ''
const specialKeys = getSpecialKeys(path, value, true)
if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
if (typeof value['$size'] !== 'undefined') {
// size does not support array element based matching
} else if (value['$elemMatch']) {
const sub = convert(innerPath, value['$elemMatch'], [], false, options)
arrayQuery = `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
return arrayQuery
} else if (value['$in']) {
const sub = convert(innerPath, value, [], true, options)
arrayQuery = `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
} else if (value['$all']) {
const cleanedValue = value['$all'].filter((v) => (v !== null && typeof v !== 'undefined'))
arrayQuery = '(' + cleanedValue.map(function (subquery) {
const sub = convert(innerPath, subquery, [], false, options)
return `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
}).join(' AND ') + ')'
} else if (specialKeys.length === 0) {
const sub = convert(innerPath, value, [], true, options)
arrayQuery = `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
} else {
const params = value
arrayQuery = '(' + Object.keys(params).map(function (subKey) {
const sub = convert(innerPath, { [subKey]: params[subKey] }, [], true, options)
return `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
}).join(' AND ') + ')'
}
} else {
const sub = convert(innerPath, value, [], true, options)
arrayQuery = `EXISTS (SELECT * FROM jsonb_array_elements(${text}) WHERE ${safeArray} ${sub})`
}
if (!arrayQuery || arrayQuery === '()') {
return singleElementQuery
}
return `(${singleElementQuery} OR ${arrayQuery})`
}
/**
* @param path {string} a dotted path
* @param op {string} sub path, especially the current operation to convert, e.g. $in
* @param value {mixed}
* @param parent {mixed} parent[path] = value
* @param arrayPaths {Array} List of dotted paths that possibly need to be handled as arrays.
*/
function convertOp(path, op, value, parent, arrayPaths, options) {
const arrayPath = getMatchingArrayPath(op, arrayPaths)
// It seems like direct matches shouldn't be array fields, but 2D arrays are possible in MongoDB
// I will need to do more testing to see if we should handle this case differently.
// const arrayDirectMatch = !isSpecialOp(op) && Array.isArray(value)
if (arrayPath) {
return createElementOrArrayQuery(path, op, value, parent, arrayPath, options)
}
switch (op) {
case '$not':
return '(NOT ' + convert(path, value, undefined, false, options) + ')'
case '$nor': {
for (const v of value) {
if (typeof v !== 'object') {
throw new Error('$or/$and/$nor entries need to be full objects')
}
}
const notted = value.map((e) => ({ $not: e }))
return convertOp(path, '$and', notted, value, arrayPaths, options)
}
case '$or':
case '$and':
if (!Array.isArray(value)) {
throw new Error('$and or $or requires an array.')
}
if (value.length == 0) {
throw new Error('$and/$or/$nor must be a nonempty array')
} else {
for (const v of value) {
if (typeof v !== 'object') {
throw new Error('$or/$and/$nor entries need to be full objects')
}
}
return '(' + value.map((subquery) => convert(path, subquery, arrayPaths, false, options)).join(op === '$or' ? ' OR ' : ' AND ') + ')'
}
// TODO (make sure this handles multiple elements correctly)
case '$elemMatch':
return convert(path, value, arrayPaths, false, options)
//return util.pathToText(path, false) + ' @> \'' + util.stringEscape(JSON.stringify(value)) + '\'::jsonb'
case '$in': {
if (value.length === 0) {
return 'FALSE'
}
if (value.length === 1) {
return convert(path, value[0], arrayPaths, false, options)
}
const cleanedValue = value.filter((v) => (v !== null && typeof v !== 'undefined'))
let partial = util.pathToText(path, typeof value[0] == 'string') + (op == '$nin' ? ' NOT' : '') + ' IN (' + cleanedValue.map(util.quote).join(', ') + ')'
if (value.length != cleanedValue.length) {
return (op === '$in' ? '(' + partial + ' OR IS NULL)' : '(' + partial + ' AND IS NOT NULL)')
}
return partial
}
case '$nin': {
/* if (value.length === 0) {
return 'FALSE'
}
if (value.length === 1) {
return convert(path, value[0], arrayPaths, false, options)
} */
const cleanedValue = value.filter((v) => (v !== null && typeof v !== 'undefined'))
let partial = util.pathToText(path, typeof value[0] == 'string') + (op == '$nin' ? ' NOT' : '') + ' IN (' + cleanedValue.map(util.quote).join(', ') + ')'
if (value.length != cleanedValue.length) {
return (op === '$in' ? '(' + partial + ' OR IS NULL)' : '(' + partial + ' AND IS NOT NULL)')
}
return partial
}
case '$text': {
const newOp = '~' + (!value['$caseSensitive'] ? '*' : '')
return util.pathToText(path, true) + ' ' + newOp + ' \'' + util.stringEscape(value['$search']) + '\''
}
case '$regex': {
var regexOp = '~'
var op2 = ''
if (parent['$options'] && parent['$options'].includes('i')) {
regexOp += '*'
}
if (!parent['$options'] || !parent['$options'].includes('s')) {
// partial newline-sensitive matching
op2 += '(?p)'
}
if (value instanceof RegExp) {
value = value.source
}
return util.pathToText(path, true) + ' ' + regexOp + ' \'' + op2 + util.stringEscape(value) + '\''
}
case '$gt':
case '$gte':
case '$lt':
case '$lte':
case '$ne':
case '$eq': {
const isSimpleComparision = (op === '$eq' || op === '$ne')
const pathContainsArrayAccess = path.some((key) => /^\d+$/.test(key))
if (isSimpleComparision && !pathContainsArrayAccess && !options.disableContainmentQuery) {
// create containment query since these can use GIN indexes
// See docs here, https://www.postgresql.org/docs/9.4/datatype-json.html#JSON-INDEXING
const [head, ...tail] = path
return `${op == '$ne' ? 'NOT ' : ''}${head} @> ` + util.pathToObject([...tail, value])
} else {
var text = util.pathToText(path, typeof value == 'string')
return text + OPS[op] + util.quote(value)
}
}
case '$type': {
const text = util.pathToText(path, false)
const type = util.getPostgresTypeName(value)
return 'jsonb_typeof(' + text + ')=' + util.quote(type)
}
case '$size': {
if (typeof value !== 'number' || value < 0 || !Number.isInteger(value)) {
throw new Error('$size only supports positive integer')
}
const text = util.pathToText(path, false)
return 'jsonb_array_length(' + text + ')=' + value
}
case '$exists': {
if (path.length > 1) {
const key = path.pop()
const text = util.pathToText(path, false)
return (value ? '' : ' NOT ') + text + ' ? ' + util.quote(key)
} else {
const text = util.pathToText(path, false)
return text + ' IS ' + (value ? 'NOT ' : '') + 'NULL'
}
}
case '$mod': {
const text = util.pathToText(path, true)
if (typeof value[0] != 'number' || typeof value[1] != 'number') {
throw new Error('$mod requires numeric inputs')
}
return 'cast(' + text + ' AS numeric) % ' + value[0] + '=' + value[1]
}
default:
// this is likely a top level field, recurse
return convert(path.concat(op.split('.')), value, undefined, false, options)
}
}
function isSpecialOp(op) {
return op in OPS || op in OTHER_OPS
}
// top level keys are always special, since you never exact match the whole object
function getSpecialKeys(path, query, forceExact) {
return Object.keys(query).filter(function (key) {
return (path.length === 1 && !forceExact) || isSpecialOp(key)
})
}
/**
* Convert a filter expression to the corresponding PostgreSQL text.
* @param path {Array} The current path
* @param query {Mixed} Any value
* @param arrayPaths {Array} List of dotted paths that possibly need to be handled as arrays.
* @param forceExact {Boolean} When true, an exact match will be required.
* @returns The corresponding PSQL expression
*/
var convert = function (path, query, arrayPaths, forceExact, options) {
if (typeof query === 'string' || typeof query === 'boolean' || typeof query == 'number' || Array.isArray(query)) {
return convertOp(path, '$eq', query, {}, arrayPaths, options)
}
if (query === null) {
const text = util.pathToText(path, false)
return '(' + text + ' IS NULL OR ' + text + ' = \'null\'::jsonb)'
}
if (query instanceof RegExp) {
var op = query.ignoreCase ? '~*' : '~'
return util.pathToText(path, true) + ' ' + op + ' \'' + util.stringEscape(query.source) + '\''
}
if (typeof query === 'object') {
// Check for an empty object
if (Object.keys(query).length === 0) {
return 'TRUE'
}
const specialKeys = getSpecialKeys(path, query, forceExact)
switch (specialKeys.length) {
case 0: {
const text = util.pathToText(path, typeof query == 'string')
return text + '=' + util.quote(query)
}
case 1: {
const key = specialKeys[0]
return convertOp(path, key, query[key], query, arrayPaths, options)
}
default:
return '(' + specialKeys.map(function (key) {
return convertOp(path, key, query[key], query, arrayPaths, options)
}).join(' and ') + ')'
}
}
}
module.exports = function (fieldName, query, arraysOrOptions) {
let arrays
let options = {}
if (arraysOrOptions && Array.isArray(arraysOrOptions)) {
arrays = arraysOrOptions
} else if (typeof arraysOrOptions === 'object') {
arrays = arraysOrOptions.arrays || []
options = arraysOrOptions
}
return convert([fieldName], query, arrays || [], false, options)
}
module.exports.convertDotNotation = util.convertDotNotation
module.exports.pathToText = util.pathToText
module.exports.countUpdateSpecialKeys = util.countUpdateSpecialKeys
module.exports.convertSelect = require('./select')
module.exports.convertUpdate = require('./update')
module.exports.convertSort = require('./sort')