/** * @fileoverview Chahua Database Manager - Database Tools Module * @description เครื่องมือสำหรับการจัดการฐานข้อมูล PostgreSQL ผ่าง command line * คุณสมบัติ: Database backup, restore, migration, PostgreSQL client detection * @author ทีมพัฒนา Chahua * @version 1.0.0 * @since 2024-01-01 * @calledBy Database Manager application, backup/restore workflows * @dependencies * - child_process: Process spawning for PostgreSQL tools * - fs: File system operations * - path: Path manipulation utilities * @features * - PostgreSQL client detection (cross-platform) * - Database backup using pg_dump * - Database restore using psql * - Migration script execution * - Environment variable configuration * @security * - Command injection protection * - Environment variable validation * - Path traversal prevention * @example * // Backup database * await backup('dbname', 'backup.sql', { * host: 'localhost', * port: 5432, * username: 'user' * }); * * // Restore database * await restore('dbname', 'backup.sql', connectionConfig); */ // tools/db-tools.js // Node 18+ แนะนำ const { spawn } = require('child_process'); const { existsSync, mkdirSync } = require('fs'); const { dirname, resolve, sep } = require('path'); /** * ฟังก์ชันสำหรับการ log ข้อมูล * @function log * @param {...any} a - ข้อมูลที่ต้องการ log * @description แสดงข้อมูล log พร้อม prefix [db-tools] */ function log(...a){ console.log('[db-tools]', ...a); } /** * ฟังก์ชันสำหรับการ log ข้อผิดพลาด * @function err * @param {...any} a - ข้อมูลข้อผิดพลาดที่ต้องการ log * @description แสดงข้อผิดพลาดพร้อม prefix [db-tools] */ function err(...a){ console.error('[db-tools]', ...a); } /** * ตรวจสอบว่าระบบปฏิบัติการเป็น Windows หรือไม่ * @function isWin * @returns {boolean} true หาก OS เป็น Windows * @description ใช้สำหรับการตรวจสอบ platform และปรับ command ให้เหมาะสม */ const isWin = () => process.platform === 'win32'; /** * ค้นหา executable ในระบบ * @async * @function which * @param {string} cmd - ชื่อคำสั่งที่ต้องการค้นหา * @returns {Promise} path ของ executable หรือ null หากไม่พบ * @description ใช้คำสั่ง 'where' (Windows) หรือ 'which' (Unix) เพื่อค้นหา executable */ function which(cmd){ try{ const p = spawn(isWin()?'where':'which',[cmd],{stdio:['ignore','pipe','pipe']}); return new Promise(res=>{ let out=''; p.stdout.on('data',d=>out+=d.toString()); p.on('close',c=>res(c===0?out.split(/\r?\n/).find(Boolean)?.trim():null)); }); }catch{ return Promise.resolve(null); } } /** * รายการไดเรกทอรีทั่วไปของ PostgreSQL * @function commonPgDirs * @returns {string[]} รายการ path ที่อาจมี PostgreSQL binaries * @description สร้างรายการ path ที่ PostgreSQL มักจะติดตั้งอยู่ตาม OS */ function commonPgDirs(){ const dirs=[]; if(isWin()){ for(let v=17; v>=9; v--){ dirs.push(`C:\\Program Files\\PostgreSQL\\${v}\\bin`, `C:\\Program Files (x86)\\PostgreSQL\\${v}\\bin`); } }else{ dirs.push('/usr/bin','/usr/local/bin','/usr/pgsql-16/bin','/usr/pgsql-15/bin','/opt/homebrew/opt/libpq/bin','/usr/local/opt/libpq/bin'); } if(process.env.PGBIN) dirs.unshift(process.env.PGBIN); return dirs; } /** * ค้นหา PostgreSQL executable * @async * @function resolveExe * @param {string} name - ชื่อ executable (เช่น pg_dump, psql) * @returns {Promise} path ของ executable * @throws {Error} หากไม่พบ executable * @description ค้นหา PostgreSQL executable ในระบบโดยเรียงลำดับความสำคัญ */ async function resolveExe(name){ const fromPath = await which(name); if(fromPath) return fromPath; for(const d of commonPgDirs()){ const c = isWin()? `${d}\\${name}.exe` : `${d}/${name}`; if(existsSync(c)) return c; } throw new Error(`ไม่พบคำสั่ง ${name}. ติดตั้ง PostgreSQL client หรือกำหนด PGBIN ให้ชี้ไปที่โฟลเดอร์ bin`); } /** * เรียกใช้เครื่องมือ PostgreSQL * @function spawnTool * @param {string} bin - path ของ executable * @param {string[]} args - arguments ที่ส่งให้ executable * @param {Object} [envExtra={}] - environment variables เพิ่มเติม * @returns {Promise} Promise ที่ resolve เมื่อคำสั่งเสร็จสิ้น * @description เรียกใช้เครื่องมือ PostgreSQL พร้อมการจัดการ environment และ encoding */ function spawnTool(bin, args, envExtra={}){ log('run:', bin, args.join(' ')); return new Promise((ok, bad)=>{ const child = spawn(bin, args, { stdio: 'inherit', env: { ...process.env, ...envExtra, PGCLIENTENCODING: 'UTF8' } }); child.on('exit', code => code===0 ? ok() : bad(new Error(`${bin} exited with code ${code}`))); }); } /** * Dump DB เป็น .sql ที่อ่านได้ (ดีฟอลต์) หรือ .dump (custom) * options: * - format: 'sql' | 'custom' (default: 'sql') * - style: 'inserts' | 'column-inserts' | 'copy' (sql เท่านั้น, default: 'inserts') * - clean: boolean ใส่ DROP ก่อนสร้าง (default: false) * - schemaOnly / dataOnly: boolean * - rowsPerInsert: number (ใช้กับ --inserts ใน pg 12+) */ async function dumpDb(cfg, outFile, options={}){ const pgDump = await resolveExe('pg_dump'); const out = resolve(outFile); const outDir = dirname(out); if(!existsSync(outDir)) mkdirSync(outDir, { recursive:true }); const format = (options.format || 'sql').toLowerCase(); const base = [ '-h', cfg.host || '127.0.0.1', '-p', String(cfg.port || 5432), '-U', cfg.user || 'postgres', '--no-owner','--no-privileges' ]; if(options.schemaOnly) base.push('--schema-only'); if(options.dataOnly) base.push('--data-only'); if(options.clean) base.push('--clean','--if-exists'); let args; if(format === 'custom'){ args = ['-Fc','-f', out, ...base, cfg.database]; }else{ // .sql (plain) const style = (options.style || 'inserts').toLowerCase(); const styleArgs = []; if(style === 'inserts') styleArgs.push('--inserts'); else if(style === 'column-inserts') styleArgs.push('--column-inserts'); // 'copy' = ไม่ใส่อะไร ปล่อยให้เป็น COPY เร็ว/เล็กกว่า if(options.rowsPerInsert && Number(options.rowsPerInsert)>0) { // ใช้ได้กับ --inserts styleArgs.push(`--rows-per-insert=${Number(options.rowsPerInsert)}`); } args = [...styleArgs, '-f', out, ...base, cfg.database]; } await spawnTool(pgDump, args, { PGPASSWORD: cfg.password || '' }); log('dump เสร็จ:', out); } /** Restore จาก .sql (psql) หรือ .dump (pg_restore) */ async function restoreDb(cfg, file){ const f = resolve(file).toLowerCase(); if(f.endsWith('.dump') || f.endsWith('.backup')){ const pgRestore = await resolveExe('pg_restore'); const args = [ '-h', cfg.host || '127.0.0.1', '-p', String(cfg.port || 5432), '-U', cfg.user || 'postgres', '--no-owner','--no-privileges','--clean','--if-exists', '-d', cfg.database, file ]; await spawnTool(pgRestore, args, { PGPASSWORD: cfg.password || '' }); }else{ const psql = await resolveExe('psql'); const args = [ '-h', cfg.host || '127.0.0.1', '-p', String(cfg.port || 5432), '-U', cfg.user || 'postgres', '-v','ON_ERROR_STOP=1', '-d', cfg.database, '-f', file ]; await spawnTool(psql, args, { PGPASSWORD: cfg.password || '' }); } log('restore เสร็จ:', file); } /** CLI: node tools/db-tools.js dump|restore ... */ async function main(){ const argv = require('minimist')(process.argv.slice(2)); const cmd = argv._[0]; const cfg = { host: argv.host || process.env.PGHOST, port: argv.port || process.env.PGPORT, user: argv.user || process.env.PGUSER, password: argv.password || process.env.PGPASSWORD, database: argv.database || process.env.PGDATABASE, }; if(!cfg.database){ err('โปรดระบุ --database หรือเซ็ต PGDATABASE'); process.exit(1); } try{ if(cmd === 'dump'){ const out = argv.out || `backup${sep}${cfg.database}-${Date.now()}.sql`; const format = (argv.format || 'sql').toLowerCase(); // sql | custom const style = argv.style || 'inserts'; // inserts | column-inserts | copy const clean = !!argv.clean; const schemaOnly = !!argv['schema-only']; const dataOnly = !!argv['data-only']; const rowsPerInsert = argv['rows-per-insert'] ? Number(argv['rows-per-insert']) : undefined; await dumpDb(cfg, out, { format, style, clean, schemaOnly, dataOnly, rowsPerInsert }); }else if(cmd === 'restore'){ const file = argv.file || argv.f; if(!file){ err('โปรดระบุ --file สำหรับ restore'); process.exit(1); } await restoreDb(cfg, file); }else{ console.log(` ใช้คำสั่ง: # ดัมพ์เป็น .sql ที่อ่านง่าย (INSERT): node tools/db-tools.js dump --database mydb --out backup/mydb.sql --format sql --style inserts --clean # ดัมพ์เป็น .sql แบบ COPY (เร็วกว่า/ไฟล์เล็กกว่า): node tools/db-tools.js dump --database mydb --out backup/mydb.sql --format sql --style copy # ดัมพ์เป็น .dump (custom): node tools/db-tools.js dump --database mydb --out backup/mydb.dump --format custom # ใส่กลับ: node tools/db-tools.js restore --database mydb --file backup/mydb.sql `.trim()); } }catch(e){ err(e.message); process.exit(1); } } if (require.main === module) main(); module.exports = { dumpDb, restoreDb };