| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| const express = require('express');
|
| const cors = require('cors');
|
| const { Pool } = require('pg');
|
| const mysql = require('mysql2/promise');
|
| const { MongoClient } = require('mongodb');
|
| const redis = require('redis');
|
| const path = require('path');
|
| const fs = require('fs');
|
| const { ensureLicensed } = require('../license-guard');
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| class DatabaseServer {
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| constructor() {
|
| this.app = express();
|
| this.server = null;
|
| this.port = 3001;
|
| this.connections = new Map();
|
| this.connectionsFile = path.join(__dirname, '..', 'data', 'connections.json');
|
|
|
| this.setupMiddleware();
|
| this.setupRoutes();
|
| this.loadConnectionsFromFile();
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async loadConnectionsFromFile() {
|
| try {
|
|
|
| const dataDir = path.dirname(this.connectionsFile);
|
| if (!fs.existsSync(dataDir)) {
|
| fs.mkdirSync(dataDir, { recursive: true });
|
| }
|
|
|
|
|
| if (fs.existsSync(this.connectionsFile)) {
|
| const data = fs.readFileSync(this.connectionsFile, 'utf8');
|
| const connectionsArray = JSON.parse(data);
|
|
|
|
|
| connectionsArray.forEach(conn => {
|
| this.connections.set(conn.id, conn);
|
| });
|
|
|
| console.log(`[SUCCESS] Loaded ${connectionsArray.length} saved connections`);
|
| } else {
|
| console.log('[FILE] No saved connections file found, starting fresh');
|
| }
|
| } catch (error) {
|
| console.error('[ERROR] Failed to load connections from file:', error);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async saveConnectionsToFile() {
|
| try {
|
| const connectionsArray = Array.from(this.connections.values());
|
| fs.writeFileSync(this.connectionsFile, JSON.stringify(connectionsArray, null, 2));
|
| console.log(`[SAVE] Saved ${connectionsArray.length} connections to file`);
|
| } catch (error) {
|
| console.error('[ERROR] Failed to save connections to file:', error);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| setupMiddleware() {
|
| this.app.use(cors({
|
| origin: '*',
|
| methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
| allowedHeaders: ['Content-Type', 'Authorization']
|
| }));
|
|
|
| this.app.use(express.json({ limit: '10mb' }));
|
| this.app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
|
|
|
|
| this.app.use((req, res, next) => {
|
| console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
|
| next();
|
| });
|
|
|
|
|
| this.app.use(async (req, res, next) => {
|
| if (req.path.startsWith('/api/health') || req.path.startsWith('/api/license')) return next();
|
| try {
|
| await ensureLicensed();
|
| return next();
|
| }
|
| catch (e) {
|
| return res.status(403).json({ ok: false, error: `License invalid: ${e.message}` });
|
| }
|
| });
|
| }
|
|
|
| |
| |
| |
| |
|
|
| setupRoutes() {
|
|
|
| this.app.get('/api/health', (req, res) => {
|
| res.json({
|
| status: 'healthy',
|
| timestamp: new Date().toISOString(),
|
| version: '2.0.0'
|
| });
|
| });
|
|
|
|
|
| this.app.get('/api/license/check', async (req, res) => {
|
| try {
|
| const d = await ensureLicensed();
|
| res.json({ ok: true, data: d });
|
| }
|
| catch (e) {
|
| res.status(200).json({ ok: false, error: e.message });
|
| }
|
| });
|
|
|
|
|
| this.app.post('/api/connections', this.createConnection.bind(this));
|
| this.app.get('/api/connections', this.getConnections.bind(this));
|
| this.app.delete('/api/connections/:id', this.deleteConnection.bind(this));
|
| this.app.post('/api/connections/:id/test', this.testConnection.bind(this));
|
|
|
|
|
| this.app.get('/api/connections/:id/structure', this.getDatabaseStructure.bind(this));
|
| this.app.get('/api/connections/:id/tables/:table/data', this.getTableData.bind(this));
|
| this.app.post('/api/connections/:id/query', this.executeQuery.bind(this));
|
|
|
|
|
| this.app.get('/api/sql-files', this.getSQLFiles.bind(this));
|
| this.app.get('/api/sql-files/:filename', this.getSQLFileContent.bind(this));
|
| this.app.post('/api/connections/:id/execute-file', this.executeSQLFile.bind(this));
|
|
|
|
|
| this.app.post('/api/connections/:id/tables/:table/rows', this.insertRow.bind(this));
|
| this.app.put('/api/connections/:id/tables/:table/rows/:rowId', this.updateRow.bind(this));
|
| this.app.delete('/api/connections/:id/tables/:table/rows/:rowId', this.deleteRow.bind(this));
|
| this.app.get('/api/connections/:id/tables/:table/columns', this.getTableColumns.bind(this));
|
|
|
|
|
| this.app.get('/api/plugins', this.getAvailablePlugins.bind(this));
|
| this.app.post('/api/plugins/:pluginName/setup', this.runPluginSetup.bind(this));
|
| this.app.post('/api/plugins/:pluginName/drop-files', this.handlePluginDropFiles.bind(this));
|
| this.app.post('/api/plugins/:pluginName/dump-sql', this.handlePluginSQLDump.bind(this));
|
| this.app.post('/api/plugin/import-file', this.handlePluginImportFile.bind(this));
|
|
|
|
|
| this.app.post('/api/connections/:id/restore', this.handleDatabaseRestore.bind(this));
|
|
|
|
|
| this.app.use((err, req, res, next) => {
|
| console.error('Server error:', err);
|
| res.status(500).json({
|
| success: false,
|
| error: err.message || 'Internal server error'
|
| });
|
| });
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| async start() {
|
| return new Promise((resolve, reject) => {
|
| this.server = this.app.listen(this.port, 'localhost', (err) => {
|
| if (err) {
|
| reject(err);
|
| } else {
|
| console.log(`[START] Database server running on http://localhost:${this.port}`);
|
| resolve();
|
| }
|
| });
|
| });
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async stop() {
|
| if (this.server) {
|
| return new Promise((resolve) => {
|
| this.server.close(() => {
|
| console.log('[STOP] Database server stopped');
|
| resolve();
|
| });
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
|
|
| getPort() {
|
| return this.port;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async createConnection(req, res) {
|
| try {
|
| const { name, type, host, port, database, username, password, options = {} } = req.body;
|
|
|
| const connectionId = Date.now().toString() + Math.random().toString(36).substr(2, 9);
|
| const connection = {
|
| id: connectionId,
|
| name,
|
| type,
|
| host,
|
| port,
|
| database,
|
| username,
|
| password,
|
| options,
|
| createdAt: new Date().toISOString(),
|
| status: 'disconnected'
|
| };
|
|
|
| this.connections.set(connectionId, connection);
|
|
|
|
|
| await this.saveConnectionsToFile();
|
|
|
| res.json({
|
| success: true,
|
| connection: {
|
| ...connection,
|
| password: undefined
|
| }
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| async getConnections(req, res) {
|
| try {
|
| const connections = Array.from(this.connections.values()).map(conn => ({
|
| ...conn,
|
| password: undefined
|
| }));
|
|
|
| res.json({
|
| success: true,
|
| connections
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async deleteConnection(req, res) {
|
| try {
|
| const { id } = req.params;
|
|
|
| if (this.connections.has(id)) {
|
| this.connections.delete(id);
|
|
|
|
|
| await this.saveConnectionsToFile();
|
|
|
| res.json({ success: true });
|
| } else {
|
| res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async testConnection(req, res) {
|
| try {
|
| const { id } = req.params;
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| let client;
|
| let testResult = false;
|
| let errorMessage = '';
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| client = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password,
|
| connectionTimeoutMillis: 5000
|
| });
|
| await client.query('SELECT 1');
|
| await client.end();
|
| testResult = true;
|
| break;
|
|
|
| case 'mysql':
|
| case 'mariadb':
|
| client = await mysql.createConnection({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password,
|
| connectTimeout: 5000
|
| });
|
| await client.execute('SELECT 1');
|
| await client.end();
|
| testResult = true;
|
| break;
|
|
|
| case 'sqlite':
|
|
|
| testResult = true;
|
| break;
|
|
|
| case 'mongodb':
|
| client = new MongoClient(`mongodb://${connection.username}:${connection.password}@${connection.host}:${connection.port}/${connection.database}`);
|
| await client.connect();
|
| await client.db().admin().ping();
|
| await client.close();
|
| testResult = true;
|
| break;
|
|
|
| case 'redis':
|
| client = redis.createClient({
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password
|
| });
|
| await client.connect();
|
| await client.ping();
|
| await client.quit();
|
| testResult = true;
|
| break;
|
|
|
| default:
|
| throw new Error(`Unsupported database type: ${connection.type}`);
|
| }
|
| } catch (error) {
|
| errorMessage = error.message;
|
| testResult = false;
|
| }
|
|
|
|
|
| connection.status = testResult ? 'connected' : 'error';
|
| connection.lastTested = new Date().toISOString();
|
| if (errorMessage) {
|
| connection.lastError = errorMessage;
|
| }
|
|
|
| res.json({
|
| success: true,
|
| connectionTest: {
|
| id,
|
| status: testResult ? 'connected' : 'failed',
|
| message: testResult ? 'Connection successful' : `Connection failed: ${errorMessage}`,
|
| testedAt: new Date().toISOString()
|
| }
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async getDatabaseStructure(req, res) {
|
| try {
|
| const { id } = req.params;
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| let structure = { database: connection.database, tables: [], views: [] };
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const tablesResult = await pgClient.query(`
|
| SELECT
|
| t.table_name,
|
| COALESCE(s.n_tup_ins, 0) as row_count
|
| FROM information_schema.tables t
|
| LEFT JOIN pg_stat_user_tables s ON t.table_name = s.relname
|
| WHERE t.table_schema = 'public'
|
| AND t.table_type = 'BASE TABLE'
|
| ORDER BY t.table_name
|
| `);
|
|
|
| const viewsResult = await pgClient.query(`
|
| SELECT table_name as view_name
|
| FROM information_schema.views
|
| WHERE table_schema = 'public'
|
| ORDER BY table_name
|
| `);
|
|
|
| structure.tables = tablesResult.rows.map(row => ({
|
| name: row.table_name,
|
| rowCount: parseInt(row.row_count) || 0
|
| }));
|
|
|
| structure.views = viewsResult.rows.map(row => ({
|
| name: row.view_name
|
| }));
|
|
|
| await pgClient.end();
|
| break;
|
|
|
| case 'mysql':
|
| case 'mariadb':
|
| const mysqlClient = await mysql.createConnection({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const [mysqlTables] = await mysqlClient.execute(`
|
| SELECT
|
| TABLE_NAME as table_name,
|
| TABLE_ROWS as row_count
|
| FROM information_schema.TABLES
|
| WHERE TABLE_SCHEMA = ?
|
| AND TABLE_TYPE = 'BASE TABLE'
|
| ORDER BY TABLE_NAME
|
| `, [connection.database]);
|
|
|
| const [mysqlViews] = await mysqlClient.execute(`
|
| SELECT TABLE_NAME as view_name
|
| FROM information_schema.VIEWS
|
| WHERE TABLE_SCHEMA = ?
|
| ORDER BY TABLE_NAME
|
| `, [connection.database]);
|
|
|
| structure.tables = mysqlTables.map(row => ({
|
| name: row.table_name,
|
| rowCount: parseInt(row.row_count) || 0
|
| }));
|
|
|
| structure.views = mysqlViews.map(row => ({
|
| name: row.view_name
|
| }));
|
|
|
| await mysqlClient.end();
|
| break;
|
|
|
| case 'sqlite':
|
|
|
| structure.tables = [
|
| { name: 'example_table', rowCount: 0 }
|
| ];
|
| break;
|
|
|
| case 'mongodb':
|
| const mongoClient = new MongoClient(`mongodb://${connection.username}:${connection.password}@${connection.host}:${connection.port}/${connection.database}`);
|
| await mongoClient.connect();
|
|
|
| const db = mongoClient.db(connection.database);
|
| const collections = await db.listCollections().toArray();
|
|
|
| structure.tables = collections.map(col => ({
|
| name: col.name,
|
| rowCount: 0
|
| }));
|
|
|
| await mongoClient.close();
|
| break;
|
|
|
| default:
|
| throw new Error(`Database structure not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Database structure error:', error);
|
| throw error;
|
| }
|
|
|
| res.json({
|
| success: true,
|
| structure
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async getTableData(req, res) {
|
| try {
|
| const { id, table } = req.params;
|
| const page = parseInt(req.query.page) || 1;
|
| const limit = parseInt(req.query.limit) || 50;
|
| const offset = (page - 1) * limit;
|
|
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| let data = { columns: [], rows: [], total: 0, page, limit, totalPages: 0 };
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
|
|
| const columnsResult = await pgClient.query(`
|
| SELECT column_name, data_type, is_nullable
|
| FROM information_schema.columns
|
| WHERE table_name = $1 AND table_schema = 'public'
|
| ORDER BY ordinal_position
|
| `, [table]);
|
|
|
| data.columns = columnsResult.rows.map(row => row.column_name);
|
|
|
|
|
| const countResult = await pgClient.query(`SELECT COUNT(*) as total FROM "${table}"`);
|
| data.total = parseInt(countResult.rows[0].total);
|
|
|
|
|
| const dataResult = await pgClient.query(`SELECT * FROM "${table}" ORDER BY 1 LIMIT $1 OFFSET $2`, [limit, offset]);
|
|
|
| data.rows = dataResult.rows.map(row =>
|
| data.columns.map(col => {
|
| const value = row[col];
|
| if (value === null) return 'NULL';
|
| if (typeof value === 'boolean') return value.toString();
|
| if (value instanceof Date) return value.toISOString().split('T')[0];
|
| if (typeof value === 'object') return JSON.stringify(value);
|
| return String(value);
|
| })
|
| );
|
|
|
| data.totalPages = Math.ceil(data.total / limit);
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`Table data not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Table data error:', error);
|
|
|
| data = {
|
| columns: [],
|
| rows: [],
|
| total: 0,
|
| page,
|
| limit,
|
| totalPages: 0,
|
| message: `Table '${table}' not found or has no data`
|
| };
|
| }
|
|
|
| res.json({
|
| success: true,
|
| data
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
|
|
| |
| |
| |
| |
|
|
| _detectParamStyle(sql) {
|
| if (/\$\d+/.test(sql)) return 'pg';
|
| if (/(^|[^:]):([a-zA-Z_]\w*)/.test(sql)) return 'named';
|
| if (/\?/.test(sql)) return 'qmark';
|
| return 'none';
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| _normalizeQuery(connection, sql, params) {
|
| const type = connection.type;
|
| const style = this._detectParamStyle(sql);
|
|
|
| if (!params || (Array.isArray(params) && params.length === 0) ||
|
| (typeof params === 'object' && !Array.isArray(params) && Object.keys(params).length === 0)) {
|
|
|
| return { sql, values: [] };
|
| }
|
|
|
|
|
| const getNamed = (name) => {
|
| if (!params || typeof params !== 'object') {
|
| throw new Error(`Expected named params object but got ${typeof params}`);
|
| }
|
| if (!(name in params)) {
|
| throw new Error(`Missing named param :${name}`);
|
| }
|
| return params[name];
|
| };
|
|
|
|
|
| let values = [];
|
|
|
|
|
| const replaceNamedWith = (placeholderBuilder) => {
|
| const seen = new Map();
|
| let idx = 0;
|
| sql = sql.replace(/(^|[^:]):([a-zA-Z_]\w*)/g, (m, prefix, name) => {
|
| if (!seen.has(name)) {
|
| seen.set(name, ++idx);
|
| values.push(getNamed(name));
|
| }
|
| const n = seen.get(name);
|
| return prefix + placeholderBuilder(n);
|
| });
|
| };
|
|
|
| if (type === 'postgresql') {
|
| if (style === 'pg') {
|
|
|
| if (Array.isArray(params)) {
|
| const order = [];
|
| sql.replace(/\$(\d+)/g, (_, n) => order.push(parseInt(n, 10) - 1));
|
| values = order.map(i => params[i]);
|
| } else {
|
|
|
| const keys = Object.keys(params).sort();
|
| const order = [];
|
| sql.replace(/\$(\d+)/g, (_, n) => order.push(parseInt(n, 10)));
|
| values = order.map(n => params[keys[n - 1]]);
|
| }
|
| } else if (style === 'qmark') {
|
|
|
| if (!Array.isArray(params)) throw new Error('For "?" style, params must be an array');
|
| let i = 0;
|
| sql = sql.replace(/\?/g, () => `$${++i}`);
|
| values = params;
|
| } else if (style === 'named') {
|
|
|
| replaceNamedWith((n) => `$${n}`);
|
| } else {
|
|
|
| values = Array.isArray(params) ? params : Object.values(params);
|
| }
|
| } else if (type === 'mysql' || type === 'mariadb') {
|
| if (style === 'pg') {
|
|
|
| const order = [];
|
| sql = sql.replace(/\$(\d+)/g, (_, n) => {
|
| order.push(parseInt(n, 10) - 1);
|
| return '?';
|
| });
|
| if (!Array.isArray(params)) throw new Error('For $n style, params must be an array');
|
| values = order.map(i => params[i]);
|
| } else if (style === 'qmark') {
|
| if (!Array.isArray(params)) throw new Error('For "?" style, params must be an array');
|
| values = params;
|
| } else if (style === 'named') {
|
|
|
| const seen = [];
|
| sql = sql.replace(/(^|[^:]):([a-zA-Z_]\w*)/g, (m, prefix, name) => {
|
| seen.push(name);
|
| return prefix + '?';
|
| });
|
| values = seen.map(n => getNamed(n));
|
| } else {
|
| values = Array.isArray(params) ? params : Object.values(params);
|
| }
|
| } else if (type === 'sqlite') {
|
|
|
| if (style === 'named') {
|
| const seen = [];
|
| sql = sql.replace(/(^|[^:]):([a-zA-Z_]\w*)/g, (m, prefix, name) => {
|
| seen.push(name);
|
| return prefix + '?';
|
| });
|
| values = seen.map(n => getNamed(n));
|
| } else if (style === 'pg') {
|
| const order = [];
|
| sql = sql.replace(/\$(\d+)/g, (_, n) => {
|
| order.push(parseInt(n, 10) - 1);
|
| return '?';
|
| });
|
| if (!Array.isArray(params)) throw new Error('For $n style, params must be an array');
|
| values = order.map(i => params[i]);
|
| } else {
|
| if (!Array.isArray(params)) throw new Error('For "?" style, params must be an array');
|
| values = params;
|
| }
|
| } else {
|
|
|
| return { sql, values: [] };
|
| }
|
|
|
| return { sql, values };
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async executeQuery(req, res) {
|
| try {
|
| const { id } = req.params;
|
| const { query, params } = req.body;
|
|
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| if (!query || typeof query !== 'string') {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Query is required'
|
| });
|
| }
|
|
|
| console.log('[EXEC] Executing query:', query.substring(0, 100) + (query.length > 100 ? '...' : ''));
|
|
|
| const startTime = Date.now();
|
| let result;
|
| let data = {
|
| type: 'other',
|
| columns: [],
|
| rows: [],
|
| rowCount: 0,
|
| message: 'Query executed.'
|
| };
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql': {
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const { sql, values } = this._normalizeQuery(connection, query, params);
|
| result = await pgClient.query(sql, values);
|
| await pgClient.end();
|
| break;
|
| }
|
|
|
| case 'mysql':
|
| case 'mariadb': {
|
| const mysqlClient = await mysql.createConnection({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password,
|
| multipleStatements: true
|
| });
|
|
|
| const { sql, values } = this._normalizeQuery(connection, query, params);
|
| const [mysqlRows, mysqlFields] = await mysqlClient.execute(sql, values);
|
|
|
| result = {
|
| command: this.getCommandFromQuery(query),
|
| rows: Array.isArray(mysqlRows) ? mysqlRows : [],
|
| fields: mysqlFields || [],
|
| rowCount: mysqlRows?.affectedRows !== undefined
|
| ? mysqlRows.affectedRows
|
| : (Array.isArray(mysqlRows) ? mysqlRows.length : 0)
|
| };
|
|
|
| await mysqlClient.end();
|
| break;
|
| }
|
|
|
| case 'sqlite':
|
| throw new Error('SQLite query execution not implemented yet');
|
| break;
|
|
|
| default:
|
| throw new Error(`Query execution not implemented for ${connection.type}`);
|
| }
|
|
|
|
|
| if ((result.command || '').toUpperCase() === 'SELECT' || Array.isArray(result.rows)) {
|
| data.type = 'select';
|
|
|
| const cols = result.fields ? result.fields.map(f => f.name) : (result.rows[0] ? Object.keys(result.rows[0]) : []);
|
| data.columns = cols;
|
| data.rows = (result.rows || []).map(row => cols.map(col => {
|
| const v = row[col];
|
| if (v === null || v === undefined) return 'NULL';
|
| if (v instanceof Date) return v.toISOString();
|
| if (typeof v === 'object' && v !== null) return JSON.stringify(v);
|
| return String(v);
|
| }));
|
| data.rowCount = typeof result.rowCount === 'number' ? result.rowCount : (result.rows ? result.rows.length : 0);
|
| } else {
|
| data.rowCount = result.rowCount || 0;
|
| data.message = `${result.command || 'OK'} executed. ${data.rowCount} rows affected.`;
|
| }
|
|
|
| const executionTime = Date.now() - startTime;
|
| data.executionTime = executionTime;
|
|
|
| } catch (error) {
|
| console.error('Query execution error:', error);
|
| return res.status(500).json({
|
| success: false,
|
| error: `SQL Error: ${error.message}`
|
| });
|
| }
|
|
|
| res.json({
|
| success: true,
|
| data,
|
| executedAt: new Date().toISOString()
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| async getSQLFiles(req, res) {
|
| try {
|
| const fs = require('fs').promises;
|
| const sqlDir = path.join(__dirname, '..', 'sql');
|
|
|
| try {
|
| const files = await fs.readdir(sqlDir);
|
| const sqlFiles = files.filter(file => file.endsWith('.sql'));
|
|
|
| const fileDetails = await Promise.all(
|
| sqlFiles.map(async (file) => {
|
| try {
|
| const filePath = path.join(sqlDir, file);
|
| const stats = await fs.stat(filePath);
|
| const content = await fs.readFile(filePath, 'utf8');
|
|
|
| return {
|
| name: file,
|
| size: this.formatFileSize(stats.size),
|
| modified: stats.mtime.toISOString().split('T')[0],
|
| type: this.detectSQLType(content),
|
| content: content.substring(0, 1000) + (content.length > 1000 ? '...' : '')
|
| };
|
| } catch (err) {
|
| console.error(`Error reading file ${file}:`, err);
|
| return null;
|
| }
|
| })
|
| );
|
|
|
| res.json({
|
| success: true,
|
| files: fileDetails.filter(f => f !== null),
|
| scannedAt: new Date().toISOString()
|
| });
|
| } catch (err) {
|
| if (err.code === 'ENOENT') {
|
| res.json({
|
| success: true,
|
| files: [],
|
| message: 'SQL folder not found',
|
| scannedAt: new Date().toISOString()
|
| });
|
| } else {
|
| throw err;
|
| }
|
| }
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| async getSQLFileContent(req, res) {
|
| try {
|
| const { filename } = req.params;
|
| const fs = require('fs').promises;
|
| const filePath = path.join(__dirname, '..', 'sql', filename);
|
|
|
| const content = await fs.readFile(filePath, 'utf8');
|
| const stats = await fs.stat(filePath);
|
|
|
| res.json({
|
| success: true,
|
| file: {
|
| name: filename,
|
| content,
|
| size: this.formatFileSize(stats.size),
|
| modified: stats.mtime.toISOString(),
|
| type: this.detectSQLType(content)
|
| }
|
| });
|
| } catch (error) {
|
| res.status(404).json({
|
| success: false,
|
| error: 'File not found'
|
| });
|
| }
|
| }
|
|
|
| async executeSQLFile(req, res) {
|
| try {
|
| const { id } = req.params;
|
| const { filename } = req.body;
|
|
|
| const fs = require('fs').promises;
|
| const filePath = path.join(__dirname, '..', 'sql', filename);
|
| const content = await fs.readFile(filePath, 'utf8');
|
|
|
|
|
| const statements = content.split(';').filter(s => s.trim().length > 0);
|
| let totalRowsAffected = 0;
|
|
|
| const connection = this.connections.get(id);
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| for (const statement of statements) {
|
| if (statement.trim()) {
|
| const result = await pgClient.query(statement);
|
| totalRowsAffected += result.rowCount || 0;
|
| }
|
| }
|
|
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`File execution not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| return res.status(500).json({
|
| success: false,
|
| error: `SQL execution error: ${error.message}`
|
| });
|
| }
|
|
|
| res.json({
|
| success: true,
|
| execution: {
|
| filename,
|
| statementsExecuted: statements.length,
|
| rowsAffected: totalRowsAffected,
|
| executedAt: new Date().toISOString()
|
| }
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async getAvailablePlugins(req, res) {
|
| try {
|
| const pluginsDir = path.join(__dirname, '..', 'plugins');
|
|
|
| if (!fs.existsSync(pluginsDir)) {
|
| return res.json({ success: true, plugins: [] });
|
| }
|
|
|
| const directories = fs.readdirSync(pluginsDir, { withFileTypes: true })
|
| .filter(dirent => dirent.isDirectory())
|
| .map(dirent => dirent.name);
|
|
|
| const plugins = [];
|
|
|
|
|
| for (const dir of directories) {
|
| const setupPath = path.join(pluginsDir, dir, 'setup.js');
|
| if (fs.existsSync(setupPath)) {
|
| try {
|
|
|
| const plugin = require(setupPath);
|
| plugins.push({
|
| name: dir,
|
| displayName: plugin.PLUGIN_INFO?.name || dir,
|
| version: plugin.PLUGIN_INFO?.version || '1.0.0',
|
| description: plugin.PLUGIN_INFO?.description || 'No description available',
|
| author: plugin.PLUGIN_INFO?.author || 'Unknown',
|
| supportedDatabases: plugin.PLUGIN_INFO?.supportedDatabases || ['postgresql'],
|
| features: plugin.PLUGIN_INFO?.features || [],
|
| ui: plugin.PLUGIN_INFO?.ui || {
|
| allowDragDrop: false,
|
| allowDirectRun: false,
|
| supportedFileTypes: []
|
| }
|
| });
|
| } catch (error) {
|
| console.warn(`[WARN] Failed to load plugin info for ${dir}:`, error.message);
|
| plugins.push({
|
| name: dir,
|
| displayName: dir,
|
| version: '1.0.0',
|
| description: 'Plugin info unavailable',
|
| author: 'Unknown',
|
| supportedDatabases: ['postgresql'],
|
| features: [],
|
| ui: {
|
| allowDragDrop: false,
|
| allowDirectRun: false,
|
| supportedFileTypes: []
|
| }
|
| });
|
| }
|
| }
|
| }
|
|
|
| console.log(`Found ${plugins.length} database templates:`, plugins.map(p => p.name).join(', '));
|
|
|
| res.json({
|
| success: true,
|
| plugins: plugins
|
| });
|
| } catch (error) {
|
| console.error('[ERROR] Error loading plugins:', error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async runPluginSetup(req, res) {
|
| try {
|
| const { pluginName } = req.params;
|
| const { connectionId } = req.body;
|
|
|
| console.log(`[RUN] Running plugin: ${pluginName} for connection: ${connectionId}`);
|
|
|
| const connection = this.connections.get(connectionId);
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| const pluginPath = path.join(__dirname, '..', 'plugins', pluginName, 'setup.js');
|
| if (!fs.existsSync(pluginPath)) {
|
| return res.status(404).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' not found.`
|
| });
|
| }
|
|
|
|
|
| const setupRunner = require(pluginPath);
|
|
|
|
|
| const supportedDbs = setupRunner.PLUGIN_INFO?.supportedDatabases || ['postgresql'];
|
| if (!supportedDbs.includes(connection.type)) {
|
| return res.status(400).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' does not support database type '${connection.type}'. Supported types: ${supportedDbs.join(', ')}`
|
| });
|
| }
|
|
|
|
|
| const databasesToTry = ['template1', 'template0', 'postgres'];
|
| let maintenanceDatabase = null;
|
|
|
| for (const dbName of databasesToTry) {
|
| try {
|
| const testClient = new (require('pg').Client)({
|
| user: connection.username,
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password,
|
| database: dbName
|
| });
|
|
|
| await testClient.connect();
|
| await testClient.end();
|
| maintenanceDatabase = dbName;
|
| console.log(`[SUCCESS] Found working maintenance database: ${dbName}`);
|
| break;
|
| } catch (err) {
|
| console.log(`[ERROR] Cannot connect to ${dbName}: ${err.message}`);
|
| }
|
| }
|
|
|
| if (!maintenanceDatabase) {
|
| throw new Error('Cannot find any working maintenance database (template1, template0, postgres). Please check your PostgreSQL installation.');
|
| }
|
|
|
| const dbConfig = {
|
| user: connection.username,
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password,
|
| database: maintenanceDatabase
|
| };
|
|
|
| const targetDatabase = connection.database;
|
|
|
|
|
| console.log('[CONFIG] Database Config:', {
|
| user: dbConfig.user,
|
| host: dbConfig.host,
|
| port: dbConfig.port,
|
| database: dbConfig.database,
|
| targetDatabase: targetDatabase
|
| });
|
|
|
|
|
| console.log(`[CHECK] Checking if database '${targetDatabase}' exists and has data...`);
|
| let shouldBackup = false;
|
|
|
| try {
|
| const checkClient = new (require('pg').Client)({
|
| user: connection.username,
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password,
|
| database: targetDatabase
|
| });
|
|
|
| await checkClient.connect();
|
| const tableCount = await checkClient.query(`
|
| SELECT COUNT(*) as count FROM information_schema.tables
|
| WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
|
| `);
|
|
|
| const hasData = parseInt(tableCount.rows[0].count) > 0;
|
| await checkClient.end();
|
|
|
| if (hasData) {
|
| shouldBackup = true;
|
| console.log(`[WARN] Database '${targetDatabase}' contains ${tableCount.rows[0].count} tables. Creating backup...`);
|
|
|
|
|
| const backupDir = path.join(__dirname, '..', 'backup');
|
| if (!fs.existsSync(backupDir)) {
|
| fs.mkdirSync(backupDir, { recursive: true });
|
| }
|
|
|
| const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
| const backupFile = path.join(backupDir, `${targetDatabase}_backup_${timestamp}.sql`);
|
|
|
| try {
|
| const { dumpDb } = require('../tools/db-tools');
|
| await dumpDb({
|
| host: connection.host,
|
| port: connection.port,
|
| database: targetDatabase,
|
| user: connection.username,
|
| password: connection.password
|
| }, backupFile, { format: 'sql', clean: false });
|
|
|
| console.log(`[SUCCESS] Backup saved to: ${backupFile}`);
|
| } catch (backupError) {
|
| console.log(`[WARN] Backup failed: ${backupError.message}`);
|
| }
|
| }
|
| } catch (checkError) {
|
| console.log(`ℹ Database '${targetDatabase}' doesn't exist or is inaccessible. Proceeding without backup.`);
|
| }
|
|
|
|
|
| console.log(`[DROP] Dropping and recreating database: ${targetDatabase}`);
|
|
|
| try {
|
| await setupRunner.createDatabase(dbConfig, targetDatabase);
|
| console.log(`[SUCCESS] Database '${targetDatabase}' created successfully`);
|
| } catch (createError) {
|
| console.error(`[ERROR] Failed to create database '${targetDatabase}':`, createError.message);
|
| throw new Error(`Database creation failed: ${createError.message}`);
|
| }
|
|
|
|
|
| console.log(`[BUILD] Setting up database structure for: ${targetDatabase}`);
|
|
|
| let result;
|
| try {
|
| result = await setupRunner.setupDatabaseStructure({
|
| dbConfig,
|
| targetDatabase
|
| });
|
|
|
| console.log(`[SUCCESS] Database structure setup completed successfully`);
|
|
|
| } catch (structureError) {
|
| console.error(`[ERROR] Database structure setup failed:`, structureError.message);
|
| if (shouldBackup) {
|
| console.log(`[RETRY] Attempting manual backup restoration...`);
|
| try {
|
| const backupDir = path.join(__dirname, '..', 'backup');
|
| const backupFiles = fs.readdirSync(backupDir)
|
| .filter(f => f.startsWith(`${targetDatabase}_backup_`))
|
| .sort()
|
| .reverse();
|
|
|
| if (backupFiles.length > 0) {
|
| const latestBackup = path.join(backupDir, backupFiles[0]);
|
| const { restoreDb } = require('../tools/db-tools');
|
|
|
|
|
| await setupRunner.createDatabase(dbConfig, targetDatabase);
|
|
|
|
|
| await restoreDb({
|
| host: connection.host,
|
| port: connection.port,
|
| database: targetDatabase,
|
| user: connection.username,
|
| password: connection.password
|
| }, latestBackup);
|
|
|
| console.log(`[SUCCESS] Database restored from backup: ${backupFiles[0]}`);
|
| }
|
| } catch (restoreError) {
|
| console.error(`[ERROR] Restore from backup failed:`, restoreError.message);
|
| }
|
| }
|
|
|
| throw new Error(`Database structure setup failed: ${structureError.message}`);
|
| }
|
|
|
| console.log(`[SUCCESS] Plugin '${pluginName}' executed successfully`);
|
|
|
| res.json({
|
| success: true,
|
| message: `Plugin '${pluginName}' executed successfully.`,
|
| summary: result?.summary || {}
|
| });
|
|
|
| } catch (error) {
|
| console.error(`[ERROR] Plugin setup for '${req.params.pluginName}' failed:`, error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async getTableColumns(req, res) {
|
| try {
|
| const { id, table } = req.params;
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| let columns = [];
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const columnsResult = await pgClient.query(`
|
| SELECT
|
| c.column_name,
|
| c.data_type,
|
| c.is_nullable,
|
| c.column_default,
|
| c.ordinal_position,
|
| CASE
|
| WHEN tc.constraint_type = 'PRIMARY KEY' THEN TRUE
|
| ELSE FALSE
|
| END as is_primary_key
|
| FROM information_schema.columns c
|
| LEFT JOIN information_schema.key_column_usage kcu
|
| ON c.table_schema = kcu.table_schema
|
| AND c.table_name = kcu.table_name
|
| AND c.column_name = kcu.column_name
|
| LEFT JOIN information_schema.table_constraints tc
|
| ON kcu.constraint_name = tc.constraint_name
|
| AND kcu.table_schema = tc.table_schema
|
| AND kcu.table_name = tc.table_name
|
| AND tc.constraint_type = 'PRIMARY KEY'
|
| WHERE c.table_name = $1 AND c.table_schema = 'public'
|
| ORDER BY c.ordinal_position
|
| `, [table]);
|
|
|
| columns = columnsResult.rows.map(row => ({
|
| name: row.column_name,
|
| type: row.data_type,
|
| nullable: row.is_nullable === 'YES',
|
| default: row.column_default,
|
| position: row.ordinal_position,
|
| isPrimaryKey: row.is_primary_key
|
| }));
|
|
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`Get columns not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Get table columns error:', error);
|
| throw error;
|
| }
|
|
|
| res.json({
|
| success: true,
|
| columns
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async insertRow(req, res) {
|
| try {
|
| const { id, table } = req.params;
|
| const { data } = req.body;
|
|
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| if (!data || typeof data !== 'object') {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Row data is required'
|
| });
|
| }
|
|
|
| let result;
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const columns = Object.keys(data);
|
| const values = Object.values(data);
|
| const placeholders = values.map((_, index) => `$${index + 1}`).join(', ');
|
|
|
| const insertQuery = `
|
| INSERT INTO "${table}" (${columns.map(col => `"${col}"`).join(', ')})
|
| VALUES (${placeholders})
|
| RETURNING *
|
| `;
|
|
|
| result = await pgClient.query(insertQuery, values);
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`Insert not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Insert row error:', error);
|
| return res.status(500).json({
|
| success: false,
|
| error: `SQL Error: ${error.message}`
|
| });
|
| }
|
|
|
| res.json({
|
| success: true,
|
| message: 'Row inserted successfully',
|
| data: result.rows[0],
|
| insertedAt: new Date().toISOString()
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async updateRow(req, res) {
|
| try {
|
| const { id, table, rowId } = req.params;
|
| const { data, primaryKey } = req.body;
|
|
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| if (!data || typeof data !== 'object') {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Update data is required'
|
| });
|
| }
|
|
|
| if (!primaryKey) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Primary key name is required'
|
| });
|
| }
|
|
|
| let result;
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const entries = Object.entries(data);
|
| const setClause = entries.map((_, index) => `"${entries[index][0]}" = $${index + 1}`).join(', ');
|
| const values = entries.map(([, value]) => value);
|
| values.push(rowId);
|
|
|
| const updateQuery = `
|
| UPDATE "${table}"
|
| SET ${setClause}
|
| WHERE "${primaryKey}" = $${values.length}
|
| RETURNING *
|
| `;
|
|
|
| result = await pgClient.query(updateQuery, values);
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`Update not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Update row error:', error);
|
| return res.status(500).json({
|
| success: false,
|
| error: `SQL Error: ${error.message}`
|
| });
|
| }
|
|
|
| if (result.rowCount === 0) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Row not found'
|
| });
|
| }
|
|
|
| res.json({
|
| success: true,
|
| message: 'Row updated successfully',
|
| data: result.rows[0],
|
| updatedAt: new Date().toISOString()
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async deleteRow(req, res) {
|
| try {
|
| const { id, table, rowId } = req.params;
|
| const primaryKey = req.body?.primaryKey || req.query.primaryKey || 'id';
|
|
|
| const connection = this.connections.get(id);
|
|
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| let result;
|
|
|
| try {
|
| switch (connection.type) {
|
| case 'postgresql':
|
| const pgClient = new Pool({
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| user: connection.username,
|
| password: connection.password
|
| });
|
|
|
| const deleteQuery = `
|
| DELETE FROM "${table}"
|
| WHERE "${primaryKey}" = $1
|
| RETURNING *
|
| `;
|
|
|
| result = await pgClient.query(deleteQuery, [rowId]);
|
| await pgClient.end();
|
| break;
|
|
|
| default:
|
| throw new Error(`Delete not implemented for ${connection.type}`);
|
| }
|
| } catch (error) {
|
| console.error('Delete row error:', error);
|
| return res.status(500).json({
|
| success: false,
|
| error: `SQL Error: ${error.message}`
|
| });
|
| }
|
|
|
|
|
| if (result.rowCount === 0) {
|
| return res.json({
|
| success: true,
|
| message: 'Row already deleted or not found',
|
| data: null,
|
| deletedAt: new Date().toISOString()
|
| });
|
| }
|
|
|
| res.json({
|
| success: true,
|
| message: 'Row deleted successfully',
|
| data: result.rows[0],
|
| deletedAt: new Date().toISOString()
|
| });
|
| } catch (error) {
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| formatFileSize(bytes) {
|
| if (bytes === 0) return '0 B';
|
| const k = 1024;
|
| const sizes = ['B', 'KB', 'MB', 'GB'];
|
| const i = Math.floor(Math.log(bytes) / Math.log(k));
|
| return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| detectSQLType(content) {
|
| const upperContent = content.toUpperCase();
|
| if (upperContent.includes('CREATE TABLE') || upperContent.includes('CREATE INDEX')) {
|
| return 'DDL';
|
| } else if (upperContent.includes('INSERT INTO') || upperContent.includes('UPDATE') || upperContent.includes('DELETE')) {
|
| return 'DML';
|
| } else {
|
| return 'SQL';
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| getCommandFromQuery(query) {
|
| const trimmed = query.trim().toUpperCase();
|
| if (trimmed.startsWith('SELECT')) return 'SELECT';
|
| if (trimmed.startsWith('INSERT')) return 'INSERT';
|
| if (trimmed.startsWith('UPDATE')) return 'UPDATE';
|
| if (trimmed.startsWith('DELETE')) return 'DELETE';
|
| if (trimmed.startsWith('CREATE')) return 'CREATE';
|
| if (trimmed.startsWith('DROP')) return 'DROP';
|
| if (trimmed.startsWith('ALTER')) return 'ALTER';
|
| return 'UNKNOWN';
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| async handlePluginDropFiles(req, res) {
|
| try {
|
| const { pluginName } = req.params;
|
| const { files, connectionId } = req.body;
|
|
|
| if (!files || !Array.isArray(files)) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'No files provided'
|
| });
|
| }
|
|
|
|
|
| const pluginPath = path.join(__dirname, '..', 'plugins', pluginName, 'setup.js');
|
| if (!fs.existsSync(pluginPath)) {
|
| return res.status(404).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' not found`
|
| });
|
| }
|
|
|
|
|
| const connection = this.connections.get(connectionId);
|
| if (!connection) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Invalid connection ID'
|
| });
|
| }
|
|
|
| const plugin = require(pluginPath);
|
|
|
|
|
| if (!plugin.PLUGIN_INFO?.ui?.allowDragDrop) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Plugin does not support drag & drop'
|
| });
|
| }
|
|
|
|
|
| const results = {
|
| processed: [],
|
| errors: [],
|
| summary: {
|
| total: files.length,
|
| success: 0,
|
| failed: 0
|
| }
|
| };
|
|
|
|
|
| const dbConfig = {
|
| user: connection.username,
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password,
|
| database: connection.database
|
| };
|
|
|
|
|
| const tempFiles = [];
|
| for (const file of files) {
|
| if (file.content && !file.path) {
|
|
|
| const tempDir = path.join(__dirname, '..', 'temp');
|
| if (!fs.existsSync(tempDir)) {
|
| fs.mkdirSync(tempDir, { recursive: true });
|
| }
|
|
|
| const tempFilePath = path.join(tempDir, `${Date.now()}_${file.name}`);
|
| fs.writeFileSync(tempFilePath, file.content, 'utf8');
|
| file.path = tempFilePath;
|
| tempFiles.push(tempFilePath);
|
| }
|
| }
|
|
|
| try {
|
|
|
| let pluginResult;
|
| if (typeof plugin.handleDroppedFiles === 'function') {
|
|
|
| pluginResult = await plugin.handleDroppedFiles(files.map(f => f.path), dbConfig);
|
| } else if (typeof plugin.importFromFile === 'function') {
|
|
|
| for (const file of files) {
|
| const fileExtension = path.extname(file.name).toLowerCase();
|
|
|
| if (plugin.PLUGIN_INFO.ui.supportedFileTypes.includes(fileExtension)) {
|
| await plugin.importFromFile(file.path, dbConfig);
|
| results.processed.push({
|
| file: file.name,
|
| type: fileExtension,
|
| status: 'success',
|
| message: `Imported by ${plugin.PLUGIN_INFO.name}`
|
| });
|
| results.summary.success++;
|
| } else {
|
| throw new Error(`Unsupported file type: ${fileExtension}`);
|
| }
|
| }
|
| } else {
|
| throw new Error('Plugin does not support file import');
|
| }
|
|
|
|
|
| if (pluginResult) {
|
| results.processed = pluginResult.processed || [];
|
| results.errors = pluginResult.errors || [];
|
| results.summary = pluginResult.summary || { total: files.length, success: 0, failed: 0 };
|
| }
|
|
|
| } finally {
|
|
|
| for (const tempFile of tempFiles) {
|
| try {
|
| if (fs.existsSync(tempFile)) {
|
| fs.unlinkSync(tempFile);
|
| }
|
| } catch (cleanupError) {
|
| console.warn('[WARN] Failed to cleanup temp file:', tempFile, cleanupError.message);
|
| }
|
| }
|
| }
|
|
|
| console.log(`[DROP] Drag & Drop: Processed ${results.summary.success} files for ${pluginName}`);
|
|
|
| res.json({
|
| success: true,
|
| data: results
|
| });
|
|
|
| } catch (error) {
|
| console.error('[ERROR] Drag & Drop error:', error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| async handlePluginSQLDump(req, res) {
|
| try {
|
| const { pluginName } = req.params;
|
| const { connectionId, tableName } = req.body;
|
|
|
| console.log(`[DUMP] SQL Dump requested for plugin: ${pluginName}`);
|
|
|
| const connection = this.connections.get(connectionId);
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: 'Connection not found'
|
| });
|
| }
|
|
|
| const pluginPath = path.join(__dirname, '..', 'plugins', pluginName, 'setup.js');
|
| if (!fs.existsSync(pluginPath)) {
|
| return res.status(404).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' not found.`
|
| });
|
| }
|
|
|
|
|
| const plugin = require(pluginPath);
|
|
|
|
|
| if (!plugin.PLUGIN_INFO?.ui?.allowSQLDump) {
|
| return res.status(400).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' does not support SQL dump functionality.`
|
| });
|
| }
|
|
|
|
|
| const supportedDbs = plugin.PLUGIN_INFO?.supportedDatabases || ['postgresql'];
|
| if (!supportedDbs.includes(connection.type)) {
|
| return res.status(400).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' does not support database type '${connection.type}'. Supported types: ${supportedDbs.join(', ')}`
|
| });
|
| }
|
|
|
|
|
| const dbConfig = {
|
| user: connection.username,
|
| host: connection.host,
|
| port: connection.port,
|
| password: connection.password,
|
| database: connection.database
|
| };
|
|
|
|
|
| const timestamp = Date.now();
|
| const outputFile = `backup/${connection.database}_${pluginName}_${timestamp}.sql`;
|
|
|
| await plugin.exportToFile(outputFile, 'sql', dbConfig);
|
|
|
| const result = {
|
| message: `Database exported successfully as SQL file (editable)`,
|
| filesCreated: [outputFile],
|
| format: 'sql',
|
| timestamp: timestamp
|
| };
|
|
|
| console.log(`[SUCCESS] Database Export completed for plugin '${pluginName}' using db-tools`);
|
|
|
| res.json({
|
| success: true,
|
| data: result
|
| });
|
|
|
| } catch (error) {
|
| console.error('[ERROR] SQL Dump error:', error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| async handlePluginImportFile(req, res) {
|
| try {
|
| const { plugin: pluginName, filePath } = req.body;
|
|
|
| if (!pluginName || !filePath) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'Plugin name and file path are required'
|
| });
|
| }
|
|
|
|
|
| const connection = this.getActiveConnection();
|
| if (!connection) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'No active database connection'
|
| });
|
| }
|
|
|
|
|
| const plugin = this.loadPlugin(pluginName);
|
| if (!plugin) {
|
| return res.status(404).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' not found`
|
| });
|
| }
|
|
|
|
|
| if (typeof plugin.importFromFile !== 'function') {
|
| return res.status(400).json({
|
| success: false,
|
| error: `Plugin '${pluginName}' does not support file import`
|
| });
|
| }
|
|
|
|
|
| const dbConfig = {
|
| host: connection.host,
|
| port: connection.port,
|
| database: connection.database,
|
| username: connection.username,
|
| password: connection.password
|
| };
|
|
|
| console.log(`[IMPORT] Starting file import for plugin '${pluginName}' from: ${filePath}`);
|
|
|
|
|
| await plugin.importFromFile(filePath, 'auto', dbConfig);
|
|
|
| const result = {
|
| message: `File imported successfully`,
|
| filePath: filePath,
|
| plugin: pluginName
|
| };
|
|
|
| console.log(`[SUCCESS] File import completed for plugin '${pluginName}'`);
|
|
|
| res.json({
|
| success: true,
|
| data: result
|
| });
|
|
|
| } catch (error) {
|
| console.error('[ERROR] File import error:', error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| async handleDatabaseRestore(req, res) {
|
| const os = require('os');
|
| const fs = require('fs');
|
| const path = require('path');
|
|
|
| try {
|
| const { id } = req.params;
|
| const { filename, contentBase64 } = req.body;
|
|
|
| if (!filename || !contentBase64) {
|
| return res.status(400).json({
|
| success: false,
|
| error: 'filename and contentBase64 are required'
|
| });
|
| }
|
|
|
|
|
| const connection = this.connections.get(id);
|
| if (!connection) {
|
| return res.status(404).json({
|
| success: false,
|
| error: `Connection '${id}' not found`
|
| });
|
| }
|
|
|
| console.log(`[RESTORE] Universal restore starting for: ${filename}`);
|
|
|
|
|
| const tmp = path.join(os.tmpdir(), `restore-${Date.now()}-${filename}`);
|
| fs.writeFileSync(tmp, Buffer.from(contentBase64, 'base64'));
|
|
|
|
|
| const { restoreDb } = require('../tools/db-tools');
|
| const dbConfig = {
|
| host: connection.host,
|
| port: connection.port,
|
| user: connection.username,
|
| password: connection.password,
|
| database: connection.database
|
| };
|
|
|
| await restoreDb(dbConfig, tmp);
|
|
|
|
|
| fs.unlink(tmp, () => { });
|
|
|
| console.log(`[SUCCESS] Universal restore completed: ${filename}`);
|
|
|
| res.json({
|
| success: true,
|
| message: 'Database restored successfully',
|
| filename: filename
|
| });
|
|
|
| } catch (error) {
|
| console.error('[ERROR] Universal restore error:', error);
|
| res.status(500).json({
|
| success: false,
|
| error: error.message
|
| });
|
| }
|
| }
|
| }
|
|
|
| module.exports = DatabaseServer;
|
|
|