File size: 2,333 Bytes
f5957a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Injectable, Logger } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';

@Injectable()
export class DatabaseService {
  private readonly logger = new Logger(DatabaseService.name);

  constructor(
    @InjectDataSource()
    private dataSource: DataSource,
  ) {}

  async getStatus() {
    const uptimeResult = await this.dataSource.query(
      "SHOW GLOBAL STATUS LIKE 'Uptime'",
    );
    const threadsResult = await this.dataSource.query(
      "SHOW GLOBAL STATUS LIKE 'Threads_connected'",
    );
    const versionResult = await this.dataSource.query(
      "SELECT VERSION() as version",
    );

    return {
      data: {
        uptime: uptimeResult[0]?.Value || 0,
        threadsConnected: threadsResult[0]?.Value || 0,
        version: versionResult[0]?.version || 'unknown',
      },
    };
  }

  async getTables() {
    const dbName = this.dataSource.options['database'] || 'eduverse_db';
    const tables = await this.dataSource.query(
      `SELECT 
        TABLE_NAME as tableName,
        TABLE_ROWS as tableRows,
        ROUND(DATA_LENGTH / 1024 / 1024, 2) as dataSizeMB,
        ROUND(INDEX_LENGTH / 1024 / 1024, 2) as indexSizeMB,
        ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) as totalSizeMB,
        ENGINE as engine,
        TABLE_COLLATION as collation
      FROM information_schema.TABLES 
      WHERE TABLE_SCHEMA = ? 
      ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC`,
      [dbName],
    );

    return { data: tables };
  }

  async optimizeDatabase() {
    const dbName = this.dataSource.options['database'] || 'eduverse_db';
    const tables = await this.dataSource.query(
      `SELECT TABLE_NAME as tableName 
       FROM information_schema.TABLES 
       WHERE TABLE_SCHEMA = ?`,
      [dbName],
    );

    const results: { table: string; result: string }[] = [];
    for (const table of tables) {
      try {
        const result = await this.dataSource.query(
          `OPTIMIZE TABLE \`${table.tableName}\``,
        );
        results.push({ table: table.tableName, result: result[0]?.Msg_text || 'OK' });
      } catch (e) {
        results.push({ table: table.tableName, result: `Error: ${e.message}` });
      }
    }

    return { data: results, message: `Optimized ${results.length} tables` };
  }
}