Skip to content

Commit 135c290

Browse files
committed
add distinctOn for postgres
1 parent 12443e1 commit 135c290

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

lib/dialects/postgresql/blocks.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,23 @@ module.exports = function(dialect) {
4141
dialect.blocks.add('explain:verbose', function() {
4242
return 'verbose';
4343
});
44-
};
44+
45+
dialect.blocks.add('distinctOn', function(params) {
46+
var distinctOn = params.distinctOn;
47+
var result = '';
48+
49+
if (_.isString(distinctOn)) distinctOn = [distinctOn];
50+
51+
if (_.isArray(distinctOn)) {
52+
result = _(distinctOn).map(function(distinctOnField) {
53+
return dialect._wrapIdentifier(distinctOnField);
54+
}).join(', ');
55+
}
56+
57+
if (result) {
58+
result = 'distinct on (' + result + ')';
59+
}
60+
61+
return result;
62+
});
63+
};

lib/dialects/postgresql/templates.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,17 @@ module.exports = function(dialect) {
3333
templateChecks.propType(type, params, 'verbose', 'boolean');
3434
}
3535
});
36+
37+
// patch parent select to add some blocks
38+
var selectTemplate = dialect.templates.get('select');
39+
selectTemplate.pattern = selectTemplate.pattern.replace('{distinct}', '{distinct} {distinctOn}');
40+
41+
var parentSelectValidate = selectTemplate.validate;
42+
selectTemplate.validate = function(type, params) {
43+
parentSelectValidate(type, params);
44+
45+
templateChecks.propType(type, params, 'distinctOn', ['string', 'array']);
46+
};
47+
48+
dialect.templates.set('select', selectTemplate);
3649
};

tests/6_dialects/0_postgresql.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,4 +261,26 @@ describe('PostgreSQL dialect', function() {
261261
});
262262

263263
});
264+
265+
describe('select', function() {
266+
describe('distinctOn', function() {
267+
it('should be ok with string value', function() {
268+
var result = jsonSql.build({
269+
table: 'users',
270+
distinctOn: 'a'
271+
});
272+
273+
expect(result.query).to.be.equal('select distinct on ("a") * from "users";');
274+
});
275+
276+
it('should be ok with array value', function() {
277+
var result = jsonSql.build({
278+
table: 'users',
279+
distinctOn: ['a', 'b']
280+
});
281+
282+
expect(result.query).to.be.equal('select distinct on ("a", "b") * from "users";');
283+
});
284+
});
285+
});
264286
});

0 commit comments

Comments
 (0)