Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async function crud(socket, reqId, databaseName, commandName, doc, build) {
const normalizedCommandName = commandName.toLowerCase()
let rawCollectionName = doc[commandName] || doc[normalizedCommandName]
let collectionName = '"' + rawCollectionName + '"'
if (commandName === 'distinct') {
if ((doc.query && typeof doc.query !== 'object') || typeof doc.key !== 'string') {
socket.write(build(reqId, { ok: 0, errmsg: '"query" had the wrong type. Expected object or null,', code: 14 }, {}))
//throw new Error('\\"query\\" had the wrong type. Expected object or null, found ' + typeof doc.query)
return true
}
const filter = doc.query || {}
let where = safeWhereConversion(filter, rawCollectionName)
const distinctField = mongoToPostgres.pathToText(['data'].concat(doc.key.split('.')), false)
const arrayCondition = `jsonb_typeof(${distinctField})='array'`
const query1 = `SELECT DISTINCT ${distinctField} AS data FROM ${collectionName} WHERE ${where} AND NOT ${arrayCondition}`
const query2 = `SELECT DISTINCT jsonb_array_elements(${distinctField}) AS data FROM ${collectionName} WHERE ${where} AND ${arrayCondition}`
const query = `${query1} UNION ${query2}`
const res = await tryOrCreateTable(async () => await doQuery(databaseName, query), databaseName, collectionName)
const rows = res.rows.map((row) => convertToBSON(row.data))
debug('pgmongo:rows')(rows)
const data = { values: rows, ok: 1 }
socket.write(build(reqId, data, {}))
return true
}
if (commandName === 'find') {
const filter = doc.filter
const where = safeWhereConversion(filter, rawCollectionName)
let select = mongoToPostgres.convertSelect('data', doc.projection)
const pgPath = keys.map(function(key) {
const path = ['data'].concat(key.split('.'))
return mongoToPostgres.pathToText(path, false)
}).join(', ')
let indexQuery = `CREATE INDEX "${index.name}" ON ${collectionName} USING gin ((${pgPath}));`