| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
|
|
|
|
| const { spawn } = require('child_process');
|
| const { existsSync, mkdirSync } = require('fs');
|
| const { dirname, resolve, sep } = require('path');
|
|
|
| |
| |
| |
| |
| |
|
|
| function log(...a){ console.log('[db-tools]', ...a); }
|
|
|
| |
| |
| |
| |
| |
|
|
| function err(...a){ console.error('[db-tools]', ...a); }
|
|
|
| |
| |
| |
| |
| |
|
|
| const isWin = () => process.platform === 'win32';
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| 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); }
|
| }
|
|
|
| |
| |
| |
| |
| |
|
|
| 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;
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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`);
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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}`)));
|
| });
|
| }
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| 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{
|
|
|
| const style = (options.style || 'inserts').toLowerCase();
|
| const styleArgs = [];
|
| if(style === 'inserts') styleArgs.push('--inserts');
|
| else if(style === 'column-inserts') styleArgs.push('--column-inserts');
|
|
|
| if(options.rowsPerInsert && Number(options.rowsPerInsert)>0) {
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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();
|
| const style = argv.style || 'inserts';
|
| 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 };
|
|
|