chahua-database-manager / server /database-server.js
chahuadev's picture
Upload 40 files
8eeb77a verified
/**
* @fileoverview Chahua Database Manager - Database Server Module
* @description Express server สำหรับจัดการการเชื่อมต่อฐานข้อมูลและการดำเนินการต่างๆ
* คุณสมบัติ: Multi-database support, Query execution, CRUD operations, Plugin system
* @author ทีมพัฒนา Chahua
* @version 1.0.0
* @since 2024-01-01
* @calledBy main.js (Electron main process), renderer UI components
* @dependencies
* - express: Web server framework
* - pg: PostgreSQL client
* - mysql2: MySQL client
* - mongodb: MongoDB client
* - redis: Redis client
* - ../license-guard: License validation
* @features
* - Multi-database support (PostgreSQL, MySQL, MongoDB, Redis)
* - RESTful API for database operations
* - Connection management and persistence
* - SQL query execution and results
* - Plugin system integration
* - License validation middleware
* @security
* - License-based access control
* - CORS configuration
* - Input validation and sanitization
* - Secure connection handling
* @example
* // Create and start server
* const server = new DatabaseServer();
* await server.start();
*
* // Test connection
* const result = await server.testConnection(connectionConfig);
*/
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');
/**
* Database Server - Express server for managing database connections and operations
* @class DatabaseServer
* @description Main server class that provides REST API for database management operations
* including connections, queries, CRUD operations, and plugin system
* @features
* - Multiple database engine support
* - Connection pooling and management
* - RESTful API endpoints
* - Plugin system integration
* - License validation
*/
class DatabaseServer {
/**
* Create a DatabaseServer instance
* @constructor
* @description Initializes Express app, sets up middleware, routes, and loads saved connections
* @features
* - Express application setup
* - CORS and middleware configuration
* - Route initialization
* - Connection persistence loading
*/
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();
}
/**
* Load saved connections from JSON file
* @async
* @function loadConnectionsFromFile
* @returns {Promise<void>}
* @description Loads connection configurations from data/connections.json file
* @features
* - Automatic data directory creation
* - JSON file parsing and validation
* - Error handling for corrupted files
*/
async loadConnectionsFromFile() {
try {
// สร้างโฟลเดอร์ data ถ้าไม่มี
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);
// โหลดเข้า Map
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);
}
}
/**
* Save connections configuration to JSON file
* @async
* @returns {Promise<void>}
* @description Persists current connections map to data/connections.json file
*/
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);
}
}
/**
* Configure Express middleware for CORS, JSON parsing, and logging
* @returns {void}
* @description Sets up CORS, JSON/URL encoding middleware, and request logging
*/
setupMiddleware() {
this.app.use(cors({
origin: '*', // Allow all origins since it's a desktop app
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' }));
// Logging middleware
this.app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
next();
});
// [LICENSE] License gate (อนุญาตเฉพาะ health)
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}` });
}
});
}
/**
* Setup Express routes for all API endpoints
* @returns {void}
* @description Configures all REST API routes including connections, queries, and CRUD operations
*/
setupRoutes() {
// Health check
this.app.get('/api/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
version: '2.0.0'
});
});
// License endpoint
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 });
}
});
// Connection management
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));
// Database operations
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));
// SQL file operations
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));
// � Table CRUD Operations
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));
// [PLUGIN] Plugin System APIs
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));
// [RESTORE] Universal Database Restore (สำหรับไฟล์ .sql/.dump ทุกชนิด)
this.app.post('/api/connections/:id/restore', this.handleDatabaseRestore.bind(this));
// Error handler
this.app.use((err, req, res, next) => {
console.error('Server error:', err);
res.status(500).json({
success: false,
error: err.message || 'Internal server error'
});
});
}
/**
* Start the Express server
* @async
* @returns {Promise<void>}
* @throws {Error} When server fails to start
* @description Starts the HTTP server on localhost with configured port
*/
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();
}
});
});
}
/**
* Stop the Express server gracefully
* @async
* @returns {Promise<void>}
* @description Closes the HTTP server and cleans up resources
*/
async stop() {
if (this.server) {
return new Promise((resolve) => {
this.server.close(() => {
console.log('[STOP] Database server stopped');
resolve();
});
});
}
}
/**
* Get the current server port
* @returns {number} The port number the server is running on
*/
getPort() {
return this.port;
}
/**
* Create a new database connection configuration
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {Object} req.body - Connection configuration
* @param {string} req.body.name - Display name for the connection
* @param {string} req.body.type - Database type (postgresql, mysql, etc.)
* @param {string} req.body.host - Database host address
* @param {number} req.body.port - Database port number
* @param {string} req.body.database - Database name
* @param {string} req.body.username - Database username
* @param {string} req.body.password - Database password
* @param {Object} [req.body.options={}] - Additional connection options
* @returns {Promise<void>}
* @description Creates and saves a new database connection configuration
*/
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);
// [SAVE] บันทึกข้อมูลลงไฟล์
await this.saveConnectionsToFile();
res.json({
success: true,
connection: {
...connection,
password: undefined // Don't send password back
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
}
/**
* Get all saved database connections (without passwords)
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @returns {Promise<void>}
* @description Returns array of all saved connections with passwords excluded for security
*/
async getConnections(req, res) {
try {
const connections = Array.from(this.connections.values()).map(conn => ({
...conn,
password: undefined // Don't send passwords
}));
res.json({
success: true,
connections
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
}
/**
* Delete a database connection configuration
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID to delete
* @returns {Promise<void>}
* @description Removes a connection configuration from memory and file storage
*/
async deleteConnection(req, res) {
try {
const { id } = req.params;
if (this.connections.has(id)) {
this.connections.delete(id);
// [SAVE] บันทึกการเปลี่ยนแปลงลงไฟล์
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
});
}
}
/**
* Test database connection validity
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID to test
* @returns {Promise<void>}
* @description Tests if the database connection can be established successfully
* @example
* // POST /api/connections/123/test
* // Returns: { success: true, connectionTest: { status: 'connected' } }
*/
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':
// SQLite is file-based, just check if file exists or can be created
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;
}
// Update connection status
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
});
}
}
/**
* Get database structure including tables and views
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @returns {Promise<void>}
* @description Retrieves complete database schema including tables, views, and row counts
* @example
* // GET /api/connections/123/structure
* // Returns: { success: true, structure: { database: 'mydb', tables: [...], views: [...] } }
*/
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':
// SQLite structure query would go here
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 // MongoDB doesn't provide easy row count
}));
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
});
}
}
/**
* Get paginated table data
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {string} req.params.table - Table name
* @param {number} [req.query.page=1] - Page number for pagination
* @param {number} [req.query.limit=50] - Number of rows per page
* @returns {Promise<void>}
* @description Retrieves table data with pagination support
* @example
* // GET /api/connections/123/tables/users/data?page=1&limit=25
* // Returns: { success: true, data: { columns: [...], rows: [...], total: 100 } }
*/
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
});
// Get columns
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);
// Get total count
const countResult = await pgClient.query(`SELECT COUNT(*) as total FROM "${table}"`);
data.total = parseInt(countResult.rows[0].total);
// Get data
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);
// Return empty data if table doesn't exist
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
});
}
}
// ===== NEW: helpers for placeholder/params =====
/**
* Detect the parameter style used in SQL query
* @param {string} sql - SQL query string
* @returns {string} - Parameter style: 'pg', 'named', 'qmark', or 'none'
*/
_detectParamStyle(sql) {
if (/\$\d+/.test(sql)) return 'pg'; // $1, $2 ...
if (/(^|[^:]):([a-zA-Z_]\w*)/.test(sql)) return 'named'; // :name (avoid ::)
if (/\?/.test(sql)) return 'qmark'; // ?, ?, ...
return 'none';
}
/**
* Normalize query + params to driver-specific placeholders.
* params can be Array (positional) or Object (named).
* @param {Object} connection - Database connection configuration
* @param {string} sql - SQL query string
* @param {Array|Object} params - Query parameters
* @returns {Object} - Normalized query with { sql, values }
*/
_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)) {
// no params – just pass through
return { sql, values: [] };
}
// Make a safe accessor for named params
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];
};
// Build
let values = [];
// Helper: replace :name in order of appearance
const replaceNamedWith = (placeholderBuilder) => {
const seen = new Map(); // name -> index
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') {
// Already $1,$2,... -> use params in the numeric order that appears in the SQL
if (Array.isArray(params)) {
const order = [];
sql.replace(/\$(\d+)/g, (_, n) => order.push(parseInt(n, 10) - 1));
values = order.map(i => params[i]);
} else {
// If params is object but SQL is $1 form, assume array-like order by $n
const keys = Object.keys(params).sort(); // best effort
const order = [];
sql.replace(/\$(\d+)/g, (_, n) => order.push(parseInt(n, 10)));
values = order.map(n => params[keys[n - 1]]);
}
} else if (style === 'qmark') {
// ? -> $1,$2,...
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') {
// :name -> $1,$2,...
replaceNamedWith((n) => `$${n}`);
} else {
// no placeholder but params provided -> ignore values
values = Array.isArray(params) ? params : Object.values(params);
}
} else if (type === 'mysql' || type === 'mariadb') {
if (style === 'pg') {
// $1,$2 -> ? and map order
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') {
// :name -> ?
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') {
// Keep same semantics as MySQL/SQLite (qmark)
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 {
// Non-SQL engines
return { sql, values: [] };
}
return { sql, values };
}
/**
* Execute SQL query on specified connection
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {Object} req.body - Request body
* @param {string} req.body.query - SQL query to execute
* @param {Array|Object} [req.body.params] - Query parameters (optional)
* @returns {Promise<void>}
* @description Executes SQL queries with support for prepared statements and multiple parameter styles
* @example
* // POST /api/connections/123/query
* // Body: { query: "SELECT * FROM users WHERE id = $1", params: [42] }
* // Returns: { success: true, data: { type: 'select', columns: [...], rows: [...] } }
*/
async executeQuery(req, res) {
try {
const { id } = req.params;
const { query, params } = req.body; // <— NOW supports params
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}`);
}
// ---- format result to UI shape ----
if ((result.command || '').toUpperCase() === 'SELECT' || Array.isArray(result.rows)) {
data.type = 'select';
// PG: result.fields[] has .name ; MySQL: we built fields above
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');
// Split into statements and execute
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
});
}
}
/**
* Get list of available plugins
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @returns {Promise<void>}
* @description Scans plugins directory and returns available plugins with metadata
* @example
* // GET /api/plugins
* // Returns: { success: true, plugins: [{ name: 'chahua-web-store', displayName: '...', ... }] }
*/
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 = [];
// ตรวจสอบแต่ละ plugin ว่ามี setup.js หรือไม่
for (const dir of directories) {
const setupPath = path.join(pluginsDir, dir, 'setup.js');
if (fs.existsSync(setupPath)) {
try {
// โหลด plugin info
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
});
}
}
/**
* Execute plugin setup for database initialization
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.pluginName - Name of the plugin to execute
* @param {Object} req.body - Request body
* @param {string} req.body.connectionId - Connection ID to use for plugin execution
* @returns {Promise<void>}
* @description Runs a plugin's setup script to initialize database structure and data
* @example
* // POST /api/plugins/chahua-web-store/setup
* // Body: { connectionId: '123' }
* // Returns: { success: true, message: 'Plugin executed successfully', summary: {...} }
*/
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(', ')}`
});
}
// เตรียม config สำหรับปลั๊กอิน - ลองหา maintenance database ที่ใช้ได้
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;
// [DEBUG] แสดง config ที่ใช้
console.log('[CONFIG] Database Config:', {
user: dbConfig.user,
host: dbConfig.host,
port: dbConfig.port,
database: dbConfig.database,
targetDatabase: targetDatabase
});
// [SAFETY] SAFETY: สำรองฐานข้อมูลก่อนลบ (ถ้ามีข้อมูล)
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.`);
}
// [SOLUTION] SOLUTION: ล้างและสร้างฐานข้อมูลใหม่ก่อนเสมอ
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
});
}
}
/**
* Get table column information including primary keys
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {string} req.params.table - Table name
* @returns {Promise<void>}
* @description Retrieves detailed column information including data types, nullability, defaults, and primary key status
* @example
* // GET /api/connections/123/tables/users/columns
* // Returns: { success: true, columns: [{ name: 'id', type: 'integer', isPrimaryKey: true, ... }] }
*/
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 // --- SOLUTION --- ส่งข้อมูล PK กลับไป
}));
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
});
}
}
/**
* Insert a new row into specified table
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {string} req.params.table - Table name
* @param {Object} req.body - Request body
* @param {Object} req.body.data - Row data to insert as key-value pairs
* @returns {Promise<void>}
* @description Inserts a new row and returns the created record
* @example
* // POST /api/connections/123/tables/users/rows
* // Body: { data: { name: 'John Doe', email: 'john@example.com' } }
* // Returns: { success: true, data: { id: 1, name: 'John Doe', ... } }
*/
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
});
}
}
/**
* Update an existing row in specified table
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {string} req.params.table - Table name
* @param {string} req.params.rowId - ID of the row to update
* @param {Object} req.body - Request body
* @param {Object} req.body.data - Updated row data as key-value pairs
* @param {string} [req.body.primaryKey='id'] - Name of the primary key column
* @returns {Promise<void>}
* @description Updates an existing row and returns the modified record
* @example
* // PUT /api/connections/123/tables/users/rows/1
* // Body: { data: { name: 'Jane Doe' }, primaryKey: 'id' }
* // Returns: { success: true, data: { id: 1, name: 'Jane Doe', ... } }
*/
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); // Add rowId as last parameter
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
});
}
}
/**
* Delete a row from specified table
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.id - Connection ID
* @param {string} req.params.table - Table name
* @param {string} req.params.rowId - ID of the row to delete
* @param {Object} req.body - Request body
* @param {string} [req.body.primaryKey='id'] - Name of the primary key column
* @returns {Promise<void>}
* @description Deletes a row and returns the deleted record
* @example
* // DELETE /api/connections/123/tables/users/rows/1
* // Body: { primaryKey: 'id' }
* // Returns: { success: true, data: { id: 1, name: 'John Doe', ... } }
*/
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}`
});
}
// [IDEMPOTENT] Idempotent response - don't throw 404 if already deleted
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
});
}
}
/**
* Format file size in human readable format
* @param {number} bytes - File size in bytes
* @returns {string} Formatted file size (e.g., "1.5 MB", "500 KB")
* @description Converts bytes to human-readable format with appropriate units
* @example
* formatFileSize(1024) // Returns: "1.0 KB"
* formatFileSize(1536) // Returns: "1.5 KB"
*/
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];
}
/**
* Detect SQL statement type from content
* @param {string} content - SQL file content
* @returns {'DDL'|'DML'|'SQL'} SQL type classification
* @description Analyzes SQL content to determine if it's DDL, DML, or general SQL
* @example
* detectSQLType("CREATE TABLE users...") // Returns: "DDL"
* detectSQLType("INSERT INTO users...") // Returns: "DML"
*/
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';
}
}
/**
* Extract SQL command type from query string
* @param {string} query - SQL query string
* @returns {'SELECT'|'INSERT'|'UPDATE'|'DELETE'|'CREATE'|'DROP'|'ALTER'|'UNKNOWN'} SQL command type
* @description Identifies the primary SQL command from a query string
* @example
* getCommandFromQuery("SELECT * FROM users") // Returns: "SELECT"
* getCommandFromQuery("UPDATE users SET...") // Returns: "UPDATE"
*/
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';
}
/**
* Handle drag & drop files for plugins
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @returns {Promise<void>}
* @description Processes files dropped on plugins with drag & drop functionality
*/
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'
});
}
// โหลด plugin
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`
});
}
// ดึงข้อมูล connection
const connection = this.connections.get(connectionId);
if (!connection) {
return res.status(400).json({
success: false,
error: 'Invalid connection ID'
});
}
const plugin = require(pluginPath);
// เช็คว่า plugin รองรับ drag & drop หรือไม่
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
}
};
// เตรียม config สำหรับฐานข้อมูล
const dbConfig = {
user: connection.username,
host: connection.host,
port: connection.port,
password: connection.password,
database: connection.database
};
// สร้าง temporary files สำหรับไฟล์ที่มี content
const tempFiles = [];
for (const file of files) {
if (file.content && !file.path) {
// สร้าง temp file สำหรับ content ที่ส่งมาจาก frontend
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 {
// เรียกใช้ฟังก์ชันจาก plugin
let pluginResult;
if (typeof plugin.handleDroppedFiles === 'function') {
// ใช้ฟังก์ชัน handleDroppedFiles ถ้ามี
pluginResult = await plugin.handleDroppedFiles(files.map(f => f.path), dbConfig);
} else if (typeof plugin.importFromFile === 'function') {
// ถ้าไม่มี handleDroppedFiles ให้ใช้ importFromFile แทน
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');
}
// ถ้าใช้ handleDroppedFiles ให้รวมผลลัพธ์
if (pluginResult) {
results.processed = pluginResult.processed || [];
results.errors = pluginResult.errors || [];
results.summary = pluginResult.summary || { total: files.length, success: 0, failed: 0 };
}
} finally {
// ลบ temp files
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
});
}
}
/**
* Handle plugin SQL dump functionality
* @async
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {string} req.params.pluginName - Name of the plugin
* @param {Object} req.body - Request body
* @param {string} req.body.connectionId - Connection ID to use for SQL dump
* @param {string} [req.body.tableName] - Specific table to dump (optional)
* @returns {Promise<void>}
* @description Executes plugin's SQL dump functionality to generate SQL files from database
* @example
* // POST /api/plugins/chahua-web-store/dump-sql
* // Body: { connectionId: '123', tableName: 'plugins' }
* // Returns: { success: true, data: { filesCreated: [...], 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);
// ตรวจสอบว่าปลั๊กอินรองรับ SQL dump หรือไม่
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(', ')}`
});
}
// เตรียม config สำหรับปลั๊กอิน
const dbConfig = {
user: connection.username,
host: connection.host,
port: connection.port,
password: connection.password,
database: connection.database
};
// ใช้ฟังก์ชันใหม่ที่ใช้ db-tools - เปลี่ยนเป็น .sql เพื่อให้แก้ไขได้
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
});
}
}
/**
* Handle plugin file import from frontend
* // POST /api/plugin/import-file
* @param {Object} req - Express request object containing { plugin, filePath }
* @param {Object} res - Express response object
* @returns {void}
* @description Imports data from .sql or .dump file into the database using plugin's importFromFile method
*/
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'
});
}
// Get active connection
const connection = this.getActiveConnection();
if (!connection) {
return res.status(400).json({
success: false,
error: 'No active database connection'
});
}
// Load plugin
const plugin = this.loadPlugin(pluginName);
if (!plugin) {
return res.status(404).json({
success: false,
error: `Plugin '${pluginName}' not found`
});
}
// Check if plugin has importFromFile method
if (typeof plugin.importFromFile !== 'function') {
return res.status(400).json({
success: false,
error: `Plugin '${pluginName}' does not support file import`
});
}
// Prepare database config
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}`);
// Import file using plugin method
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
});
}
}
/**
* Universal Database Restore using PostgreSQL native tools
* POST /api/connections/:id/restore
* @param {Object} req - Express request { filename, contentBase64 }
* @param {Object} res - Express response
* @description ใช้ pg_restore/psql แท้ๆ แทนการแตก SQL เอง รองรับทุกชนิดไฟล์
*/
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'
});
}
// Get connection
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}`);
// Save to temp file
const tmp = path.join(os.tmpdir(), `restore-${Date.now()}-${filename}`);
fs.writeFileSync(tmp, Buffer.from(contentBase64, 'base64'));
// Import using db-tools with proper UTF-8 support
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);
// Cleanup temp file
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;