chore: databse utils

This commit is contained in:
Chareice 2023-02-10 12:52:23 +08:00
parent 9c9c39c0cd
commit 5e603b5a52
4 changed files with 56 additions and 27 deletions

View File

@ -0,0 +1,38 @@
import Database from '../database';
import lodash from 'lodash';
export default class DatabaseUtils {
constructor(public db: Database) {}
addSchema(tableName, schema?) {
if (this.db.options.schema) {
schema = this.db.options.schema;
}
if (schema) {
// @ts-ignore
tableName = this.db.sequelize.getQueryInterface().queryGenerator.addSchema({
tableName,
_schema: this.db.options.schema,
});
}
return tableName;
}
quoteTable(tableName) {
const queryGenerator = this.db.sequelize.getQueryInterface().queryGenerator;
// @ts-ignore
tableName = queryGenerator.quoteTable(lodash.isPlainObject(tableName) ? tableName : this.addSchema(tableName));
return tableName;
}
schema() {
if (!this.db.inDialect('postgres')) {
return undefined;
}
return this.db.options.schema || 'public';
}
}

View File

@ -61,6 +61,8 @@ import {
ValidateListener, ValidateListener,
} from './types'; } from './types';
import DatabaseUtils from './database-utils';
export interface MergeOptions extends merge.Options {} export interface MergeOptions extends merge.Options {}
export interface PendingOptions { export interface PendingOptions {
@ -155,6 +157,7 @@ export class Database extends EventEmitter implements AsyncEmitter {
modelCollection = new Map<ModelStatic<any>, Collection>(); modelCollection = new Map<ModelStatic<any>, Collection>();
tableNameCollectionMap = new Map<string, Collection>(); tableNameCollectionMap = new Map<string, Collection>();
utils = new DatabaseUtils(this);
referenceMap = new ReferencesMap(); referenceMap = new ReferencesMap();
inheritanceMap = new InheritanceMap(); inheritanceMap = new InheritanceMap();

View File

@ -31,6 +31,9 @@ export class SyncRunner {
const tableName = model.tableName; const tableName = model.tableName;
const schemaTableName = db.utils.addSchema(tableName);
const quoteTableName = db.utils.quoteTable(tableName);
const attributes = model.tableAttributes; const attributes = model.tableAttributes;
const childAttributes = lodash.pickBy(attributes, (value) => { const childAttributes = lodash.pickBy(attributes, (value) => {
@ -85,7 +88,7 @@ export class SyncRunner {
} }
} }
await this.createTable(tableName, childAttributes, options, model, parentTables, schemaName); await this.createTable(schemaTableName, childAttributes, options, model, parentTables, db);
if (maxSequenceName) { if (maxSequenceName) {
const parentsDeep = Array.from(db.inheritanceMap.getParents(inheritedCollection.name)).map( const parentsDeep = Array.from(db.inheritanceMap.getParents(inheritedCollection.name)).map(
@ -134,9 +137,7 @@ WHERE table_name='${queryName}' and column_name='id' and table_schema = '${schem
} }
} }
static async createTable(tableName, attributes, options, model, parentTables, schema) { static async createTable(tableName, attributes, options, model, parentTables, db) {
tableName = model.queryGenerator.addSchema({ tableName, _schema: schema, _schemaDelimiter: '' });
let sql = ''; let sql = '';
options = { ...options }; options = { ...options };
@ -161,7 +162,11 @@ WHERE table_name='${queryName}' and column_name='id' and table_schema = '${schem
sql = `${queryGenerator.createTableQuery(tableName, attributes, options)}`.replace( sql = `${queryGenerator.createTableQuery(tableName, attributes, options)}`.replace(
';', ';',
` INHERITS (${parentTables.map((t) => `"${schema}"."${t}"`).join(', ')});`, ` INHERITS (${parentTables
.map((t) => {
return db.utils.quoteTable(db.utils.addSchema(t, db.options.schema));
})
.join(', ')});`,
); );
return await model.sequelize.query(sql, options); return await model.sequelize.query(sql, options);

View File

@ -127,7 +127,7 @@ export class Restorer extends AppMigrator {
const metaContent = await fsPromises.readFile(collectionMetaPath, 'utf8'); const metaContent = await fsPromises.readFile(collectionMetaPath, 'utf8');
const meta = JSON.parse(metaContent); const meta = JSON.parse(metaContent);
const tableName = this.quoteTable(meta.tableName); const tableName = this.app.db.utils.quoteTable(meta.tableName);
try { try {
// disable trigger // disable trigger
@ -199,25 +199,6 @@ export class Restorer extends AppMigrator {
await decompress(backupFilePath, this.workDir); await decompress(backupFilePath, this.workDir);
} }
quoteTable(tableName) {
// @ts-ignore
tableName = this.app.db.sequelize.getQueryInterface().queryGenerator.quoteTable(this.addSchema(tableName));
return tableName;
}
addSchema(tableName) {
if (this.app.db.options.schema) {
// @ts-ignore
tableName = this.app.db.sequelize.getQueryInterface().queryGenerator.addSchema({
tableName,
_schema: this.app.db.options.schema,
});
}
return tableName;
}
async importCollection(options: { async importCollection(options: {
name: string; name: string;
insert?: boolean; insert?: boolean;
@ -225,6 +206,8 @@ export class Restorer extends AppMigrator {
rowCondition?: (row: any) => boolean; rowCondition?: (row: any) => boolean;
}) { }) {
const app = this.app; const app = this.app;
const db = app.db;
const collectionName = options.name; const collectionName = options.name;
const dir = this.workDir; const dir = this.workDir;
const collection = app.db.getCollection(collectionName); const collection = app.db.getCollection(collectionName);
@ -235,8 +218,8 @@ export class Restorer extends AppMigrator {
const meta = JSON.parse(metaContent); const meta = JSON.parse(metaContent);
app.log.info(`collection meta ${metaContent}`); app.log.info(`collection meta ${metaContent}`);
const addSchemaTableName = this.addSchema(meta.tableName); const addSchemaTableName = db.utils.addSchema(meta.tableName);
const tableName = this.quoteTable(meta.tableName); const tableName = db.utils.quoteTable(meta.tableName);
if (options.clear !== false) { if (options.clear !== false) {
// truncate old data // truncate old data