rawsql-ts
Version:
[beta]High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.
40 lines • 2.15 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqlFormatter = exports.VALID_PRESETS = void 0;
const SqlPrintTokenParser_1 = require("../parsers/SqlPrintTokenParser");
const SqlPrinter_1 = require("./SqlPrinter");
// Define valid preset names as a union type
exports.VALID_PRESETS = ['mysql', 'postgres', 'sqlserver', 'sqlite'];
/**
* SqlFormatter class combines parsing and printing of SQL queries into a single interface.
*/
class SqlFormatter {
constructor(options = {}) {
var _a, _b, _c;
const presetConfig = options.preset ? SqlPrintTokenParser_1.PRESETS[options.preset] : undefined;
if (options.preset && !presetConfig) {
throw new Error(`Invalid preset: ${options.preset}`); // Throw error for invalid preset
}
const parserOptions = {
...presetConfig, // Apply preset configuration
identifierEscape: (_a = options.identifierEscape) !== null && _a !== void 0 ? _a : presetConfig === null || presetConfig === void 0 ? void 0 : presetConfig.identifierEscape,
parameterSymbol: (_b = options.parameterSymbol) !== null && _b !== void 0 ? _b : presetConfig === null || presetConfig === void 0 ? void 0 : presetConfig.parameterSymbol,
parameterStyle: (_c = options.parameterStyle) !== null && _c !== void 0 ? _c : presetConfig === null || presetConfig === void 0 ? void 0 : presetConfig.parameterStyle,
};
this.parser = new SqlPrintTokenParser_1.SqlPrintTokenParser(parserOptions);
this.printer = new SqlPrinter_1.SqlPrinter(options);
}
/**
* Formats a SQL query string with the given parameters.
* @param sqlText The SQL query string to format.
* @param parameters A dictionary of parameters to replace in the query.
* @returns An object containing the formatted SQL string and the parameters.
*/
format(sql) {
const { token, params } = this.parser.parse(sql);
const formattedSql = this.printer.print(token);
return { formattedSql, params };
}
}
exports.SqlFormatter = SqlFormatter;
//# sourceMappingURL=SqlFormatter.js.map
;