orange-orm
Version:
Object Relational Mapper
62 lines (54 loc) • 1.76 kB
JavaScript
const getSessionSingleton = require('../getSessionSingleton');
function extractOrderBy(context, table, alias, orderBy, originalOrderBy) {
const quote = getSessionSingleton(context, 'quote');
alias = quote(alias);
var dbNames = [];
var i;
if (orderBy) {
if (typeof orderBy === 'string')
orderBy = [orderBy];
for (i = 0; i < orderBy.length; i++) {
var nameAndDirection = extractNameAndDirection(orderBy[i]);
pushColumn(nameAndDirection.name, nameAndDirection.direction);
}
} else {
if(originalOrderBy)
return originalOrderBy;
for (i = 0; i < table._primaryColumns.length; i++) {
pushColumn(table._primaryColumns[i].alias);
}
}
function extractNameAndDirection(orderBy) {
var elements = orderBy.split(' ');
var direction = '';
if (elements.length > 1) {
direction = ' ' + elements[1];
}
return {
name: elements[0],
direction: direction
};
}
function pushColumn(property, direction) {
direction = direction || '';
var column = getTableColumn(property);
var jsonQuery = getJsonQuery(property, column.alias);
dbNames.push(alias + '.' + quote(column._dbName) + jsonQuery + direction);
}
function getTableColumn(property) {
var column = table[property] || table[property.split(/(-|
if(!column){
throw new Error(`Unable to get column on orderBy '${property}'. If jsonb query, only
}
return column;
}
function getJsonQuery(property, column) {
let containsJson = (/(-|
if(!containsJson){
return '';
}
return property.replace(column, '');
}
return ' order by ' + dbNames.join(',');
}
module.exports = extractOrderBy;