Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support order by array of objects and preserve backward compatibility #126

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/query-helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,7 @@ Add an ORDER BY clause. There are many different acceptable inputs here best des
// quote your columns and add in the default table
, order: { id: 'desc', name: 'asc' }
, order: ['id desc', 'name asc']
, order: [{ id: 'desc'}, { name: 'asc'}]
, order: 'id desc'
}
```
Expand Down
14 changes: 13 additions & 1 deletion helpers/query/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,19 @@ helpers.register('order', function(order, values, query){

if (typeof order === 'string') return output + order;

if (Array.isArray(order)) return output + order.join(', ');
if (Array.isArray(order)) {
if (typeof order[0] === 'string') {
return output + order.join(', ');
} else {
for (var i in order) {
for (var key in order[i]){
output += utils.quoteObject(key, query.__defaultTable) + ' ' + order[i][key] + ', ';
}
}
return output.substring(0, output.length - 2);
}

}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me, we'll just need to make the tabs consistent (I know, I know nitpick). Just use two spaces and in place of tabs and I'll merge and get this pushed to npm


for (var key in order){
output += utils.quoteObject(key, query.__defaultTable) + ' ' + order[key] + ', ';
Expand Down
13 changes: 13 additions & 0 deletions test/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,19 @@ describe('Built-In Query Types', function(){
);
});

it ('order by array of objects', function(){
var query = builder.sql({
type: 'select'
, table: 'users'
, order: [{ id: 'desc'}, { name: 'asc'}]
});

assert.equal(
query.toString()
, 'select "users".* from "users" order by "users"."id" desc, "users"."name" asc'
);
});

it ('order by object', function(){
var query = builder.sql({
type: 'select'
Expand Down