typenative 0.7.0 → 0.7.1

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.
Files changed (217) hide show
  1. package/bin/node/assert.js +2 -2
  2. package/bin/node/child_process.js +66 -8
  3. package/bin/node/fs.js +1012 -4
  4. package/bin/node/histogram.js +1991 -0
  5. package/bin/node/process.js +14 -2
  6. package/bin/node/sqlite.js +1488 -5
  7. package/bin/node/stream.js +2 -1
  8. package/bin/node/system_extra.js +3 -270
  9. package/bin/node/test.js +39 -1
  10. package/bin/node/test_report.js +47 -1
  11. package/bin/node/test_run.js +57 -2
  12. package/bin/node/util.js +8 -5
  13. package/bin/node/webassembly.js +20 -5
  14. package/bin/node/webview.js +3257 -244
  15. package/bin/node/zlib.js +118 -14
  16. package/bin/node/zlib_iter.js +585 -0
  17. package/bin/transpiler.js +1370 -258
  18. package/bin/version.js +1 -1
  19. package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
  20. package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
  21. package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
  22. package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
  23. package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
  24. package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
  25. package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
  26. package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
  27. package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
  28. package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
  29. package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
  30. package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
  31. package/package.json +10 -1
  32. package/types/tsconfig.json +17 -0
  33. package/types/typenative-npm.d.ts +492 -12
  34. package/types/typenative.d.ts +88 -2
  35. package/.gitattributes +0 -1
  36. package/.github/workflows/ci.yml +0 -68
  37. package/.github/workflows/npm-publish-github-packages.yml +0 -88
  38. package/CHANGELOG.md +0 -1746
  39. package/CONTRIBUTION.md +0 -133
  40. package/conformance.md +0 -1497
  41. package/examples/README.md +0 -114
  42. package/examples/angular-templates/README.md +0 -141
  43. package/examples/angular-templates/bench.mjs +0 -173
  44. package/examples/angular-templates/dom-type-globals.d.ts +0 -21
  45. package/examples/angular-templates/dom-type-stubs.ts +0 -21
  46. package/examples/angular-templates/main.ts +0 -135
  47. package/examples/angular-templates/parity.mjs +0 -157
  48. package/examples/angular-templates/run-node.mjs +0 -69
  49. package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
  50. package/examples/desktop-notes/README.md +0 -106
  51. package/examples/desktop-notes/bench.mjs +0 -125
  52. package/examples/desktop-notes/main.ts +0 -131
  53. package/examples/desktop-notes/package-lock.json +0 -726
  54. package/examples/desktop-notes/package.json +0 -9
  55. package/examples/desktop-notes/ui.ts +0 -176
  56. package/examples/dupe-finder/README.md +0 -78
  57. package/examples/dupe-finder/bench.mjs +0 -120
  58. package/examples/dupe-finder/main.ts +0 -87
  59. package/examples/fibonacci/README.md +0 -89
  60. package/examples/fibonacci/bench.mjs +0 -87
  61. package/examples/fibonacci/main.ts +0 -21
  62. package/examples/hello-world/README.md +0 -62
  63. package/examples/hello-world/bench.mjs +0 -66
  64. package/examples/hello-world/main.ts +0 -7
  65. package/examples/json-server/README.md +0 -132
  66. package/examples/json-server/bench.mjs +0 -263
  67. package/examples/json-server/main.ts +0 -67
  68. package/examples/mandelbrot-png/README.md +0 -63
  69. package/examples/mandelbrot-png/bench.mjs +0 -95
  70. package/examples/mandelbrot-png/main.ts +0 -98
  71. package/examples/mandelbrot-png/preview.png +0 -0
  72. package/examples/marked-cli/README.md +0 -174
  73. package/examples/marked-cli/bench.mjs +0 -178
  74. package/examples/marked-cli/main.ts +0 -410
  75. package/examples/marked-cli/parity.mjs +0 -185
  76. package/examples/marked-cli/vendor/marked/LICENSE +0 -44
  77. package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
  78. package/examples/openai-chat/README.md +0 -148
  79. package/examples/openai-chat/bench.mjs +0 -175
  80. package/examples/openai-chat/main.ts +0 -488
  81. package/examples/react-compiler/README.md +0 -185
  82. package/examples/react-compiler/bench.mjs +0 -181
  83. package/examples/react-compiler/main.ts +0 -324
  84. package/examples/react-compiler/parity.mjs +0 -362
  85. package/examples/react-compiler/run-node.mjs +0 -90
  86. package/examples/react-compiler/vendor/babel/LICENSE +0 -22
  87. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
  88. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
  89. package/examples/react-compiler/vendor/charcodes/package.json +0 -25
  90. package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
  91. package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
  92. package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
  93. package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
  94. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
  95. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
  96. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
  97. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
  98. package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
  99. package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
  100. package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
  101. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
  102. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
  103. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
  104. package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
  105. package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
  106. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
  107. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
  108. package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
  109. package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
  110. package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
  111. package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
  112. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
  113. package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
  114. package/examples/react-compiler/vendor/zod/LICENSE +0 -21
  115. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
  116. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
  117. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
  118. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
  119. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
  120. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
  121. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
  122. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
  123. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
  124. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
  125. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
  126. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
  127. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
  128. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
  129. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
  130. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
  131. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
  132. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
  133. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
  134. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
  135. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
  136. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
  137. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
  138. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
  139. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
  140. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
  141. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
  142. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
  143. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
  144. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
  145. package/examples/react-compiler/vendor.mjs +0 -688
  146. package/examples/todo-cli/README.md +0 -69
  147. package/examples/todo-cli/bench.mjs +0 -89
  148. package/examples/todo-cli/main.ts +0 -92
  149. package/examples/yaml-cli/README.md +0 -152
  150. package/examples/yaml-cli/bench.mjs +0 -265
  151. package/examples/yaml-cli/main.ts +0 -251
  152. package/examples/yaml-cli/parity.mjs +0 -156
  153. package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
  154. package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
  155. package/performance/README.md +0 -248
  156. package/performance/any-dynamic.ts +0 -21
  157. package/performance/any-record-view.ts +0 -20
  158. package/performance/arr-for-of.ts +0 -29
  159. package/performance/arr-hof.ts +0 -21
  160. package/performance/arr-push-index.ts +0 -15
  161. package/performance/arr-push-local.ts +0 -39
  162. package/performance/arr-slice-concat.ts +0 -24
  163. package/performance/arr-sort.ts +0 -21
  164. package/performance/async-await.ts +0 -24
  165. package/performance/async-promise-all.ts +0 -38
  166. package/performance/bigint-arith.ts +0 -36
  167. package/performance/buf-encode.ts +0 -29
  168. package/performance/class-accessors.ts +0 -48
  169. package/performance/class-dispatch.ts +0 -52
  170. package/performance/date-format.ts +0 -18
  171. package/performance/events-emit.ts +0 -27
  172. package/performance/exc-throw-rare.ts +0 -25
  173. package/performance/exc-try-catch.ts +0 -26
  174. package/performance/fn-closures.ts +0 -29
  175. package/performance/fn-recursion-tree.ts +0 -31
  176. package/performance/fn-rest-spread.ts +0 -43
  177. package/performance/gen-for-of.ts +0 -46
  178. package/performance/gen-next.ts +0 -32
  179. package/performance/iter-helpers.ts +0 -38
  180. package/performance/json-any.ts +0 -30
  181. package/performance/json-roundtrip.ts +0 -27
  182. package/performance/map-delete.ts +0 -24
  183. package/performance/map-iterate.ts +0 -26
  184. package/performance/map-number-keys.ts +0 -37
  185. package/performance/map-string-keys.ts +0 -22
  186. package/performance/num-arith-loop.ts +0 -14
  187. package/performance/num-bitwise.ts +0 -21
  188. package/performance/num-hash-imul.ts +0 -36
  189. package/performance/num-mod-int.ts +0 -16
  190. package/performance/num-to-string.ts +0 -16
  191. package/performance/obj-alloc.ts +0 -32
  192. package/performance/obj-keys-entries.ts +0 -44
  193. package/performance/obj-optional-chain.ts +0 -42
  194. package/performance/obj-record-dict.ts +0 -24
  195. package/performance/obj-spread-destructure.ts +0 -40
  196. package/performance/regex-exec.ts +0 -29
  197. package/performance/regex-replace-fn.ts +0 -24
  198. package/performance/regex-site.ts +0 -28
  199. package/performance/set-ops.ts +0 -20
  200. package/performance/str-char-scan.ts +0 -35
  201. package/performance/str-concat-plus.ts +0 -18
  202. package/performance/str-concat.ts +0 -24
  203. package/performance/str-methods.ts +0 -24
  204. package/performance/str-short-scan.ts +0 -26
  205. package/performance/str-split-join.ts +0 -23
  206. package/performance/str-switch-compare.ts +0 -50
  207. package/performance/str-template.ts +0 -16
  208. package/performance/str-unicode.ts +0 -25
  209. package/performance/typed-array.ts +0 -30
  210. package/performance/union-switch.ts +0 -57
  211. package/performance/union-typeof.ts +0 -40
  212. package/performance/wasm-call.ts +0 -63
  213. package/tsparser/check.go +0 -158
  214. package/tsparser/go.mod +0 -14
  215. package/tsparser/go.sum +0 -22
  216. package/tsparser/main.go +0 -363
  217. package/tsparser/tsparser.exe +0 -4
@@ -31,6 +31,8 @@ type TnSqliteDb struct {
31
31
  // A JS throw inside a user-defined function, rethrown after the statement
32
32
  pending interface{}
33
33
  hasPending bool
34
+ // Active sessions sharing this connection's preupdate hook
35
+ sessions []*TnSqliteSession
34
36
  }
35
37
 
36
38
  type TnSqliteStmt struct {
@@ -363,6 +365,11 @@ func (db *TnSqliteDb) setAuthorizer(callback interface{}) {
363
365
 
364
366
  func (db *TnSqliteDb) close() {
365
367
  db.requireOpen()
368
+ for _, sess := range db.sessions {
369
+ sess.open = false
370
+ }
371
+ db.sessions = nil
372
+ db.conn.PreUpdateHook(nil)
366
373
  for s := range db.live {
367
374
  s.Close()
368
375
  }
@@ -489,6 +496,10 @@ func tnSqliteResult(ctx sqlite3.Context, v interface{}) {
489
496
  ctx.ResultInt64(x.Int64())
490
497
  }
491
498
  default:
499
+ if _, isNull := v.(interface{ TnIsNullValue() }); isNull {
500
+ ctx.ResultNull()
501
+ return
502
+ }
492
503
  rv := reflect.ValueOf(v)
493
504
  switch {
494
505
  case rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Float64 && rv.Kind() != reflect.Uintptr:
@@ -497,6 +508,8 @@ func tnSqliteResult(ctx sqlite3.Context, v interface{}) {
497
508
  panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "Asynchronous user-defined functions are not supported"))
498
509
  case (rv.Kind() == reflect.Pointer || rv.Kind() == reflect.Func || rv.Kind() == reflect.Slice || rv.Kind() == reflect.Map) && rv.IsNil():
499
510
  ctx.ResultNull()
511
+ case rv.Kind() == reflect.Pointer && rv.Elem().Kind() != reflect.Struct:
512
+ tnSqliteResult(ctx, rv.Elem().Interface())
500
513
  default:
501
514
  panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "Returned JavaScript value cannot be converted to a SQLite value"))
502
515
  }
@@ -607,6 +620,451 @@ func (db *TnSqliteDb) aggregate(name string, options interface{}) {
607
620
  db.check(err)
608
621
  }
609
622
 
623
+ // createModule(name, options): virtual-table module backed by JS callbacks
624
+ type tnSqliteVTabCol struct {
625
+ name string
626
+ typ string
627
+ hidden bool
628
+ hiddenIdx int
629
+ visibleIdx int
630
+ }
631
+
632
+ type tnSqliteVTab struct {
633
+ db *TnSqliteDb
634
+ cols []tnSqliteVTabCol
635
+ nHidden int
636
+ rowsFn interface{}
637
+ bigInts bool
638
+ }
639
+
640
+ type tnSqliteVTabCursor struct {
641
+ vt *tnSqliteVTab
642
+ args []interface{}
643
+ rowid int64
644
+ eof bool
645
+ curRow interface{}
646
+ isSlice bool
647
+ rvSlice reflect.Value
648
+ sliceIdx int
649
+ isChan bool
650
+ chanVal interface{}
651
+ rvChan reflect.Value
652
+ nextFn interface{}
653
+ returnFn interface{}
654
+ }
655
+
656
+ func tnSqliteIsObject(v interface{}) bool {
657
+ if v == nil {
658
+ return false
659
+ }
660
+ switch v.(type) {
661
+ case string, float64, bool, *tnbig.Int:
662
+ return false
663
+ }
664
+ rv := reflect.ValueOf(v)
665
+ switch rv.Kind() {
666
+ case reflect.Slice, reflect.Array, reflect.Func, reflect.Chan:
667
+ return false
668
+ case reflect.Pointer:
669
+ if rv.IsNil() || rv.Elem().Kind() == reflect.Slice {
670
+ return false
671
+ }
672
+ }
673
+ if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Complex128 {
674
+ return false
675
+ }
676
+ return true
677
+ }
678
+
679
+ func tnSqliteOptBool(obj interface{}, key string, errMsg string) bool {
680
+ v := TnGetValue(obj, key)
681
+ if v == nil {
682
+ return false
683
+ }
684
+ switch b := v.(type) {
685
+ case bool:
686
+ return b
687
+ case *bool:
688
+ if b == nil {
689
+ return false
690
+ }
691
+ return *b
692
+ }
693
+ panic(tnSqliteArgType(errMsg))
694
+ }
695
+
696
+ func (db *TnSqliteDb) callVTab(fn func() error) (err error) {
697
+ defer func() {
698
+ if r := recover(); r != nil {
699
+ if !db.hasPending {
700
+ db.pending, db.hasPending = r, true
701
+ }
702
+ err = errors.New(fmt.Sprint(r))
703
+ }
704
+ }()
705
+ return fn()
706
+ }
707
+
708
+ func (vt *tnSqliteVTab) BestIndex(idx *sqlite3.IndexInfo) error {
709
+ var used []string
710
+ seen := make([]bool, vt.nHidden)
711
+ argv := 1
712
+ for i, c := range idx.Constraint {
713
+ if c.Op != sqlite3.INDEX_CONSTRAINT_EQ {
714
+ continue
715
+ }
716
+ if c.Column < 0 || c.Column >= len(vt.cols) || !vt.cols[c.Column].hidden {
717
+ continue
718
+ }
719
+ if !c.Usable {
720
+ return sqlite3.CONSTRAINT
721
+ }
722
+ hIdx := vt.cols[c.Column].hiddenIdx
723
+ if seen[hIdx] {
724
+ continue
725
+ }
726
+ seen[hIdx] = true
727
+ idx.ConstraintUsage[i].ArgvIndex = argv
728
+ idx.ConstraintUsage[i].Omit = true
729
+ used = append(used, strconv.Itoa(hIdx))
730
+ argv++
731
+ }
732
+ idx.IdxStr = strings.Join(used, ",")
733
+ idx.EstimatedCost = 1000.0 / float64(1+len(used))
734
+ return nil
735
+ }
736
+
737
+ func (vt *tnSqliteVTab) Open() (sqlite3.VTabCursor, error) {
738
+ return &tnSqliteVTabCursor{vt: vt, eof: true}, nil
739
+ }
740
+
741
+ func (cur *tnSqliteVTabCursor) closeIter() {
742
+ if !cur.eof {
743
+ if cur.isChan {
744
+ if c, ok := tnGenCtrls.Load(cur.chanVal); ok {
745
+ ctrl := c.(*tnGenCtrl)
746
+ ctrl.mu.Lock()
747
+ done := ctrl.done
748
+ ctrl.mu.Unlock()
749
+ if !done {
750
+ ctrl.in <- tnGenCmd{kind: tnGenCmdReturn}
751
+ for {
752
+ if _, ok := cur.rvChan.Recv(); !ok {
753
+ break
754
+ }
755
+ }
756
+ ctrl.mu.Lock()
757
+ hasErr := ctrl.hasErr
758
+ errVal := ctrl.errVal
759
+ ctrl.hasErr = false
760
+ ctrl.mu.Unlock()
761
+ if hasErr && !cur.vt.db.hasPending {
762
+ if _, isNil := errVal.(tnGenNilErr); isNil {
763
+ cur.vt.db.pending, cur.vt.db.hasPending = nil, true
764
+ } else {
765
+ cur.vt.db.pending, cur.vt.db.hasPending = errVal, true
766
+ }
767
+ }
768
+ }
769
+ }
770
+ } else if cur.returnFn != nil {
771
+ _ = cur.vt.db.callVTab(func() error {
772
+ TnInvoke(cur.returnFn)
773
+ return nil
774
+ })
775
+ }
776
+ }
777
+ cur.eof = true
778
+ cur.curRow = nil
779
+ cur.isSlice = false
780
+ cur.rvSlice = reflect.Value{}
781
+ cur.sliceIdx = 0
782
+ cur.isChan = false
783
+ cur.chanVal = nil
784
+ cur.rvChan = reflect.Value{}
785
+ cur.nextFn = nil
786
+ cur.returnFn = nil
787
+ }
788
+
789
+ func (cur *tnSqliteVTabCursor) Close() error {
790
+ cur.closeIter()
791
+ return nil
792
+ }
793
+
794
+ func (cur *tnSqliteVTabCursor) initIter(res interface{}) error {
795
+ if res == nil {
796
+ return errors.New("The \\"options.rows\\" function must return an iterable object")
797
+ }
798
+ rv := reflect.ValueOf(res)
799
+ if m := rv.MethodByName("Symbol_iterator"); m.IsValid() && m.Type().NumIn() == 0 && m.Type().NumOut() >= 1 {
800
+ res = m.Call(nil)[0].Interface()
801
+ if res == nil {
802
+ return errors.New("The \\"options.rows\\" function must return an iterable object")
803
+ }
804
+ rv = reflect.ValueOf(res)
805
+ }
806
+ if m, ok := res.(interface{ Entries() [][]interface{} }); ok {
807
+ res = m.Entries()
808
+ rv = reflect.ValueOf(res)
809
+ } else if s, ok := res.(interface{ TnItems() *[]interface{} }); ok {
810
+ res = *s.TnItems()
811
+ rv = reflect.ValueOf(res)
812
+ }
813
+ if rv.Kind() == reflect.Pointer && !rv.IsNil() && rv.Elem().Kind() == reflect.Slice {
814
+ rv = rv.Elem()
815
+ }
816
+ if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
817
+ cur.isSlice = true
818
+ cur.rvSlice = rv
819
+ cur.sliceIdx = 0
820
+ return nil
821
+ }
822
+ if rv.Kind() == reflect.Chan {
823
+ cur.isChan = true
824
+ cur.chanVal = res
825
+ cur.rvChan = rv
826
+ return nil
827
+ }
828
+ if nextFn := TnGet(res, "next"); tnSqliteIsFunc(nextFn) {
829
+ cur.nextFn = nextFn
830
+ if retFn := TnGet(res, "return"); tnSqliteIsFunc(retFn) {
831
+ cur.returnFn = retFn
832
+ }
833
+ return nil
834
+ }
835
+ return errors.New("The \\"options.rows\\" function must return an iterable object")
836
+ }
837
+
838
+ func (cur *tnSqliteVTabCursor) advance() {
839
+ cur.curRow = nil
840
+ if cur.isSlice {
841
+ if cur.sliceIdx >= cur.rvSlice.Len() {
842
+ cur.eof = true
843
+ return
844
+ }
845
+ cur.curRow = cur.rvSlice.Index(cur.sliceIdx).Interface()
846
+ cur.sliceIdx++
847
+ cur.rowid++
848
+ return
849
+ }
850
+ if cur.isChan {
851
+ if c, ok := tnGenCtrls.Load(cur.chanVal); ok {
852
+ ctrl := c.(*tnGenCtrl)
853
+ ctrl.mu.Lock()
854
+ done := ctrl.done
855
+ ctrl.mu.Unlock()
856
+ if done {
857
+ cur.eof = true
858
+ return
859
+ }
860
+ ctrl.in <- tnGenCmd{kind: tnGenCmdNext}
861
+ v, ok := cur.rvChan.Recv()
862
+ if ok {
863
+ cur.curRow = v.Interface()
864
+ cur.rowid++
865
+ return
866
+ }
867
+ ctrl.mu.Lock()
868
+ hasErr := ctrl.hasErr
869
+ errVal := ctrl.errVal
870
+ ctrl.hasErr = false
871
+ ctrl.mu.Unlock()
872
+ cur.eof = true
873
+ if hasErr {
874
+ if _, isNil := errVal.(tnGenNilErr); isNil {
875
+ panic(nil)
876
+ }
877
+ panic(errVal)
878
+ }
879
+ return
880
+ }
881
+ v, ok := cur.rvChan.Recv()
882
+ if ok {
883
+ cur.curRow = v.Interface()
884
+ cur.rowid++
885
+ return
886
+ }
887
+ cur.eof = true
888
+ return
889
+ }
890
+ if cur.nextFn != nil {
891
+ step := TnInvoke(cur.nextFn)
892
+ if tnSqliteFlag(step, "done", false) {
893
+ cur.eof = true
894
+ return
895
+ }
896
+ cur.curRow = TnGetValue(step, "value")
897
+ cur.rowid++
898
+ return
899
+ }
900
+ cur.eof = true
901
+ }
902
+
903
+ func (cur *tnSqliteVTabCursor) Filter(idxNum int, idxStr string, arg ...sqlite3.Value) error {
904
+ cur.closeIter()
905
+ cur.rowid = 0
906
+ cur.eof = false
907
+ cur.args = make([]interface{}, cur.vt.nHidden)
908
+ return cur.vt.db.callVTab(func() error {
909
+ if idxStr != "" {
910
+ parts := strings.Split(idxStr, ",")
911
+ for i, p := range parts {
912
+ if i >= len(arg) {
913
+ break
914
+ }
915
+ hIdx, err := strconv.Atoi(p)
916
+ if err == nil && hIdx >= 0 && hIdx < len(cur.args) {
917
+ cur.args[hIdx] = cur.vt.db.argValue(arg[i], cur.vt.bigInts)
918
+ }
919
+ }
920
+ }
921
+ res := TnInvoke(cur.vt.rowsFn, cur.args...)
922
+ if err := cur.initIter(res); err != nil {
923
+ cur.eof = true
924
+ return err
925
+ }
926
+ cur.advance()
927
+ return nil
928
+ })
929
+ }
930
+
931
+ func (cur *tnSqliteVTabCursor) Next() error {
932
+ return cur.vt.db.callVTab(func() error {
933
+ cur.advance()
934
+ return nil
935
+ })
936
+ }
937
+
938
+ func (cur *tnSqliteVTabCursor) EOF() bool {
939
+ return cur.eof
940
+ }
941
+
942
+ func (cur *tnSqliteVTabCursor) Column(ctx sqlite3.Context, n int) error {
943
+ if n < 0 || n >= len(cur.vt.cols) {
944
+ ctx.ResultNull()
945
+ return nil
946
+ }
947
+ col := cur.vt.cols[n]
948
+ return cur.vt.db.callVTab(func() error {
949
+ if col.hidden {
950
+ if col.hiddenIdx < len(cur.args) {
951
+ tnSqliteResult(ctx, cur.args[col.hiddenIdx])
952
+ } else {
953
+ ctx.ResultNull()
954
+ }
955
+ return nil
956
+ }
957
+ if cur.curRow == nil {
958
+ ctx.ResultNull()
959
+ return nil
960
+ }
961
+ rv := reflect.ValueOf(cur.curRow)
962
+ if rv.Kind() == reflect.Pointer && !rv.IsNil() && rv.Elem().Kind() == reflect.Slice {
963
+ rv = rv.Elem()
964
+ }
965
+ if (rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array) && col.visibleIdx < rv.Len() {
966
+ tnSqliteResult(ctx, rv.Index(col.visibleIdx).Interface())
967
+ } else {
968
+ ctx.ResultNull()
969
+ }
970
+ return nil
971
+ })
972
+ }
973
+
974
+ func (cur *tnSqliteVTabCursor) RowID() (int64, error) {
975
+ return cur.rowid, nil
976
+ }
977
+
978
+ func (db *TnSqliteDb) createModule(name interface{}, opts ...interface{}) {
979
+ db.requireOpen()
980
+ nameStr, ok := name.(string)
981
+ if !ok {
982
+ panic(tnSqliteArgType("The \\"name\\" argument must be a string."))
983
+ }
984
+ var options interface{}
985
+ if len(opts) > 0 {
986
+ options = opts[0]
987
+ }
988
+ if !tnSqliteIsObject(options) {
989
+ panic(tnSqliteArgType("The \\"options\\" argument must be an object."))
990
+ }
991
+ colsVal := TnGetValue(options, "columns")
992
+ if colsVal == nil {
993
+ panic(tnSqliteArgType("The \\"options.columns\\" argument must be an array."))
994
+ }
995
+ colsRV := reflect.ValueOf(colsVal)
996
+ if colsRV.Kind() == reflect.Pointer && !colsRV.IsNil() && colsRV.Elem().Kind() == reflect.Slice {
997
+ colsRV = colsRV.Elem()
998
+ }
999
+ if colsRV.Kind() != reflect.Slice && colsRV.Kind() != reflect.Array {
1000
+ panic(tnSqliteArgType("The \\"options.columns\\" argument must be an array."))
1001
+ }
1002
+ if colsRV.Len() == 0 {
1003
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The \\"options.columns\\" array must not be empty."))
1004
+ }
1005
+ cols := make([]tnSqliteVTabCol, colsRV.Len())
1006
+ defs := make([]string, colsRV.Len())
1007
+ nHidden := 0
1008
+ nVisible := 0
1009
+ for i := 0; i < colsRV.Len(); i++ {
1010
+ c := colsRV.Index(i).Interface()
1011
+ if !tnSqliteIsObject(c) {
1012
+ panic(tnSqliteArgType("Each column in \\"options.columns\\" must be an object."))
1013
+ }
1014
+ cName, ok := TnGetValue(c, "name").(string)
1015
+ if !ok {
1016
+ panic(tnSqliteArgType("The column \\"name\\" property must be a string."))
1017
+ }
1018
+ cType, ok := TnGetValue(c, "type").(string)
1019
+ if !ok {
1020
+ panic(tnSqliteArgType("The column \\"type\\" property must be a string."))
1021
+ }
1022
+ switch cType {
1023
+ case "INTEGER", "TEXT", "REAL", "BLOB", "ANY":
1024
+ default:
1025
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The column \\"type\\" property must be one of 'INTEGER', 'TEXT', 'REAL', 'BLOB', or 'ANY'."))
1026
+ }
1027
+ hidden := tnSqliteOptBool(c, "hidden", "The column \\"hidden\\" property must be a boolean.")
1028
+ col := tnSqliteVTabCol{name: cName, typ: cType, hidden: hidden}
1029
+ def := tnSqliteQuoteIdent(cName) + " " + cType
1030
+ if hidden {
1031
+ col.hiddenIdx = nHidden
1032
+ nHidden++
1033
+ def += " HIDDEN"
1034
+ } else {
1035
+ col.visibleIdx = nVisible
1036
+ nVisible++
1037
+ }
1038
+ cols[i] = col
1039
+ defs[i] = def
1040
+ }
1041
+ rowsFn := TnGet(options, "rows")
1042
+ if !tnSqliteIsFunc(rowsFn) {
1043
+ panic(tnSqliteArgType("The \\"options.rows\\" argument must be a function."))
1044
+ }
1045
+ directOnly := tnSqliteOptBool(options, "directOnly", "The \\"options.directOnly\\" argument must be a boolean.")
1046
+ bigInts := tnSqliteOptBool(options, "useBigIntArguments", "The \\"options.useBigIntArguments\\" argument must be a boolean.")
1047
+ createSQL := "CREATE TABLE x(" + strings.Join(defs, ", ") + ")"
1048
+ ctor := func(conn *sqlite3.Conn, module, schema, table string, arg ...string) (*tnSqliteVTab, error) {
1049
+ if err := conn.DeclareVTab(createSQL); err != nil {
1050
+ return nil, err
1051
+ }
1052
+ if directOnly {
1053
+ if err := conn.VTabConfig(sqlite3.VTAB_DIRECTONLY); err != nil {
1054
+ return nil, err
1055
+ }
1056
+ }
1057
+ return &tnSqliteVTab{
1058
+ db: db,
1059
+ cols: cols,
1060
+ nHidden: nHidden,
1061
+ rowsFn: rowsFn,
1062
+ bigInts: bigInts,
1063
+ }, nil
1064
+ }
1065
+ db.check(sqlite3.CreateModule(db.conn, nameStr, nil, ctor))
1066
+ }
1067
+
610
1068
  func (db *TnSqliteDb) enableLoadExtension(allow bool) {
611
1069
  db.requireOpen()
612
1070
  if !db.allowExt {
@@ -622,14 +1080,1038 @@ func (db *TnSqliteDb) loadExtension(path string, entry ...interface{}) {
622
1080
  panic(tnSqliteState("Loading SQLite extensions is not supported: SQLite runs as Wasm inside the program"))
623
1081
  }
624
1082
 
625
- func (db *TnSqliteDb) createSession(options ...interface{}) interface{} {
1083
+ // Session / changeset / patchset emulation over SQLite's preupdate hook.
1084
+ // Produces and consumes SQLite's official binary changeset ('T') and patchset
1085
+ // ('P') formats so buffers are wire-compatible with SQLite's session extension.
1086
+ type tnSqliteSessVal struct {
1087
+ kind byte // 0=undefined, 1=INTEGER, 2=FLOAT, 3=TEXT, 4=BLOB, 5=NULL
1088
+ i64 int64
1089
+ f64 float64
1090
+ str string
1091
+ blob []byte
1092
+ }
1093
+
1094
+ type tnSqliteTableInfo struct {
1095
+ cols []string
1096
+ pk []byte // 0 if non-PK, else 1-based PK position
1097
+ pkCols []int // column indices where pk[i] != 0, in table column order
1098
+ }
1099
+
1100
+ type tnSqliteSessRow struct {
1101
+ key string
1102
+ pkVals []tnSqliteSessVal
1103
+ existedBefore bool
1104
+ origOld []tnSqliteSessVal
1105
+ indirect bool
1106
+ }
1107
+
1108
+ type tnSqliteSessTable struct {
1109
+ name string
1110
+ info tnSqliteTableInfo
1111
+ rows map[string]*tnSqliteSessRow
1112
+ order []string
1113
+ }
1114
+
1115
+ type TnSqliteSession struct {
1116
+ db *TnSqliteDb
1117
+ dbName string
1118
+ table string
1119
+ open bool
1120
+ tables map[string]*tnSqliteSessTable
1121
+ tableOrder []string
1122
+ }
1123
+
1124
+ func tnSqliteQuoteIdent(name string) string {
1125
+ return "\\"" + strings.ReplaceAll(name, "\\"", "\\"\\"") + "\\""
1126
+ }
1127
+
1128
+ func tnSqliteValFromSQLite(v sqlite3.Value) tnSqliteSessVal {
1129
+ switch v.Type() {
1130
+ case sqlite3.INTEGER:
1131
+ return tnSqliteSessVal{kind: 1, i64: v.Int64()}
1132
+ case sqlite3.FLOAT:
1133
+ return tnSqliteSessVal{kind: 2, f64: v.Float()}
1134
+ case sqlite3.TEXT:
1135
+ return tnSqliteSessVal{kind: 3, str: v.Text()}
1136
+ case sqlite3.BLOB:
1137
+ return tnSqliteSessVal{kind: 4, blob: append([]byte(nil), v.RawBlob()...)}
1138
+ default:
1139
+ return tnSqliteSessVal{kind: 5}
1140
+ }
1141
+ }
1142
+
1143
+ func tnSqliteValFromStmt(s *sqlite3.Stmt, col int) tnSqliteSessVal {
1144
+ switch s.ColumnType(col) {
1145
+ case sqlite3.INTEGER:
1146
+ return tnSqliteSessVal{kind: 1, i64: s.ColumnInt64(col)}
1147
+ case sqlite3.FLOAT:
1148
+ return tnSqliteSessVal{kind: 2, f64: s.ColumnFloat(col)}
1149
+ case sqlite3.TEXT:
1150
+ return tnSqliteSessVal{kind: 3, str: s.ColumnText(col)}
1151
+ case sqlite3.BLOB:
1152
+ return tnSqliteSessVal{kind: 4, blob: append([]byte(nil), s.ColumnRawBlob(col)...)}
1153
+ default:
1154
+ return tnSqliteSessVal{kind: 5}
1155
+ }
1156
+ }
1157
+
1158
+ func tnSqliteBindSessVal(s *sqlite3.Stmt, idx int, v tnSqliteSessVal) error {
1159
+ switch v.kind {
1160
+ case 1:
1161
+ return s.BindInt64(idx, v.i64)
1162
+ case 2:
1163
+ return s.BindFloat(idx, v.f64)
1164
+ case 3:
1165
+ return s.BindText(idx, v.str)
1166
+ case 4:
1167
+ return s.BindBlob(idx, v.blob)
1168
+ default:
1169
+ return s.BindNull(idx)
1170
+ }
1171
+ }
1172
+
1173
+ func tnSqliteSessValEqual(a, b tnSqliteSessVal) bool {
1174
+ if a.kind != b.kind {
1175
+ return false
1176
+ }
1177
+ switch a.kind {
1178
+ case 0, 5:
1179
+ return true
1180
+ case 1:
1181
+ return a.i64 == b.i64
1182
+ case 2:
1183
+ return math.Float64bits(a.f64) == math.Float64bits(b.f64)
1184
+ case 3:
1185
+ return a.str == b.str
1186
+ case 4:
1187
+ return len(a.blob) == len(b.blob) && string(a.blob) == string(b.blob)
1188
+ }
1189
+ return false
1190
+ }
1191
+
1192
+ func tnSqliteAppendVarint(buf []byte, v uint64) []byte {
1193
+ if v < 0x80 {
1194
+ return append(buf, byte(v))
1195
+ }
1196
+ if v >= (1 << 56) {
1197
+ return append(buf,
1198
+ byte(v>>57)|0x80, byte(v>>50)|0x80, byte(v>>43)|0x80, byte(v>>36)|0x80,
1199
+ byte(v>>29)|0x80, byte(v>>22)|0x80, byte(v>>15)|0x80, byte(v>>8)|0x80,
1200
+ byte(v),
1201
+ )
1202
+ }
1203
+ var tmp [9]byte
1204
+ n := 0
1205
+ for {
1206
+ tmp[n] = byte(v & 0x7f)
1207
+ n++
1208
+ v >>= 7
1209
+ if v == 0 {
1210
+ break
1211
+ }
1212
+ }
1213
+ for i := n - 1; i > 0; i-- {
1214
+ buf = append(buf, tmp[i]|0x80)
1215
+ }
1216
+ return append(buf, tmp[0])
1217
+ }
1218
+
1219
+ func tnSqliteReadVarint(b []byte, pos int) (uint64, int, bool) {
1220
+ if pos >= len(b) {
1221
+ return 0, pos, false
1222
+ }
1223
+ var v uint64
1224
+ for i := 0; i < 8; i++ {
1225
+ if pos+i >= len(b) {
1226
+ return 0, pos, false
1227
+ }
1228
+ c := b[pos+i]
1229
+ v = (v << 7) | uint64(c&0x7f)
1230
+ if c&0x80 == 0 {
1231
+ return v, pos + i + 1, true
1232
+ }
1233
+ }
1234
+ if pos+8 >= len(b) {
1235
+ return 0, pos, false
1236
+ }
1237
+ v = (v << 8) | uint64(b[pos+8])
1238
+ return v, pos + 9, true
1239
+ }
1240
+
1241
+ func tnSqliteAppendVal(buf []byte, v tnSqliteSessVal) []byte {
1242
+ buf = append(buf, v.kind)
1243
+ switch v.kind {
1244
+ case 1:
1245
+ var tmp [8]byte
1246
+ binary.BigEndian.PutUint64(tmp[:], uint64(v.i64))
1247
+ buf = append(buf, tmp[:]...)
1248
+ case 2:
1249
+ var tmp [8]byte
1250
+ binary.BigEndian.PutUint64(tmp[:], math.Float64bits(v.f64))
1251
+ buf = append(buf, tmp[:]...)
1252
+ case 3:
1253
+ buf = tnSqliteAppendVarint(buf, uint64(len(v.str)))
1254
+ buf = append(buf, v.str...)
1255
+ case 4:
1256
+ buf = tnSqliteAppendVarint(buf, uint64(len(v.blob)))
1257
+ buf = append(buf, v.blob...)
1258
+ }
1259
+ return buf
1260
+ }
1261
+
1262
+ func tnSqliteReadVal(b []byte, pos int) (tnSqliteSessVal, int, bool) {
1263
+ if pos >= len(b) {
1264
+ return tnSqliteSessVal{}, pos, false
1265
+ }
1266
+ kind := b[pos]
1267
+ pos++
1268
+ switch kind {
1269
+ case 0, 5:
1270
+ return tnSqliteSessVal{kind: kind}, pos, true
1271
+ case 1:
1272
+ if pos+8 > len(b) {
1273
+ return tnSqliteSessVal{}, pos, false
1274
+ }
1275
+ u := binary.BigEndian.Uint64(b[pos : pos+8])
1276
+ return tnSqliteSessVal{kind: 1, i64: int64(u)}, pos + 8, true
1277
+ case 2:
1278
+ if pos+8 > len(b) {
1279
+ return tnSqliteSessVal{}, pos, false
1280
+ }
1281
+ u := binary.BigEndian.Uint64(b[pos : pos+8])
1282
+ return tnSqliteSessVal{kind: 2, f64: math.Float64frombits(u)}, pos + 8, true
1283
+ case 3:
1284
+ n, next, ok := tnSqliteReadVarint(b, pos)
1285
+ if !ok || n > uint64(len(b)-next) {
1286
+ return tnSqliteSessVal{}, pos, false
1287
+ }
1288
+ return tnSqliteSessVal{kind: 3, str: string(b[next : next+int(n)])}, next + int(n), true
1289
+ case 4:
1290
+ n, next, ok := tnSqliteReadVarint(b, pos)
1291
+ if !ok || n > uint64(len(b)-next) {
1292
+ return tnSqliteSessVal{}, pos, false
1293
+ }
1294
+ blob := append([]byte(nil), b[next:next+int(n)]...)
1295
+ return tnSqliteSessVal{kind: 4, blob: blob}, next + int(n), true
1296
+ default:
1297
+ return tnSqliteSessVal{}, pos, false
1298
+ }
1299
+ }
1300
+
1301
+ func tnSqliteEncodePK(vals []tnSqliteSessVal) (string, bool) {
1302
+ var buf []byte
1303
+ for _, v := range vals {
1304
+ if v.kind == 5 || v.kind == 0 {
1305
+ return "", false
1306
+ }
1307
+ buf = tnSqliteAppendVal(buf, v)
1308
+ }
1309
+ return string(buf), true
1310
+ }
1311
+
1312
+ func (db *TnSqliteDb) tableInfo(schema, table string) (tnSqliteTableInfo, error) {
1313
+ q := fmt.Sprintf("PRAGMA %s.table_info(%s)", tnSqliteQuoteIdent(schema), tnSqliteQuoteIdent(table))
1314
+ st, _, err := db.conn.Prepare(q)
1315
+ if err != nil {
1316
+ return tnSqliteTableInfo{}, err
1317
+ }
1318
+ defer st.Close()
1319
+ var info tnSqliteTableInfo
1320
+ for st.Step() {
1321
+ name := st.ColumnText(1)
1322
+ pk := byte(st.ColumnInt(5))
1323
+ idx := len(info.cols)
1324
+ info.cols = append(info.cols, name)
1325
+ info.pk = append(info.pk, pk)
1326
+ if pk != 0 {
1327
+ info.pkCols = append(info.pkCols, idx)
1328
+ }
1329
+ }
1330
+ if err := st.Err(); err != nil {
1331
+ return tnSqliteTableInfo{}, err
1332
+ }
1333
+ return info, nil
1334
+ }
1335
+
1336
+ func tnSqliteIsConstraint(err error) bool {
1337
+ var se *sqlite3.Error
1338
+ if errors.As(err, &se) {
1339
+ return se.Code() == sqlite3.CONSTRAINT
1340
+ }
1341
+ if code, ok := err.(sqlite3.ErrorCode); ok {
1342
+ return code == sqlite3.CONSTRAINT
1343
+ }
1344
+ if code, ok := err.(sqlite3.ExtendedErrorCode); ok {
1345
+ return sqlite3.ErrorCode(code&0xff) == sqlite3.CONSTRAINT
1346
+ }
1347
+ return false
1348
+ }
1349
+
1350
+ func (db *TnSqliteDb) onPreUpdate(pud sqlite3.PreUpdateData) {
1351
+ if len(db.sessions) == 0 {
1352
+ return
1353
+ }
1354
+ nCol := pud.Count()
1355
+ indirect := pud.Depth() > 0
1356
+ var oldVals []tnSqliteSessVal
1357
+ var newVals []tnSqliteSessVal
1358
+ readOld := func() []tnSqliteSessVal {
1359
+ if oldVals == nil {
1360
+ oldVals = make([]tnSqliteSessVal, nCol)
1361
+ for i := 0; i < nCol; i++ {
1362
+ if v, err := pud.Old(i); err == nil {
1363
+ oldVals[i] = tnSqliteValFromSQLite(v)
1364
+ } else {
1365
+ oldVals[i] = tnSqliteSessVal{kind: 5}
1366
+ }
1367
+ }
1368
+ }
1369
+ return oldVals
1370
+ }
1371
+ readNew := func() []tnSqliteSessVal {
1372
+ if newVals == nil {
1373
+ newVals = make([]tnSqliteSessVal, nCol)
1374
+ for i := 0; i < nCol; i++ {
1375
+ if v, err := pud.New(i); err == nil {
1376
+ newVals[i] = tnSqliteValFromSQLite(v)
1377
+ } else {
1378
+ newVals[i] = tnSqliteSessVal{kind: 5}
1379
+ }
1380
+ }
1381
+ }
1382
+ return newVals
1383
+ }
1384
+ for _, sess := range db.sessions {
1385
+ if !sess.open {
1386
+ continue
1387
+ }
1388
+ if !strings.EqualFold(pud.Schema, sess.dbName) {
1389
+ continue
1390
+ }
1391
+ if sess.table != "" && !strings.EqualFold(pud.Table, sess.table) {
1392
+ continue
1393
+ }
1394
+ tKey := strings.ToLower(pud.Table)
1395
+ tbl, ok := sess.tables[tKey]
1396
+ if !ok || len(tbl.info.cols) != nCol {
1397
+ info, err := db.tableInfo(pud.Schema, pud.Table)
1398
+ if err != nil || len(info.pkCols) == 0 {
1399
+ continue
1400
+ }
1401
+ if !ok {
1402
+ tbl = &tnSqliteSessTable{
1403
+ name: pud.Table,
1404
+ info: info,
1405
+ rows: map[string]*tnSqliteSessRow{},
1406
+ }
1407
+ sess.tables[tKey] = tbl
1408
+ sess.tableOrder = append(sess.tableOrder, tKey)
1409
+ } else {
1410
+ tbl.info = info
1411
+ }
1412
+ }
1413
+ if len(tbl.info.pkCols) == 0 {
1414
+ continue
1415
+ }
1416
+ extractPK := func(vals []tnSqliteSessVal) ([]tnSqliteSessVal, string, bool) {
1417
+ pkVals := make([]tnSqliteSessVal, len(tbl.info.pkCols))
1418
+ for i, colIdx := range tbl.info.pkCols {
1419
+ if colIdx < len(vals) {
1420
+ pkVals[i] = vals[colIdx]
1421
+ } else {
1422
+ pkVals[i] = tnSqliteSessVal{kind: 5}
1423
+ }
1424
+ }
1425
+ key, valid := tnSqliteEncodePK(pkVals)
1426
+ return pkVals, key, valid
1427
+ }
1428
+ recordKey := func(key string, pkVals []tnSqliteSessVal, existed bool, orig []tnSqliteSessVal) {
1429
+ if row, exists := tbl.rows[key]; exists {
1430
+ if !indirect {
1431
+ row.indirect = false
1432
+ }
1433
+ return
1434
+ }
1435
+ var saved []tnSqliteSessVal
1436
+ if existed {
1437
+ saved = append([]tnSqliteSessVal(nil), orig...)
1438
+ }
1439
+ tbl.rows[key] = &tnSqliteSessRow{
1440
+ key: key,
1441
+ pkVals: pkVals,
1442
+ existedBefore: existed,
1443
+ origOld: saved,
1444
+ indirect: indirect,
1445
+ }
1446
+ tbl.order = append(tbl.order, key)
1447
+ }
1448
+ switch pud.Op {
1449
+ case sqlite3.AUTH_INSERT:
1450
+ nv := readNew()
1451
+ if pkVals, key, valid := extractPK(nv); valid {
1452
+ recordKey(key, pkVals, false, nil)
1453
+ }
1454
+ case sqlite3.AUTH_DELETE:
1455
+ ov := readOld()
1456
+ if pkVals, key, valid := extractPK(ov); valid {
1457
+ recordKey(key, pkVals, true, ov)
1458
+ }
1459
+ case sqlite3.AUTH_UPDATE:
1460
+ ov := readOld()
1461
+ nv := readNew()
1462
+ oldPK, oldKey, oldValid := extractPK(ov)
1463
+ newPK, newKey, newValid := extractPK(nv)
1464
+ if oldValid {
1465
+ recordKey(oldKey, oldPK, true, ov)
1466
+ }
1467
+ if newValid && (!oldValid || newKey != oldKey) {
1468
+ recordKey(newKey, newPK, false, nil)
1469
+ }
1470
+ }
1471
+ }
1472
+ }
1473
+
1474
+ func (db *TnSqliteDb) createSession(options ...interface{}) *TnSqliteSession {
626
1475
  db.requireOpen()
627
- panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "Sessions are not supported: the bundled SQLite has no session extension"))
1476
+ dbName := "main"
1477
+ table := ""
1478
+ if len(options) > 0 && options[0] != nil {
1479
+ if s := tnSqliteString(options[0], "db", ""); s != "" {
1480
+ dbName = s
1481
+ }
1482
+ table = tnSqliteString(options[0], "table", "")
1483
+ }
1484
+ sess := &TnSqliteSession{
1485
+ db: db,
1486
+ dbName: dbName,
1487
+ table: table,
1488
+ open: true,
1489
+ tables: map[string]*tnSqliteSessTable{},
1490
+ }
1491
+ if len(db.sessions) == 0 {
1492
+ db.conn.PreUpdateHook(db.onPreUpdate)
1493
+ }
1494
+ db.sessions = append(db.sessions, sess)
1495
+ return sess
628
1496
  }
629
1497
 
1498
+ func (s *TnSqliteSession) requireOpen() {
1499
+ s.db.requireOpen()
1500
+ if !s.open {
1501
+ panic(tnSqliteState("session is not open"))
1502
+ }
1503
+ }
1504
+
1505
+ func (s *TnSqliteSession) close() {
1506
+ s.requireOpen()
1507
+ s.open = false
1508
+ for i, cur := range s.db.sessions {
1509
+ if cur == s {
1510
+ s.db.sessions = append(s.db.sessions[:i], s.db.sessions[i+1:]...)
1511
+ break
1512
+ }
1513
+ }
1514
+ if len(s.db.sessions) == 0 {
1515
+ s.db.conn.PreUpdateHook(nil)
1516
+ }
1517
+ }
1518
+
1519
+ func (s *TnSqliteSession) __dispose() {
1520
+ if s.open && s.db.conn != nil {
1521
+ s.close()
1522
+ }
1523
+ }
1524
+
1525
+ func (s *TnSqliteSession) buildSet(isPatchset bool) []byte {
1526
+ s.requireOpen()
1527
+ out := []byte{}
1528
+ for _, tKey := range s.tableOrder {
1529
+ tbl := s.tables[tKey]
1530
+ info, err := s.db.tableInfo(s.dbName, tbl.name)
1531
+ if err != nil || len(info.cols) == 0 || len(info.pkCols) == 0 {
1532
+ continue
1533
+ }
1534
+ nCol := len(info.cols)
1535
+ colList := make([]string, nCol)
1536
+ for i, c := range info.cols {
1537
+ colList[i] = tnSqliteQuoteIdent(c)
1538
+ }
1539
+ whereParts := make([]string, len(info.pkCols))
1540
+ for i, colIdx := range info.pkCols {
1541
+ whereParts[i] = tnSqliteQuoteIdent(info.cols[colIdx]) + " = ?"
1542
+ }
1543
+ selSQL := fmt.Sprintf("SELECT %s FROM %s.%s WHERE %s",
1544
+ strings.Join(colList, ", "),
1545
+ tnSqliteQuoteIdent(s.dbName),
1546
+ tnSqliteQuoteIdent(tbl.name),
1547
+ strings.Join(whereParts, " AND "),
1548
+ )
1549
+ st, _, err := s.db.conn.Prepare(selSQL)
1550
+ if err != nil {
1551
+ continue
1552
+ }
1553
+ var tableBuf []byte
1554
+ for _, rKey := range tbl.order {
1555
+ row := tbl.rows[rKey]
1556
+ if len(row.pkVals) != len(info.pkCols) {
1557
+ continue
1558
+ }
1559
+ for i, pv := range row.pkVals {
1560
+ tnSqliteBindSessVal(st, i+1, pv)
1561
+ }
1562
+ existsNow := st.Step()
1563
+ var curVals []tnSqliteSessVal
1564
+ if existsNow {
1565
+ curVals = make([]tnSqliteSessVal, nCol)
1566
+ for i := 0; i < nCol; i++ {
1567
+ curVals[i] = tnSqliteValFromStmt(st, i)
1568
+ }
1569
+ }
1570
+ st.Reset()
1571
+ st.ClearBindings()
1572
+ var ind byte
1573
+ if row.indirect {
1574
+ ind = 1
1575
+ }
1576
+ if !row.existedBefore && !existsNow {
1577
+ continue
1578
+ }
1579
+ if !row.existedBefore && existsNow {
1580
+ tableBuf = append(tableBuf, 18, ind)
1581
+ for i := 0; i < nCol; i++ {
1582
+ tableBuf = tnSqliteAppendVal(tableBuf, curVals[i])
1583
+ }
1584
+ continue
1585
+ }
1586
+ orig := row.origOld
1587
+ if len(orig) < nCol {
1588
+ padded := make([]tnSqliteSessVal, nCol)
1589
+ copy(padded, orig)
1590
+ for i := len(orig); i < nCol; i++ {
1591
+ padded[i] = tnSqliteSessVal{kind: 5}
1592
+ }
1593
+ orig = padded
1594
+ }
1595
+ if row.existedBefore && !existsNow {
1596
+ tableBuf = append(tableBuf, 9, ind)
1597
+ if isPatchset {
1598
+ for _, colIdx := range info.pkCols {
1599
+ tableBuf = tnSqliteAppendVal(tableBuf, orig[colIdx])
1600
+ }
1601
+ } else {
1602
+ for i := 0; i < nCol; i++ {
1603
+ tableBuf = tnSqliteAppendVal(tableBuf, orig[i])
1604
+ }
1605
+ }
1606
+ continue
1607
+ }
1608
+ // Both existed before and exists now -> UPDATE if any column differs
1609
+ changed := make([]bool, nCol)
1610
+ anyChanged := false
1611
+ for i := 0; i < nCol; i++ {
1612
+ if !tnSqliteSessValEqual(orig[i], curVals[i]) {
1613
+ changed[i] = true
1614
+ anyChanged = true
1615
+ }
1616
+ }
1617
+ if !anyChanged {
1618
+ continue
1619
+ }
1620
+ tableBuf = append(tableBuf, 23, ind)
1621
+ if isPatchset {
1622
+ for i := 0; i < nCol; i++ {
1623
+ if changed[i] || info.pk[i] != 0 {
1624
+ tableBuf = tnSqliteAppendVal(tableBuf, curVals[i])
1625
+ } else {
1626
+ tableBuf = append(tableBuf, 0)
1627
+ }
1628
+ }
1629
+ } else {
1630
+ for i := 0; i < nCol; i++ {
1631
+ if info.pk[i] != 0 || changed[i] {
1632
+ tableBuf = tnSqliteAppendVal(tableBuf, orig[i])
1633
+ } else {
1634
+ tableBuf = append(tableBuf, 0)
1635
+ }
1636
+ }
1637
+ for i := 0; i < nCol; i++ {
1638
+ if changed[i] {
1639
+ tableBuf = tnSqliteAppendVal(tableBuf, curVals[i])
1640
+ } else {
1641
+ tableBuf = append(tableBuf, 0)
1642
+ }
1643
+ }
1644
+ }
1645
+ }
1646
+ st.Close()
1647
+ if len(tableBuf) > 0 {
1648
+ if isPatchset {
1649
+ out = append(out, 'P')
1650
+ } else {
1651
+ out = append(out, 'T')
1652
+ }
1653
+ out = tnSqliteAppendVarint(out, uint64(nCol))
1654
+ out = append(out, info.pk...)
1655
+ out = append(out, tbl.name...)
1656
+ out = append(out, 0)
1657
+ out = append(out, tableBuf...)
1658
+ }
1659
+ }
1660
+ return out
1661
+ }
1662
+
1663
+ func (s *TnSqliteSession) changeset() []byte { return s.buildSet(false) }
1664
+ func (s *TnSqliteSession) patchset() []byte { return s.buildSet(true) }
1665
+
630
1666
  func (db *TnSqliteDb) applyChangeset(changeset []byte, options ...interface{}) bool {
631
1667
  db.requireOpen()
632
- panic(TnNodeError("Error", "ERR_SQLITE_ERROR", "Changesets are not supported: the bundled SQLite has no session extension"))
1668
+ var filterFn, conflictFn interface{}
1669
+ if len(options) > 0 && options[0] != nil {
1670
+ if v := TnGet(options[0], "filter"); v != nil {
1671
+ if !tnSqliteIsFunc(v) {
1672
+ panic(tnSqliteArgType("The \\"options.filter\\" argument must be a function."))
1673
+ }
1674
+ filterFn = v
1675
+ }
1676
+ if v := TnGet(options[0], "onConflict"); v != nil {
1677
+ if !tnSqliteIsFunc(v) {
1678
+ panic(tnSqliteArgType("The \\"options.onConflict\\" argument must be a function."))
1679
+ }
1680
+ conflictFn = v
1681
+ }
1682
+ }
1683
+ if len(changeset) == 0 {
1684
+ return true
1685
+ }
1686
+ callConflict := func(kind int) int {
1687
+ if conflictFn == nil {
1688
+ return 2 // SQLITE_CHANGESET_ABORT
1689
+ }
1690
+ res := TnInvoke(conflictFn, float64(kind))
1691
+ n, ok := res.(float64)
1692
+ if !ok || (n != 0 && n != 1 && n != 2) {
1693
+ panic(tnSqliteCodeError(21, "bad parameter or other API misuse"))
1694
+ }
1695
+ action := int(n)
1696
+ if action == 1 && kind != 1 && kind != 3 {
1697
+ // SQLITE_CHANGESET_REPLACE is only valid for DATA (1) and CONFLICT (3)
1698
+ panic(tnSqliteCodeError(21, "bad parameter or other API misuse"))
1699
+ }
1700
+ return action
1701
+ }
1702
+ corrupt := func() {
1703
+ panic(tnSqliteCodeError(11, "database disk image is malformed"))
1704
+ }
1705
+
1706
+ fkeyEnabled, _ := db.conn.Config(sqlite3.DBCONFIG_ENABLE_FKEY)
1707
+ trigEnabled, _ := db.conn.Config(sqlite3.DBCONFIG_ENABLE_TRIGGER)
1708
+ if fkeyEnabled {
1709
+ db.conn.Config(sqlite3.DBCONFIG_ENABLE_FKEY, false)
1710
+ }
1711
+ if trigEnabled {
1712
+ db.conn.Config(sqlite3.DBCONFIG_ENABLE_TRIGGER, false)
1713
+ }
1714
+ db.check(db.conn.Exec("SAVEPOINT __tn_changeset"))
1715
+ committed := false
1716
+ defer func() {
1717
+ if !committed {
1718
+ db.conn.Exec("ROLLBACK TO SAVEPOINT __tn_changeset")
1719
+ db.conn.Exec("RELEASE SAVEPOINT __tn_changeset")
1720
+ }
1721
+ if fkeyEnabled {
1722
+ db.conn.Config(sqlite3.DBCONFIG_ENABLE_FKEY, true)
1723
+ }
1724
+ if trigEnabled {
1725
+ db.conn.Config(sqlite3.DBCONFIG_ENABLE_TRIGGER, true)
1726
+ }
1727
+ }()
1728
+
1729
+ pos := 0
1730
+ for pos < len(changeset) {
1731
+ hdr := changeset[pos]
1732
+ if hdr != 'T' && hdr != 'P' {
1733
+ corrupt()
1734
+ }
1735
+ isPatchset := hdr == 'P'
1736
+ pos++
1737
+ nColU, nextPos, ok := tnSqliteReadVarint(changeset, pos)
1738
+ if !ok || nColU == 0 || nColU > 32767 {
1739
+ corrupt()
1740
+ }
1741
+ nCol := int(nColU)
1742
+ pos = nextPos
1743
+ if pos+nCol > len(changeset) {
1744
+ corrupt()
1745
+ }
1746
+ pkFlags := changeset[pos : pos+nCol]
1747
+ pos += nCol
1748
+ var pkCols []int
1749
+ for i := 0; i < nCol; i++ {
1750
+ if pkFlags[i] != 0 {
1751
+ pkCols = append(pkCols, i)
1752
+ }
1753
+ }
1754
+ if len(pkCols) == 0 {
1755
+ corrupt()
1756
+ }
1757
+ nul := -1
1758
+ for i := pos; i < len(changeset); i++ {
1759
+ if changeset[i] == 0 {
1760
+ nul = i
1761
+ break
1762
+ }
1763
+ }
1764
+ if nul < 0 {
1765
+ corrupt()
1766
+ }
1767
+ tableName := string(changeset[pos:nul])
1768
+ pos = nul + 1
1769
+
1770
+ applyTable := true
1771
+ if filterFn != nil {
1772
+ applyTable = TnTruthy(TnInvoke(filterFn, tableName))
1773
+ }
1774
+ var targetInfo tnSqliteTableInfo
1775
+ if applyTable {
1776
+ info, err := db.tableInfo("main", tableName)
1777
+ db.check(err)
1778
+ if len(info.cols) == 0 {
1779
+ applyTable = false
1780
+ } else {
1781
+ if len(info.cols) < nCol {
1782
+ panic(tnSqliteCodeError(17, "database schema has changed"))
1783
+ }
1784
+ for i := 0; i < nCol; i++ {
1785
+ if (info.pk[i] != 0) != (pkFlags[i] != 0) {
1786
+ panic(tnSqliteCodeError(17, "database schema has changed"))
1787
+ }
1788
+ }
1789
+ for i := nCol; i < len(info.cols); i++ {
1790
+ if info.pk[i] != 0 {
1791
+ panic(tnSqliteCodeError(17, "database schema has changed"))
1792
+ }
1793
+ }
1794
+ targetInfo = info
1795
+ }
1796
+ }
1797
+
1798
+ var qTable string
1799
+ var colNames []string
1800
+ var whereClause string
1801
+ if applyTable {
1802
+ qTable = tnSqliteQuoteIdent(tableName)
1803
+ colNames = make([]string, nCol)
1804
+ for i := 0; i < nCol; i++ {
1805
+ colNames[i] = tnSqliteQuoteIdent(targetInfo.cols[i])
1806
+ }
1807
+ whereParts := make([]string, len(pkCols))
1808
+ for i, colIdx := range pkCols {
1809
+ whereParts[i] = colNames[colIdx] + " = ?"
1810
+ }
1811
+ whereClause = strings.Join(whereParts, " AND ")
1812
+ }
1813
+
1814
+ selectRow := func(pkVals []tnSqliteSessVal) ([]tnSqliteSessVal, bool) {
1815
+ selSQL := fmt.Sprintf("SELECT %s FROM %s WHERE %s", strings.Join(colNames, ", "), qTable, whereClause)
1816
+ st, _, err := db.conn.Prepare(selSQL)
1817
+ db.check(err)
1818
+ defer st.Close()
1819
+ for i, v := range pkVals {
1820
+ db.check(tnSqliteBindSessVal(st, i+1, v))
1821
+ }
1822
+ if !st.Step() {
1823
+ db.check(st.Err())
1824
+ return nil, false
1825
+ }
1826
+ vals := make([]tnSqliteSessVal, nCol)
1827
+ for i := 0; i < nCol; i++ {
1828
+ vals[i] = tnSqliteValFromStmt(st, i)
1829
+ }
1830
+ return vals, true
1831
+ }
1832
+
1833
+ for pos < len(changeset) && changeset[pos] != 'T' && changeset[pos] != 'P' {
1834
+ if pos+2 > len(changeset) {
1835
+ corrupt()
1836
+ }
1837
+ op := changeset[pos]
1838
+ indirect := changeset[pos+1]
1839
+ if indirect > 1 {
1840
+ corrupt()
1841
+ }
1842
+ pos += 2
1843
+ var oldVals, newVals, delPK []tnSqliteSessVal
1844
+ switch op {
1845
+ case 18: // INSERT
1846
+ newVals = make([]tnSqliteSessVal, nCol)
1847
+ for i := 0; i < nCol; i++ {
1848
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1849
+ if !ok || v.kind == 0 {
1850
+ corrupt()
1851
+ }
1852
+ newVals[i] = v
1853
+ pos = next
1854
+ }
1855
+ case 9: // DELETE
1856
+ if isPatchset {
1857
+ delPK = make([]tnSqliteSessVal, len(pkCols))
1858
+ for i := 0; i < len(pkCols); i++ {
1859
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1860
+ if !ok || v.kind == 0 {
1861
+ corrupt()
1862
+ }
1863
+ delPK[i] = v
1864
+ pos = next
1865
+ }
1866
+ } else {
1867
+ oldVals = make([]tnSqliteSessVal, nCol)
1868
+ for i := 0; i < nCol; i++ {
1869
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1870
+ if !ok || v.kind == 0 {
1871
+ corrupt()
1872
+ }
1873
+ oldVals[i] = v
1874
+ pos = next
1875
+ }
1876
+ }
1877
+ case 23: // UPDATE
1878
+ if isPatchset {
1879
+ newVals = make([]tnSqliteSessVal, nCol)
1880
+ for i := 0; i < nCol; i++ {
1881
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1882
+ if !ok {
1883
+ corrupt()
1884
+ }
1885
+ newVals[i] = v
1886
+ pos = next
1887
+ }
1888
+ } else {
1889
+ oldVals = make([]tnSqliteSessVal, nCol)
1890
+ for i := 0; i < nCol; i++ {
1891
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1892
+ if !ok {
1893
+ corrupt()
1894
+ }
1895
+ oldVals[i] = v
1896
+ pos = next
1897
+ }
1898
+ newVals = make([]tnSqliteSessVal, nCol)
1899
+ for i := 0; i < nCol; i++ {
1900
+ v, next, ok := tnSqliteReadVal(changeset, pos)
1901
+ if !ok {
1902
+ corrupt()
1903
+ }
1904
+ newVals[i] = v
1905
+ pos = next
1906
+ }
1907
+ }
1908
+ default:
1909
+ corrupt()
1910
+ }
1911
+ if !applyTable {
1912
+ continue
1913
+ }
1914
+
1915
+ switch op {
1916
+ case 18: // INSERT
1917
+ placeholders := make([]string, nCol)
1918
+ for i := 0; i < nCol; i++ {
1919
+ placeholders[i] = "?"
1920
+ }
1921
+ insSQL := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", qTable, strings.Join(colNames, ", "), strings.Join(placeholders, ", "))
1922
+ st, _, err := db.conn.Prepare(insSQL)
1923
+ db.check(err)
1924
+ for i, v := range newVals {
1925
+ db.check(tnSqliteBindSessVal(st, i+1, v))
1926
+ }
1927
+ err = st.Exec()
1928
+ st.Close()
1929
+ if err != nil {
1930
+ if !tnSqliteIsConstraint(err) {
1931
+ db.check(err)
1932
+ }
1933
+ pkVals := make([]tnSqliteSessVal, len(pkCols))
1934
+ for i, colIdx := range pkCols {
1935
+ pkVals[i] = newVals[colIdx]
1936
+ }
1937
+ _, pkExists := selectRow(pkVals)
1938
+ if pkExists {
1939
+ action := callConflict(3) // SQLITE_CHANGESET_CONFLICT
1940
+ if action == 2 {
1941
+ return false
1942
+ }
1943
+ if action == 1 {
1944
+ var setParts []string
1945
+ var setVals []tnSqliteSessVal
1946
+ for i := 0; i < nCol; i++ {
1947
+ if pkFlags[i] == 0 {
1948
+ setParts = append(setParts, colNames[i]+" = ?")
1949
+ setVals = append(setVals, newVals[i])
1950
+ }
1951
+ }
1952
+ if len(setParts) > 0 {
1953
+ updSQL := fmt.Sprintf("UPDATE %s SET %s WHERE %s", qTable, strings.Join(setParts, ", "), whereClause)
1954
+ ust, _, uerr := db.conn.Prepare(updSQL)
1955
+ db.check(uerr)
1956
+ for i, v := range setVals {
1957
+ db.check(tnSqliteBindSessVal(ust, i+1, v))
1958
+ }
1959
+ for i, v := range pkVals {
1960
+ db.check(tnSqliteBindSessVal(ust, len(setVals)+i+1, v))
1961
+ }
1962
+ uerr = ust.Exec()
1963
+ ust.Close()
1964
+ if uerr != nil {
1965
+ if !tnSqliteIsConstraint(uerr) {
1966
+ db.check(uerr)
1967
+ }
1968
+ if callConflict(4) == 2 {
1969
+ return false
1970
+ }
1971
+ }
1972
+ }
1973
+ }
1974
+ } else {
1975
+ if callConflict(4) == 2 { // SQLITE_CHANGESET_CONSTRAINT
1976
+ return false
1977
+ }
1978
+ }
1979
+ }
1980
+
1981
+ case 9: // DELETE
1982
+ pkVals := delPK
1983
+ if !isPatchset {
1984
+ pkVals = make([]tnSqliteSessVal, len(pkCols))
1985
+ for i, colIdx := range pkCols {
1986
+ pkVals[i] = oldVals[colIdx]
1987
+ }
1988
+ }
1989
+ curVals, exists := selectRow(pkVals)
1990
+ if !exists {
1991
+ if callConflict(2) == 2 { // SQLITE_CHANGESET_NOTFOUND
1992
+ return false
1993
+ }
1994
+ continue
1995
+ }
1996
+ if !isPatchset {
1997
+ mismatch := false
1998
+ for i := 0; i < nCol; i++ {
1999
+ if !tnSqliteSessValEqual(curVals[i], oldVals[i]) {
2000
+ mismatch = true
2001
+ break
2002
+ }
2003
+ }
2004
+ if mismatch {
2005
+ action := callConflict(1) // SQLITE_CHANGESET_DATA
2006
+ if action == 2 {
2007
+ return false
2008
+ }
2009
+ if action == 0 {
2010
+ continue
2011
+ }
2012
+ }
2013
+ }
2014
+ delSQL := fmt.Sprintf("DELETE FROM %s WHERE %s", qTable, whereClause)
2015
+ dst, _, derr := db.conn.Prepare(delSQL)
2016
+ db.check(derr)
2017
+ for i, v := range pkVals {
2018
+ db.check(tnSqliteBindSessVal(dst, i+1, v))
2019
+ }
2020
+ derr = dst.Exec()
2021
+ dst.Close()
2022
+ if derr != nil {
2023
+ if !tnSqliteIsConstraint(derr) {
2024
+ db.check(derr)
2025
+ }
2026
+ if callConflict(4) == 2 {
2027
+ return false
2028
+ }
2029
+ }
2030
+
2031
+ case 23: // UPDATE
2032
+ pkVals := make([]tnSqliteSessVal, len(pkCols))
2033
+ if isPatchset {
2034
+ for i, colIdx := range pkCols {
2035
+ pkVals[i] = newVals[colIdx]
2036
+ }
2037
+ } else {
2038
+ for i, colIdx := range pkCols {
2039
+ pkVals[i] = oldVals[colIdx]
2040
+ }
2041
+ }
2042
+ curVals, exists := selectRow(pkVals)
2043
+ if !exists {
2044
+ if callConflict(2) == 2 { // SQLITE_CHANGESET_NOTFOUND
2045
+ return false
2046
+ }
2047
+ continue
2048
+ }
2049
+ if !isPatchset {
2050
+ mismatch := false
2051
+ for i := 0; i < nCol; i++ {
2052
+ if oldVals[i].kind != 0 && !tnSqliteSessValEqual(curVals[i], oldVals[i]) {
2053
+ mismatch = true
2054
+ break
2055
+ }
2056
+ }
2057
+ if mismatch {
2058
+ action := callConflict(1) // SQLITE_CHANGESET_DATA
2059
+ if action == 2 {
2060
+ return false
2061
+ }
2062
+ if action == 0 {
2063
+ continue
2064
+ }
2065
+ }
2066
+ }
2067
+ var setParts []string
2068
+ var setVals []tnSqliteSessVal
2069
+ for i := 0; i < nCol; i++ {
2070
+ if newVals[i].kind != 0 && (!isPatchset || pkFlags[i] == 0) {
2071
+ setParts = append(setParts, colNames[i]+" = ?")
2072
+ setVals = append(setVals, newVals[i])
2073
+ }
2074
+ }
2075
+ if len(setParts) > 0 {
2076
+ updSQL := fmt.Sprintf("UPDATE %s SET %s WHERE %s", qTable, strings.Join(setParts, ", "), whereClause)
2077
+ ust, _, uerr := db.conn.Prepare(updSQL)
2078
+ db.check(uerr)
2079
+ for i, v := range setVals {
2080
+ db.check(tnSqliteBindSessVal(ust, i+1, v))
2081
+ }
2082
+ for i, v := range pkVals {
2083
+ db.check(tnSqliteBindSessVal(ust, len(setVals)+i+1, v))
2084
+ }
2085
+ uerr = ust.Exec()
2086
+ ust.Close()
2087
+ if uerr != nil {
2088
+ if !tnSqliteIsConstraint(uerr) {
2089
+ db.check(uerr)
2090
+ }
2091
+ if callConflict(4) == 2 {
2092
+ return false
2093
+ }
2094
+ }
2095
+ }
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ if fkeyEnabled {
2101
+ st, _, err := db.conn.Prepare("PRAGMA foreign_key_check")
2102
+ db.check(err)
2103
+ hasFKViolation := st.Step()
2104
+ st.Close()
2105
+ if hasFKViolation {
2106
+ action := callConflict(5) // SQLITE_CHANGESET_FOREIGN_KEY
2107
+ if action == 2 {
2108
+ panic(tnSqliteCodeError(19, "constraint failed"))
2109
+ }
2110
+ }
2111
+ }
2112
+ db.check(db.conn.Exec("RELEASE SAVEPOINT __tn_changeset"))
2113
+ committed = true
2114
+ return true
633
2115
  }
634
2116
 
635
2117
  // serialize(dbName = 'main') / deserialize(buffer, { dbName }): the database
@@ -1153,9 +2635,10 @@ func TnSqliteBackup(db *TnSqliteDb, path string, opts ...interface{}) chan float
1153
2635
  }`;
1154
2636
  export function registerSqlite(r) {
1155
2637
  defineModule(r, 'sqlite');
1156
- defineHelper(r, 'nodeSqlite', ['github.com/ncruces/go-sqlite3', 'errors', 'fmt', 'math', 'math/big', 'os', 'reflect', 'runtime', 'sort', 'strconv', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'nodeInvoke', 'eventLoop', 'promise'], sqliteHelper);
2638
+ defineHelper(r, 'nodeSqlite', ['github.com/ncruces/go-sqlite3', 'encoding/binary', 'errors', 'fmt', 'math', 'math/big', 'os', 'reflect', 'runtime', 'sort', 'strconv', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'nodeInvoke', 'eventLoop', 'promise', 'generatorStep'], sqliteHelper);
1157
2639
  const use = () => r.helper('nodeSqlite');
1158
- defineClass(r, 'sqlite.DatabaseSync', '*TnSqliteDb', 'class', 'open=; close=; exec=; prepare=*TnSqliteStmt; location=*string; function=; aggregate=; enableLoadExtension=; enableDefensive=; loadExtension=; setAuthorizer=; createTagStore=*TnSqliteTagStore; createSession=interface{}; applyChangeset=bool; serialize=[]byte; deserialize=', '', 'isOpen=bool; isTransaction=bool; limits=*TnSqliteLimits', '');
2640
+ defineClass(r, 'sqlite.DatabaseSync', '*TnSqliteDb', 'class', 'open=; close=; exec=; prepare=*TnSqliteStmt; location=*string; function=; aggregate=; createModule=; enableLoadExtension=; enableDefensive=; loadExtension=; setAuthorizer=; createTagStore=*TnSqliteTagStore; createSession=*TnSqliteSession; applyChangeset=bool; serialize=[]byte; deserialize=', '', 'isOpen=bool; isTransaction=bool; limits=*TnSqliteLimits', '');
2641
+ defineClass(r, 'sqlite.Session', '*TnSqliteSession', 'class', 'changeset=[]byte; patchset=[]byte; close=; __dispose=', '', '', '');
1159
2642
  defineClass(r, 'sqlite.StatementSync', '*TnSqliteStmt', 'class', 'run=*TnSqliteRunResult; get=interface{}; all=[]interface{}; iterate=*TnSqliteIterator; columns=[]interface{}; setReadBigInts=; setReturnArrays=; setAllowBareNamedParameters=; setAllowUnknownNamedParameters=; close=; __dispose=; stat=float64; resetStats=', '', 'sourceSQL=string; expandedSQL=string', '');
1160
2643
  defineClass(r, 'sqlite.StatementResultingChanges', '*TnSqliteRunResult', 'class', '', 'changes=interface{}; lastInsertRowid=interface{}', '', '');
1161
2644
  defineClass(r, 'sqlite.SQLTagStore', '*TnSqliteTagStore', 'class', 'get=interface{}; all=[]interface{}; iterate=*TnSqliteIterator; run=*TnSqliteRunResult; clear=', '', 'size=float64; capacity=float64; db=*TnSqliteDb', '');