2022-01-19 10:02:52 +08:00
|
|
|
import Database, { MagicAttributeModel } from '@nocobase/database';
|
2022-02-22 16:11:19 +08:00
|
|
|
import { SyncOptions, Transactionable } from 'sequelize';
|
2022-01-19 10:02:52 +08:00
|
|
|
|
2022-01-24 14:57:04 +08:00
|
|
|
interface LoadOptions extends Transactionable {
|
2022-01-19 10:02:52 +08:00
|
|
|
// TODO
|
|
|
|
skipExist?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class FieldModel extends MagicAttributeModel {
|
|
|
|
get db(): Database {
|
|
|
|
return (<any>this.constructor).database;
|
|
|
|
}
|
|
|
|
|
|
|
|
async load(loadOptions?: LoadOptions) {
|
2022-01-24 14:10:35 +08:00
|
|
|
const { skipExist = false } = loadOptions || {};
|
2022-01-19 10:02:52 +08:00
|
|
|
const collectionName = this.get('collectionName');
|
|
|
|
if (!this.db.hasCollection(collectionName)) {
|
2022-02-22 16:11:19 +08:00
|
|
|
return;
|
2022-01-19 10:02:52 +08:00
|
|
|
}
|
|
|
|
const collection = this.db.getCollection(collectionName);
|
|
|
|
const name = this.get('name');
|
|
|
|
if (skipExist && collection.hasField(name)) {
|
|
|
|
return collection.getField(name);
|
|
|
|
}
|
2022-06-10 17:46:46 +08:00
|
|
|
const options = this.get();
|
|
|
|
if (options.uiSchemaUid) {
|
|
|
|
const UISchema = this.db.getModel('uiSchemas');
|
|
|
|
const uiSchema = await UISchema.findByPk(options.uiSchemaUid, {
|
|
|
|
transaction: loadOptions.transaction,
|
|
|
|
});
|
2022-06-14 15:01:53 +08:00
|
|
|
return collection.setField(name, { ...options, uiSchema: uiSchema.get() });
|
2022-06-10 17:46:46 +08:00
|
|
|
} else {
|
|
|
|
return collection.setField(name, options);
|
|
|
|
}
|
2022-01-19 10:02:52 +08:00
|
|
|
}
|
|
|
|
|
2022-01-24 14:57:04 +08:00
|
|
|
async migrate(options?: SyncOptions & Transactionable) {
|
|
|
|
const field = await this.load({
|
|
|
|
transaction: options.transaction,
|
|
|
|
});
|
2022-02-22 16:11:19 +08:00
|
|
|
if (!field) {
|
|
|
|
return;
|
|
|
|
}
|
2022-06-11 20:46:30 +08:00
|
|
|
try {
|
|
|
|
await field.sync(options);
|
|
|
|
} catch (error) {
|
|
|
|
// field sync failed, delete from memory
|
|
|
|
field.remove();
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* TODO: drop column from the database
|
|
|
|
*
|
|
|
|
* @param options
|
|
|
|
* @returns
|
|
|
|
*/
|
|
|
|
async remove(options?: any) {
|
|
|
|
const collectionName = this.get('collectionName');
|
|
|
|
const fieldName = this.get('name');
|
|
|
|
if (!this.db.hasCollection(collectionName)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const collection = this.db.getCollection(collectionName);
|
|
|
|
// delete from memory
|
|
|
|
const result = collection.removeField(this.get('name'));
|
|
|
|
// TODO: drop column from the database
|
|
|
|
// this.db.sequelize.getQueryInterface().removeColumn(collectionName, fieldName);
|
|
|
|
return result;
|
2022-01-19 10:02:52 +08:00
|
|
|
}
|
|
|
|
}
|