tachybase_todo/packages/plugins/collection-manager/src/models/collection.ts
ChengLei Shao 0832a56868
feat: multiple apps (#1540)
* chore: skip yarn install in pm command

* feat: dump sub app by sub app name

* feat: dump & restore by sub app

* chore: enable application name to edit

* chore: field belongsTo uiSchema

* test: drop schema

* feat: uiSchema migrator

* fix: test

* fix: remove uiSchema

* fix: rerun migration

* chore: migrate fieldsHistory uiSchema

* fix: set uiSchema options

* chore: transaction params

* fix: sql error in mysql

* fix: sql compatibility

* feat: collection group api

* chore: restore & dump action template

* chore: tmp commit

* chore: collectionGroupAction

* feat: dumpableCollection api

* refactor: dump command

* fix: remove uiSchemaUid

* chore: get uiSchemaUid from tmp field

* feat: return dumped file url in dumper.dump

* feat: dump api

* refactor: collection groyoup

* chore: comment

* feat: restore command force option

* feat: dump with collection groups

* refactor: restore command

* feat: restore http api

* fix: test

* fix: test

* fix: restore test

* chore: volta pin

* fix: sub app load collection options

* fix: stop sub app

* feat: add stopped status to application to prevent duplicate application stop

* chore: tmp commit

* test: upgrade

* feat: pass upgrade event to sub app

* fix: app manager client

* fix: remove stopped status

* fix: emit beforeStop event

* feat: support dump & restore subApp through api

* chore: dumpable collections api

* refactor: getTableNameWithSchema

* fix: schema name

* feat:  cname

* refactor: collection 同步实现方式

* refactor: move collection group manager to database

* fix: test

* fix: remove uiSchema

* fix: uiSchema

* fix: remove settings

* chore: plugin enable & disable event

* feat: modal warning

* fix: users_jobs namespace

* fix: rolesUischemas namespace

* fix: am snippet

* feat: beforeSubAppInstall event

* fix: improve NOCOBASE_LOCALE_KEY & NOCOBASE_ROLE_KEY

---------

Co-authored-by: chenos <chenlinxh@gmail.com>
2023-03-10 19:16:00 +08:00

180 lines
4.4 KiB
TypeScript

import Database, { Collection, MagicAttributeModel } from '@nocobase/database';
import { SyncOptions, Transactionable } from 'sequelize';
import { FieldModel } from './field';
import lodash from 'lodash';
interface LoadOptions extends Transactionable {
// TODO
skipField?: boolean;
skipExist?: boolean;
}
export class CollectionModel extends MagicAttributeModel {
get db(): Database {
return (<any>this.constructor).database;
}
async load(loadOptions: LoadOptions = {}) {
const { skipExist, skipField, transaction } = loadOptions;
const name = this.get('name');
let collection: Collection;
const collectionOptions = {
...this.get(),
fields: [],
};
if (this.db.hasCollection(name)) {
collection = this.db.getCollection(name);
if (skipExist) {
return collection;
}
collection.updateOptions(collectionOptions);
} else {
collection = this.db.collection(collectionOptions);
}
if (!skipField) {
await this.loadFields({ transaction });
}
await this.db.emitAsync('collection:loaded', {
collection,
transaction,
});
return collection;
}
async loadFields(options: Transactionable = {}) {
// @ts-ignore
const instances: FieldModel[] = await this.getFields(options);
for (const instance of instances) {
await instance.load(options);
}
}
async remove(options?: any) {
const { transaction } = options || {};
const name = this.get('name');
const collection = this.db.getCollection(name);
if (!collection) {
return;
}
const fields = await this.db.getRepository('fields').find({
filter: {
'type.$in': ['belongsToMany', 'belongsTo', 'hasMany', 'hasOne'],
},
transaction,
});
for (const field of fields) {
if (field.get('target') && field.get('target') === name) {
await field.destroy({ transaction });
} else if (field.get('through') && field.get('through') === name) {
await field.destroy({ transaction });
}
}
await collection.removeFromDb({
transaction,
});
}
async migrate(options?: SyncOptions & Transactionable) {
const collection = await this.load({
transaction: options?.transaction,
});
// postgres support zero column table, other database should not sync it to database
// @ts-ignore
if (Object.keys(collection.model.tableAttributes).length == 0 && !this.db.inDialect('postgres')) {
return;
}
try {
await collection.sync({
force: false,
alter: {
drop: false,
},
...options,
});
} catch (error) {
console.error(error);
const name = this.get('name');
this.db.removeCollection(name);
throw error;
}
}
isInheritedModel() {
return this.get('inherits');
}
async findParents(options: Transactionable) {
const { transaction } = options;
const findModelParents = async (model: CollectionModel, carry = []) => {
if (!model.get('inherits')) {
return;
}
const parents = lodash.castArray(model.get('inherits'));
for (const parent of parents) {
const parentModel = (await this.db.getCollection('collections').repository.findOne({
filterByTk: parent,
transaction,
})) as CollectionModel;
carry.push(parentModel.get('name'));
await findModelParents(parentModel, carry);
}
return carry;
};
return findModelParents(this);
}
async parentFields(options: Transactionable) {
const { transaction } = options;
return this.db.getCollection('fields').repository.find({
filter: {
collectionName: { $in: await this.findParents({ transaction }) },
},
transaction,
});
}
// sync fields from parents
async syncParentFields(options: Transactionable) {
const { transaction } = options;
const ancestorFields = await this.parentFields({ transaction });
const selfFields = await this.getFields({ transaction });
const inheritedFields = ancestorFields.filter((field: FieldModel) => {
return (
!field.isAssociationField() &&
!selfFields.find((selfField: FieldModel) => selfField.get('name') == field.get('name'))
);
});
for (const inheritedField of inheritedFields) {
await this.createField(lodash.omit(inheritedField.toJSON(), ['key', 'collectionName', 'sort']), {
transaction,
});
}
}
}