96 lines
2.7 KiB
TypeScript
96 lines
2.7 KiB
TypeScript
import { Inject, Injectable } from "@nestjs/common";
|
|
import { InjectRepository } from "@nestjs/typeorm";
|
|
import { Database } from "../entities/database.entity";
|
|
import { Repository } from "typeorm";
|
|
import { ProjectService } from "src/project/project.service";
|
|
import { DatabaseEncryptionService } from "../database.encryption.service";
|
|
import { DatabaseNodeService } from "../databaseNode/database.node.service";
|
|
import * as mysql from "mysql2/promise";
|
|
|
|
@Injectable()
|
|
export class DatabaseManagerService extends DatabaseEncryptionService {
|
|
constructor(
|
|
@InjectRepository(Database)
|
|
private databaseRepository: Repository<Database>,
|
|
@Inject(ProjectService)
|
|
private readonly projectService: ProjectService,
|
|
@Inject(DatabaseNodeService)
|
|
private readonly databaseNodeService: DatabaseNodeService
|
|
) {
|
|
super();
|
|
}
|
|
|
|
async findById(id: string): Promise<Database | null> {
|
|
return this.databaseRepository.findOne({ where: { id } });
|
|
}
|
|
|
|
async runQuery(databaseId: string, query: string) {
|
|
const database = await this.findById(databaseId);
|
|
|
|
if (!database) {
|
|
throw new Error("Database not found");
|
|
}
|
|
|
|
const dbConnection = await mysql.createConnection({
|
|
host: database.node.host,
|
|
port: database.node.port,
|
|
user: database.c_username,
|
|
password: this.decryptPassword(database.password),
|
|
database: database.database,
|
|
enableKeepAlive: true,
|
|
});
|
|
|
|
try {
|
|
const [results] = await dbConnection.execute(query);
|
|
return results;
|
|
} finally {
|
|
await dbConnection.end();
|
|
}
|
|
}
|
|
|
|
async createDatabase(
|
|
databaseNodeId: string,
|
|
projectId: string
|
|
): Promise<Database> {
|
|
const node = await this.databaseNodeService.findById(databaseNodeId);
|
|
|
|
if (!node) {
|
|
throw new Error("Database node not found");
|
|
}
|
|
|
|
const project = await this.projectService.findById(projectId);
|
|
|
|
if (!project) {
|
|
throw new Error("Project not found");
|
|
}
|
|
|
|
const c_username = `c_user_${Math.random().toString(36).substring(2, 8)}`;
|
|
const q_username = `q_user_${Math.random().toString(36).substring(2, 8)}`;
|
|
const databaseName = `db_${Math.random().toString(36).substring(2, 8)}`;
|
|
const password = this.encryptPassword(
|
|
Math.random().toString(36).substring(2, 10)
|
|
);
|
|
|
|
await this.databaseNodeService.initDatabase(
|
|
{
|
|
database: databaseName,
|
|
c_username,
|
|
q_username,
|
|
password: this.decryptPassword(password),
|
|
},
|
|
databaseNodeId
|
|
);
|
|
|
|
const database = this.databaseRepository.create({
|
|
q_username,
|
|
c_username,
|
|
database: databaseName,
|
|
password,
|
|
node,
|
|
project,
|
|
});
|
|
|
|
return await this.databaseRepository.save(database);
|
|
}
|
|
}
|