pg-deparser
Version:
PostgreSQL AST Deparser
117 lines (92 loc) • 2.91 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transform = exports.cleanTreeWithStmt = exports.cleanTree = exports.cleanLines = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
/* eslint-disable no-restricted-syntax */
var cleanLines = function cleanLines(sql) {
return sql.split('\n').map(function (l) {
return l.trim();
}).filter(function (a) {
return a;
}).join('\n');
};
exports.cleanLines = cleanLines;
var transform = function transform(obj, props) {
var copy = null; // Handle the 3 simple types, and null or undefined
if (obj == null || (0, _typeof2["default"])(obj) !== 'object') {
return obj;
} // Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
} // Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = transform(obj[i], props);
}
return copy;
} // Handle Object
if (obj instanceof Object || (0, _typeof2["default"])(obj) === 'object') {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
if (props.hasOwnProperty(attr)) {
if (typeof props[attr] === 'function') {
copy[attr] = props[attr](obj[attr]);
} else if (props[attr].hasOwnProperty(obj[attr])) {
copy[attr] = props[attr][obj[attr]];
} else {
copy[attr] = transform(obj[attr], props);
}
} else {
copy[attr] = transform(obj[attr], props);
}
} else {
copy[attr] = transform(obj[attr], props);
}
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
};
exports.transform = transform;
var noop = function noop() {
return undefined;
};
var cleanTree = function cleanTree(tree) {
return transform(tree, {
stmt_len: noop,
stmt_location: noop,
location: noop,
DefElem: function DefElem(obj) {
if (obj.defname === 'as') {
if (Array.isArray(obj.arg) && obj.arg.length) {
// function
obj.arg[0].String.str = obj.arg[0].String.str.trim();
} else if (obj.arg.List && obj.arg.List.items) {
// function
obj.arg.List.items[0].String.str = obj.arg.List.items[0].String.str.trim();
} else {
// do stmt
obj.arg.String.str = obj.arg.String.str.trim();
}
return cleanTree(obj);
} else {
return cleanTree(obj);
}
}
});
};
exports.cleanTree = cleanTree;
var cleanTreeWithStmt = function cleanTreeWithStmt(tree) {
return transform(tree, {
stmt_location: noop,
location: noop
});
};
exports.cleanTreeWithStmt = cleanTreeWithStmt;