100 lines
2.2 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-06-17 16:17:15 +02:00
const createSchemaStorage = require('./schema-storage');
const { diffSchemas } = require('./schema-diff');
const { metadataToSchema, createTable } = require('./schema');
const addInternalTables = schema => {
schema.addTable(
createTable({
tableName: 'strapi_database_schema',
attributes: {
id: {
type: 'increments',
},
schema: {
type: 'json',
},
createdAt: {
type: 'datetime',
},
},
})
);
};
2021-05-18 10:16:03 +02:00
const createSchemaProvider = db => {
2021-06-17 16:17:15 +02:00
const currentSchema = metadataToSchema(db.metadata);
// Add Internal tables to schema
addInternalTables(currentSchema);
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),
schemaStorage: createSchemaStorage(db),
/**
* Drops the database schema
*/
async drop() {
const DBSchema = await this.schemaStorage.read();
if (!DBSchema) {
return;
}
await this.builder.dropSchema(DBSchema);
},
/**
* Creates the database schema
*/
async create() {
await this.builder.createSchema(currentSchema);
await this.schemaStorage.create(currentSchema);
},
/**
* 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-06-02 15:53:22 +02:00
async sync() {
2021-06-17 16:17:15 +02:00
// load previous schema
const DBSchema = await this.schemaStorage.read();
if (!DBSchema) {
return this.create();
}
// run migrations
// reload updated schema
// diff schema
const { status, diff } = diffSchemas(DBSchema, currentSchema);
// TODO: replace by schemaDiff.hasChanged()
if (status === 'UNCHANGED') {
console.log('Unchanged');
// NOTE: should we still update the schema in DB ?
return;
}
// update schema
await this.builder.updateSchema(diff);
// persist new schema
await this.schemaStorage.update(currentSchema);
2021-06-02 15:53:22 +02:00
},
};
2021-05-18 10:16:03 +02:00
};
module.exports = createSchemaProvider;