Skip to content

Commit

Permalink
feat: added automatic schema creation to sequelize.sync() and model.c…
Browse files Browse the repository at this point in the history
…reate()
  • Loading branch information
yumin2002 committed Apr 26, 2024
1 parent c8729db commit a6b3c69
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/core/src/model.js
Expand Up @@ -1916,6 +1916,13 @@ ${associationOwner._getAssociationDebugList()}`);
static async create(values, options) {
options = cloneDeep(options) ?? {};

if (options.schema) {
const schemas = await this.queryInterface.listSchemas();
if (!schemas.includes(options.schema)) {
await this.queryInterface.createSchema(options.schema);
}
}

return await this.build(values, {
isNewRecord: true,
attributes: options.fields,
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/sequelize.js
Expand Up @@ -456,6 +456,13 @@ Use Sequelize#query if you wish to use replacements.`);
);
}

if (options.schema) {
const schemas = await this.queryInterface.listSchemas();
if (!schemas.includes(options.schema)) {
await this.queryInterface.createSchema(options.schema);
}
}

if (options.hooks) {
await this.hooks.runAsync('beforeBulkSync', options);
}
Expand Down
24 changes: 24 additions & 0 deletions packages/core/test/integration/model/create/include.test.js
Expand Up @@ -533,6 +533,30 @@ describe(Support.getTestDialectTeaser('Model'), () => {
expect(persistedUser.jobs).to.be.ok;
expect(persistedUser.jobs.length).to.equal(2);
});
it('should create a schema if the schema does not exist when create', async function () {
try {
const before = await this.sequelize.queryInterface.listSchemas();
const User = this.sequelize.define('User', {
username: DataTypes.STRING,
});
await this.sequelize.sync({ force: true });
await User.create(
{
username: 'John',
},
{
schema: 'temp',
},
);
const after = await this.sequelize.queryInterface.listSchemas();
const difference = after.length - before.length;
expect(difference).to.equal(1);
} catch (error) {
if (!error.message.includes('Schemas are not supported in')) {
throw error;
}
}
});
});
});
});
8 changes: 8 additions & 0 deletions packages/core/test/integration/model/sync.test.js
Expand Up @@ -687,6 +687,14 @@ describe(getTestDialectTeaser('Model.sync & Sequelize#sync'), () => {
});
expect(results).to.have.length(1);
});

it('should create a schema if the schema does not exist when syncing', async () => {
const before = await this.sequelize.queryInterface.listSchemas();
await sequelize.sync({ schema: 'temp' });
const after = await this.sequelize.queryInterface.listSchemas();
const difference = after.length - before.length;
expect(difference).to.equal(1);
});
}

// TODO add support for db2 and mssql dialects
Expand Down

0 comments on commit a6b3c69

Please sign in to comment.