Files
mayfly-go/mayfly_go_web/src/views/ops/db/db.ts

466 lines
12 KiB
TypeScript
Raw Normal View History

/* eslint-disable no-unused-vars */
import { dbApi } from './api';
import { getTextWidth } from '@/common/utils/string';
import SqlExecBox from './component/SqlExecBox';
const dbInstCache: Map<number, DbInst> = new Map();
export class DbInst {
2023-02-15 21:28:01 +08:00
/**
*
*/
tagPath: string;
2023-02-15 21:28:01 +08:00
/**
* id
*/
id: number;
2023-02-15 21:28:01 +08:00
/**
*
*/
name: string;
2023-02-15 21:28:01 +08:00
/**
* , mysql postgres
*/
type: string;
/**
* schema -> db
*/
dbs: Map<string, Db> = new Map();
2023-06-13 15:57:08 +08:00
/** 数据库schema多个用空格隔开 */
databases: string;
2023-06-13 15:57:08 +08:00
/**
*
*/
static DefaultLimit = 20;
/**
*
* @param dbName
* @returns db实例
*/
getDb(dbName: string) {
if (!dbName) {
throw new Error('dbName不能为空');
}
let db = this.dbs.get(dbName);
if (db) {
return db;
}
console.info(`new db -> dbId: ${this.id}, dbName: ${dbName}`);
db = new Db();
db.name = dbName;
this.dbs.set(dbName, db);
return db;
}
/**
*
* @param dbName
2023-03-28 15:22:05 +08:00
* @param reload
* @returns
*/
2023-03-28 15:22:05 +08:00
async loadTables(dbName: string, reload?: boolean) {
const db = this.getDb(dbName);
// 优先从 table map中获取
let tables = db.tables;
2023-03-28 15:22:05 +08:00
if (!reload && tables) {
return tables;
}
2023-04-05 22:41:53 +08:00
// 重置列信息缓存与表提示信息
db.columnsMap?.clear();
db.tableHints = null;
console.log(`load tables -> dbName: ${dbName}`);
tables = await dbApi.tableMetadata.request({ id: this.id, db: dbName });
db.tables = tables;
return tables;
}
/**
*
* @param table
*/
async loadColumns(dbName: string, table: string) {
const db = this.getDb(dbName);
// 优先从 table map中获取
let columns = db.getColumns(table);
if (columns) {
return columns;
}
console.log(`load columns -> dbName: ${dbName}, table: ${table}`);
columns = await dbApi.columnMetadata.request({
id: this.id,
db: dbName,
tableName: table,
});
db.columnsMap.set(table, columns);
return columns;
}
/**
*
* @param table
*/
async loadTableColumn(dbName: string, table: string, columnName?: string) {
// 确保该表的列信息都已加载
await this.loadColumns(dbName, table);
return this.getDb(dbName).getColumn(table, columnName);
}
/**
*
*/
async loadDbHints(dbName: string) {
const db = this.getDb(dbName);
if (db.tableHints) {
return db.tableHints;
}
console.log(`load db-hits -> dbName: ${dbName}`);
const hits = await dbApi.hintTables.request({ id: this.id, db: db.name });
db.tableHints = hits;
return hits;
}
/**
* sql
*
* @param sql sql
* @param remark
*/
async runSql(dbName: string, sql: string, remark: string = '') {
return await dbApi.sqlExec.request({
id: this.id,
db: dbName,
sql: sql.trim(),
remark,
});
}
/**
* count sql
* @param table
* @param condition
* @returns count sql
*/
getDefaultCountSql = (table: string, condition?: string) => {
return `SELECT COUNT(*) count FROM ${this.wrapName(table)} ${condition ? 'WHERE ' + condition : ''} limit 1`;
};
// 获取指定表的默认查询sql
getDefaultSelectSql(table: string, condition: string, orderBy: string, pageNum: number, limit: number = DbInst.DefaultLimit) {
const baseSql = `SELECT * FROM ${this.wrapName(table)} ${condition ? 'WHERE ' + condition : ''} ${orderBy ? orderBy : ''}`;
if (this.type == 'mysql') {
return `${baseSql} LIMIT ${(pageNum - 1) * limit}, ${limit};`;
}
if (this.type == 'postgres') {
return `${baseSql} OFFSET ${(pageNum - 1) * limit} LIMIT ${limit};`;
}
return baseSql;
}
/**
* insert语句
* @param dbName
* @param table
* @param datas
*/
genInsertSql(dbName: string, table: string, datas: any[]): string {
if (!datas) {
return '';
}
const columns = this.getDb(dbName).getColumns(table);
const sqls = [];
for (let data of datas) {
let colNames = [];
let values = [];
for (let column of columns) {
const colName = column.columnName;
colNames.push(this.wrapName(colName));
values.push(DbInst.wrapValueByType(data[colName]));
}
sqls.push(`INSERT INTO ${this.wrapName(table)} (${colNames.join(', ')}) VALUES(${values.join(', ')})`);
}
return sqls.join(';\n') + ';';
}
/**
* sql语句
* @param table
* @param datas
*/
genDeleteByPrimaryKeysSql(db: string, table: string, datas: any[]) {
const primaryKey = this.getDb(db).getColumn(table);
const primaryKeyColumnName = primaryKey.columnName;
const ids = datas.map((d: any) => `${DbInst.wrapColumnValue(primaryKey.columnType, d[primaryKeyColumnName])}`).join(',');
return `DELETE FROM ${this.wrapName(table)} WHERE ${this.wrapName(primaryKeyColumnName)} IN (${ids})`;
}
2023-06-13 15:57:08 +08:00
/*
* sql
*/
promptExeSql = (db: string, sql: string, cancelFunc: any = null, successFunc: any = null) => {
SqlExecBox({
sql,
dbId: this.id,
db,
runSuccessCallback: successFunc,
cancelCallback: cancelFunc,
});
};
/**
* 使
* @param table
* @param condition
* @returns
*/
wrapName = (name: string) => {
if (this.type == 'mysql') {
return `\`${name}\``;
}
if (this.type == 'postgres') {
return `"${name}"`;
}
return name;
};
2023-02-15 21:28:01 +08:00
/**
* dbInst
* @param inst
* @returns DbInst
*/
static getOrNewInst(inst: any) {
if (!inst) {
throw new Error('inst不能为空');
2023-02-15 21:28:01 +08:00
}
let dbInst = dbInstCache.get(inst.id);
if (dbInst) {
return dbInst;
}
console.info(`new dbInst: ${inst.id}, tagPath: ${inst.tagPath}`);
dbInst = new DbInst();
dbInst.tagPath = inst.tagPath;
dbInst.id = inst.id;
dbInst.name = inst.name;
dbInst.type = inst.type;
2023-06-13 15:57:08 +08:00
dbInst.databases = inst.databases;
2023-02-15 21:28:01 +08:00
dbInstCache.set(dbInst.id, dbInst);
return dbInst;
}
/**
* id
* @param dbId id
* @param dbType
* @returns
*/
2023-02-15 21:28:01 +08:00
static getInst(dbId?: number): DbInst {
if (!dbId) {
throw new Error('dbId不能为空');
}
let dbInst = dbInstCache.get(dbId);
if (dbInst) {
return dbInst;
}
2023-02-15 21:28:01 +08:00
throw new Error('dbInst不存在! 请在合适调用点使用DbInst.newInst()新建该实例');
}
/**
*
*/
static clearAll() {
dbInstCache.clear();
}
/**
* ''
* @param val
* @returns
*/
static wrapValueByType = (val: any) => {
if (val == null) {
return 'NULL';
}
if (typeof val == 'number') {
return val;
}
return `'${val}'`;
};
/**
*
*/
static wrapColumnValue(columnType: string, value: any) {
if (this.isNumber(columnType)) {
return value;
}
return `'${value}'`;
}
/**
*
* @param columnType
2023-06-13 15:57:08 +08:00
* @returns
*/
static isNumber(columnType: string) {
return columnType.match(/int|double|float|nubmer|decimal|byte|bit/gi);
}
/**
2023-06-13 15:57:08 +08:00
*
* @param str
* @param tableData
* @param flag
* @returns
*/
static flexColumnWidth = (prop: any, tableData: any) => {
if (!prop || !prop.length || prop.length === 0 || prop === undefined) {
return;
}
// 获取列名称的长度 加上排序图标长度
const columnWidth: number = getTextWidth(prop) + 40;
// prop为该列的字段名(传字符串);tableData为该表格的数据源(传变量);
if (!tableData || !tableData.length || tableData.length === 0 || tableData === undefined) {
return columnWidth;
}
// 获取该列中最长的数据(内容)
let maxWidthText = '';
let maxWidthValue;
// 获取该列中最长的数据(内容)
for (let i = 0; i < tableData.length; i++) {
let nowValue = tableData[i][prop];
if (!nowValue) {
continue;
}
// 转为字符串比较长度
let nowText = nowValue + '';
if (nowText.length > maxWidthText.length) {
maxWidthText = nowText;
maxWidthValue = nowValue;
}
}
const contentWidth: number = getTextWidth(maxWidthText) + 15;
const flexWidth: number = contentWidth > columnWidth ? contentWidth : columnWidth;
return flexWidth > 500 ? 500 : flexWidth;
};
}
/**
*
*/
class Db {
name: string; // 库名
tables: []; // 数据库实例表信息
columnsMap: Map<string, any> = new Map(); // table -> columns
tableHints: any = null; // 提示词
/**
* dbInst.loadColumns
* @param table
*/
getColumns(table: string) {
return this.columnsMap.get(table);
}
/**
*
* @param table
* @param columnName
*/
getColumn(table: string, columnName: string = '') {
const cols = this.getColumns(table);
if (!columnName) {
const col = cols.find((c: any) => c.columnKey == 'PRI');
return col || cols[0];
}
return cols.find((c: any) => c.columnName == columnName);
}
}
export enum TabType {
/**
*
*/
TableData,
/**
*
*/
Query,
}
export class TabInfo {
/**
* tab唯一keylabelname都一致
*/
key: string;
/**
* key
*/
treeNodeKey: string;
/**
* id
*/
dbId: number;
/**
*
*/
db: string = '';
/**
* tab
*/
type: TabType;
/**
* tab需要的其他信息
*/
params: any;
getNowDbInst() {
2023-02-15 21:28:01 +08:00
return DbInst.getInst(this.dbId);
}
getNowDb() {
return this.getNowDbInst().getDb(this.db);
}
}
/** 修改表字段所需数据 */
export type UpdateFieldsMeta = {
// 主键值
primaryKey: string;
// 主键名
primaryKeyName: string;
// 主键类型
primaryKeyType: string;
// 新值
fields: FieldsMeta[];
};
export type FieldsMeta = {
// 字段所在div
div: HTMLElement;
// 字段名
fieldName: string;
// 字段所在的表格行数据
row: any;
// 字段类型
fieldType: string;
// 原值
oldValue: string;
// 新值
newValue: string;
};