@wener/miniquery
Version:
SQL Where like **safe** filter expression for ORM.
285 lines (284 loc) • 10.4 kB
JavaScript
function _array_like_to_array(arr, len) {
if (len == null || len > arr.length)
len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++)
arr2[i] = arr[i];
return arr2;
}
function _array_with_holes(arr) {
if (Array.isArray(arr))
return arr;
}
function _array_without_holes(arr) {
if (Array.isArray(arr))
return _array_like_to_array(arr);
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
}
else {
obj[key] = value;
}
return obj;
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null)
return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null)
return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i)
break;
}
}
catch (err) {
_d = true;
_e = err;
}
finally {
try {
if (!_n && _i["return"] != null)
_i["return"]();
}
finally {
if (_d)
throw _e;
}
}
return _arr;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
}
else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _type_of(obj) {
"@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o)
return;
if (typeof o === "string")
return _array_like_to_array(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor)
n = o.constructor.name;
if (n === "Map" || n === "Set")
return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
return _array_like_to_array(o, minLen);
}
import { DisableKey, IgnoreKeyPrefix } from "./const.js";
export function formatDocumentQuery(o) {
if (!o || Object.keys(o).length === 0) {
return undefined;
}
var conditions = _format(o, {
path: [],
out: []
});
if (conditions.length === 0) {
return undefined;
}
return conditions.join(" AND ");
}
function formatValue(v) {
if (Array.isArray(v)) {
return "(".concat(v.map(formatValue).join(", "), ")");
}
return JSON.stringify(v);
}
function _format(o, ctx) {
if (o === undefined || o === null || (typeof o === "undefined" ? "undefined" : _type_of(o)) === "object" && o[DisableKey] === true) {
return ctx.out;
}
if ((typeof o === "undefined" ? "undefined" : _type_of(o)) !== "object" || Array.isArray(o)) {
throw new Error("Invalid query segment: ".concat(JSON.stringify(o), " at path ").concat(ctx.path.join(".")));
}
var path = ctx.path, out = ctx.out;
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
var _loop = function () {
var _step_value = _sliced_to_array(_step.value, 2), k = _step_value[0], v = _step_value[1];
if (v === undefined || k.startsWith(IgnoreKeyPrefix)) {
return "continue";
}
if (k.startsWith("$")) {
var field = path.join(".");
switch (k) {
case "$or":
case "$and":
case "$nor":
{
var queries = Array.isArray(v) ? v : Object.values(v || {});
var all = queries.map(function (vv) {
return formatDocumentQuery(vv);
}).filter(Boolean);
if (all.length > 0) {
var op = k === "$and" ? "AND" : "OR";
var joined = all.length > 1 ? "(".concat(all.join(" ".concat(op, " ")), ")") : all[0];
out.push(k === "$nor" ? "NOT (".concat(joined, ")") : joined);
}
break;
}
case "$not":
{
var subQuery = formatDocumentQuery(v);
if (subQuery) {
out.push("NOT (".concat(subQuery, ")"));
}
break;
}
case "$exists":
out.push("".concat(field, " IS ").concat(v ? "NOT NULL" : "NULL"));
break;
case "$size":
out.push("LENGTH(".concat(field, ") = ").concat(v));
break;
case "$all":
if (!Array.isArray(v))
throw new Error("$all requires an array");
v.forEach(function (item) {
return out.push("CONTAINS(".concat(field, ", ").concat(formatValue(item), ")"));
});
break;
case "$elemMatch":
{
var subQuery1 = formatDocumentQuery(v);
if (subQuery1) {
out.push("ELEM_MATCH(".concat(field, ", '").concat(subQuery1.replace(/'/g, "''"), "')"));
}
break;
}
default:
{
var op1 = InfixOperator[k.slice(1)];
if (op1 && field) {
out.push("".concat(field, " ").concat(op1, " ").concat(formatValue(v)));
}
else {
throw new Error("Unsupported operator: ".concat(k, " at path ").concat(field));
}
}
}
return "continue";
}
var segments = k.split(".");
var currentPath = _to_consumable_array(path).concat(_to_consumable_array(segments));
var field1 = currentPath.join(".");
if (v === null) {
out.push("".concat(field1, " IS NULL"));
}
else if (Array.isArray(v)) {
out.push("".concat(field1, " IN ").concat(formatValue(v)));
}
else if ((typeof v === "undefined" ? "undefined" : _type_of(v)) === "object") {
_format(v, _object_spread_props(_object_spread({}, ctx), {
path: currentPath
}));
}
else {
out.push("".concat(field1, " = ").concat(formatValue(v)));
}
};
for (var _iterator = Object.entries(o).sort(function (a, b) {
return a[0].localeCompare(b[0]);
})[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)
_loop();
}
catch (err) {
_didIteratorError = true;
_iteratorError = err;
}
finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
}
finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return out;
}
var InfixOperator = {
eq: "=",
ne: "!=",
gt: ">",
gte: ">=",
lt: "<",
lte: "<=",
in: "IN",
nin: "NOT IN",
like: "LIKE",
nlike: "NOT LIKE",
regex: "RLIKE",
type: "TYPE",
expr: "EXPR"
};