UNPKG

@pgsql/cli

Version:

Unified CLI for PostgreSQL AST parsing, deparsing, and code generation

67 lines (66 loc) 2.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.deparseCommand = deparseCommand; const fs_1 = require("fs"); const path_1 = require("path"); const pgsql_deparser_1 = require("pgsql-deparser"); const chalk_1 = __importDefault(require("chalk")); const help_1 = require("../utils/help"); async function deparseCommand(argv) { if (argv.help) { (0, help_1.showHelp)('deparse'); process.exit(0); } try { let ast; // Read AST from file or stdin if (argv.input || argv.i) { const inputFile = argv.input || argv.i; const filePath = inputFile.startsWith('/') ? inputFile : (0, path_1.resolve)((0, path_1.join)(process.cwd(), inputFile)); const content = (0, fs_1.readFileSync)(filePath, 'utf-8'); ast = JSON.parse(content); } else if (!process.stdin.isTTY) { // Read from stdin const chunks = []; for await (const chunk of process.stdin) { chunks.push(chunk); } const content = Buffer.concat(chunks).toString(); ast = JSON.parse(content); } else { console.error(chalk_1.default.red('Error: No input provided. Use -i <file> or pipe input via stdin')); (0, help_1.showHelp)('deparse'); process.exit(1); } // Deparse AST to SQL const sql = await (0, pgsql_deparser_1.deparse)(ast); // Write output if (argv.output || argv.o) { const outputFile = argv.output || argv.o; (0, fs_1.writeFileSync)(outputFile, sql); console.log(chalk_1.default.green(`✓ SQL written to ${outputFile}`)); } else { process.stdout.write(sql); } } catch (error) { if (error.code === 'ENOENT') { console.error(chalk_1.default.red(`Error: File not found: ${argv.input || argv.i}`)); } else if (error instanceof SyntaxError) { console.error(chalk_1.default.red('Error: Invalid JSON input')); } else { console.error(chalk_1.default.red('Deparse error:'), error.message || error); } process.exit(1); } }