diff --git a/lib/migration.js b/lib/migration.js index 6778526..38f0193 100644 --- a/lib/migration.js +++ b/lib/migration.js @@ -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) { @@ -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)'; } diff --git a/test/id.test.js b/test/id.test.js index b330edf..af0dc40 100644 --- a/test/id.test.js +++ b/test/id.test.js @@ -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 = {