|
| 1 | +import { BadRequestException, HttpException, HttpStatus, Inject, Injectable, Scope } from '@nestjs/common'; |
| 2 | +import { validateSchemaCache } from '@rocketadmin/shared-code/dist/src/caching/schema-cache-validator.js'; |
| 3 | +import { getDataAccessObject } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/create-data-access-object.js'; |
| 4 | +import { ForeignKeyDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/foreign-key.ds.js'; |
| 5 | +import { PrimaryKeyDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/primary-key.ds.js'; |
| 6 | +import { TableStructureDS } from '@rocketadmin/shared-code/dist/src/data-access-layer/shared/data-structures/table-structure.ds.js'; |
| 7 | +import { ConnectionTypesEnum } from '@rocketadmin/shared-code/dist/src/shared/enums/connection-types-enum.js'; |
| 8 | +import AbstractUseCase from '../../../common/abstract-use.case.js'; |
| 9 | +import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js'; |
| 10 | +import { BaseType } from '../../../common/data-injection.tokens.js'; |
| 11 | +import { ExceptionOperations } from '../../../exceptions/custom-exceptions/exception-operation.js'; |
| 12 | +import { UnknownSQLException } from '../../../exceptions/custom-exceptions/unknown-sql-exception.js'; |
| 13 | +import { Messages } from '../../../exceptions/text/messages.js'; |
| 14 | +import { isConnectionTypeAgent } from '../../../helpers/is-connection-entity-agent.js'; |
| 15 | +import { PreviewConnectionDiagramDs } from '../application/data-structures/preview-connection-diagram.ds.js'; |
| 16 | +import { ConnectionDiagramPreviewResponseDTO } from '../application/dto/connection-diagram-preview-response.dto.js'; |
| 17 | +import { applyProposedDdl, SchemaDiff } from '../utils/apply-proposed-ddl.util.js'; |
| 18 | +import { buildMermaidErDiagram, MermaidTableInput } from '../utils/build-mermaid-er-diagram.util.js'; |
| 19 | +import { isSqlConnectionType } from '../utils/is-sql-connection-type.util.js'; |
| 20 | +import { IPreviewConnectionDiagram } from './use-cases.interfaces.js'; |
| 21 | + |
| 22 | +@Injectable({ scope: Scope.REQUEST }) |
| 23 | +export class PreviewConnectionDiagramUseCase |
| 24 | + extends AbstractUseCase<PreviewConnectionDiagramDs, ConnectionDiagramPreviewResponseDTO> |
| 25 | + implements IPreviewConnectionDiagram |
| 26 | +{ |
| 27 | + constructor( |
| 28 | + @Inject(BaseType.GLOBAL_DB_CONTEXT) |
| 29 | + protected _dbContext: IGlobalDatabaseContext, |
| 30 | + ) { |
| 31 | + super(); |
| 32 | + } |
| 33 | + |
| 34 | + protected async implementation(inputData: PreviewConnectionDiagramDs): Promise<ConnectionDiagramPreviewResponseDTO> { |
| 35 | + const { connectionId, masterPwd, userId, sqlCommands } = inputData; |
| 36 | + const connection = await this._dbContext.connectionRepository.findAndDecryptConnection(connectionId, masterPwd); |
| 37 | + if (!connection) { |
| 38 | + throw new HttpException({ message: Messages.CONNECTION_NOT_FOUND }, HttpStatus.BAD_REQUEST); |
| 39 | + } |
| 40 | + if (!isSqlConnectionType(connection.type)) { |
| 41 | + throw new BadRequestException(Messages.DIAGRAM_NOT_SUPPORTED_FOR_CONNECTION_TYPE); |
| 42 | + } |
| 43 | + |
| 44 | + const dao = getDataAccessObject(connection); |
| 45 | + const userEmail = isConnectionTypeAgent(connection.type) |
| 46 | + ? await this._dbContext.userRepository.getUserEmailOrReturnNull(userId) |
| 47 | + : undefined; |
| 48 | + |
| 49 | + await validateSchemaCache(dao, userEmail); |
| 50 | + dao.invalidateMetadataCache(); |
| 51 | + |
| 52 | + let tables: Array<{ tableName: string; isView: boolean }>; |
| 53 | + try { |
| 54 | + tables = await dao.getTablesFromDB(userEmail); |
| 55 | + } catch (e) { |
| 56 | + throw new UnknownSQLException(e.message, ExceptionOperations.FAILED_TO_GET_TABLES); |
| 57 | + } |
| 58 | + |
| 59 | + const realTables = tables.filter((t) => !t.isView); |
| 60 | + const tableInputs: Array<MermaidTableInput> = await Promise.all( |
| 61 | + realTables.map((t) => this.collectTableInfo(dao, t.tableName, userEmail)), |
| 62 | + ); |
| 63 | + |
| 64 | + const { mutatedTables, diff } = applyProposedDdl(tableInputs, sqlCommands, connection.type as ConnectionTypesEnum); |
| 65 | + |
| 66 | + const { diagram, description } = buildMermaidErDiagram(connection.database || null, mutatedTables, { |
| 67 | + addedTables: diff.addedTables, |
| 68 | + addedColumns: diff.addedColumns, |
| 69 | + addedForeignKeys: diff.addedForeignKeys, |
| 70 | + }); |
| 71 | + |
| 72 | + return { |
| 73 | + connectionId, |
| 74 | + databaseType: connection.type as ConnectionTypesEnum, |
| 75 | + diagram, |
| 76 | + description, |
| 77 | + diff: serializeDiff(diff), |
| 78 | + generatedAt: new Date().toISOString(), |
| 79 | + }; |
| 80 | + } |
| 81 | + |
| 82 | + private async collectTableInfo( |
| 83 | + dao: ReturnType<typeof getDataAccessObject>, |
| 84 | + tableName: string, |
| 85 | + userEmail: string | undefined, |
| 86 | + ): Promise<MermaidTableInput> { |
| 87 | + const [structure, primaryColumns, foreignKeys] = await Promise.all([ |
| 88 | + this.safe<Array<TableStructureDS>>(() => dao.getTableStructure(tableName, userEmail), []), |
| 89 | + this.safe<Array<PrimaryKeyDS>>(() => dao.getTablePrimaryColumns(tableName, userEmail), []), |
| 90 | + this.safe<Array<ForeignKeyDS>>(() => dao.getTableForeignKeys(tableName, userEmail), []), |
| 91 | + ]); |
| 92 | + return { tableName, structure, primaryColumns, foreignKeys }; |
| 93 | + } |
| 94 | + |
| 95 | + private async safe<T>(fn: () => Promise<T>, fallback: T): Promise<T> { |
| 96 | + try { |
| 97 | + return await fn(); |
| 98 | + } catch { |
| 99 | + return fallback; |
| 100 | + } |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +function serializeDiff(diff: SchemaDiff): ConnectionDiagramPreviewResponseDTO['diff'] { |
| 105 | + return { |
| 106 | + addedTables: Array.from(diff.addedTables), |
| 107 | + droppedTables: Array.from(diff.droppedTables), |
| 108 | + addedColumns: mapSetToObject(diff.addedColumns), |
| 109 | + droppedColumns: mapSetToObject(diff.droppedColumns), |
| 110 | + addedForeignKeys: mapSetToObject(diff.addedForeignKeys), |
| 111 | + statementResults: diff.statementResults, |
| 112 | + }; |
| 113 | +} |
| 114 | + |
| 115 | +function mapSetToObject(map: Map<string, Set<string>>): Record<string, Array<string>> { |
| 116 | + const out: Record<string, Array<string>> = {}; |
| 117 | + for (const [key, set] of map.entries()) { |
| 118 | + out[key] = Array.from(set); |
| 119 | + } |
| 120 | + return out; |
| 121 | +} |
0 commit comments