rhombic
Version:
SQL parsing, lineage extraction and manipulation
37 lines • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixOrderItem = void 0;
const ProjectionItemsVisitor_1 = require("../visitors/ProjectionItemsVisitor");
const replaceText_1 = require("./replaceText");
/**
* Fix order by item after a projectionItem refactor. Indeed if the order by rely on an alias,
* and the alias is not in the query anymore, the query will be unvalid.
*
* @param cst
* @param prevProjectionItem
* @param index
*/
const fixOrderItem = (parsedSql, prevProjectionItem, index) => {
const visitor = new ProjectionItemsVisitor_1.ProjectionItemsVisitor();
visitor.visit(parsedSql.cst);
const projectionItems = visitor.output;
// We don't need to deal with asterisk expansion here,
// if it was needed, we are already after the refactor.
const nextProjectionItem = projectionItems[index];
// Same alias as before
if (prevProjectionItem.alias && prevProjectionItem.alias === nextProjectionItem.alias) {
return parsedSql.toString();
}
// Search old references in `sort` statement
const orderItemsToRename = visitor.sort.filter(i => i.expression === prevProjectionItem.expression || i.expression === prevProjectionItem.alias);
if (orderItemsToRename.length > 1) {
// Why this is not supported?
// Because `replaceText` can be applyed only one time without recompute everything
throw new Error("Renaming multiple order items is not supported");
}
let nextSql = parsedSql.toString();
orderItemsToRename.forEach(i => (nextSql = replaceText_1.replaceText(nextSql, nextProjectionItem.alias || nextProjectionItem.expression, i.expressionRange)));
return nextSql;
};
exports.fixOrderItem = fixOrderItem;
//# sourceMappingURL=fixOrderItem.js.map