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