UNPKG

rawsql-ts

Version:

High-performance SQL parser and AST analyzer written in TypeScript. Provides fast parsing and advanced transformation capabilities.

72 lines 3.03 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dedupeWhereTopLevelAndConditions = exports.dedupeTopLevelAndConditions = exports.dedupeTopLevelAndConditionsWithMetadata = void 0; const Clause_1 = require("../models/Clause"); const ValueComponent_1 = require("../models/ValueComponent"); const SqlComponentFormatter_1 = require("./SqlComponentFormatter"); // API output shape review: this internal helper keeps optimizer result sql/query shape unchanged; // formatSqlComponent is used only as a caller-configurable canonical key for exact duplicate detection. const unwrapParens = (expression) => { let candidate = expression; while (candidate instanceof ValueComponent_1.ParenExpression) { candidate = candidate.expression; } return candidate; }; const isAndExpression = (expression) => { const candidate = unwrapParens(expression); return candidate instanceof ValueComponent_1.BinaryExpression && candidate.operator.value.trim().toLowerCase() === "and"; }; const collectTopLevelAndTerms = (expression) => { const candidate = unwrapParens(expression); if (!isAndExpression(candidate)) { return [expression]; } return [ ...collectTopLevelAndTerms(candidate.left), ...collectTopLevelAndTerms(candidate.right) ]; }; const dedupeTopLevelAndConditionsWithMetadata = (expression, options) => { const terms = collectTopLevelAndTerms(expression); if (terms.length < 2) { return { expression, removedConditionSql: [] }; } const seen = new Set(); const uniqueTerms = []; const removedConditionSql = []; for (const term of terms) { const key = (0, SqlComponentFormatter_1.formatSqlComponent)(unwrapParens(term), options); if (seen.has(key)) { removedConditionSql.push(key); continue; } seen.add(key); uniqueTerms.push(term); } if (uniqueTerms.length === terms.length) { return { expression, removedConditionSql: [] }; } let rebuilt = uniqueTerms[0]; for (let index = 1; index < uniqueTerms.length; index += 1) { rebuilt = new ValueComponent_1.BinaryExpression(rebuilt, "and", uniqueTerms[index]); } return { expression: rebuilt, removedConditionSql }; }; exports.dedupeTopLevelAndConditionsWithMetadata = dedupeTopLevelAndConditionsWithMetadata; const dedupeTopLevelAndConditions = (expression, options) => { return (0, exports.dedupeTopLevelAndConditionsWithMetadata)(expression, options).expression; }; exports.dedupeTopLevelAndConditions = dedupeTopLevelAndConditions; const dedupeWhereTopLevelAndConditions = (query, options) => { if (!query.whereClause) { return; } query.whereClause = new Clause_1.WhereClause((0, exports.dedupeTopLevelAndConditions)(query.whereClause.condition, options)); }; exports.dedupeWhereTopLevelAndConditions = dedupeWhereTopLevelAndConditions; //# sourceMappingURL=TopLevelAndConditionDeduper.js.map