61 lines
1.5 KiB
JavaScript
Raw Normal View History

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');
const { metadataToSchema } = require('./schema');
2021-05-18 10:16:03 +02:00
const createSchemaProvider = db => {
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() {
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() {
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
// 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
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
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;