2021-05-18 10:16:03 +02:00
|
|
|
'use strict';
|
|
|
|
|
2021-06-02 15:53:22 +02:00
|
|
|
const createSchemaBuilder = require('./builder');
|
2021-09-15 12:25:09 +02:00
|
|
|
const createSchemaDiff = require('./schema-diff');
|
2021-09-16 11:44:43 +02:00
|
|
|
const { metadataToSchema } = require('./schema');
|
2021-05-18 10:16:03 +02:00
|
|
|
|
|
|
|
const createSchemaProvider = db => {
|
2021-09-16 11:44:43 +02:00
|
|
|
const schema = metadataToSchema(db.metadata);
|
2021-05-18 10:16:03 +02:00
|
|
|
|
2021-06-02 15:53:22 +02:00
|
|
|
return {
|
2021-06-17 16:17:15 +02:00
|
|
|
builder: createSchemaBuilder(db),
|
2021-09-15 12:25:09 +02:00
|
|
|
schemaDiff: createSchemaDiff(db),
|
2021-06-17 16:17:15 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Drops the database schema
|
|
|
|
*/
|
|
|
|
async drop() {
|
2021-09-16 11:44:43 +02:00
|
|
|
const DBSchema = await db.dialect.schemaInspector.getSchema();
|
2021-06-17 16:17:15 +02:00
|
|
|
await this.builder.dropSchema(DBSchema);
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates the database schema
|
|
|
|
*/
|
|
|
|
async create() {
|
2021-09-16 11:44:43 +02:00
|
|
|
await this.builder.createSchema(schema);
|
2021-06-17 16:17:15 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Resets the database schema
|
|
|
|
*/
|
|
|
|
async reset() {
|
|
|
|
await this.drop();
|
|
|
|
await this.create();
|
2021-06-02 15:53:22 +02:00
|
|
|
},
|
2021-06-17 16:17:15 +02:00
|
|
|
|
|
|
|
// TODO: support options to migrate softly or forcefully
|
|
|
|
// TODO: support option to disable auto migration & run a CLI command instead to avoid doing it at startup
|
2021-09-16 11:44:43 +02:00
|
|
|
// TODO: Allow keeping extra indexes / extra tables / extra columns (globally or on a per table basis)
|
2021-06-02 15:53:22 +02:00
|
|
|
async sync() {
|
2021-09-16 13:37:13 +02:00
|
|
|
// Run users migrations
|
2021-09-13 12:03:12 +02:00
|
|
|
db.migration.up();
|
2021-06-17 16:17:15 +02:00
|
|
|
|
2021-09-16 13:37:13 +02:00
|
|
|
// Read schema from DB
|
|
|
|
const DBSchema = await db.dialect.schemaInspector.getSchema();
|
|
|
|
|
|
|
|
// Diff schema
|
2021-09-16 11:44:43 +02:00
|
|
|
const { status, diff } = this.schemaDiff.diff(DBSchema, schema);
|
2021-09-15 12:25:09 +02:00
|
|
|
|
2021-06-17 16:17:15 +02:00
|
|
|
if (status === 'UNCHANGED') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-16 13:37:13 +02:00
|
|
|
// Update schema
|
2021-06-17 16:17:15 +02:00
|
|
|
await this.builder.updateSchema(diff);
|
2021-06-02 15:53:22 +02:00
|
|
|
},
|
|
|
|
};
|
2021-05-18 10:16:03 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = createSchemaProvider;
|