w-orm-reladb 1.1.9 → 1.1.10

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/src/cvFind.mjs CHANGED
@@ -1,14 +1,17 @@
1
1
  import Sequelize from 'sequelize'
2
+ import cvOrmFind from 'wsemi/src/cvOrmFind.mjs'
2
3
 
3
4
 
4
5
  //查詢條件(find)之轉譯, 供select與delAll共用, 令同一find於兩函數由同一SQL謂詞決定命中
5
6
  //
6
- //原select內之cvObj以lodash之each迭代並以Op[k]直譯$鍵, 有下列缺陷而不得供破壞性之delAll使用:
7
- // 1. 不支援之運算子成為鍵'undefined', 運算子物件被交給sequelize之欄位型別stringify:
8
- // FLOAT成'NaN'、INTEGER成'[object Object]'、DATE成本地今日00:00, 致靜默無命中或刪錯列
9
- // 2. 具數值length之物件被當成陣列樣迭代而丟棄全部條件(回全表)、Symbol鍵被丟棄
10
- // 3. $regex轉LIKE而未跳脫萬用字元, 欄位層$not遇運算子物件被轉為!=
11
- //本模組改以白名單轉譯, 凡不能保證語意者一律拋錯, 規則見CLAUDE_rulebook.md之R1–R6;
7
+ //分兩階段(規則見CLAUDE_rulebook.md之R11):
8
+ // 1. 形狀檢核: 第一步經wsemi之cvOrmFind依系列白名單檢核並回傳全新之null原型深複本(檢查之值即使用之值), 之後只走訪複本;
9
+ // 白名單外之運算子、非純量之值、非條件物件之find、異常結構(存取器、Symbol鍵、洞…)一律整批reject, 不靜默忽略、不改變語意、不擴大刪除範圍
10
+ // 2. 翻譯: 本模組負責後端專屬之檢核與轉譯——欄名嚴格鍵、依欄位型別檢核純量、主鍵正規化(R8)、DATE範圍與ctx.dateNoTz、
11
+ // 空集合之欄位引用($in:[]), 見R3–R5、R8
12
+ //歷史: 原select內之cvObj以lodash之each迭代並以Op[k]直譯$鍵, 不支援之運算子成為鍵'undefined'、具數值length之物件被當成陣列樣迭代而丟棄全部條件,
13
+ //不得供破壞性之delAll使用, 1.1.7起改自寫白名單; 第33項批1起形狀層改由cvOrmFind單一擁有, 本模組刪除Symbol/Op全集、$not $nor $regex $options $exists、
14
+ //RegExp值、陣列值即$in、非物件視為{}等形狀層(破壞性變更見CLAUDE_rulebook.md與README)
12
15
  //主鍵值之正規化(normPk)亦屬本模組, 供主鍵函數與主鍵欄條件共用, 規則見R8
13
16
 
14
17
 
@@ -16,8 +19,17 @@ import Sequelize from 'sequelize'
16
19
  let Op = Sequelize.Op
17
20
 
18
21
 
19
- //sequelize之運算子Symbol全集, 非其成員之Symbol會被sequelize靜默丟棄, 故一律拒收
20
- let setOp = new Set(Object.values(Op))
22
+ //形狀檢核之上限(傳給cvOrmFind): $and/$or長度999——SQLite平鋪$or/$and恰1000項即Expression tree is too large(DB錯誤), 本套件使用SQLite故下調(預設1000);
23
+ //其餘上限用預設: 邏輯巢狀深度32、$in/$nin長度10000、節點總數100000、欄名128
24
+ let optShape = { maxList: 999 }
25
+
26
+
27
+ //$and/$or清單(含同一條件物件內並列欄位之隱含AND)項數超過此值者, 遞迴二分為平衡樹再交sequelize:
28
+ //SQLite之運算式樹深度上限1000(Expression tree is too large), 平鋪之a OR b OR …為左深樹(深度隨項數線性成長), select因欄位帶表別名(`t`.`c`)而較delAll少容1項
29
+ //(實測平鋪$or: select最多998項、delAll最多999項, 999項時select報DB錯誤而delAll照常刪除, 違反select命中即delAll刪除之對象一致);
30
+ //巢狀層數亦會累加(32層 × 每層33項平鋪即超限, 外審sol F1), 另有巢狀遞迴上限(實測右深巢狀OR約830層, SQLITE_ERROR: Recursion limit);
31
+ //二分後每個清單之樹深僅約log2(項數)+3, 邏輯巢狀上限32層下全樹深度恆遠低於兩種上限, select與delAll皆可執行
32
+ let nFlat = 4
21
33
 
22
34
 
23
35
  //比較運算子, 值須為純量(null僅$eq與$ne)
@@ -31,41 +43,6 @@ let mCmp = {
31
43
  }
32
44
 
33
45
 
34
- //sequelize之Symbol運算子對應之$名稱, 令呼叫端以Symbol給條件時亦經同一檢核與轉譯
35
- let mSymCmp = new Map([
36
- [Op.eq, '$eq'],
37
- [Op.ne, '$ne'],
38
- [Op.gt, '$gt'],
39
- [Op.gte, '$gte'],
40
- [Op.lt, '$lt'],
41
- [Op.lte, '$lte'],
42
- [Op.in, '$in'],
43
- [Op.notIn, '$nin'],
44
- [Op.not, '$not'],
45
- ])
46
-
47
-
48
- //欄位層不接受之Symbol: 邏輯運算子於sequelize欄位層會提前返回而丟棄同層其他條件;
49
- //Op.values與Op.join不在sequelize之OperatorMap(各方言皆然), 欄位層遇之退回等值並把整個運算子物件交欄型stringify(DATEONLY成查詢當日、DATE成現在、INTEGER成'[object Object]')
50
- let setSymFieldNo = new Set([Op.and, Op.or, Op.values, Op.join])
51
-
52
-
53
- //sequelize以value[0]、value[1]取值之Symbol運算子, 值須為兩元素陣列(字串被逐字元取值、短陣列補NULL, NOT BETWEEN可命中全部非NULL列)
54
- let setSymBetween = new Set([Op.between, Op.notBetween])
55
-
56
-
57
- //sequelize以字串樣板(`${value}%`)插值之Symbol運算子: DATE欄之值(轉為Date後)會成為隨主機時區與語系而變之文字, 故不得用於DATE欄
58
- let setSymInterp = new Set([Op.startsWith, Op.endsWith, Op.substring])
59
-
60
-
61
- //LIKE之跳脫字元, 選用於各方言字串常值內皆無特殊意義者, 令ESCAPE子句不需依方言跳脫
62
- let cEsc = '!'
63
-
64
-
65
- //巢狀深度上限, 防循環參照與過深之條件
66
- let nDepthMax = 32
67
-
68
-
69
46
  //欄位型別分類, 以sequelize之型別類別判定(各方言之型別皆繼承之), 另以type.key補判
70
47
  //註: DataTypes.DOUBLE之key為'DOUBLE PRECISION', 只比對key會漏判而不檢型別
71
48
  let DT = Sequelize.DataTypes
@@ -158,30 +135,11 @@ function err(msg, path) {
158
135
 
159
136
 
160
137
  /**
161
- * 是否為一般物件: 原型為Object.prototype或null者
162
- * 註: 不以toString判定, 因帶Symbol.toStringTag之一般物件會被誤判為非物件, 而class實例、Object.create(proto)會被誤判為一般物件,
163
- * 其條件可能放在原型上而取不到自有鍵, 被當成{}而刪全表
164
- *
165
- * @ignore
166
- */
167
- function isPlainObj(v) {
168
- if (v === null || typeof v !== 'object') {
169
- return false
170
- }
171
- let p = Object.getPrototypeOf(v)
172
- return p === Object.prototype || p === null
173
- }
174
-
175
-
176
- /**
177
- * 恆真與恆假之謂詞, 以明確之SQL表示, 不以空條件表示
178
- * 註: sequelize會把空條件(如{}、空$and)於OR、NOT內濾除, 致恆真被當成不存在而改變語意(如$nor:[{}]成全部)
138
+ * 恆假之謂詞, 以明確之SQL表示, 不以空條件表示
139
+ * 註: sequelize會把空條件於OR、NOT內濾除而改變語意; 本模組僅用於$in:[]之f IS NULL AND 1 = 0(仍引用欄位, 見R5)
179
140
  *
180
141
  * @ignore
181
142
  */
182
- function sqlTrue() {
183
- return Sequelize.literal('1 = 1')
184
- }
185
143
  function sqlFalse() {
186
144
  return Sequelize.literal('1 = 0')
187
145
  }
@@ -536,43 +494,31 @@ function normPk(v, kind, scale = null) {
536
494
  return { kind: 'invalid' }
537
495
  }
538
496
 
539
-
540
497
  /**
541
- * 檢核純量值: 字串、有限數值、布林、有效Date、Buffer, 以及允許時之null; 並須符合欄位型別分類
542
- * 註: 物件、陣列等不得交sequelize之型別stringify, 否則FLOAT成'NaN'、INTEGER成'[object Object]'、DATE成本地今日00:00而誤刪
498
+ * 檢核純量值: 字串、有限數值、布林、有效Date, 以及null(是否允許null已由cvOrmFind依運算子判定); 並須符合欄位型別分類
499
+ * 註: 物件、陣列等不得交sequelize之型別stringify, 否則FLOAT成'NaN'、INTEGER成'[object Object]'、DATE成本地今日00:00而誤刪;
500
+ * 形狀層(cvOrmFind)已保證僅此類值到達, 此處保留型別檢核作為fail-closed之防線(日後上游放寬時不得靜默放行)
543
501
  * 註: 主鍵欄(pk為true)之字串類、整數類與其他數值類以normPk正規化後回傳(如字串類主鍵欄之123即'123'), 無效或型別不符者拒收,
544
502
  * 令select與delAll對主鍵之認定與selectByPk、del等主鍵函數一致; 非主鍵欄不轉型
545
503
  * 註: kind為date且呼叫端以ctx.dateNoTz明示'local'(dateNoTz為'local')時, 無時區日期時間字串依主機時區轉為Date回傳(見parseNoTzLocal), 其餘值照舊判定
546
504
  *
547
505
  * @ignore
548
506
  */
549
- function chkScalar(v, path, allowNull, kind = 'any', scale = null, pk = false, dateNoTz = undefined) {
507
+ function chkScalar(v, path, kind = 'any', scale = null, pk = false, dateNoTz = undefined) {
550
508
  if (v === null) {
551
- if (allowNull) {
552
- return v
553
- }
554
- err('null is not allowed here', path)
555
- }
556
- let ok = false
557
- if (typeof v === 'string' || typeof v === 'boolean') {
558
- ok = true
509
+ return v
559
510
  }
560
- else if (typeof v === 'number') {
511
+ if (typeof v === 'number') {
561
512
  if (!Number.isFinite(v)) {
562
513
  err(`number must be finite, got [${v}]`, path)
563
514
  }
564
- ok = true
565
515
  }
566
516
  else if (v instanceof Date) {
567
517
  if (isNaN(v.getTime())) {
568
518
  err('invalid Date', path)
569
519
  }
570
- ok = true
571
520
  }
572
- else if (Buffer.isBuffer(v)) {
573
- ok = kind === 'any'
574
- }
575
- if (!ok) {
521
+ else if (typeof v !== 'string' && typeof v !== 'boolean') {
576
522
  err(`value must be a string, finite number, boolean, Date or null, got [${Object.prototype.toString.call(v)}]`, path)
577
523
  }
578
524
  if (pk && (kind === 'str' || kind === 'int' || kind === 'num')) {
@@ -602,398 +548,181 @@ function chkScalar(v, path, allowNull, kind = 'any', scale = null, pk = false, d
602
548
 
603
549
 
604
550
  /**
605
- * 取陣列之各元素, 稀疏陣列之洞與undefined一律拒收
606
- * 註: forEach與map會略過洞, 洞若被略過則$and之子式消失而成恆真
607
- *
608
- * @ignore
609
- */
610
- function getItems(arr, path) {
611
- let rs = []
612
- for (let i = 0; i < arr.length; i++) {
613
- if (!(i in arr) || arr[i] === undefined) {
614
- err('array must not contain holes or undefined', `${path}.${i}`)
615
- }
616
- rs.push(arr[i])
617
- }
618
- return rs
619
- }
620
-
621
-
622
- /**
623
- * 檢核sequelize原生Symbol運算子之值: 純量、純量陣列或sequelize之literal/fn/col
624
- * 註: 原生寫法由呼叫端自負語意, 但仍不得把物件交sequelize之型別stringify
625
- *
626
- * @ignore
627
- */
628
- function chkRawSym(x, path, kind, scale, pk, dateNoTz) {
629
- if (x instanceof Sequelize.Utils.SequelizeMethod) {
630
- return x
631
- }
632
- if (Array.isArray(x)) {
633
- return getItems(x, path).map((y, i) => (y instanceof Sequelize.Utils.SequelizeMethod ? y : chkScalar(y, `${path}.${i}`, true, kind, scale, pk, dateNoTz)))
634
- }
635
- return chkScalar(x, path, true, kind, scale, pk, dateNoTz)
636
- }
637
-
638
-
639
- /**
640
- * 將正規式來源轉為字面字串, 僅接受無未跳脫元字元者
641
- *
642
- * @ignore
643
- */
644
- function regexToLiteral(src, path) {
645
- let r = ''
646
- let meta = '\\^$.|?*+()[]{}/'
647
- for (let i = 0; i < src.length; i++) {
648
- let c = src[i]
649
- if (c === '\\') {
650
- let n = src[i + 1]
651
- if (n !== undefined && meta.indexOf(n) >= 0) {
652
- r += n
653
- i++
654
- continue
655
- }
656
- err(`$regex supports literal substrings only, escape [\\${n === undefined ? '' : n}] is not supported`, path)
657
- }
658
- if (meta.indexOf(c) >= 0) {
659
- err(`$regex supports literal substrings only, unescaped metacharacter [${c}] is not supported`, path)
660
- }
661
- r += c
662
- }
663
- if (r.indexOf('\u0000') >= 0) {
664
- err('$regex must not contain NUL', path)
665
- }
666
- return r
667
- }
668
-
669
-
670
- /**
671
- * 正規化正規式旗標, 僅接受i; '$i'為既有寫法, 過渡期視同i
672
- *
673
- * @ignore
674
- */
675
- function normFlags(fs, path) {
676
- if (fs === undefined || fs === null || fs === '') {
677
- return false
678
- }
679
- if (typeof fs !== 'string') {
680
- err('$options must be a string', path)
681
- }
682
- let s = fs === '$i' ? 'i' : fs
683
- for (let c of s) {
684
- if (c !== 'i') {
685
- err(`$options/flags supports [i] only, got [${fs}]`, path)
686
- }
687
- }
688
- return s.indexOf('i') >= 0
689
- }
690
-
691
-
692
- /**
693
- * 產生LIKE子字串條件, 跳脫萬用字元並帶ESCAPE子句; 不分大小寫時兩側皆以LOWER處理
694
- * 註: sqlite之LOWER只折疊ASCII, 故sqlite下給i而字面含非ASCII之大小寫字母者拒收, 不宣稱做不到之語意
695
- *
696
- * @ignore
697
- */
698
- function cvRegex(field, col, re, options, path, ctx, kind) {
699
- if (kind !== 'str' && kind !== 'any') {
700
- err(`$regex requires a string column, column type is [${kind}]`, path)
701
- }
702
- let src
703
- let ci
704
- if (re instanceof RegExp) {
705
- if (options !== undefined) {
706
- err('$options can not be used with a RegExp $regex', path)
707
- }
708
- let flags = re.flags.replace(/[gu]/g, '') //g、u不影響是否命中
709
- src = re.source === '(?:)' ? '' : re.source //new RegExp('')之source為(?:), 即空字串
710
- ci = normFlags(flags, path)
711
- }
712
- else if (typeof re === 'string') {
713
- src = re
714
- ci = normFlags(options, path)
715
- }
716
- else {
717
- err('$regex must be a string or RegExp', path)
718
- }
719
- let lit = regexToLiteral(src, path)
720
- if (ci && col[0] === '*') {
721
- //sequelize之Col遇以*開頭之名稱一律回傳*, LOWER(col)成LOWER(*)
722
- err(`unsupported column name [${col}], it can not be used with $regex and i`, path)
723
- }
724
- if (ci && ctx.dialect === 'sqlite') {
725
- for (let c of lit) {
726
- if (c.charCodeAt(0) > 127 && c.toLowerCase() !== c.toUpperCase()) {
727
- err(`$regex with i supports ASCII letters only on sqlite, got [${c}]`, path)
728
- }
729
- }
730
- }
731
- let pat = `%${lit.replace(/[!%_[]/g, (c) => `${cEsc}${c}`)}%`
732
- let q = ctx.escape(pat)
733
- if (ci) {
734
- //LOWER內須為資料庫之實際欄名col, model之屬性名與欄名可不同(欄名已由resolveAttr核對可安全交sequelize)
735
- return Sequelize.where(Sequelize.fn('LOWER', Sequelize.col(col)), Op.like, Sequelize.literal(`LOWER(${q}) ESCAPE '${cEsc}'`))
736
- }
737
- return { [field]: { [Op.like]: Sequelize.literal(`${q} ESCAPE '${cEsc}'`) } }
738
- }
739
-
740
-
741
- /**
742
- * $in與$nin, 含null者另以IS [NOT] NULL補上, 與{欄位:null}一致; 空集合以恆假/恆真表示
551
+ * $in與$nin, 元素為純量(不含null, 已由cvOrmFind保證); 空$in以引用欄位之恆假表示
552
+ * 註: $nin:[]已由cvOrmFind拒收(恆真, 易因清單恰為空而刪全表); 此處再擋以免上游放寬時靜默放行
743
553
  *
744
554
  * @ignore
745
555
  */
746
556
  function cvIn(field, arr, path, neg, kind, scale, pk, dateNoTz) {
747
- if (!Array.isArray(arr)) {
748
- err(`${neg ? '$nin' : '$in'} must be an array`, path)
749
- }
750
- let hasNull = false
751
557
  let vs = []
752
- getItems(arr, path).forEach((v, k) => {
753
- if (v === null) {
754
- hasNull = true
755
- return
558
+ for (let i = 0; i < arr.length; i++) {
559
+ if (arr[i] === null) {
560
+ err('null is not allowed here', `${path}[${i}]`)
756
561
  }
757
- vs.push(chkScalar(v, `${path}.${k}`, false, kind, scale, pk, dateNoTz))
758
- })
562
+ vs.push(chkScalar(arr[i], `${path}[${i}]`, kind, scale, pk, dateNoTz))
563
+ }
759
564
  if (!neg) {
760
565
  if (vs.length === 0) {
761
- return hasNull ? { [field]: null } : { [Op.and]: [{ [field]: null }, sqlFalse()] }
566
+ //f IS NULL恆為二值(永不為UNKNOWN), 整式二值, 且欄名會出現在SQL中, 不存在之欄由資料庫回報(R5)
567
+ return { [Op.and]: [{ [field]: null }, sqlFalse()] }
762
568
  }
763
- let c = { [field]: { [Op.in]: vs } }
764
- return hasNull ? { [Op.or]: [c, { [field]: null }] } : c
569
+ return { [field]: { [Op.in]: vs } }
765
570
  }
766
571
  if (vs.length === 0) {
767
- return hasNull ? { [field]: { [Op.ne]: null } } : { [Op.or]: [{ [field]: null }, sqlTrue()] }
572
+ err('$nin with empty array is always true', path)
768
573
  }
769
- let c = { [field]: { [Op.notIn]: vs } }
770
- return hasNull ? { [Op.and]: [c, { [field]: { [Op.ne]: null } }] } : c
574
+ return { [field]: { [Op.notIn]: vs } }
771
575
  }
772
576
 
773
577
 
774
578
  /**
775
- * 欄位層條件, 回傳以AND結合之子式陣列
579
+ * 欄位層條件, 回傳以AND結合之子式陣列; v為純量、null、Date(等值)或運算子物件(null原型, 鍵為$eq $ne $gt $gte $lt $lte $in $nin)
776
580
  *
777
581
  * @ignore
778
582
  */
779
- function cvField(field, v, path, depth, ctx) {
780
- if (depth > nDepthMax) {
781
- err('find is too deep', path)
782
- }
783
- if (field === '' || field === '__proto__') {
784
- err(`invalid column name [${field}]`, path)
785
- }
786
- if (v === undefined) {
787
- err('value is undefined', path)
788
- }
583
+ function cvField(field, v, path, ctx) {
789
584
 
790
585
  //欄名先解析為model之屬性名再判型別與主鍵(R4欄名解析); attrs已給而解析不到者拒收, attrs未給者為any, 交資料庫處置
791
586
  let an = resolveAttr(ctx.attrs, ctx.attrIdx, field, path)
792
- let col = an === null ? field : colOf(ctx.attrs, an) //資料庫實際欄名
793
587
  let kind = an === null ? 'any' : getColKind(ctx.attrs, an)
794
588
  let scale = an === null ? null : getColScale(ctx.attrs, an)
795
589
  let pk = ctx.pk !== undefined && an === ctx.pk //主鍵欄之純量依normPk正規化(R8)
796
590
  let dateNoTz = ctx.dateNoTz
797
- if (Array.isArray(v)) {
798
- //陣列值即$in(含null與空陣列之處置), 與MongoDB之陣列比對不同, 已文件化
799
- return [cvIn(field, v, path, false, kind, scale, pk, dateNoTz)]
800
- }
801
- if (v instanceof RegExp) {
802
- return [cvRegex(field, col, v, undefined, path, ctx, kind)]
803
- }
804
- if (!isPlainObj(v)) {
805
- return [{ [field]: chkScalar(v, path, true, kind, scale, pk, dateNoTz) }]
806
- }
807
- let ks = Reflect.ownKeys(v)
808
- if (ks.length === 0) {
809
- err('empty operator object', path)
591
+
592
+ //欄位直給(等值)
593
+ if (v === null || typeof v !== 'object' || v instanceof Date) {
594
+ return [{ [field]: chkScalar(v, path, kind, scale, pk, dateNoTz) }]
810
595
  }
596
+
597
+ //運算子物件
811
598
  let simple = {}
812
599
  let nSimple = 0
813
600
  let cs = []
814
- let hasRegex = false
815
- for (let k of ks) {
816
- let kp = `${path}.${String(k)}`
601
+ for (let k of Object.keys(v)) {
602
+ let kp = `${path}.${k}`
817
603
  let x = v[k]
818
- let name = k
819
- if (typeof k === 'symbol') {
820
- if (!setOp.has(k) || setSymFieldNo.has(k)) {
821
- err(`unsupported symbol operator [${String(k)}]`, kp)
822
- }
823
- name = mSymCmp.get(k)
824
- if (name === undefined) {
825
- if (kind === 'date' && setSymInterp.has(k)) {
826
- err(`operator [${String(k)}] is not supported on a date column`, kp)
827
- }
828
- if (setSymBetween.has(k)) {
829
- //值須為兩元素陣列, 元素為純量(不含null)或sequelize之方法物件
830
- if (!Array.isArray(x) || x.length !== 2) {
831
- err(`${String(k)} requires an array of two values`, kp)
832
- }
833
- cs.push({ [field]: { [k]: getItems(x, kp).map((y, i) => (y instanceof Sequelize.Utils.SequelizeMethod ? y : chkScalar(y, `${kp}.${i}`, false, kind, scale, pk, dateNoTz))) } })
834
- continue
835
- }
836
- //其餘sequelize之Symbol運算子為呼叫端自負之原生寫法, 值經檢核後各自成一子式
837
- cs.push({ [field]: { [k]: chkRawSym(x, kp, kind, scale, pk, dateNoTz) } })
838
- continue
839
- }
840
- }
841
- if (typeof name !== 'string' || name[0] !== '$') {
842
- err('nested object is not supported, operators must start with $', kp)
843
- }
844
- if (mCmp[name] !== undefined) {
845
- let allowNull = name === '$eq' || name === '$ne'
846
- let y = chkScalar(x, kp, allowNull, kind, scale, pk, dateNoTz)
847
- if (Object.prototype.hasOwnProperty.call(simple, mCmp[name])) {
848
- //同義之鍵(如$gt與Op.gt)各自成一子式, 不得互相覆寫
849
- cs.push({ [field]: { [mCmp[name]]: y } })
850
- }
851
- else {
852
- simple[mCmp[name]] = y
853
- nSimple++
854
- }
855
- }
856
- else if (name === '$in' || name === '$nin') {
857
- cs.push(cvIn(field, x, kp, name === '$nin', kind, scale, pk, dateNoTz))
858
- }
859
- else if (name === '$exists') {
860
- if (x !== true && x !== false && x !== 0 && x !== 1) {
861
- err('$exists must be a boolean, 0 or 1', kp)
604
+ if (k === '$in' || k === '$nin') {
605
+ if (!Array.isArray(x)) {
606
+ err(`${k} must be an array`, kp)
862
607
  }
863
- cs.push(x ? { [field]: { [Op.ne]: null } } : { [field]: null })
608
+ cs.push(cvIn(field, x, kp, k === '$nin', kind, scale, pk, dateNoTz))
864
609
  }
865
- else if (name === '$regex') {
866
- hasRegex = true
867
- cs.push(cvRegex(field, col, x, v.$options, kp, ctx, kind))
868
- }
869
- else if (name === '$options') {
870
- //由$regex一併處理
871
- }
872
- else if (name === '$not') {
873
- if (Array.isArray(x)) {
874
- err('$not does not accept an array', kp)
875
- }
876
- let ns = cvField(field, x, kp, depth + 1, ctx)
877
- cs.push({ [Op.not]: { [Op.and]: ns } })
610
+ else if (Object.prototype.hasOwnProperty.call(mCmp, k)) {
611
+ //同欄之比較運算子併入同一欄位物件, 以AND結合
612
+ simple[mCmp[k]] = chkScalar(x, kp, kind, scale, pk, dateNoTz)
613
+ nSimple++
878
614
  }
879
615
  else {
880
- err(`unsupported operator [${name}]`, kp)
616
+ err(`unsupported operator [${k}]`, kp)
881
617
  }
882
618
  }
883
- if (v.$options !== undefined && !hasRegex) {
884
- err('$options requires $regex', path)
885
- }
886
- if (cs.length === 0 && nSimple === 0) {
887
- //如僅有值為undefined之$options: 不產生任何子式, 該條件即消失而成恆真, delAll會刪全表
888
- err('operator object has no operator', path)
889
- }
890
619
  if (nSimple > 0) {
891
620
  cs.unshift({ [field]: simple })
892
621
  }
622
+ if (cs.length === 0) {
623
+ //不產生任何子式者條件即消失而成恆真, delAll會刪全表; cvOrmFind已拒收空運算子物件, 此處再擋(含非Date之物件值)
624
+ err('operator object has no operator', path)
625
+ }
893
626
  return cs
894
627
  }
895
628
 
896
629
 
897
630
  /**
898
- * 文件層條件(含頂層邏輯運算子)
631
+ * 文件層條件(含$and、$or), o為cvOrmFind之複本(null原型, 鍵僅字串)
899
632
  *
900
633
  * @ignore
901
634
  */
902
- function cvDoc(o, path, depth, ctx) {
903
- if (depth > nDepthMax) {
904
- err('find is too deep', path)
905
- }
906
- if (!isPlainObj(o)) {
907
- err('condition must be an object', path)
908
- }
909
- let cvList = (x, kp) => {
910
- if (!Array.isArray(x)) {
911
- err('logical operator requires an array', kp)
912
- }
913
- //空陣列拒收(同MongoDB), 以免呼叫端之條件清單恰為空時成為恆真而刪全表
914
- if (x.length === 0) {
915
- err('logical operator requires a nonempty array', kp)
916
- }
917
- return getItems(x, kp).map((y, i) => cvDoc(y, `${kp}.${i}`, depth + 1, ctx))
918
- }
635
+ function cvDoc(o, path, ctx) {
919
636
  let cs = []
920
- for (let k of Reflect.ownKeys(o)) {
637
+ for (let k of Object.keys(o)) {
921
638
  let x = o[k]
922
- let kp = path ? `${path}.${String(k)}` : String(k)
923
- if (typeof k === 'symbol') {
924
- if (k === Op.and) {
925
- cs.push(cvAnd(cvList(x, kp)))
639
+ let kp = `${path}.${k}`
640
+ if (k === '$and' || k === '$or') {
641
+ if (!Array.isArray(x) || x.length === 0) {
642
+ err(`${k} requires a nonempty array`, kp)
926
643
  }
927
- else if (k === Op.or) {
928
- cs.push(cvOr(cvList(x, kp)))
644
+ let sub = []
645
+ for (let i = 0; i < x.length; i++) {
646
+ sub.push(cvDoc(x[i], `${kp}[${i}]`, ctx))
929
647
  }
930
- else if (k === Op.not) {
931
- cs.push({ [Op.not]: cvDoc(x, kp, depth + 1, ctx) })
932
- }
933
- else {
934
- err(`unsupported symbol operator at document level [${String(k)}]`, kp)
935
- }
936
- continue
648
+ cs.push(cvGroup(k === '$and' ? cvAnd : cvOr, sub))
937
649
  }
938
- if (k[0] === '$') {
939
- if (k === '$and') {
940
- cs.push(cvAnd(cvList(x, kp)))
941
- }
942
- else if (k === '$or') {
943
- cs.push(cvOr(cvList(x, kp)))
944
- }
945
- else if (k === '$nor') {
946
- cs.push({ [Op.not]: cvOr(cvList(x, kp)) })
947
- }
948
- else {
949
- err(`unsupported operator [${k}]`, kp)
950
- }
951
- continue
650
+ else if (k[0] === '$') {
651
+ err(`unsupported operator [${k}]`, kp)
652
+ }
653
+ else {
654
+ cs.push(...cvField(k, x, kp, ctx))
952
655
  }
953
- cs.push(...cvField(k, x, kp, depth + 1, ctx))
954
656
  }
955
- return cvAnd(cs)
657
+ if (cs.length === 0) {
658
+ err('empty condition', path)
659
+ }
660
+ return cvGroup(cvAnd, cs)
956
661
  }
957
662
 
958
663
 
959
664
  /**
960
- * 以AND結合子式, 無子式者為恆真
665
+ * 以AND結合子式
961
666
  *
962
667
  * @ignore
963
668
  */
964
669
  function cvAnd(cs) {
965
- if (cs.length === 0) {
966
- return { [Op.and]: [sqlTrue()] }
967
- }
968
670
  return { [Op.and]: cs }
969
671
  }
970
672
 
971
673
 
972
674
  /**
973
- * 以OR結合子式, 無子式者為恆假
675
+ * 以OR結合子式
974
676
  *
975
677
  * @ignore
976
678
  */
977
679
  function cvOr(cs) {
978
- if (cs.length === 0) {
979
- return { [Op.and]: [sqlFalse()] }
980
- }
981
680
  return { [Op.or]: cs }
982
681
  }
983
682
 
984
683
 
684
+ /**
685
+ * 子式過多者遞迴二分為平衡樹, 避免SQLite之運算式樹深度與遞迴上限(見nFlat); 語意不變(AND與OR皆滿足結合律, 含NULL之三值邏輯), 子式順序不變
686
+ *
687
+ * @ignore
688
+ */
689
+ function cvGroup(fn, cs) {
690
+ if (cs.length <= nFlat) {
691
+ return fn(cs)
692
+ }
693
+ let k = Math.ceil(cs.length / 2)
694
+ return fn([cvGroup(fn, cs.slice(0, k)), cvGroup(fn, cs.slice(k))])
695
+ }
696
+
697
+
698
+ /**
699
+ * 檢核find之形狀(系列白名單, 由wsemi之cvOrmFind單一擁有, 規則見R11)並回傳全新之null原型深複本, 後續一律只使用複本(檢查之值即使用之值)
700
+ * 註: 未給/undefined/{}回傳空物件(全部); 其餘非條件物件、白名單外之運算子與值、異常結構一律throw Error('invalid find: 原因 at [路徑]')
701
+ * 註: maxList傳999(SQLite之運算式樹深度上限); select與delAll於載入model與建立sequelize實例之前先呼叫本函數, 使形狀不合法者不連線、不送出任何SQL
702
+ * 註: 對複本再呼叫為冪等(複本本身符合白名單)
703
+ *
704
+ * @ignore
705
+ * @param {*} find 輸入查詢條件
706
+ * @returns {Object} 回傳null原型之條件複本, 無自有鍵代表全部
707
+ */
708
+ function chkFindShape(find) {
709
+ return cvOrmFind(find, optShape)
710
+ }
711
+
712
+
985
713
  /**
986
714
  * 將查詢條件轉為sequelize之where, 供select與delAll共用, 令同一find於兩函數由同一SQL謂詞決定命中
987
715
  *
988
- * 註: 支援欄位等值與$eq、$ne、$gt、$gte、$lt、$lte、$in、$nin、$not、$regex($options僅i)、$exists, 以及$and、$or、$nor
989
- * 註: 不支援之運算子、非純量之值、與欄位型別不符之純量一律拋錯, 不得交sequelize之型別stringify(見本檔之chkScalar)
990
- * 註: NULL依SQL三值邏輯; $regex僅支援字面子字串; 非物件之find回{}(即全部), 此為現況保留
716
+ * 註: 第一步經chkFindShape(wsemi之cvOrmFind)依系列白名單檢核並取複本, 其後只走訪複本; 白名單: 欄位等值{欄:純量|null}、
717
+ * $eq $ne $gt $gte $lt $lte(純量)、$in $nin(純量陣列)、$and $or(條件物件之非空陣列); 其餘(含$not $nor $regex $options $exists、RegExp、Symbol鍵、陣列值)一律拋錯
718
+ * 註: 未給、undefined或{}回傳{}(全部); 其餘非條件物件(null、陣列、字串、數值等)拋錯, 不再視為{}
719
+ * 註: 與欄位型別不符之純量、不存在之欄一律拋錯, 不得交sequelize之型別stringify(見本檔之chkScalar); NULL依SQL三值邏輯
991
720
  *
992
721
  * @param {*} find 輸入查詢條件
993
722
  * @param {Object} ctx 輸入轉換所需之依賴物件
994
- * @param {Function} ctx.escape 輸入依方言將字串轉為SQL字串常值之函數, 通常為sequelize實例之escape
723
+ * @param {Function} [ctx.escape] 已不使用(原供$regex之LIKE字面常值; 第33項批1移除$regex), 保留接受以相容既有呼叫端
995
724
  * @param {Object} [ctx.attrs] 輸入執行where之model之rawAttributes, 供欄名解析(嚴格鍵: 鍵須與屬性名或資料庫欄名完全相符, 其餘拒收)、依欄位型別檢核純量與取得實際欄名; 未給時不解析鍵、不檢型別而交資料庫(見CLAUDE_rulebook.md之R4)
996
- * @param {String} [ctx.dialect] 輸入資料庫種類字串, 供判定方言能力(如sqlite之LOWER僅折疊ASCII)
725
+ * @param {String} [ctx.dialect] 已不使用(原供判定sqlite之LOWER僅折疊ASCII), 保留接受以相容既有呼叫端
997
726
  * @param {String} [ctx.pk] 輸入主鍵欄位名, 該欄之純量條件值依normPk正規化(如字串類主鍵欄之123即'123'), 未給時不正規化
998
727
  * @param {String} [ctx.dateNoTz] 輸入無時區日期時間字串之處置, 僅接受undefined(預設, 無時區者拒收)或'local'(依主機時區解析, 與以本地時間分量建構之Date同義), 其餘值拋錯; 僅作用於DATE欄, 供Jet等無時區後端之呼叫端明示啟用
999
728
  * @returns {Object} 回傳sequelize之where物件, 條件不合法時拋出錯誤
@@ -1005,18 +734,11 @@ function cvFind(find, ctx) {
1005
734
  throw new Error(`invalid ctx: dateNoTz must be 'local' or undefined, got [${String(ctx.dateNoTz)}]`)
1006
735
  }
1007
736
 
1008
- //check, 非物件(undefined、null、字串、數值等純量)與陣列視為未給條件, 此為現況保留, 系列規格另案處理
1009
- if (find === null || typeof find !== 'object' || Array.isArray(find)) {
1010
- return {}
1011
- }
1012
-
1013
- //check, 非一般物件(class實例、Object.create(proto)、Date、Map等)之條件可能不在自有鍵上, 拒收而不當成{}
1014
- if (!isPlainObj(find)) {
1015
- err('find must be a plain object')
1016
- }
737
+ //step1, 形狀檢核(R11), 其後一律只使用複本
738
+ let fd = chkFindShape(find)
1017
739
 
1018
740
  //check, 空物件為全部
1019
- if (Reflect.ownKeys(find).length === 0) {
741
+ if (Reflect.ownKeys(fd).length === 0) {
1020
742
  return {}
1021
743
  }
1022
744
 
@@ -1026,9 +748,9 @@ function cvFind(find, ctx) {
1026
748
  }
1027
749
 
1028
750
  //attrs之索引每次轉譯只建一次(內部欄位attrIdx, 不屬ctx之介面)
1029
- return cvDoc(find, '', 0, ctx && ctx.attrs ? { ...ctx, attrIdx: buildAttrIdx(ctx.attrs) } : ctx)
751
+ return cvDoc(fd, 'find', ctx && ctx.attrs ? { ...ctx, attrIdx: buildAttrIdx(ctx.attrs) } : ctx)
1030
752
  }
1031
753
 
1032
754
 
1033
- export { getColKind, getColScale, normPk }
755
+ export { getColKind, getColScale, normPk, chkFindShape }
1034
756
  export default cvFind