Skip to content

Commit 75c9bf4

Browse files
committed
Add support for compound UNIQUE and PRIMARY KEY constraints
1 parent b95e63e commit 75c9bf4

File tree

4 files changed

+53
-2
lines changed

4 files changed

+53
-2
lines changed

helpers/query-types.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ queryTypes.add(
3030

3131
queryTypes.add(
3232
'create-table'
33-
, '{with} create table {ifNotExists} {table} ({definition})'
33+
, '{with} create table {ifNotExists} {table} ({definition}{constraints})'
3434
);
3535

3636
queryTypes.add(

helpers/query/constraints.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
var helpers = require('../../lib/query-helpers');
2+
var utils = require('../../lib/utils');
3+
4+
var quoteList = function(vals){
5+
return vals.map(function(val){
6+
return utils.quoteObject(val)
7+
}).join(', ');
8+
};
9+
10+
helpers.register('constraints', function(constraints, values, query){
11+
var output = [];
12+
13+
for (var k in constraints) {
14+
switch(k) {
15+
case 'primaryKey':
16+
output.push('primary key (' + quoteList(constraints[k]) +')');
17+
break;
18+
case 'unique':
19+
output.push('unique (' + quoteList(constraints[k]) + ')');
20+
break;
21+
}
22+
}
23+
24+
if (!output.length) return '';
25+
return ', ' + output.join(', ');
26+
});

index.js

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ require('./helpers/query/boolean-helpers');
2222
require('./helpers/query/cascade');
2323
require('./helpers/query/column-constraint');
2424
require('./helpers/query/columns');
25+
require('./helpers/query/constraints');
2526
require('./helpers/query/definition');
2627
require('./helpers/query/distinct');
2728
require('./helpers/query/expression');

test/create-table.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,6 @@ describe('Built-In Query Types', function(){
258258
}
259259
}
260260
});
261-
console.log(query.toString());
262261
assert.equal(
263262
query.toString()
264263
, [ 'create table "posts" ('
@@ -270,5 +269,30 @@ describe('Built-In Query Types', function(){
270269
);
271270
});
272271

272+
it('Should support table constraints', function(){
273+
var query = builder.sql({
274+
type: 'create-table'
275+
, table: 'foo'
276+
, definition: {
277+
name: { type: 'text' }
278+
, email: { type: 'text' }
279+
}
280+
281+
, constraints: {
282+
primaryKey: ['name', 'email']
283+
, unique: ['email', 'name']
284+
}
285+
});
286+
assert.equal(
287+
query.toString()
288+
, [ 'create table "foo" ('
289+
, '"name" text, "email" text, '
290+
, 'primary key ("name", "email"), '
291+
, 'unique ("email", "name")'
292+
, ')'
293+
].join('')
294+
);
295+
});
296+
273297
});
274298
});

0 commit comments

Comments
 (0)