| |
| |
| |
| |
| |
| |
|
|
|
|
| const { Client } = require('pg');
|
| const fs = require('fs');
|
| const path = require('path');
|
|
|
|
|
| const { restoreDb, dumpDb } = require('../../tools/db-tools');
|
|
|
|
|
| const enumsModule = require('./modules/01-enums');
|
| const coreTablesModule = require('./modules/02-core-tables');
|
| const paymentTablesModule = require('./modules/03-payment-tables');
|
| const forumTablesModule = require('./modules/04-forum-tables');
|
| const pluginSubmissionTablesModule = require('./modules/05-plugin-submission-tables');
|
| const dashboardTablesModule = require('./modules/06-dashboard-tables');
|
| const bankTransferTablesModule = require('./modules/07-bank-transfer-tables');
|
| const functionsTriggersModule = require('./modules/08-functions-triggers');
|
| const indexesViewsModule = require('./modules/09-indexes-views');
|
|
|
|
|
| const PLUGIN_INFO = {
|
| name: ' Chahua Web Store',
|
| version: 'v1.2.1',
|
| description: 'Complete database schema for Chahua Web Store platform with Drag & Drop support and SQL Dump',
|
| author: 'Chahua Development Thailand',
|
| supportedDatabases: ['postgresql'],
|
| features: ['drag-drop', 'direct-execution', 'modular-setup', 'sql-dump'],
|
| ui: {
|
| allowDragDrop: true,
|
| allowDirectRun: true,
|
| allowSQLDump: true,
|
| supportedFileTypes: ['.sql', '.json']
|
| }
|
| };
|
|
|
| |
| |
| |
| |
| |
|
|
| async function handleDroppedFiles(filePaths, dbConfig) {
|
| console.log(' Processing dropped files...');
|
|
|
| if (!Array.isArray(filePaths)) {
|
| filePaths = [filePaths];
|
| }
|
|
|
| const results = {
|
| processed: [],
|
| errors: [],
|
| summary: {
|
| total: filePaths.length,
|
| success: 0,
|
| failed: 0
|
| }
|
| };
|
|
|
| for (const filePath of filePaths) {
|
| try {
|
| console.log(` Processing: ${path.basename(filePath)}`);
|
|
|
| const fileExtension = path.extname(filePath).toLowerCase();
|
| const fileName = path.basename(filePath);
|
|
|
| if (fileExtension === '.sql') {
|
| const result = await processSQLFile(filePath, dbConfig);
|
| results.processed.push({
|
| file: fileName,
|
| type: 'sql',
|
| status: 'success',
|
| result: result
|
| });
|
| results.summary.success++;
|
| } else if (fileExtension === '.json') {
|
| const result = await processJSONFile(filePath, dbConfig);
|
| results.processed.push({
|
| file: fileName,
|
| type: 'json',
|
| status: 'success',
|
| result: result
|
| });
|
| results.summary.success++;
|
| } else {
|
| throw new Error(`Unsupported file type: ${fileExtension}`);
|
| }
|
|
|
| } catch (error) {
|
| console.error(` Error processing ${filePath}:`, error.message);
|
| results.errors.push({
|
| file: path.basename(filePath),
|
| error: error.message
|
| });
|
| results.summary.failed++;
|
| }
|
| }
|
|
|
| console.log(` Drag & Drop processing completed: ${results.summary.success} success, ${results.summary.failed} failed`);
|
| return results;
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async function processSQLFile(filePath, dbConfig) {
|
| const sqlContent = fs.readFileSync(filePath, 'utf8');
|
|
|
| if (!sqlContent.trim()) {
|
| throw new Error('SQL file is empty');
|
| }
|
|
|
| const client = new Client(dbConfig);
|
|
|
| try {
|
| await client.connect();
|
| console.log(` Executing SQL from: ${path.basename(filePath)}`);
|
|
|
|
|
| const statements = sqlContent
|
| .split(';')
|
| .map(s => s.trim())
|
| .filter(s => s.length > 0);
|
|
|
| const results = [];
|
|
|
| for (const statement of statements) {
|
| const result = await client.query(statement);
|
| results.push({
|
| command: statement.substring(0, 50) + '...',
|
| rowsAffected: result.rowCount || 0
|
| });
|
| }
|
|
|
| return {
|
| statements: results.length,
|
| totalRows: results.reduce((sum, r) => sum + r.rowsAffected, 0)
|
| };
|
|
|
| } finally {
|
| await client.end();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async function processJSONFile(filePath, dbConfig) {
|
| const jsonContent = fs.readFileSync(filePath, 'utf8');
|
| const data = JSON.parse(jsonContent);
|
|
|
| const fileName = path.basename(filePath, '.json');
|
|
|
|
|
| if (fileName.includes('data') || fileName === 'plugins' || fileName === 'users') {
|
| return await insertJSONData(data, dbConfig, fileName);
|
| }
|
|
|
|
|
| return {
|
| type: 'config',
|
| keys: Object.keys(data),
|
| message: 'JSON configuration loaded'
|
| };
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
|
|
| async function insertJSONData(data, dbConfig, tableName = null) {
|
| const client = new Client(dbConfig);
|
|
|
| try {
|
| await client.connect();
|
|
|
| if (Array.isArray(data)) {
|
|
|
| let insertCount = 0;
|
|
|
| for (const item of data) {
|
| if (typeof item === 'object' && item !== null) {
|
| const table = tableName || inferTableName(item);
|
|
|
|
|
| const processedItem = { ...item };
|
| if (Array.isArray(processedItem.features)) {
|
| processedItem.features = JSON.stringify(processedItem.features);
|
| }
|
| if (Array.isArray(processedItem.tags)) {
|
| processedItem.tags = JSON.stringify(processedItem.tags);
|
| }
|
|
|
| const columns = Object.keys(processedItem);
|
| const values = Object.values(processedItem);
|
| const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
|
|
|
| const insertSQL = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders}) ON CONFLICT (id) DO UPDATE SET ${columns.filter(c => c !== 'id').map(c => `${c} = EXCLUDED.${c}`).join(', ')}`;
|
|
|
| try {
|
| const result = await client.query(insertSQL, values);
|
| insertCount++;
|
| } catch (err) {
|
| console.warn(`Warning: Could not insert into ${table}:`, err.message);
|
| }
|
| }
|
| }
|
|
|
| return {
|
| type: 'data_insert',
|
| records: data.length,
|
| inserted: insertCount
|
| };
|
| } else if (typeof data === 'object') {
|
|
|
| const results = {};
|
|
|
| for (const [key, value] of Object.entries(data)) {
|
| if (Array.isArray(value)) {
|
| results[key] = await insertJSONData(value, { client }, key);
|
| }
|
| }
|
|
|
| return {
|
| type: 'multi_table_insert',
|
| tables: results
|
| };
|
| }
|
|
|
| return {
|
| type: 'unknown',
|
| message: 'JSON structure not recognized'
|
| };
|
|
|
| } finally {
|
| await client.end();
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| function inferTableName(item) {
|
| const keys = Object.keys(item);
|
|
|
|
|
| if (keys.includes('user_id') || keys.includes('username')) return 'users';
|
| if (keys.includes('plugin_id') || keys.includes('plugin_name')) return 'plugins';
|
| if (keys.includes('product_id') || keys.includes('product_name')) return 'products';
|
| if (keys.includes('category_id') || keys.includes('category_name')) return 'categories';
|
| if (keys.includes('order_id') || keys.includes('order_status')) return 'orders';
|
|
|
| return 'data_import';
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async function dumpDatabaseToSQL(dbConfig, tableName = null) {
|
| console.log(' Dumping database to SQL files...');
|
| console.log(` ${PLUGIN_INFO.name} ${PLUGIN_INFO.version}`);
|
| console.log(` ${PLUGIN_INFO.author}`);
|
|
|
| const client = new Client(dbConfig);
|
|
|
| try {
|
| await client.connect();
|
| console.log(` Connected to database for dumping...`);
|
|
|
| if (tableName) {
|
|
|
| return {
|
| success: false,
|
| error: 'Table dump functionality not available'
|
| };
|
| } else {
|
|
|
| return {
|
| success: false,
|
| error: 'SQL dump functionality not available'
|
| };
|
| }
|
|
|
| } catch (error) {
|
| console.error(' Database dump failed:', error.message);
|
| throw error;
|
| } finally {
|
| await client.end();
|
| console.log(' Disconnected from database.');
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| async function runPlugin(config = null) {
|
| console.log(' Running Chahua Web Store Plugin directly...');
|
| console.log(` ${PLUGIN_INFO.name} ${PLUGIN_INFO.version}`);
|
| console.log(` ${PLUGIN_INFO.author}`);
|
|
|
| try {
|
|
|
| if (!config) {
|
| config = {
|
| dbConfig: {
|
| host: 'localhost',
|
| port: 5432,
|
| database: 'postgres',
|
| user: 'postgres',
|
| password: 'password'
|
| },
|
| targetDatabase: 'chahua_web_store'
|
| };
|
| }
|
|
|
|
|
| await createDatabase(config.dbConfig, config.targetDatabase);
|
|
|
|
|
| const result = await setupDatabaseStructure(config);
|
|
|
| console.log(' Plugin execution completed successfully!');
|
|
|
| return {
|
| ...result,
|
| pluginInfo: PLUGIN_INFO,
|
| timestamp: new Date().toISOString()
|
| };
|
|
|
| } catch (error) {
|
| console.error(' Plugin execution failed:', error.message);
|
| throw error;
|
| }
|
| }
|
| async function createDatabase(dbConfig, targetDatabase) {
|
|
|
| const maintenanceClient = new Client({
|
| ...dbConfig,
|
| database: 'template1'
|
| });
|
|
|
| try {
|
| await maintenanceClient.connect();
|
| console.log(' Connected to PostgreSQL server for maintenance...');
|
|
|
|
|
| const checkDbResult = await maintenanceClient.query('SELECT 1 FROM pg_database WHERE datname = $1', [targetDatabase]);
|
|
|
| if (checkDbResult.rows.length > 0) {
|
| console.log(` Terminating existing connections to "${targetDatabase}"...`);
|
|
|
| await maintenanceClient.query(`
|
| SELECT pg_terminate_backend(pid) FROM pg_stat_activity
|
| WHERE datname = $1 AND pid <> pg_backend_pid()`, [targetDatabase]);
|
|
|
| console.log(` Dropping old database "${targetDatabase}"...`);
|
|
|
| await maintenanceClient.query(`DROP DATABASE "${targetDatabase}"`);
|
| }
|
|
|
|
|
| console.log(` Creating new database "${targetDatabase}"...`);
|
|
|
|
|
| const os = require('os');
|
| const isWindows = os.platform() === 'win32';
|
|
|
| let createDbQuery;
|
| if (isWindows) {
|
|
|
| console.log(' Detected Windows - checking available locales...');
|
|
|
| try {
|
|
|
| const localesResult = await maintenanceClient.query(`
|
| SELECT datcollate, datctype FROM pg_database WHERE datname = 'template1'
|
| `);
|
|
|
| const templateLocale = localesResult.rows[0];
|
| console.log(` Template locale: ${templateLocale.datcollate} / ${templateLocale.datctype}`);
|
|
|
|
|
| if (templateLocale.datcollate && templateLocale.datctype) {
|
| createDbQuery = `
|
| CREATE DATABASE "${targetDatabase}"
|
| WITH ENCODING 'UTF8'
|
| LC_COLLATE '${templateLocale.datcollate}'
|
| LC_CTYPE '${templateLocale.datctype}'
|
| TEMPLATE template0
|
| `;
|
| } else {
|
|
|
| createDbQuery = `
|
| CREATE DATABASE "${targetDatabase}"
|
| WITH ENCODING 'UTF8'
|
| TEMPLATE template0
|
| `;
|
| }
|
| } catch (localeError) {
|
| console.log(' Could not detect locale, using minimal setup');
|
| createDbQuery = `
|
| CREATE DATABASE "${targetDatabase}"
|
| WITH ENCODING 'UTF8'
|
| TEMPLATE template0
|
| `;
|
| }
|
| } else {
|
|
|
| console.log(' Detected Unix/Linux - using C.UTF-8 locale');
|
| createDbQuery = `
|
| CREATE DATABASE "${targetDatabase}"
|
| WITH ENCODING 'UTF8'
|
| LC_COLLATE 'C.UTF-8'
|
| LC_CTYPE 'C.UTF-8'
|
| TEMPLATE template0
|
| `;
|
| }
|
|
|
| console.log(' Executing database creation query...');
|
| await maintenanceClient.query(createDbQuery);
|
| console.log(` Database "${targetDatabase}" has been successfully created.`);
|
|
|
| } catch (err) {
|
| console.error(' Error during database creation:', err.message);
|
| throw err;
|
| } finally {
|
|
|
| await maintenanceClient.end();
|
| console.log(' Disconnected from maintenance database.');
|
| }
|
| }
|
|
|
| |
| |
|
|
| async function setupDatabaseStructure(config = null) {
|
| const dbConfig = config?.dbConfig;
|
| const targetDatabase = config?.targetDatabase;
|
|
|
|
|
| const appClient = new Client({
|
| ...dbConfig,
|
| database: targetDatabase
|
| });
|
|
|
| try {
|
| await appClient.connect();
|
| console.log(` Connected to target database "${targetDatabase}" to build structure...`);
|
|
|
|
|
| console.log('\n Starting structure setup...');
|
| await enumsModule.createEnums(appClient);
|
| await coreTablesModule.createCoreTables(appClient);
|
| await paymentTablesModule.createPaymentTables(appClient);
|
| await forumTablesModule.createForumTables(appClient);
|
| await pluginSubmissionTablesModule.createPluginSubmissionTables(appClient);
|
| await dashboardTablesModule.createDashboardTables(appClient);
|
| await bankTransferTablesModule.createBankTransferTables(appClient);
|
| await functionsTriggersModule.createFunctionsAndTriggers(appClient);
|
|
|
|
|
| const tablesResult = await appClient.query("SELECT tablename FROM pg_tables WHERE schemaname = 'public'");
|
| const existingTables = tablesResult.rows.map(row => row.tablename);
|
|
|
| await functionsTriggersModule.createTriggers(appClient, existingTables);
|
| await indexesViewsModule.createIndexes(appClient, existingTables);
|
| await indexesViewsModule.createViews(appClient);
|
|
|
| console.log(' Database setup completed successfully!');
|
|
|
| return {
|
| success: true,
|
| summary: {
|
| totalTables: existingTables.length,
|
| pluginName: 'Chahua Web Store'
|
| }
|
| };
|
|
|
| } catch (err) {
|
| console.error(' Error setting up database structure:', err.message);
|
| throw err;
|
| } finally {
|
| await appClient.end();
|
| console.log(` Disconnected from "${targetDatabase}".`);
|
| }
|
| }
|
|
|
| |
| |
| |
| |
|
|
| async function importFromFile(filePath, config = {}) {
|
| const cfg = {
|
| host: config.host || process.env.DB_HOST || '127.0.0.1',
|
| port: config.port || process.env.DB_PORT || 5432,
|
| user: config.user || process.env.DB_USER || 'postgres',
|
| password: config.password || process.env.DB_PASS || '',
|
| database: config.database || process.env.DB_NAME || 'chahua_web_store',
|
| };
|
|
|
| console.log(' Importing database from:', filePath);
|
| await restoreDb(cfg, filePath);
|
| console.log(' Database import completed');
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| async function exportToFile(outFile, format = 'custom', config = {}) {
|
| const cfg = {
|
| host: config.host || process.env.DB_HOST || '127.0.0.1',
|
| port: config.port || process.env.DB_PORT || 5432,
|
| user: config.user || process.env.DB_USER || 'postgres',
|
| password: config.password || process.env.DB_PASS || '',
|
| database: config.database || process.env.DB_NAME || 'chahua_web_store',
|
| };
|
|
|
| console.log(' Exporting database to:', outFile);
|
| await dumpDb(cfg, outFile, { format });
|
| console.log(' Database export completed');
|
| }
|
|
|
| module.exports = {
|
| PLUGIN_INFO,
|
| createDatabase,
|
| setupDatabaseStructure,
|
| handleDroppedFiles,
|
| processSQLFile,
|
| processJSONFile,
|
| dumpDatabaseToSQL,
|
| runPlugin,
|
| importFromFile,
|
| exportToFile
|
| }; |