Skip to content

Commit

Permalink
feat: allow creating model instance with a specific id (#679)
Browse files Browse the repository at this point in the history
  • Loading branch information
jamemackson authored and zacharygolba committed Feb 14, 2017
1 parent 33a0ef3 commit 2e223df
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
9 changes: 8 additions & 1 deletion src/packages/database/model/utils/persistence.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,19 @@ export function create(record: Model, trx: Object): Array<Object> {
updatedAt: timestamp
});

const { constructor: { primaryKey } } = record;
const columns = omit(getColumns(record), primaryKey);

if (record.dirtyAttributes.has(primaryKey)) {
columns[primaryKey] = record.getPrimaryKey();
}

return [
record.constructor
.table()
.transacting(trx)
.returning(record.constructor.primaryKey)
.insert(omit(getColumns(record), record.constructor.primaryKey))
.insert(columns)
];
}

Expand Down
14 changes: 12 additions & 2 deletions src/packages/database/test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,13 +348,13 @@ describe('module "database/model"', () => {
};
}

before(async () => {
beforeEach(async () => {
await Subject.initialize(store, () => {
return store.connection(Subject.tableName);
});
});

after(async () => {
afterEach(async () => {
await result.destroy();
});

Expand Down Expand Up @@ -382,6 +382,16 @@ describe('module "database/model"', () => {
// $FlowIgnore
expect(await result.user).to.have.property('id', user.getPrimaryKey());
});

it('constructs and persists a `Model` instance with an integer id specified', async () => {
const id = 999;

result = await Subject.create({ id });

expect(result).to.be.an.instanceof(Subject);
expect(result).to.have.property('id', id);
});

});

describe('.transacting()', async () => {
Expand Down

0 comments on commit 2e223df

Please sign in to comment.