@carbonorm/carbonnode 3.9.4 → 3.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -14,6 +14,7 @@ var C6Constants = {
14
14
  ADDTIME: 'ADDTIME',
15
15
  AS: 'AS',
16
16
  ASC: 'ASC',
17
+ AND: 'AND',
17
18
  BETWEEN: 'BETWEEN',
18
19
  CONCAT: 'CONCAT',
19
20
  CONVERT_TZ: 'CONVERT_TZ',
@@ -87,6 +88,7 @@ var C6Constants = {
87
88
  NOW: 'NOW',
88
89
  NULL: 'NULL',
89
90
  ORDER: 'ORDER',
91
+ OR: 'OR',
90
92
  PAGE: 'PAGE',
91
93
  PAGINATION: 'PAGINATION',
92
94
  RIGHT_OUTER: 'RIGHT_OUTER',
@@ -1292,6 +1294,10 @@ var AggregateBuilder = /** @class */ (function (_super) {
1292
1294
  args.pop();
1293
1295
  }
1294
1296
  var F = String(fn).toUpperCase();
1297
+ var isGeomFromText = F === C6C.ST_GEOMFROMTEXT.toUpperCase();
1298
+ if (args.length === 1 && Array.isArray(args[0])) {
1299
+ args = args[0];
1300
+ }
1295
1301
  // Parameter placeholder helper: [C6C.PARAM, value]
1296
1302
  if (F === C6C.PARAM) {
1297
1303
  if (!params) {
@@ -1321,7 +1327,7 @@ var AggregateBuilder = /** @class */ (function (_super) {
1321
1327
  }
1322
1328
  var identifierPathRegex = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/;
1323
1329
  var argList = args
1324
- .map(function (arg) {
1330
+ .map(function (arg, index) {
1325
1331
  if (Array.isArray(arg))
1326
1332
  return _this.buildAggregateField(arg, params);
1327
1333
  if (typeof arg === 'string') {
@@ -1332,6 +1338,15 @@ var AggregateBuilder = /** @class */ (function (_super) {
1332
1338
  // Treat numeric-looking strings as literals, not identifier paths
1333
1339
  if (isNumericString(arg))
1334
1340
  return arg;
1341
+ if (isGeomFromText && index === 0) {
1342
+ var trimmed = arg.trim();
1343
+ var alreadyQuoted = trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2;
1344
+ if (alreadyQuoted) {
1345
+ return trimmed;
1346
+ }
1347
+ var escaped = arg.replace(/'/g, "''");
1348
+ return "'".concat(escaped, "'");
1349
+ }
1335
1350
  return arg;
1336
1351
  }
1337
1352
  return String(arg);
@@ -1439,24 +1454,43 @@ var ConditionBuilder = /** @class */ (function (_super) {
1439
1454
  var _this = _super !== null && _super.apply(this, arguments) || this;
1440
1455
  _this.aliasMap = {};
1441
1456
  _this.derivedAliases = new Set();
1442
- _this.OPERATORS = new Set([
1443
- C6C.EQUAL, C6C.NOT_EQUAL, C6C.LESS_THAN, C6C.LESS_THAN_OR_EQUAL_TO,
1444
- C6C.GREATER_THAN, C6C.GREATER_THAN_OR_EQUAL_TO,
1445
- C6C.LIKE, C6C.NOT_LIKE,
1446
- C6C.IN, C6C.NOT_IN, 'NOT IN',
1447
- C6C.IS, C6C.IS_NOT,
1448
- C6C.BETWEEN, 'NOT BETWEEN',
1449
- C6C.MATCH_AGAINST,
1450
- C6C.ST_DISTANCE_SPHERE,
1451
- // spatial predicates
1452
- C6C.ST_CONTAINS,
1453
- C6C.ST_INTERSECTS,
1454
- C6C.ST_WITHIN,
1455
- C6C.ST_CROSSES,
1456
- C6C.ST_DISJOINT,
1457
- C6C.ST_EQUALS,
1458
- C6C.ST_OVERLAPS,
1459
- C6C.ST_TOUCHES
1457
+ _this.BOOLEAN_OPERATORS = new Map([
1458
+ [C6C.AND, 'AND'],
1459
+ ['AND', 'AND'],
1460
+ [C6C.OR, 'OR'],
1461
+ ['OR', 'OR'],
1462
+ ]);
1463
+ _this.OPERATOR_ALIASES = new Map([
1464
+ [C6C.EQUAL, C6C.EQUAL],
1465
+ ['=', C6C.EQUAL],
1466
+ [C6C.EQUAL_NULL_SAFE, C6C.EQUAL_NULL_SAFE],
1467
+ ['<=>', C6C.EQUAL_NULL_SAFE],
1468
+ [C6C.NOT_EQUAL, C6C.NOT_EQUAL],
1469
+ ['<>', C6C.NOT_EQUAL],
1470
+ [C6C.LESS_THAN, C6C.LESS_THAN],
1471
+ ['<', C6C.LESS_THAN],
1472
+ [C6C.LESS_THAN_OR_EQUAL_TO, C6C.LESS_THAN_OR_EQUAL_TO],
1473
+ ['<=', C6C.LESS_THAN_OR_EQUAL_TO],
1474
+ [C6C.GREATER_THAN, C6C.GREATER_THAN],
1475
+ ['>', C6C.GREATER_THAN],
1476
+ [C6C.GREATER_THAN_OR_EQUAL_TO, C6C.GREATER_THAN_OR_EQUAL_TO],
1477
+ ['>=', C6C.GREATER_THAN_OR_EQUAL_TO],
1478
+ [C6C.LIKE, C6C.LIKE],
1479
+ ['LIKE', C6C.LIKE],
1480
+ [C6C.NOT_LIKE, 'NOT LIKE'],
1481
+ ['NOT LIKE', 'NOT LIKE'],
1482
+ [C6C.IN, C6C.IN],
1483
+ ['IN', C6C.IN],
1484
+ [C6C.NOT_IN, 'NOT IN'],
1485
+ ['NOT IN', 'NOT IN'],
1486
+ [C6C.IS, C6C.IS],
1487
+ ['IS', C6C.IS],
1488
+ [C6C.IS_NOT, 'IS NOT'],
1489
+ ['IS NOT', 'IS NOT'],
1490
+ [C6C.BETWEEN, C6C.BETWEEN],
1491
+ ['BETWEEN', C6C.BETWEEN],
1492
+ ['NOT BETWEEN', 'NOT BETWEEN'],
1493
+ [C6C.MATCH_AGAINST, C6C.MATCH_AGAINST],
1460
1494
  ]);
1461
1495
  return _this;
1462
1496
  }
@@ -1538,11 +1572,6 @@ var ConditionBuilder = /** @class */ (function (_super) {
1538
1572
  return (fullKey in table.COLUMNS ||
1539
1573
  Object.values(table.COLUMNS).includes(column));
1540
1574
  };
1541
- ConditionBuilder.prototype.validateOperator = function (op) {
1542
- if (!this.OPERATORS.has(op)) {
1543
- throw new Error("Invalid or unsupported SQL operator detected: '".concat(op, "'"));
1544
- }
1545
- };
1546
1575
  ConditionBuilder.prototype.addParam = function (params, column, value) {
1547
1576
  var _a, _b, _c, _d, _e;
1548
1577
  // Determine column definition from C6.TABLES to support type-aware conversions (e.g., BINARY hex -> Buffer)
@@ -1564,250 +1593,444 @@ var ConditionBuilder = /** @class */ (function (_super) {
1564
1593
  return '?';
1565
1594
  }
1566
1595
  };
1567
- ConditionBuilder.prototype.buildBooleanJoinedConditions = function (set, andMode, params) {
1568
- var _this = this;
1569
- if (andMode === void 0) { andMode = true; }
1570
- if (params === void 0) { params = []; }
1571
- var booleanOperator = andMode ? 'AND' : 'OR';
1572
- var addCondition = function (column, op, value) {
1573
- // Normalize common variants
1574
- var valueNorm = (value === C6C.NULL) ? null : value;
1575
- var displayOp = typeof op === 'string' ? op.replace('_', ' ') : op;
1576
- var extractSubSelect = function (input) {
1577
- if (Array.isArray(input) && input.length >= 2 && input[0] === C6C.SUBSELECT) {
1578
- return input[1];
1579
- }
1580
- if (input && typeof input === 'object' && C6C.SUBSELECT in input) {
1581
- return input[C6C.SUBSELECT];
1596
+ ConditionBuilder.prototype.normalizeOperatorKey = function (op) {
1597
+ if (typeof op !== 'string')
1598
+ return undefined;
1599
+ return this.OPERATOR_ALIASES.get(op);
1600
+ };
1601
+ ConditionBuilder.prototype.formatOperator = function (op) {
1602
+ var normalized = this.normalizeOperatorKey(op);
1603
+ if (!normalized) {
1604
+ throw new Error("Invalid or unsupported SQL operator detected: '".concat(op, "'"));
1605
+ }
1606
+ switch (normalized) {
1607
+ case 'NOT LIKE':
1608
+ case 'NOT IN':
1609
+ case 'IS NOT':
1610
+ case 'NOT BETWEEN':
1611
+ return normalized;
1612
+ case C6C.MATCH_AGAINST:
1613
+ return C6C.MATCH_AGAINST;
1614
+ default:
1615
+ return normalized;
1616
+ }
1617
+ };
1618
+ ConditionBuilder.prototype.isOperator = function (op) {
1619
+ return !!this.normalizeOperatorKey(op);
1620
+ };
1621
+ ConditionBuilder.prototype.looksLikeSafeFunctionExpression = function (value) {
1622
+ if (typeof value !== 'string')
1623
+ return false;
1624
+ var trimmed = value.trim();
1625
+ if (trimmed.length === 0)
1626
+ return false;
1627
+ if (trimmed.includes(';') || trimmed.includes('--') || trimmed.includes('/*') || trimmed.includes('*/')) {
1628
+ return false;
1629
+ }
1630
+ if (!trimmed.includes('(') || !trimmed.endsWith(')')) {
1631
+ return false;
1632
+ }
1633
+ var functionMatch = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*\(/);
1634
+ if (!functionMatch) {
1635
+ return false;
1636
+ }
1637
+ var allowedCharacters = /^[A-Za-z0-9_().,'"\s-]+$/;
1638
+ if (!allowedCharacters.test(trimmed)) {
1639
+ return false;
1640
+ }
1641
+ var depth = 0;
1642
+ for (var _i = 0, trimmed_1 = trimmed; _i < trimmed_1.length; _i++) {
1643
+ var char = trimmed_1[_i];
1644
+ if (char === '(') {
1645
+ depth += 1;
1646
+ }
1647
+ else if (char === ')') {
1648
+ depth -= 1;
1649
+ if (depth < 0) {
1650
+ return false;
1582
1651
  }
1583
- return undefined;
1584
- };
1585
- var rightSubSelectPayload = extractSubSelect(valueNorm);
1586
- var buildSubSelect = function (payload) {
1587
- if (!payload)
1588
- return undefined;
1589
- var builder = _this.buildScalarSubSelect;
1652
+ }
1653
+ }
1654
+ return depth === 0;
1655
+ };
1656
+ ConditionBuilder.prototype.ensureWrapped = function (expression) {
1657
+ var trimmed = expression.trim();
1658
+ if (!trimmed)
1659
+ return trimmed;
1660
+ if (trimmed.startsWith('(') && trimmed.endsWith(')')) {
1661
+ return trimmed;
1662
+ }
1663
+ return "(".concat(trimmed, ")");
1664
+ };
1665
+ ConditionBuilder.prototype.joinBooleanParts = function (parts, operator) {
1666
+ if (parts.length === 0)
1667
+ return '';
1668
+ if (parts.length === 1) {
1669
+ return parts[0];
1670
+ }
1671
+ return parts
1672
+ .map(function (part) {
1673
+ var trimmed = part.trim();
1674
+ var upper = trimmed.toUpperCase();
1675
+ var containsAnd = upper.includes(' AND ');
1676
+ var containsOr = upper.includes(' OR ');
1677
+ var needsWrap = (operator === 'AND' && containsOr) ||
1678
+ (operator === 'OR' && containsAnd);
1679
+ return needsWrap ? "(".concat(trimmed, ")") : trimmed;
1680
+ })
1681
+ .join(" ".concat(operator, " "));
1682
+ };
1683
+ ConditionBuilder.prototype.normalizeFunctionField = function (field, params) {
1684
+ var _this = this;
1685
+ if (field instanceof Map) {
1686
+ field = Object.fromEntries(field);
1687
+ }
1688
+ if (Array.isArray(field)) {
1689
+ if (field.length === 0)
1690
+ return field;
1691
+ var fn = field[0], args = field.slice(1);
1692
+ var normalizedArgs = args.map(function (arg) { return _this.normalizeFunctionField(arg, params); });
1693
+ return tslib.__spreadArray([fn], normalizedArgs, true);
1694
+ }
1695
+ if (field && typeof field === 'object') {
1696
+ if (C6C.SUBSELECT in field) {
1697
+ var builder = this.buildScalarSubSelect;
1590
1698
  if (typeof builder !== 'function') {
1591
1699
  throw new Error('Scalar subselect handling requires JoinBuilder context.');
1592
1700
  }
1593
- return builder.call(_this, payload, params);
1594
- };
1595
- var rightSubSelectSql = buildSubSelect(rightSubSelectPayload);
1596
- // Support function-based expressions like [C6C.ST_DISTANCE_SPHERE, col1, col2]
1597
- if (typeof column === 'string' &&
1598
- _this.OPERATORS.has(column) &&
1599
- Array.isArray(op)) {
1600
- // Helper to serialize operand which may be a qualified identifier or a nested function array
1601
- var serializeOperand = function (arg) {
1602
- var identifierPathRegex = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/;
1603
- if (Array.isArray(arg)) {
1604
- // Delegate to aggregate builder to handle nested functions/params
1605
- // @ts-ignore - buildAggregateField is defined upstream in AggregateBuilder
1606
- return _this.buildAggregateField(arg, params);
1607
- }
1608
- if (typeof arg === 'string') {
1609
- if (identifierPathRegex.test(arg)) {
1610
- _this.assertValidIdentifier(arg, 'WHERE argument');
1611
- return arg;
1612
- }
1613
- return arg;
1614
- }
1615
- return String(arg);
1616
- };
1617
- if (column === C6C.ST_DISTANCE_SPHERE) {
1618
- var col1 = op[0], col2 = op[1];
1619
- var threshold = Array.isArray(value) ? value[0] : value;
1620
- var left = serializeOperand(col1);
1621
- var right = serializeOperand(col2);
1622
- return "ST_Distance_Sphere(".concat(left, ", ").concat(right, ") < ").concat(_this.addParam(params, '', threshold));
1623
- }
1624
- if ([
1625
- C6C.ST_CONTAINS,
1626
- C6C.ST_INTERSECTS,
1627
- C6C.ST_WITHIN,
1628
- C6C.ST_CROSSES,
1629
- C6C.ST_DISJOINT,
1630
- C6C.ST_EQUALS,
1631
- C6C.ST_OVERLAPS,
1632
- C6C.ST_TOUCHES
1633
- ].includes(column)) {
1634
- var geom1 = op[0], geom2 = op[1];
1635
- var left = serializeOperand(geom1);
1636
- var right = serializeOperand(geom2);
1637
- return "".concat(column, "(").concat(left, ", ").concat(right, ")");
1701
+ return builder.call(this, field[C6C.SUBSELECT], params);
1702
+ }
1703
+ var entries = Object.entries(field);
1704
+ if (entries.length === 1) {
1705
+ var _a = entries[0], key = _a[0], value = _a[1];
1706
+ if (this.isOperator(key)) {
1707
+ return this.buildOperatorExpression(key, value, params);
1638
1708
  }
1709
+ return this.buildFunctionCall(key, value, params);
1639
1710
  }
1640
- var leftIsCol = _this.isColumnRef(column);
1641
- var leftIsRef = _this.isTableReference(column);
1642
- var rightIsCol = typeof value === 'string' && _this.isColumnRef(value);
1643
- if (!leftIsCol && !leftIsRef && !rightIsCol && !rightSubSelectSql) {
1644
- throw new Error("Potential SQL injection detected: '".concat(column, " ").concat(op, " ").concat(value, "'"));
1711
+ }
1712
+ return field;
1713
+ };
1714
+ ConditionBuilder.prototype.buildFunctionCall = function (fn, value, params) {
1715
+ var args = Array.isArray(value) ? value : [value];
1716
+ var normalized = this.normalizeFunctionField(tslib.__spreadArray([fn], args, true), params);
1717
+ return this.buildAggregateField(normalized, params);
1718
+ };
1719
+ ConditionBuilder.prototype.serializeOperand = function (operand, params, contextColumn) {
1720
+ var _a;
1721
+ var _this = this;
1722
+ var asParam = function (val) { return _this.addParam(params, contextColumn !== null && contextColumn !== void 0 ? contextColumn : '', val); };
1723
+ if (operand === C6C.NULL) {
1724
+ operand = null;
1725
+ }
1726
+ if (operand === null || typeof operand === 'number' || typeof operand === 'boolean') {
1727
+ return { sql: asParam(operand), isReference: false, isExpression: false, isSubSelect: false };
1728
+ }
1729
+ if (typeof operand === 'string') {
1730
+ if (this.isTableReference(operand) || this.isColumnRef(operand)) {
1731
+ return { sql: operand, isReference: true, isExpression: false, isSubSelect: false };
1645
1732
  }
1646
- _this.validateOperator(op);
1647
- if (op === C6C.MATCH_AGAINST && Array.isArray(value)) {
1648
- var search = value[0], mode = value[1];
1649
- var paramName = _this.useNamedParams ? "param".concat(Object.keys(params).length) : null;
1650
- if (_this.useNamedParams) {
1651
- params[paramName] = search;
1652
- }
1653
- else {
1654
- params.push(search);
1655
- }
1656
- var againstClause = void 0;
1657
- switch ((mode || '').toUpperCase()) {
1658
- case 'BOOLEAN':
1659
- againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " IN BOOLEAN MODE)") : "AGAINST(? IN BOOLEAN MODE)";
1660
- break;
1661
- case 'WITH QUERY EXPANSION':
1662
- againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, " WITH QUERY EXPANSION)") : "AGAINST(? WITH QUERY EXPANSION)";
1663
- break;
1664
- default: // NATURAL or undefined
1665
- againstClause = _this.useNamedParams ? "AGAINST(:".concat(paramName, ")") : "AGAINST(?)";
1666
- break;
1667
- }
1668
- if (!leftIsCol) {
1669
- throw new Error("MATCH_AGAINST requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1733
+ if (this.looksLikeSafeFunctionExpression(operand)) {
1734
+ return { sql: operand.trim(), isReference: false, isExpression: true, isSubSelect: false };
1735
+ }
1736
+ return { sql: asParam(operand), isReference: false, isExpression: false, isSubSelect: false };
1737
+ }
1738
+ if (Array.isArray(operand)) {
1739
+ var normalized = this.normalizeFunctionField(operand, params);
1740
+ var sql = this.buildAggregateField(normalized, params);
1741
+ return { sql: sql, isReference: false, isExpression: true, isSubSelect: false };
1742
+ }
1743
+ if (operand instanceof Map) {
1744
+ operand = Object.fromEntries(operand);
1745
+ }
1746
+ if (typeof operand === 'object' && operand !== null) {
1747
+ if (C6C.SUBSELECT in operand) {
1748
+ var builder = this.buildScalarSubSelect;
1749
+ if (typeof builder !== 'function') {
1750
+ throw new Error('Scalar subselect handling requires JoinBuilder context.');
1670
1751
  }
1671
- var matchClause = "(MATCH(".concat(column, ") ").concat(againstClause, ")");
1672
- _this.config.verbose && console.log("[MATCH_AGAINST] ".concat(matchClause));
1673
- return matchClause;
1752
+ var subSql = builder.call(this, operand[C6C.SUBSELECT], params);
1753
+ return { sql: subSql, isReference: false, isExpression: true, isSubSelect: true };
1674
1754
  }
1675
- if ((op === C6C.IN || op === C6C.NOT_IN) && Array.isArray(value)) {
1676
- if (rightSubSelectSql) {
1677
- if (!leftIsRef) {
1678
- throw new Error("IN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1679
- }
1680
- var normalized_1 = op.replace('_', ' ');
1681
- return "( ".concat(column, " ").concat(normalized_1, " ").concat(rightSubSelectSql, " )");
1755
+ var entries = Object.entries(operand);
1756
+ if (entries.length === 1) {
1757
+ var _b = entries[0], key = _b[0], value = _b[1];
1758
+ if (this.isOperator(key)) {
1759
+ var sql_1 = this.buildOperatorExpression(key, value, params);
1760
+ return { sql: this.ensureWrapped(sql_1), isReference: false, isExpression: true, isSubSelect: false };
1682
1761
  }
1683
- var placeholders = value.map(function (v) {
1684
- return _this.isColumnRef(v) ? v : _this.addParam(params, column, v);
1685
- }).join(', ');
1686
- var normalized = op.replace('_', ' ');
1687
- if (!leftIsRef) {
1688
- throw new Error("IN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1762
+ if (this.BOOLEAN_OPERATORS.has(key)) {
1763
+ var sql_2 = this.buildBooleanExpression((_a = {}, _a[key] = value, _a), params, 'AND');
1764
+ return { sql: this.ensureWrapped(sql_2), isReference: false, isExpression: true, isSubSelect: false };
1689
1765
  }
1690
- return "( ".concat(column, " ").concat(normalized, " (").concat(placeholders, ") )");
1766
+ var sql = this.buildFunctionCall(key, value, params);
1767
+ return { sql: sql, isReference: false, isExpression: true, isSubSelect: false };
1691
1768
  }
1692
- if (op === C6C.BETWEEN || op === 'NOT BETWEEN') {
1693
- if (!Array.isArray(value) || value.length !== 2) {
1694
- throw new Error("BETWEEN operator requires an array of two values");
1769
+ }
1770
+ throw new Error('Unsupported operand type in SQL expression.');
1771
+ };
1772
+ ConditionBuilder.prototype.buildOperatorExpression = function (op, rawOperands, params, contextColumn) {
1773
+ var _a, _b;
1774
+ var _this = this;
1775
+ var operator = this.formatOperator(op);
1776
+ if (operator === C6C.MATCH_AGAINST) {
1777
+ if (!Array.isArray(rawOperands) || rawOperands.length !== 2) {
1778
+ throw new Error('MATCH_AGAINST requires an array of two operands.');
1779
+ }
1780
+ var left = rawOperands[0], right = rawOperands[1];
1781
+ var leftInfo_1 = this.serializeOperand(left, params, contextColumn);
1782
+ if (!leftInfo_1.isReference) {
1783
+ throw new Error('MATCH_AGAINST requires the left operand to be a table reference.');
1784
+ }
1785
+ if (!Array.isArray(right) || right.length === 0) {
1786
+ throw new Error('MATCH_AGAINST expects an array [search, mode?].');
1787
+ }
1788
+ var search = right[0], mode = right[1];
1789
+ var placeholder = this.addParam(params, leftInfo_1.sql, search);
1790
+ var againstClause = void 0;
1791
+ switch (typeof mode === 'string' ? mode.toUpperCase() : '') {
1792
+ case 'BOOLEAN':
1793
+ againstClause = "AGAINST(".concat(placeholder, " IN BOOLEAN MODE)");
1794
+ break;
1795
+ case 'WITH QUERY EXPANSION':
1796
+ againstClause = "AGAINST(".concat(placeholder, " WITH QUERY EXPANSION)");
1797
+ break;
1798
+ case 'NATURAL LANGUAGE MODE':
1799
+ againstClause = "AGAINST(".concat(placeholder, " IN NATURAL LANGUAGE MODE)");
1800
+ break;
1801
+ default:
1802
+ againstClause = "AGAINST(".concat(placeholder, ")");
1803
+ break;
1804
+ }
1805
+ var clause = "(MATCH(".concat(leftInfo_1.sql, ") ").concat(againstClause, ")");
1806
+ this.config.verbose && console.log("[MATCH_AGAINST] ".concat(clause));
1807
+ return clause;
1808
+ }
1809
+ var operands = Array.isArray(rawOperands) ? rawOperands : [rawOperands];
1810
+ if (operator === C6C.IN || operator === 'NOT IN') {
1811
+ if (operands.length < 2) {
1812
+ throw new Error("".concat(operator, " requires two operands."));
1813
+ }
1814
+ var leftRaw = operands[0], rest = operands.slice(1);
1815
+ var left_1 = leftRaw;
1816
+ var right = rest.length <= 1 ? rest[0] : rest;
1817
+ var leftInfo_2 = this.serializeOperand(left_1, params, typeof left_1 === 'string' ? left_1 : contextColumn);
1818
+ if (!leftInfo_2.isReference) {
1819
+ throw new Error("".concat(operator, " requires the left operand to be a table reference."));
1820
+ }
1821
+ if (Array.isArray(right)) {
1822
+ if (right.length === 0) {
1823
+ throw new Error("".concat(operator, " requires at least one value."));
1695
1824
  }
1696
- var start = value[0], end = value[1];
1697
- if (!leftIsRef) {
1698
- throw new Error("BETWEEN operator requires a table reference as the left operand. Column '".concat(column, "' is not a valid table reference."));
1825
+ if (right.length === 2 && right[0] === C6C.SUBSELECT) {
1826
+ var sub = this.serializeOperand(right, params, typeof left_1 === 'string' ? left_1 : contextColumn);
1827
+ return "( ".concat(leftInfo_2.sql, " ").concat(operator, " ").concat(sub.sql, " )");
1699
1828
  }
1700
- return "(".concat(column, ") ").concat(op.replace('_', ' '), " ").concat(_this.addParam(params, column, start), " AND ").concat(_this.addParam(params, column, end));
1829
+ var placeholders = right.map(function (item) {
1830
+ if (typeof item === 'string' && _this.isTableReference(item)) {
1831
+ return item;
1832
+ }
1833
+ var sql = _this.serializeOperand(item, params, typeof left_1 === 'string' ? left_1 : contextColumn).sql;
1834
+ return sql;
1835
+ });
1836
+ return "( ".concat(leftInfo_2.sql, " ").concat(operator, " (").concat(placeholders.join(', '), ") )");
1701
1837
  }
1702
- var rightIsRef = rightSubSelectSql ? false : _this.isTableReference(value);
1703
- if (leftIsRef && rightIsRef) {
1704
- return "(".concat(column, ") ").concat(displayOp, " ").concat(value);
1838
+ var rightInfo_1 = this.serializeOperand(right, params, typeof left_1 === 'string' ? left_1 : contextColumn);
1839
+ if (!rightInfo_1.isSubSelect) {
1840
+ throw new Error("".concat(operator, " requires an array of values or a subselect."));
1705
1841
  }
1706
- if (leftIsRef && rightSubSelectSql) {
1707
- return "(".concat(column, ") ").concat(displayOp, " ").concat(rightSubSelectSql);
1842
+ return "( ".concat(leftInfo_2.sql, " ").concat(operator, " ").concat(rightInfo_1.sql, " )");
1843
+ }
1844
+ if (operator === C6C.BETWEEN || operator === 'NOT BETWEEN') {
1845
+ var left = void 0;
1846
+ var start = void 0;
1847
+ var end = void 0;
1848
+ if (operands.length === 3) {
1849
+ left = operands[0], start = operands[1], end = operands[2];
1708
1850
  }
1709
- if (leftIsRef && !rightIsRef) {
1710
- return "(".concat(column, ") ").concat(displayOp, " ").concat(_this.addParam(params, column, valueNorm));
1851
+ else if (operands.length === 2 && Array.isArray(operands[1]) && operands[1].length === 2) {
1852
+ _a = operands, left = _a[0], _b = _a[1], start = _b[0], end = _b[1];
1711
1853
  }
1712
- if (rightIsRef) {
1713
- return "(".concat(_this.addParam(params, column, column), ") ").concat(displayOp, " ").concat(value);
1854
+ else {
1855
+ throw new Error("".concat(operator, " requires three operands."));
1714
1856
  }
1715
- throw new Error("Neither operand appears to be a table reference (".concat(column, ") or (").concat(value, ")"));
1716
- };
1717
- var parts = [];
1718
- var buildFromObject = function (obj, mode) {
1719
- var subParts = [];
1720
- var entries = Object.entries(obj);
1721
- var nonNumeric = entries.filter(function (_a) {
1722
- var k = _a[0];
1723
- return isNaN(Number(k));
1724
- });
1725
- var numeric = entries.filter(function (_a) {
1726
- var k = _a[0];
1727
- return !isNaN(Number(k));
1728
- });
1729
- var processEntry = function (k, v) {
1730
- // Operator-as-key handling, e.g., { [C6C.ST_DISTANCE_SPHERE]: [arg1, arg2, threshold] }
1731
- if (typeof k === 'string' && _this.OPERATORS.has(k) && Array.isArray(v)) {
1732
- if (k === C6C.ST_DISTANCE_SPHERE) {
1733
- // Accept either [arg1, arg2, threshold] or [[arg1, arg2], threshold]
1734
- var args = void 0;
1735
- var threshold = void 0;
1736
- if (Array.isArray(v[0]) && v.length >= 2) {
1737
- args = v[0];
1738
- threshold = v[1];
1739
- }
1740
- else {
1741
- args = v.slice(0, 2);
1742
- threshold = v[2];
1743
- }
1744
- subParts.push(addCondition(k, args, threshold));
1745
- return;
1746
- }
1747
- }
1748
- if (typeof v === 'object' && v !== null && Object.keys(v).length === 1) {
1749
- var _a = Object.entries(v)[0], op = _a[0], val = _a[1];
1750
- subParts.push(addCondition(k, op, val));
1857
+ var leftInfo_3 = this.serializeOperand(left, params, typeof left === 'string' ? left : contextColumn);
1858
+ if (!leftInfo_3.isReference) {
1859
+ throw new Error("".concat(operator, " requires the left operand to be a table reference."));
1860
+ }
1861
+ var startInfo = this.serializeOperand(start, params, typeof left === 'string' ? left : contextColumn);
1862
+ var endInfo = this.serializeOperand(end, params, typeof left === 'string' ? left : contextColumn);
1863
+ var betweenOperator = operator === 'NOT BETWEEN' ? 'NOT BETWEEN' : 'BETWEEN';
1864
+ return "".concat(this.ensureWrapped(leftInfo_3.sql), " ").concat(betweenOperator, " ").concat(startInfo.sql, " AND ").concat(endInfo.sql);
1865
+ }
1866
+ if (operands.length !== 2) {
1867
+ throw new Error("".concat(operator, " requires two operands."));
1868
+ }
1869
+ var leftOperand = operands[0], rightOperand = operands[1];
1870
+ var leftInfo = this.serializeOperand(leftOperand, params, typeof leftOperand === 'string' ? leftOperand : contextColumn);
1871
+ var rightInfo = this.serializeOperand(rightOperand, params, typeof leftOperand === 'string' ? leftOperand : contextColumn);
1872
+ if (!leftInfo.isReference && !leftInfo.isExpression && !rightInfo.isReference && !rightInfo.isExpression) {
1873
+ throw new Error("Potential SQL injection detected: '".concat(operator, "' with non-reference operands."));
1874
+ }
1875
+ var leftSql = leftInfo.isExpression ? leftInfo.sql : this.ensureWrapped(leftInfo.sql);
1876
+ var rightSql = rightInfo.isExpression ? rightInfo.sql : rightInfo.sql;
1877
+ return "".concat(leftSql, " ").concat(operator, " ").concat(rightSql);
1878
+ };
1879
+ ConditionBuilder.prototype.buildLegacyColumnCondition = function (column, value, params) {
1880
+ var _a;
1881
+ var _this = this;
1882
+ if (value instanceof Map) {
1883
+ value = Object.fromEntries(value);
1884
+ }
1885
+ if (Array.isArray(value)) {
1886
+ if (value.length >= 2 && typeof value[0] === 'string') {
1887
+ var op = value[0], rest = value.slice(1);
1888
+ return this.buildOperatorExpression(op, tslib.__spreadArray([column], rest, true), params, column);
1889
+ }
1890
+ if (value.length === 3 && typeof value[0] === 'string' && typeof value[1] === 'string') {
1891
+ return this.buildOperatorExpression(value[1], [value[0], value[2]], params, value[0]);
1892
+ }
1893
+ }
1894
+ if (typeof value === 'object' && value !== null) {
1895
+ var entries = Object.entries(value);
1896
+ if (entries.length === 1) {
1897
+ var _b = entries[0], op = _b[0], operand = _b[1];
1898
+ if (this.isOperator(op)) {
1899
+ return this.buildOperatorExpression(op, [column, operand], params, column);
1751
1900
  }
1752
- else if (Array.isArray(v) && v.length >= 2 && typeof v[0] === 'string') {
1753
- var _b = v, op = _b[0], val = _b[1];
1754
- subParts.push(addCondition(k, op, val));
1901
+ if (this.BOOLEAN_OPERATORS.has(op)) {
1902
+ var expression = this.buildBooleanExpression((_a = {}, _a[op] = operand, _a), params, 'AND');
1903
+ return expression;
1755
1904
  }
1756
- else if (typeof v === 'object' && v !== null) {
1757
- var sub = _this.buildBooleanJoinedConditions(v, mode, params);
1758
- if (sub)
1759
- subParts.push(sub);
1905
+ }
1906
+ var subParts = entries.map(function (_a) {
1907
+ var _b;
1908
+ var op = _a[0], operand = _a[1];
1909
+ if (_this.isOperator(op)) {
1910
+ return _this.buildOperatorExpression(op, [column, operand], params, column);
1760
1911
  }
1761
- else {
1762
- subParts.push(addCondition(k, '=', v));
1912
+ return _this.buildBooleanExpression((_b = {}, _b[op] = operand, _b), params, 'AND');
1913
+ }).filter(Boolean);
1914
+ return this.joinBooleanParts(subParts, 'AND');
1915
+ }
1916
+ return this.buildOperatorExpression(C6C.EQUAL, [column, value], params, column);
1917
+ };
1918
+ ConditionBuilder.prototype.buildBooleanExpression = function (node, params, defaultOperator) {
1919
+ var _this = this;
1920
+ if (node === null || node === undefined) {
1921
+ return '';
1922
+ }
1923
+ if (Array.isArray(node)) {
1924
+ if (node.length === 0)
1925
+ return '';
1926
+ if (node.length === 3 && typeof node[0] === 'string' && typeof node[1] === 'string') {
1927
+ return this.buildOperatorExpression(node[1], [node[0], node[2]], params, node[0]);
1928
+ }
1929
+ var parts_1 = node
1930
+ .map(function (item) { return _this.buildBooleanExpression(item, params, 'OR'); })
1931
+ .filter(Boolean);
1932
+ return this.joinBooleanParts(parts_1, 'OR');
1933
+ }
1934
+ if (node instanceof Map) {
1935
+ node = Object.fromEntries(node);
1936
+ }
1937
+ if (typeof node !== 'object') {
1938
+ throw new Error('Invalid WHERE clause structure.');
1939
+ }
1940
+ var entries = Object.entries(node);
1941
+ if (entries.length === 0)
1942
+ return '';
1943
+ if (entries.length === 1) {
1944
+ var _a = entries[0], key = _a[0], value = _a[1];
1945
+ if (this.BOOLEAN_OPERATORS.has(key)) {
1946
+ if (!Array.isArray(value)) {
1947
+ throw new Error("".concat(key, " expects an array of expressions."));
1763
1948
  }
1764
- };
1765
- // Process non-numeric keys first to preserve intuitive insertion order for params
1766
- for (var _i = 0, nonNumeric_1 = nonNumeric; _i < nonNumeric_1.length; _i++) {
1767
- var _a = nonNumeric_1[_i], k = _a[0], v = _a[1];
1768
- processEntry(k, v);
1949
+ var op_1 = this.BOOLEAN_OPERATORS.get(key);
1950
+ var parts_2 = value
1951
+ .map(function (item) { return _this.buildBooleanExpression(item, params, op_1); })
1952
+ .filter(Boolean);
1953
+ return this.joinBooleanParts(parts_2, op_1);
1769
1954
  }
1770
- // Then process numeric keys (treated as grouped OR conditions)
1771
- for (var _b = 0, numeric_1 = numeric; _b < numeric_1.length; _b++) {
1772
- var _c = numeric_1[_b]; _c[0]; var v = _c[1];
1773
- var sub = _this.buildBooleanJoinedConditions(v, false, params);
1774
- if (sub)
1775
- subParts.push(sub);
1955
+ if (this.isOperator(key)) {
1956
+ return this.buildOperatorExpression(key, value, params);
1776
1957
  }
1777
- return subParts.join(" ".concat(mode ? 'AND' : 'OR', " "));
1778
- };
1779
- if (Array.isArray(set)) {
1780
- // Detect a single condition triple: [column, op, value]
1781
- if (set.length === 3 && typeof set[0] === 'string' && typeof set[1] === 'string') {
1782
- var _a = set, column = _a[0], rawOp = _a[1], rawVal = _a[2];
1783
- var op = rawOp;
1784
- var value = rawVal === C6C.NULL ? null : rawVal;
1785
- var sub = addCondition(column, op, value);
1786
- if (sub)
1787
- parts.push(sub);
1958
+ if (!isNaN(Number(key))) {
1959
+ return this.buildBooleanExpression(value, params, 'OR');
1788
1960
  }
1789
- else {
1790
- for (var _i = 0, set_1 = set; _i < set_1.length; _i++) {
1791
- var item = set_1[_i];
1792
- var sub = this.buildBooleanJoinedConditions(item, false, params);
1793
- if (sub)
1794
- parts.push(sub);
1961
+ }
1962
+ var parts = [];
1963
+ var nonNumeric = entries.filter(function (_a) {
1964
+ var k = _a[0];
1965
+ return isNaN(Number(k));
1966
+ });
1967
+ var numeric = entries.filter(function (_a) {
1968
+ var k = _a[0];
1969
+ return !isNaN(Number(k));
1970
+ });
1971
+ var _loop_1 = function (key, value) {
1972
+ if (this_1.BOOLEAN_OPERATORS.has(key)) {
1973
+ var op_2 = this_1.BOOLEAN_OPERATORS.get(key);
1974
+ if (!Array.isArray(value)) {
1975
+ throw new Error("".concat(key, " expects an array of expressions."));
1976
+ }
1977
+ var nested = value
1978
+ .map(function (item) { return _this.buildBooleanExpression(item, params, op_2); })
1979
+ .filter(Boolean);
1980
+ if (nested.length) {
1981
+ parts.push(this_1.joinBooleanParts(nested, op_2));
1795
1982
  }
1983
+ return "continue";
1796
1984
  }
1985
+ if (this_1.isOperator(key)) {
1986
+ parts.push(this_1.buildOperatorExpression(key, value, params));
1987
+ return "continue";
1988
+ }
1989
+ parts.push(this_1.buildLegacyColumnCondition(key, value, params));
1990
+ };
1991
+ var this_1 = this;
1992
+ for (var _i = 0, nonNumeric_1 = nonNumeric; _i < nonNumeric_1.length; _i++) {
1993
+ var _b = nonNumeric_1[_i], key = _b[0], value = _b[1];
1994
+ _loop_1(key, value);
1797
1995
  }
1798
- else if (typeof set === 'object' && set !== null) {
1799
- var sub = buildFromObject(set, andMode);
1800
- if (sub)
1801
- parts.push(sub);
1996
+ for (var _c = 0, numeric_1 = numeric; _c < numeric_1.length; _c++) {
1997
+ var _d = numeric_1[_c], value = _d[1];
1998
+ var nested = this.buildBooleanExpression(value, params, 'OR');
1999
+ if (nested) {
2000
+ parts.push(nested);
2001
+ }
1802
2002
  }
1803
- var clause = parts.join(" ".concat(booleanOperator, " "));
1804
- return clause ? "(".concat(clause, ")") : '';
2003
+ return this.joinBooleanParts(parts, defaultOperator);
2004
+ };
2005
+ ConditionBuilder.prototype.buildBooleanJoinedConditions = function (set, andMode, params) {
2006
+ if (andMode === void 0) { andMode = true; }
2007
+ if (params === void 0) { params = []; }
2008
+ var expression = this.buildBooleanExpression(set, params, andMode ? 'AND' : 'OR');
2009
+ if (!expression)
2010
+ return '';
2011
+ return this.ensureWrapped(expression);
1805
2012
  };
1806
2013
  ConditionBuilder.prototype.buildWhereClause = function (whereArg, params) {
1807
2014
  var clause = this.buildBooleanJoinedConditions(whereArg, true, params);
1808
2015
  if (!clause)
1809
2016
  return '';
1810
- var trimmed = clause.replace(/^\((.*)\)$/, '$1');
2017
+ var trimmed = clause.trim();
2018
+ var upper = trimmed.toUpperCase();
2019
+ if (!upper.includes(' AND ') && !upper.includes(' OR ')) {
2020
+ if (trimmed.startsWith('(') && trimmed.endsWith(')')) {
2021
+ var inner = trimmed.substring(1, trimmed.length - 1);
2022
+ var innerUpper = inner.toUpperCase();
2023
+ var requiresOuterWrap = innerUpper.includes(' IN ') ||
2024
+ innerUpper.includes(' BETWEEN ') ||
2025
+ innerUpper.includes(' SELECT ');
2026
+ if (requiresOuterWrap) {
2027
+ trimmed = "( ".concat(inner.trim(), " )");
2028
+ }
2029
+ else {
2030
+ trimmed = inner.trim();
2031
+ }
2032
+ }
2033
+ }
1811
2034
  this.config.verbose && console.log("[WHERE] ".concat(trimmed));
1812
2035
  return " WHERE ".concat(trimmed);
1813
2036
  };
@@ -1824,24 +2047,29 @@ var JoinBuilder = /** @class */ (function (_super) {
1824
2047
  };
1825
2048
  JoinBuilder.prototype.buildJoinClauses = function (joinArgs, params) {
1826
2049
  var sql = '';
1827
- var _loop_1 = function (joinType) {
1828
- var joinKind = joinType.replace('_', ' ').toUpperCase();
2050
+ var joinTypeEntries = joinArgs instanceof Map
2051
+ ? Array.from(joinArgs.entries()).map(function (_a) {
2052
+ var key = _a[0], value = _a[1];
2053
+ return [String(key), value];
2054
+ })
2055
+ : Object.keys(joinArgs).map(function (key) { return [key, joinArgs[key]]; });
2056
+ var _loop_1 = function (joinTypeRaw, joinSection) {
2057
+ var joinKind = joinTypeRaw.replace('_', ' ').toUpperCase();
1829
2058
  var entries = [];
1830
- var joinSection = joinArgs[joinType];
1831
2059
  if (joinSection instanceof Map) {
1832
2060
  joinSection.forEach(function (value, key) {
1833
2061
  entries.push([key, value]);
1834
2062
  });
1835
2063
  }
1836
2064
  else {
1837
- for (var raw in joinSection) {
2065
+ Object.keys(joinSection).forEach(function (raw) {
1838
2066
  entries.push([raw, joinSection[raw]]);
1839
- }
2067
+ });
1840
2068
  }
1841
- for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
1842
- var _a = entries_1[_i], rawKey = _a[0], conditions = _a[1];
2069
+ for (var _b = 0, entries_1 = entries; _b < entries_1.length; _b++) {
2070
+ var _c = entries_1[_b], rawKey = _c[0], conditions = _c[1];
1843
2071
  var raw = typeof rawKey === 'string' ? rawKey : String(rawKey);
1844
- var _b = raw.trim().split(/\s+/, 2), table = _b[0], aliasCandidate = _b[1];
2072
+ var _d = raw.trim().split(/\s+/, 2), table = _d[0], aliasCandidate = _d[1];
1845
2073
  if (!table)
1846
2074
  continue;
1847
2075
  if (isDerivedTableKey(table)) {
@@ -1865,7 +2093,7 @@ var JoinBuilder = /** @class */ (function (_super) {
1865
2093
  throw new Error('Derived table subselects require a base table defined with C6C.FROM.');
1866
2094
  }
1867
2095
  var subBuilder = this_1.createSelectBuilder(subRequest);
1868
- var _c = subBuilder.build(fromTable, true), subSql = _c.sql, subParams = _c.params;
2096
+ var _e = subBuilder.build(fromTable, true), subSql = _e.sql, subParams = _e.params;
1869
2097
  var normalizedSql = this_1.integrateSubSelectParams(subSql, subParams, params);
1870
2098
  var formatted = normalizedSql.trim().split('\n').map(function (line) { return " ".concat(line); }).join('\n');
1871
2099
  var joinSql = "(\n".concat(formatted, "\n) AS `").concat(alias, "`");
@@ -1890,8 +2118,9 @@ var JoinBuilder = /** @class */ (function (_super) {
1890
2118
  }
1891
2119
  };
1892
2120
  var this_1 = this;
1893
- for (var joinType in joinArgs) {
1894
- _loop_1(joinType);
2121
+ for (var _i = 0, joinTypeEntries_1 = joinTypeEntries; _i < joinTypeEntries_1.length; _i++) {
2122
+ var _a = joinTypeEntries_1[_i], joinTypeRaw = _a[0], joinSection = _a[1];
2123
+ _loop_1(joinTypeRaw, joinSection);
1895
2124
  }
1896
2125
  this.config.verbose && console.log("[JOIN] ".concat(sql.trim()));
1897
2126
  return sql;