Skip to content

Commit

Permalink
Merge pull request #236 from ataft/composite-key
Browse files Browse the repository at this point in the history
allows composite keys on migration only
  • Loading branch information
dhmlau authored Oct 17, 2021
2 parents 8bc29f7 + 3852180 commit 80d555c
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/migration.js
Original file line number Diff line number Diff line change
Expand Up @@ -355,13 +355,15 @@ function mixinMigration(MsSQL) {
// debugger;
const self = this;
const objModel = this._models[model];
const modelPKID = this.idName(model);
const modelPKIDs = this.idNames(model);
let j=0;

const sql = [];
const props = Object.keys(objModel.properties);
for (let i = 0, n = props.length; i < n; i++) {
const prop = props[i];
if (prop === modelPKID) {
if (modelPKIDs && modelPKIDs.indexOf(prop) !== -1) {
const modelPKID = modelPKIDs[j++];
const idProp = objModel.properties[modelPKID];
if (idProp.type === Number) {
if (idProp.generated !== false) {
Expand All @@ -387,9 +389,9 @@ function mixinMigration(MsSQL) {
}
let joinedSql = sql.join(',' + MsSQL.newline + ' ');
let cmd = '';
if (modelPKID) {
if (modelPKIDs && modelPKIDs.length) {
cmd = 'PRIMARY KEY CLUSTERED' + MsSQL.newline + '(' + MsSQL.newline;
cmd += ' ' + self.columnEscaped(model, modelPKID) + ' ASC' + MsSQL.newline;
cmd += ' ' + modelPKIDs.map(function(modelPKID) { return self.columnEscaped(model, modelPKID) + ' ASC'; }).join(', ') + MsSQL.newline;
cmd += ') WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, ' +
'IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)';
}
Expand Down
55 changes: 55 additions & 0 deletions test/id.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,61 @@ describe('Manipulating id column', function() {
});
});

it('should create composite key', function(done) {
const schema =
{
name: 'CompositeKeyTest',
options: {
idInjection: false,
mssql: {
schema: 'dbo',
table: 'COMPOSITE_KEY_TEST',
},
},
properties: {
idOne: {
type: 'Number',
id: true,
generated: false,
},
idTwo: {
type: 'Number',
id: true,
generated: false,
},
name: {
type: 'String',
required: false,
length: 40,
},
},
};

const models = ds.modelBuilder.buildModels(schema);
const Model = models.CompositeKeyTest;
Model.attachTo(ds);

ds.automigrate(function(err) {
assert(!err);
async.series([
function(callback) {
Model.destroyAll(callback);
},
function(callback) {
Model.create({idOne: 1, idTwo: 2, name: 'w1'},
callback);
},
function(callback) {
ds.discoverPrimaryKeys('COMPOSITE_KEY_TEST', function(err, models) {
if (err) return done(err);
assert(models.length === 2);
callback();
});
},
], done);
});
});

it('should use bigint id', function(done) {
const schema =
{
Expand Down

0 comments on commit 80d555c

Please sign in to comment.