Skip to content

Commit

Permalink
Add support for compound UNIQUE and PRIMARY KEY constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
brianc committed Jun 15, 2016
1 parent 6af93df commit 8ad15ab
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 2 deletions.
2 changes: 1 addition & 1 deletion helpers/query-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ queryTypes.add(

queryTypes.add(
'create-table'
, '{with} create table {ifNotExists} {table} ({definition})'
, '{with} create table {ifNotExists} {table} ({definition}{constraints})'
);

queryTypes.add(
Expand Down
26 changes: 26 additions & 0 deletions helpers/query/constraints.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var helpers = require('../../lib/query-helpers');
var utils = require('../../lib/utils');

var quoteList = function(vals){
return vals.map(function(val){
return utils.quoteObject(val)
}).join(', ');
};

helpers.register('constraints', function(constraints, values, query){
var output = [];

for (var k in constraints) {
switch(k) {
case 'primaryKey':
output.push('primary key (' + quoteList(constraints[k]) +')');
break;
case 'unique':
output.push('unique (' + quoteList(constraints[k]) + ')');
break;
}
}

if (!output.length) return '';
return ', ' + output.join(', ');
});
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ require('./helpers/query/cascade');
require('./helpers/query/column-constraint');
require('./helpers/query/columns');
require('./helpers/query/conflict');
require('./helpers/query/constraints');
require('./helpers/query/definition');
require('./helpers/query/distinct');
require('./helpers/query/expression');
Expand Down
26 changes: 25 additions & 1 deletion test/create-table.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,6 @@ describe('Built-In Query Types', function(){
}
}
});

assert.equal(
query.toString()
, [ 'create table "posts" ('
Expand All @@ -270,5 +269,30 @@ describe('Built-In Query Types', function(){
);
});

it('Should support table constraints', function(){
var query = builder.sql({
type: 'create-table'
, table: 'foo'
, definition: {
name: { type: 'text' }
, email: { type: 'text' }
}

, constraints: {
primaryKey: ['name', 'email']
, unique: ['email', 'name']
}
});
assert.equal(
query.toString()
, [ 'create table "foo" ('
, '"name" text, "email" text, '
, 'primary key ("name", "email"), '
, 'unique ("email", "name")'
, ')'
].join('')
);
});

});
});

0 comments on commit 8ad15ab

Please sign in to comment.