sqlstack 1.0.17 → 1.0.18

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.
@@ -276,6 +276,562 @@ export function createBinder(dialect) {
276
276
  i = updateEnd;
277
277
  continue;
278
278
  }
279
+ // Check for :insert(...) syntax (case-insensitive)
280
+ const insertMatch = /^:insert\s*\(/i.exec(sql.slice(i));
281
+ if (insertMatch) {
282
+ if (isArrayArgs) {
283
+ throw new Error(':insert() syntax only works with named parameters');
284
+ }
285
+ // Parse the column list inside parentheses
286
+ let j = i + insertMatch[0].length; // Skip ':insert('
287
+ const columnStart = j;
288
+ let parenDepth = 1;
289
+ let inString = false;
290
+ let stringChar = '';
291
+ // Find matching closing parenthesis
292
+ while (j < len && parenDepth > 0) {
293
+ const c = sql[j];
294
+ const cNext = j + 1 < len ? sql[j + 1] : '';
295
+ if (!inString) {
296
+ if (c === "'" || c === '"') {
297
+ inString = true;
298
+ stringChar = c;
299
+ }
300
+ else if (c === '(') {
301
+ parenDepth++;
302
+ }
303
+ else if (c === ')') {
304
+ parenDepth--;
305
+ }
306
+ }
307
+ else {
308
+ if (c === stringChar) {
309
+ // Check for escaped quote
310
+ if (cNext === stringChar) {
311
+ j++; // Skip escaped quote
312
+ }
313
+ else {
314
+ inString = false;
315
+ }
316
+ }
317
+ }
318
+ if (parenDepth > 0)
319
+ j++;
320
+ }
321
+ if (parenDepth > 0) {
322
+ throw new Error('Unclosed :insert() parentheses');
323
+ }
324
+ // Extract column list (between the parentheses)
325
+ const columnList = sql.slice(columnStart, j).trim();
326
+ const insertEnd = j + 1; // Include closing ')'
327
+ // Parse column list (split by comma, respecting quotes and parentheses)
328
+ const items = [];
329
+ let current = '';
330
+ let inSQ = false; // single quote string
331
+ let inDQ = false; // double quote identifier
332
+ let itemParenDepth = 0;
333
+ for (let k = 0; k < columnList.length; k++) {
334
+ const ch = columnList[k];
335
+ const next = k + 1 < columnList.length ? columnList[k + 1] : '';
336
+ if (inSQ) {
337
+ current += ch;
338
+ if (ch === "'" && next === "'") {
339
+ current += next;
340
+ k++;
341
+ }
342
+ else if (ch === "'") {
343
+ inSQ = false;
344
+ }
345
+ continue;
346
+ }
347
+ if (inDQ) {
348
+ current += ch;
349
+ if (ch === '"' && next === '"') {
350
+ current += next;
351
+ k++;
352
+ }
353
+ else if (ch === '"') {
354
+ inDQ = false;
355
+ }
356
+ continue;
357
+ }
358
+ if (ch === "'") {
359
+ current += ch;
360
+ inSQ = true;
361
+ continue;
362
+ }
363
+ if (ch === '"') {
364
+ current += ch;
365
+ inDQ = true;
366
+ continue;
367
+ }
368
+ if (ch === '(') {
369
+ current += ch;
370
+ itemParenDepth++;
371
+ continue;
372
+ }
373
+ if (ch === ')') {
374
+ current += ch;
375
+ itemParenDepth--;
376
+ continue;
377
+ }
378
+ if (ch === ',' && itemParenDepth === 0) {
379
+ const trimmed = current.trim();
380
+ if (trimmed.length > 0) {
381
+ items.push(trimmed);
382
+ }
383
+ current = '';
384
+ continue;
385
+ }
386
+ current += ch;
387
+ }
388
+ // Add the last item
389
+ const trimmed = current.trim();
390
+ if (trimmed.length > 0) {
391
+ items.push(trimmed);
392
+ }
393
+ if (items.length === 0) {
394
+ throw new Error(':insert() requires at least one column name');
395
+ }
396
+ // Build column list and VALUES clause
397
+ const obj = args;
398
+ const columnNames = [];
399
+ const valueParts = [];
400
+ const insertParams = [];
401
+ let hasParameterized = false;
402
+ for (const item of items) {
403
+ const trimmed = item.trim();
404
+ // Check if this is a literal expression (contains = not inside quotes)
405
+ let isLiteral = false;
406
+ let eqIndex = -1;
407
+ let inString = false;
408
+ let stringChar = '';
409
+ for (let k = 0; k < trimmed.length; k++) {
410
+ const ch = trimmed[k];
411
+ const next = k + 1 < trimmed.length ? trimmed[k + 1] : '';
412
+ if (!inString && (ch === "'" || ch === '"')) {
413
+ inString = true;
414
+ stringChar = ch;
415
+ }
416
+ else if (inString) {
417
+ if (ch === stringChar) {
418
+ if (next === stringChar) {
419
+ k++; // Skip escaped quote
420
+ }
421
+ else {
422
+ inString = false;
423
+ }
424
+ }
425
+ }
426
+ else if (ch === '=') {
427
+ eqIndex = k;
428
+ isLiteral = true;
429
+ break;
430
+ }
431
+ }
432
+ if (isLiteral && eqIndex >= 0) {
433
+ // Literal SQL expression - extract column name and value
434
+ const colName = trimmed.slice(0, eqIndex).trim();
435
+ const literalValue = trimmed.slice(eqIndex + 1).trim();
436
+ columnNames.push(colName);
437
+ valueParts.push(literalValue);
438
+ }
439
+ else {
440
+ // Parameterized column - check if defined in args
441
+ hasParameterized = true;
442
+ if (Object.prototype.hasOwnProperty.call(obj, trimmed) && obj[trimmed] !== undefined) {
443
+ columnNames.push(trimmed);
444
+ valueParts.push(placeholder(pgIndex));
445
+ insertParams.push(obj[trimmed]);
446
+ }
447
+ }
448
+ }
449
+ // Only throw error if all parameterized columns are undefined (literals are always included)
450
+ if (hasParameterized && columnNames.length === 0) {
451
+ throw new Error('All columns in :insert() are undefined');
452
+ }
453
+ if (columnNames.length === 0) {
454
+ throw new Error(':insert() requires at least one column name');
455
+ }
456
+ // Replace :insert(...) with column list and VALUES clause
457
+ out.push('(', columnNames.join(', '), ') VALUES (', valueParts.join(', '), ')');
458
+ params.push(...insertParams);
459
+ i = insertEnd;
460
+ continue;
461
+ }
462
+ // Check for :filter(...) syntax (case-insensitive)
463
+ const filterMatch = /^:filter\s*\(/i.exec(sql.slice(i));
464
+ if (filterMatch) {
465
+ if (isArrayArgs) {
466
+ throw new Error(':filter() syntax only works with named parameters');
467
+ }
468
+ // Parse the condition list inside parentheses
469
+ let j = i + filterMatch[0].length; // Skip ':filter('
470
+ const conditionStart = j;
471
+ let parenDepth = 1;
472
+ let inString = false;
473
+ let stringChar = '';
474
+ // Find matching closing parenthesis
475
+ while (j < len && parenDepth > 0) {
476
+ const c = sql[j];
477
+ const cNext = j + 1 < len ? sql[j + 1] : '';
478
+ if (!inString) {
479
+ if (c === "'" || c === '"') {
480
+ inString = true;
481
+ stringChar = c;
482
+ }
483
+ else if (c === '(') {
484
+ parenDepth++;
485
+ }
486
+ else if (c === ')') {
487
+ parenDepth--;
488
+ }
489
+ }
490
+ else {
491
+ if (c === stringChar) {
492
+ // Check for escaped quote
493
+ if (cNext === stringChar) {
494
+ j++; // Skip escaped quote
495
+ }
496
+ else {
497
+ inString = false;
498
+ }
499
+ }
500
+ }
501
+ if (parenDepth > 0)
502
+ j++;
503
+ }
504
+ if (parenDepth > 0) {
505
+ throw new Error('Unclosed :filter() parentheses');
506
+ }
507
+ // Extract condition list (between the parentheses)
508
+ const conditionList = sql.slice(conditionStart, j).trim();
509
+ const filterEnd = j + 1; // Include closing ')'
510
+ // Parse condition list (split by comma, respecting quotes and parentheses)
511
+ const items = [];
512
+ let current = '';
513
+ let inSQ = false; // single quote string
514
+ let inDQ = false; // double quote identifier
515
+ let itemParenDepth = 0;
516
+ for (let k = 0; k < conditionList.length; k++) {
517
+ const ch = conditionList[k];
518
+ const next = k + 1 < conditionList.length ? conditionList[k + 1] : '';
519
+ if (inSQ) {
520
+ current += ch;
521
+ if (ch === "'" && next === "'") {
522
+ current += next;
523
+ k++;
524
+ }
525
+ else if (ch === "'") {
526
+ inSQ = false;
527
+ }
528
+ continue;
529
+ }
530
+ if (inDQ) {
531
+ current += ch;
532
+ if (ch === '"' && next === '"') {
533
+ current += next;
534
+ k++;
535
+ }
536
+ else if (ch === '"') {
537
+ inDQ = false;
538
+ }
539
+ continue;
540
+ }
541
+ if (ch === "'") {
542
+ current += ch;
543
+ inSQ = true;
544
+ continue;
545
+ }
546
+ if (ch === '"') {
547
+ current += ch;
548
+ inDQ = true;
549
+ continue;
550
+ }
551
+ if (ch === '(') {
552
+ current += ch;
553
+ itemParenDepth++;
554
+ continue;
555
+ }
556
+ if (ch === ')') {
557
+ current += ch;
558
+ itemParenDepth--;
559
+ continue;
560
+ }
561
+ if (ch === ',' && itemParenDepth === 0) {
562
+ const trimmed = current.trim();
563
+ if (trimmed.length > 0) {
564
+ items.push(trimmed);
565
+ }
566
+ current = '';
567
+ continue;
568
+ }
569
+ current += ch;
570
+ }
571
+ // Add the last item
572
+ const trimmed = current.trim();
573
+ if (trimmed.length > 0) {
574
+ items.push(trimmed);
575
+ }
576
+ if (items.length === 0) {
577
+ throw new Error(':filter() requires at least one condition');
578
+ }
579
+ // Build WHERE/HAVING conditions
580
+ const obj = args;
581
+ const conditions = [];
582
+ const filterParams = [];
583
+ let hasParameterized = false;
584
+ // Helper function to expand :or(:param) patterns
585
+ const expandOr = (expr) => {
586
+ // Find all :or(:param) patterns
587
+ const orPattern = /:or\s*\(\s*:(\w+)\s*\)/gi;
588
+ const matches = [];
589
+ let match;
590
+ while ((match = orPattern.exec(expr)) !== null) {
591
+ matches.push({
592
+ fullMatch: match[0],
593
+ paramName: match[1],
594
+ index: match.index
595
+ });
596
+ }
597
+ if (matches.length === 0) {
598
+ return { condition: '', params: [] };
599
+ }
600
+ // Check if all parameters are defined
601
+ let shouldInclude = true;
602
+ const replacements = [];
603
+ for (const m of matches) {
604
+ if (!Object.prototype.hasOwnProperty.call(obj, m.paramName) || obj[m.paramName] === undefined) {
605
+ shouldInclude = false;
606
+ break;
607
+ }
608
+ const arr = obj[m.paramName];
609
+ if (!Array.isArray(arr) || arr.length === 0) {
610
+ shouldInclude = false;
611
+ break;
612
+ }
613
+ // Find the column expression for this :or() pattern
614
+ // Look backwards from the match to find the column name and operator
615
+ const beforeOr = expr.slice(0, m.index);
616
+ const afterOr = expr.slice(m.index + m.fullMatch.length);
617
+ // Try to match column name and operator pattern
618
+ // Match patterns like "col =", "col >", "col <=", "col LIKE", etc.
619
+ const beforeTrimmed = beforeOr.trim();
620
+ const operatorMatch = beforeTrimmed.match(/(\w+)\s+([=<>!]+|>=|<=|!=|<>|LIKE|IN|BETWEEN|IS(?:\s+NOT)?)\s*$/i);
621
+ if (operatorMatch) {
622
+ const colName = operatorMatch[1];
623
+ const operator = operatorMatch[2];
624
+ const parts = [];
625
+ const params = [];
626
+ for (const val of arr) {
627
+ if (val === undefined)
628
+ continue;
629
+ parts.push(`${colName} ${operator} ${placeholder(pgIndex)}`);
630
+ params.push(val);
631
+ }
632
+ if (parts.length > 0) {
633
+ // Replace the column/operator and :or() together
634
+ // Find the operator text in the original expr by searching backwards
635
+ const operatorText = operatorMatch[0];
636
+ // Find the last occurrence of this pattern before m.index
637
+ let operatorStart = -1;
638
+ for (let pos = m.index - operatorText.length; pos >= 0; pos--) {
639
+ if (expr.slice(pos, pos + operatorText.length) === operatorText) {
640
+ operatorStart = pos;
641
+ break;
642
+ }
643
+ }
644
+ if (operatorStart === -1) {
645
+ // Fallback: use m.index - operatorText.length
646
+ operatorStart = Math.max(0, m.index - operatorText.length);
647
+ }
648
+ replacements.push({
649
+ index: operatorStart,
650
+ length: m.index + m.fullMatch.length - operatorStart,
651
+ replacement: parts.join(' OR '),
652
+ params
653
+ });
654
+ }
655
+ else {
656
+ shouldInclude = false;
657
+ break;
658
+ }
659
+ }
660
+ else {
661
+ // Fallback: use the entire before/after context
662
+ const parts = [];
663
+ const params = [];
664
+ for (const val of arr) {
665
+ if (val === undefined)
666
+ continue;
667
+ parts.push(`${beforeTrimmed}${placeholder(pgIndex)}${afterOr.trim()}`);
668
+ params.push(val);
669
+ }
670
+ if (parts.length > 0) {
671
+ replacements.push({
672
+ index: m.index,
673
+ length: m.fullMatch.length,
674
+ replacement: parts.join(' OR '),
675
+ params
676
+ });
677
+ }
678
+ else {
679
+ shouldInclude = false;
680
+ break;
681
+ }
682
+ }
683
+ }
684
+ if (!shouldInclude || replacements.length === 0) {
685
+ return { condition: '', params: [] };
686
+ }
687
+ // Replace from end to start to preserve indices
688
+ let resultExpr = expr;
689
+ const allParams = [];
690
+ for (const rep of replacements.reverse()) {
691
+ const before = resultExpr.slice(0, rep.index);
692
+ const after = resultExpr.slice(rep.index + rep.length);
693
+ resultExpr = before + rep.replacement + after;
694
+ allParams.unshift(...rep.params);
695
+ }
696
+ // Check if the original expression was already wrapped in parentheses
697
+ const trimmedExpr = expr.trim();
698
+ const alreadyWrapped = trimmedExpr.startsWith('(') && trimmedExpr.endsWith(')');
699
+ const wrappedCondition = alreadyWrapped ? resultExpr : `(${resultExpr})`;
700
+ return { condition: wrappedCondition, params: allParams };
701
+ };
702
+ for (const item of items) {
703
+ const trimmed = item.trim();
704
+ // Check for :or(:param) pattern first
705
+ const orResult = expandOr(trimmed);
706
+ if (orResult.condition) {
707
+ conditions.push(orResult.condition);
708
+ filterParams.push(...orResult.params);
709
+ continue;
710
+ }
711
+ // Check if this is a simple column name (no operators, no :param)
712
+ let hasOperator = false;
713
+ let hasParam = false;
714
+ let inString = false;
715
+ let stringChar = '';
716
+ for (let k = 0; k < trimmed.length; k++) {
717
+ const ch = trimmed[k];
718
+ const next = k + 1 < trimmed.length ? trimmed[k + 1] : '';
719
+ if (!inString && (ch === "'" || ch === '"')) {
720
+ inString = true;
721
+ stringChar = ch;
722
+ }
723
+ else if (inString) {
724
+ if (ch === stringChar) {
725
+ if (next === stringChar) {
726
+ k++; // Skip escaped quote
727
+ }
728
+ else {
729
+ inString = false;
730
+ }
731
+ }
732
+ }
733
+ else {
734
+ // Check for operators (outside strings)
735
+ if ((ch === '>' || ch === '<' || ch === '=' || ch === '!') ||
736
+ (ch === 'L' && trimmed.slice(k, k + 4).toUpperCase() === 'LIKE') ||
737
+ (ch === 'I' && trimmed.slice(k, k + 2).toUpperCase() === 'IN') ||
738
+ (ch === 'B' && trimmed.slice(k, k + 7).toUpperCase() === 'BETWEEN') ||
739
+ (ch === 'I' && trimmed.slice(k, k + 2).toUpperCase() === 'IS')) {
740
+ hasOperator = true;
741
+ }
742
+ // Check for :param pattern
743
+ if (ch === ':' && next && /[a-zA-Z_]/.test(next)) {
744
+ hasParam = true;
745
+ }
746
+ }
747
+ }
748
+ if (!hasOperator && !hasParam) {
749
+ // Simple column name → equality
750
+ hasParameterized = true;
751
+ if (Object.prototype.hasOwnProperty.call(obj, trimmed) && obj[trimmed] !== undefined) {
752
+ conditions.push(`${trimmed} = ${placeholder(pgIndex)}`);
753
+ filterParams.push(obj[trimmed]);
754
+ }
755
+ }
756
+ else if (hasParam) {
757
+ // Parameterized expression → extract and bind parameters
758
+ hasParameterized = true;
759
+ // Extract all :param patterns and check if they're defined
760
+ let shouldInclude = true;
761
+ const paramMatches = [];
762
+ let searchStart = 0;
763
+ while (true) {
764
+ const paramMatch = /:([a-zA-Z_][a-zA-Z0-9_]*)/g.exec(trimmed.slice(searchStart));
765
+ if (!paramMatch)
766
+ break;
767
+ const paramName = paramMatch[1];
768
+ const fullIndex = searchStart + paramMatch.index;
769
+ paramMatches.push({ name: paramName, index: fullIndex });
770
+ if (!Object.prototype.hasOwnProperty.call(obj, paramName) || obj[paramName] === undefined) {
771
+ shouldInclude = false;
772
+ break;
773
+ }
774
+ searchStart = fullIndex + paramMatch[0].length;
775
+ }
776
+ if (shouldInclude && paramMatches.length > 0) {
777
+ // Replace :param with placeholders (from end to start to preserve indices)
778
+ let conditionExpr = trimmed;
779
+ const orderedParams = [];
780
+ for (const pm of paramMatches.reverse()) {
781
+ const paramValue = obj[pm.name];
782
+ const before = conditionExpr.slice(0, pm.index);
783
+ const after = conditionExpr.slice(pm.index + pm.name.length + 1);
784
+ // Check if this is an array parameter (for IN clauses)
785
+ if (Array.isArray(paramValue)) {
786
+ if (paramValue.length === 0) {
787
+ shouldInclude = false;
788
+ break;
789
+ }
790
+ // Expand array: replace :ids with ?, ?, ?
791
+ const placeholders = paramValue.map(() => placeholder(pgIndex)).join(', ');
792
+ conditionExpr = before + placeholders + after;
793
+ orderedParams.unshift(...paramValue);
794
+ }
795
+ else {
796
+ conditionExpr = before + placeholder(pgIndex) + after;
797
+ orderedParams.unshift(paramValue);
798
+ }
799
+ }
800
+ if (shouldInclude) {
801
+ // Add params in original order
802
+ const finalParams = [];
803
+ for (const pm of paramMatches.reverse()) {
804
+ const paramValue = obj[pm.name];
805
+ if (Array.isArray(paramValue)) {
806
+ finalParams.push(...paramValue);
807
+ }
808
+ else {
809
+ finalParams.push(paramValue);
810
+ }
811
+ }
812
+ conditions.push(conditionExpr);
813
+ filterParams.push(...finalParams);
814
+ }
815
+ }
816
+ }
817
+ else {
818
+ // Literal expression → include as-is
819
+ conditions.push(trimmed);
820
+ }
821
+ }
822
+ // Only throw error if all parameterized conditions are undefined (literals are always included)
823
+ if (hasParameterized && conditions.length === 0) {
824
+ throw new Error('All conditions in :filter() are undefined');
825
+ }
826
+ if (conditions.length === 0) {
827
+ throw new Error(':filter() requires at least one condition');
828
+ }
829
+ // Replace :filter(...) with conditions joined by AND
830
+ out.push(conditions.join(' AND '));
831
+ params.push(...filterParams);
832
+ i = filterEnd;
833
+ continue;
834
+ }
279
835
  // Attempt to parse a parameter token
280
836
  let j = i + 1;
281
837
  const start = j;