@quereus/quereus 0.7.2 → 0.7.4

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 (566) hide show
  1. package/package.json +3 -3
  2. package/dist/src/common/constants.js.map +0 -1
  3. package/dist/src/common/datatype.js.map +0 -1
  4. package/dist/src/common/errors.js.map +0 -1
  5. package/dist/src/common/json-types.js.map +0 -1
  6. package/dist/src/common/logger.js.map +0 -1
  7. package/dist/src/common/type-inference.js.map +0 -1
  8. package/dist/src/common/types.js.map +0 -1
  9. package/dist/src/core/database-options.js.map +0 -1
  10. package/dist/src/core/database.js.map +0 -1
  11. package/dist/src/core/param.js.map +0 -1
  12. package/dist/src/core/statement.js.map +0 -1
  13. package/dist/src/func/builtins/aggregate.js.map +0 -1
  14. package/dist/src/func/builtins/builtin-window-functions.js.map +0 -1
  15. package/dist/src/func/builtins/conversion.js.map +0 -1
  16. package/dist/src/func/builtins/datetime.js.map +0 -1
  17. package/dist/src/func/builtins/explain.js.map +0 -1
  18. package/dist/src/func/builtins/generation.js.map +0 -1
  19. package/dist/src/func/builtins/index.js.map +0 -1
  20. package/dist/src/func/builtins/json-helpers.js.map +0 -1
  21. package/dist/src/func/builtins/json-tvf.js.map +0 -1
  22. package/dist/src/func/builtins/json.js.map +0 -1
  23. package/dist/src/func/builtins/scalar.js.map +0 -1
  24. package/dist/src/func/builtins/schema.js.map +0 -1
  25. package/dist/src/func/builtins/string.js.map +0 -1
  26. package/dist/src/func/builtins/timespan.js.map +0 -1
  27. package/dist/src/func/context.js.map +0 -1
  28. package/dist/src/func/registration.js.map +0 -1
  29. package/dist/src/index.js.map +0 -1
  30. package/dist/src/parser/ast.js.map +0 -1
  31. package/dist/src/parser/index.js.map +0 -1
  32. package/dist/src/parser/lexer.js.map +0 -1
  33. package/dist/src/parser/parser.js.map +0 -1
  34. package/dist/src/parser/utils.js.map +0 -1
  35. package/dist/src/parser/visitor.js.map +0 -1
  36. package/dist/src/planner/analysis/binding-collector.js.map +0 -1
  37. package/dist/src/planner/analysis/const-evaluator.js.map +0 -1
  38. package/dist/src/planner/analysis/const-pass.js.map +0 -1
  39. package/dist/src/planner/analysis/constraint-extractor.js.map +0 -1
  40. package/dist/src/planner/analysis/predicate-normalizer.js.map +0 -1
  41. package/dist/src/planner/building/alter-table.js.map +0 -1
  42. package/dist/src/planner/building/block.js.map +0 -1
  43. package/dist/src/planner/building/constraint-builder.js.map +0 -1
  44. package/dist/src/planner/building/create-assertion.js.map +0 -1
  45. package/dist/src/planner/building/create-view.js.map +0 -1
  46. package/dist/src/planner/building/ddl.js.map +0 -1
  47. package/dist/src/planner/building/declare-schema.js.map +0 -1
  48. package/dist/src/planner/building/delete.js.map +0 -1
  49. package/dist/src/planner/building/drop-assertion.js.map +0 -1
  50. package/dist/src/planner/building/drop-table.js.map +0 -1
  51. package/dist/src/planner/building/drop-view.js.map +0 -1
  52. package/dist/src/planner/building/expression.js.map +0 -1
  53. package/dist/src/planner/building/function-call.js.map +0 -1
  54. package/dist/src/planner/building/insert.js.map +0 -1
  55. package/dist/src/planner/building/pragma.js.map +0 -1
  56. package/dist/src/planner/building/schema-resolution.js.map +0 -1
  57. package/dist/src/planner/building/select-aggregates.js.map +0 -1
  58. package/dist/src/planner/building/select-compound.js.map +0 -1
  59. package/dist/src/planner/building/select-context.js.map +0 -1
  60. package/dist/src/planner/building/select-modifiers.js.map +0 -1
  61. package/dist/src/planner/building/select-projections.js.map +0 -1
  62. package/dist/src/planner/building/select-window.js.map +0 -1
  63. package/dist/src/planner/building/select.js.map +0 -1
  64. package/dist/src/planner/building/table-function.js.map +0 -1
  65. package/dist/src/planner/building/table.js.map +0 -1
  66. package/dist/src/planner/building/transaction.js.map +0 -1
  67. package/dist/src/planner/building/update.js.map +0 -1
  68. package/dist/src/planner/building/with.js.map +0 -1
  69. package/dist/src/planner/cache/correlation-detector.js.map +0 -1
  70. package/dist/src/planner/cache/materialization-advisory.js.map +0 -1
  71. package/dist/src/planner/cache/reference-graph.js.map +0 -1
  72. package/dist/src/planner/cost/index.js.map +0 -1
  73. package/dist/src/planner/debug/logger-utils.js.map +0 -1
  74. package/dist/src/planner/debug.js.map +0 -1
  75. package/dist/src/planner/framework/characteristics.js.map +0 -1
  76. package/dist/src/planner/framework/context.js.map +0 -1
  77. package/dist/src/planner/framework/pass.js.map +0 -1
  78. package/dist/src/planner/framework/physical-utils.js.map +0 -1
  79. package/dist/src/planner/framework/registry.js.map +0 -1
  80. package/dist/src/planner/framework/trace.js.map +0 -1
  81. package/dist/src/planner/nodes/add-constraint-node.js.map +0 -1
  82. package/dist/src/planner/nodes/aggregate-function.js.map +0 -1
  83. package/dist/src/planner/nodes/aggregate-node.js.map +0 -1
  84. package/dist/src/planner/nodes/array-index-node.js.map +0 -1
  85. package/dist/src/planner/nodes/block.js.map +0 -1
  86. package/dist/src/planner/nodes/cache-node.js.map +0 -1
  87. package/dist/src/planner/nodes/constraint-check-node.js.map +0 -1
  88. package/dist/src/planner/nodes/create-assertion-node.js.map +0 -1
  89. package/dist/src/planner/nodes/create-index-node.js.map +0 -1
  90. package/dist/src/planner/nodes/create-table-node.js.map +0 -1
  91. package/dist/src/planner/nodes/create-view-node.js.map +0 -1
  92. package/dist/src/planner/nodes/cte-node.js.map +0 -1
  93. package/dist/src/planner/nodes/cte-reference-node.js.map +0 -1
  94. package/dist/src/planner/nodes/declarative-schema.js.map +0 -1
  95. package/dist/src/planner/nodes/delete-node.js.map +0 -1
  96. package/dist/src/planner/nodes/distinct-node.js.map +0 -1
  97. package/dist/src/planner/nodes/dml-executor-node.js.map +0 -1
  98. package/dist/src/planner/nodes/drop-assertion-node.js.map +0 -1
  99. package/dist/src/planner/nodes/drop-table-node.js.map +0 -1
  100. package/dist/src/planner/nodes/drop-view-node.js.map +0 -1
  101. package/dist/src/planner/nodes/filter.js.map +0 -1
  102. package/dist/src/planner/nodes/function.js.map +0 -1
  103. package/dist/src/planner/nodes/insert-node.js.map +0 -1
  104. package/dist/src/planner/nodes/internal-recursive-cte-ref-node.js.map +0 -1
  105. package/dist/src/planner/nodes/join-node.js.map +0 -1
  106. package/dist/src/planner/nodes/limit-offset.js.map +0 -1
  107. package/dist/src/planner/nodes/plan-node-type.js.map +0 -1
  108. package/dist/src/planner/nodes/plan-node.js.map +0 -1
  109. package/dist/src/planner/nodes/pragma.js.map +0 -1
  110. package/dist/src/planner/nodes/project-node.js.map +0 -1
  111. package/dist/src/planner/nodes/recursive-cte-node.js.map +0 -1
  112. package/dist/src/planner/nodes/reference.js.map +0 -1
  113. package/dist/src/planner/nodes/remote-query-node.js.map +0 -1
  114. package/dist/src/planner/nodes/retrieve-node.js.map +0 -1
  115. package/dist/src/planner/nodes/returning-node.js.map +0 -1
  116. package/dist/src/planner/nodes/scalar.js.map +0 -1
  117. package/dist/src/planner/nodes/sequencing-node.js.map +0 -1
  118. package/dist/src/planner/nodes/set-operation-node.js.map +0 -1
  119. package/dist/src/planner/nodes/single-row.js.map +0 -1
  120. package/dist/src/planner/nodes/sink-node.js.map +0 -1
  121. package/dist/src/planner/nodes/sort.js.map +0 -1
  122. package/dist/src/planner/nodes/stream-aggregate.js.map +0 -1
  123. package/dist/src/planner/nodes/subquery.js.map +0 -1
  124. package/dist/src/planner/nodes/table-access-nodes.js.map +0 -1
  125. package/dist/src/planner/nodes/table-function-call.js.map +0 -1
  126. package/dist/src/planner/nodes/transaction-node.js.map +0 -1
  127. package/dist/src/planner/nodes/update-node.js.map +0 -1
  128. package/dist/src/planner/nodes/values-node.js.map +0 -1
  129. package/dist/src/planner/nodes/view-reference-node.js.map +0 -1
  130. package/dist/src/planner/nodes/window-function.js.map +0 -1
  131. package/dist/src/planner/nodes/window-node.js.map +0 -1
  132. package/dist/src/planner/optimizer-tuning.js.map +0 -1
  133. package/dist/src/planner/optimizer.js.map +0 -1
  134. package/dist/src/planner/planning-context.js.map +0 -1
  135. package/dist/src/planner/resolve.js.map +0 -1
  136. package/dist/src/planner/rules/access/rule-select-access-path.js.map +0 -1
  137. package/dist/src/planner/rules/aggregate/rule-aggregate-streaming.js.map +0 -1
  138. package/dist/src/planner/rules/cache/rule-cte-optimization.js.map +0 -1
  139. package/dist/src/planner/rules/cache/rule-materialization-advisory.js.map +0 -1
  140. package/dist/src/planner/rules/cache/rule-mutating-subquery-cache.js.map +0 -1
  141. package/dist/src/planner/rules/join/rule-join-greedy-commute.js.map +0 -1
  142. package/dist/src/planner/rules/join/rule-join-key-inference.js.map +0 -1
  143. package/dist/src/planner/rules/join/rule-quickpick-enumeration.js.map +0 -1
  144. package/dist/src/planner/rules/predicate/rule-predicate-pushdown.js.map +0 -1
  145. package/dist/src/planner/rules/retrieve/rule-grow-retrieve.js.map +0 -1
  146. package/dist/src/planner/scopes/aliased.js.map +0 -1
  147. package/dist/src/planner/scopes/base.js.map +0 -1
  148. package/dist/src/planner/scopes/empty.js.map +0 -1
  149. package/dist/src/planner/scopes/global.js.map +0 -1
  150. package/dist/src/planner/scopes/multi.js.map +0 -1
  151. package/dist/src/planner/scopes/param.js.map +0 -1
  152. package/dist/src/planner/scopes/registered.js.map +0 -1
  153. package/dist/src/planner/scopes/scope.js.map +0 -1
  154. package/dist/src/planner/stats/basic-estimates.js.map +0 -1
  155. package/dist/src/planner/stats/index.js.map +0 -1
  156. package/dist/src/planner/type-utils.js.map +0 -1
  157. package/dist/src/planner/util/key-utils.js.map +0 -1
  158. package/dist/src/planner/validation/determinism-validator.js.map +0 -1
  159. package/dist/src/planner/validation/plan-validator.js.map +0 -1
  160. package/dist/src/runtime/async-util.js.map +0 -1
  161. package/dist/src/runtime/cache/shared-cache.js.map +0 -1
  162. package/dist/src/runtime/context-helpers.js.map +0 -1
  163. package/dist/src/runtime/deferred-constraint-queue.js.map +0 -1
  164. package/dist/src/runtime/emission-context.js.map +0 -1
  165. package/dist/src/runtime/emit/add-constraint.js.map +0 -1
  166. package/dist/src/runtime/emit/aggregate.js.map +0 -1
  167. package/dist/src/runtime/emit/array-index.js.map +0 -1
  168. package/dist/src/runtime/emit/between.js.map +0 -1
  169. package/dist/src/runtime/emit/binary.js.map +0 -1
  170. package/dist/src/runtime/emit/block.js.map +0 -1
  171. package/dist/src/runtime/emit/cache.js.map +0 -1
  172. package/dist/src/runtime/emit/case.js.map +0 -1
  173. package/dist/src/runtime/emit/cast.js.map +0 -1
  174. package/dist/src/runtime/emit/collate.js.map +0 -1
  175. package/dist/src/runtime/emit/column-reference.js.map +0 -1
  176. package/dist/src/runtime/emit/constraint-check.js.map +0 -1
  177. package/dist/src/runtime/emit/create-assertion.js.map +0 -1
  178. package/dist/src/runtime/emit/create-index.js.map +0 -1
  179. package/dist/src/runtime/emit/create-table.js.map +0 -1
  180. package/dist/src/runtime/emit/create-view.js.map +0 -1
  181. package/dist/src/runtime/emit/cte-reference.js.map +0 -1
  182. package/dist/src/runtime/emit/cte.js.map +0 -1
  183. package/dist/src/runtime/emit/delete.js.map +0 -1
  184. package/dist/src/runtime/emit/distinct.js.map +0 -1
  185. package/dist/src/runtime/emit/dml-executor.js.map +0 -1
  186. package/dist/src/runtime/emit/drop-assertion.js.map +0 -1
  187. package/dist/src/runtime/emit/drop-table.js.map +0 -1
  188. package/dist/src/runtime/emit/drop-view.js.map +0 -1
  189. package/dist/src/runtime/emit/filter.js.map +0 -1
  190. package/dist/src/runtime/emit/insert.js.map +0 -1
  191. package/dist/src/runtime/emit/internal-recursive-cte-ref.js.map +0 -1
  192. package/dist/src/runtime/emit/join.js.map +0 -1
  193. package/dist/src/runtime/emit/limit-offset.js.map +0 -1
  194. package/dist/src/runtime/emit/literal.js.map +0 -1
  195. package/dist/src/runtime/emit/parameter.js.map +0 -1
  196. package/dist/src/runtime/emit/pragma.js.map +0 -1
  197. package/dist/src/runtime/emit/project.js.map +0 -1
  198. package/dist/src/runtime/emit/recursive-cte.js.map +0 -1
  199. package/dist/src/runtime/emit/remote-query.js.map +0 -1
  200. package/dist/src/runtime/emit/retrieve.js.map +0 -1
  201. package/dist/src/runtime/emit/returning.js.map +0 -1
  202. package/dist/src/runtime/emit/scalar-function.js.map +0 -1
  203. package/dist/src/runtime/emit/scan.js.map +0 -1
  204. package/dist/src/runtime/emit/schema-declarative.js.map +0 -1
  205. package/dist/src/runtime/emit/sequencing.js.map +0 -1
  206. package/dist/src/runtime/emit/set-operation.js.map +0 -1
  207. package/dist/src/runtime/emit/sink.js.map +0 -1
  208. package/dist/src/runtime/emit/sort.js.map +0 -1
  209. package/dist/src/runtime/emit/subquery.js.map +0 -1
  210. package/dist/src/runtime/emit/table-valued-function.js.map +0 -1
  211. package/dist/src/runtime/emit/temporal-arithmetic.js.map +0 -1
  212. package/dist/src/runtime/emit/transaction.js.map +0 -1
  213. package/dist/src/runtime/emit/unary.js.map +0 -1
  214. package/dist/src/runtime/emit/update.js.map +0 -1
  215. package/dist/src/runtime/emit/values.js.map +0 -1
  216. package/dist/src/runtime/emit/window-function.js.map +0 -1
  217. package/dist/src/runtime/emit/window.js.map +0 -1
  218. package/dist/src/runtime/emitters.js.map +0 -1
  219. package/dist/src/runtime/register.js.map +0 -1
  220. package/dist/src/runtime/scheduler.js.map +0 -1
  221. package/dist/src/runtime/types.js.map +0 -1
  222. package/dist/src/runtime/utils.js.map +0 -1
  223. package/dist/src/schema/assertion.js.map +0 -1
  224. package/dist/src/schema/catalog.js.map +0 -1
  225. package/dist/src/schema/change-events.js.map +0 -1
  226. package/dist/src/schema/column.js.map +0 -1
  227. package/dist/src/schema/declared-schema-manager.js.map +0 -1
  228. package/dist/src/schema/function.js.map +0 -1
  229. package/dist/src/schema/manager.js.map +0 -1
  230. package/dist/src/schema/schema-differ.js.map +0 -1
  231. package/dist/src/schema/schema-hasher.js.map +0 -1
  232. package/dist/src/schema/schema.js.map +0 -1
  233. package/dist/src/schema/table.js.map +0 -1
  234. package/dist/src/schema/view.js.map +0 -1
  235. package/dist/src/schema/window-function.js.map +0 -1
  236. package/dist/src/types/builtin-types.js.map +0 -1
  237. package/dist/src/types/index.js.map +0 -1
  238. package/dist/src/types/json-type.js.map +0 -1
  239. package/dist/src/types/logical-type.js.map +0 -1
  240. package/dist/src/types/plugin-interface.js.map +0 -1
  241. package/dist/src/types/registry.js.map +0 -1
  242. package/dist/src/types/temporal-types.js.map +0 -1
  243. package/dist/src/types/validation.js.map +0 -1
  244. package/dist/src/util/affinity.js.map +0 -1
  245. package/dist/src/util/ast-stringify.js.map +0 -1
  246. package/dist/src/util/cached.js.map +0 -1
  247. package/dist/src/util/coercion.js.map +0 -1
  248. package/dist/src/util/comparison.js.map +0 -1
  249. package/dist/src/util/environment.js.map +0 -1
  250. package/dist/src/util/hash.js.map +0 -1
  251. package/dist/src/util/latches.js.map +0 -1
  252. package/dist/src/util/mutation-statement.js.map +0 -1
  253. package/dist/src/util/patterns.js.map +0 -1
  254. package/dist/src/util/plan-formatter.js.map +0 -1
  255. package/dist/src/util/plugin-helper.js.map +0 -1
  256. package/dist/src/util/row-descriptor.js.map +0 -1
  257. package/dist/src/util/serialization.js.map +0 -1
  258. package/dist/src/util/sql-literal.js.map +0 -1
  259. package/dist/src/util/working-table-iterable.js.map +0 -1
  260. package/dist/src/vtab/best-access-plan.js.map +0 -1
  261. package/dist/src/vtab/connection.js.map +0 -1
  262. package/dist/src/vtab/filter-info.js.map +0 -1
  263. package/dist/src/vtab/index-info.js.map +0 -1
  264. package/dist/src/vtab/manifest.js.map +0 -1
  265. package/dist/src/vtab/memory/connection.js.map +0 -1
  266. package/dist/src/vtab/memory/index.js.map +0 -1
  267. package/dist/src/vtab/memory/layer/base-cursor.js.map +0 -1
  268. package/dist/src/vtab/memory/layer/base.js.map +0 -1
  269. package/dist/src/vtab/memory/layer/connection.js.map +0 -1
  270. package/dist/src/vtab/memory/layer/interface.js.map +0 -1
  271. package/dist/src/vtab/memory/layer/manager.js.map +0 -1
  272. package/dist/src/vtab/memory/layer/safe-iterate.js.map +0 -1
  273. package/dist/src/vtab/memory/layer/scan-plan.js.map +0 -1
  274. package/dist/src/vtab/memory/layer/transaction-cursor.js.map +0 -1
  275. package/dist/src/vtab/memory/layer/transaction.js.map +0 -1
  276. package/dist/src/vtab/memory/module.js.map +0 -1
  277. package/dist/src/vtab/memory/table.js.map +0 -1
  278. package/dist/src/vtab/memory/types.js.map +0 -1
  279. package/dist/src/vtab/memory/utils/logging.js.map +0 -1
  280. package/dist/src/vtab/memory/utils/primary-key.js.map +0 -1
  281. package/dist/src/vtab/module.js.map +0 -1
  282. package/dist/src/vtab/table.js.map +0 -1
  283. package/src/common/constants.ts +0 -60
  284. package/src/common/datatype.ts +0 -85
  285. package/src/common/errors.ts +0 -189
  286. package/src/common/json-types.ts +0 -16
  287. package/src/common/logger.ts +0 -97
  288. package/src/common/type-inference.ts +0 -39
  289. package/src/common/types.ts +0 -151
  290. package/src/core/database-options.ts +0 -258
  291. package/src/core/database.ts +0 -1461
  292. package/src/core/param.ts +0 -56
  293. package/src/core/statement.ts +0 -528
  294. package/src/func/builtins/aggregate.ts +0 -269
  295. package/src/func/builtins/builtin-window-functions.ts +0 -166
  296. package/src/func/builtins/conversion.ts +0 -226
  297. package/src/func/builtins/datetime.ts +0 -500
  298. package/src/func/builtins/explain.ts +0 -779
  299. package/src/func/builtins/generation.ts +0 -43
  300. package/src/func/builtins/index.ts +0 -167
  301. package/src/func/builtins/json-helpers.ts +0 -237
  302. package/src/func/builtins/json-tvf.ts +0 -224
  303. package/src/func/builtins/json.ts +0 -588
  304. package/src/func/builtins/scalar.ts +0 -423
  305. package/src/func/builtins/schema.ts +0 -213
  306. package/src/func/builtins/string.ts +0 -306
  307. package/src/func/builtins/timespan.ts +0 -179
  308. package/src/func/context.ts +0 -258
  309. package/src/func/registration.ts +0 -201
  310. package/src/index.ts +0 -172
  311. package/src/parser/ast.ts +0 -581
  312. package/src/parser/index.ts +0 -65
  313. package/src/parser/lexer.ts +0 -806
  314. package/src/parser/parser.ts +0 -3352
  315. package/src/parser/utils.ts +0 -10
  316. package/src/parser/visitor.ts +0 -188
  317. package/src/planner/analysis/README.md +0 -93
  318. package/src/planner/analysis/binding-collector.ts +0 -83
  319. package/src/planner/analysis/const-evaluator.ts +0 -63
  320. package/src/planner/analysis/const-pass.ts +0 -282
  321. package/src/planner/analysis/constraint-extractor.ts +0 -764
  322. package/src/planner/analysis/predicate-normalizer.ts +0 -237
  323. package/src/planner/building/alter-table.ts +0 -49
  324. package/src/planner/building/block.ts +0 -93
  325. package/src/planner/building/constraint-builder.ts +0 -178
  326. package/src/planner/building/create-assertion.ts +0 -7
  327. package/src/planner/building/create-view.ts +0 -29
  328. package/src/planner/building/ddl.ts +0 -24
  329. package/src/planner/building/declare-schema.ts +0 -22
  330. package/src/planner/building/delete.ts +0 -218
  331. package/src/planner/building/drop-assertion.ts +0 -11
  332. package/src/planner/building/drop-table.ts +0 -13
  333. package/src/planner/building/drop-view.ts +0 -19
  334. package/src/planner/building/expression.ts +0 -205
  335. package/src/planner/building/function-call.ts +0 -129
  336. package/src/planner/building/insert.ts +0 -435
  337. package/src/planner/building/pragma.ts +0 -34
  338. package/src/planner/building/schema-resolution.ts +0 -176
  339. package/src/planner/building/select-aggregates.ts +0 -318
  340. package/src/planner/building/select-compound.ts +0 -119
  341. package/src/planner/building/select-context.ts +0 -85
  342. package/src/planner/building/select-modifiers.ts +0 -236
  343. package/src/planner/building/select-projections.ts +0 -177
  344. package/src/planner/building/select-window.ts +0 -259
  345. package/src/planner/building/select.ts +0 -567
  346. package/src/planner/building/table-function.ts +0 -49
  347. package/src/planner/building/table.ts +0 -40
  348. package/src/planner/building/transaction.ts +0 -23
  349. package/src/planner/building/update.ts +0 -331
  350. package/src/planner/building/with.ts +0 -180
  351. package/src/planner/cache/correlation-detector.ts +0 -83
  352. package/src/planner/cache/materialization-advisory.ts +0 -265
  353. package/src/planner/cache/reference-graph.ts +0 -196
  354. package/src/planner/cost/index.ts +0 -169
  355. package/src/planner/debug/logger-utils.ts +0 -68
  356. package/src/planner/debug.ts +0 -480
  357. package/src/planner/framework/README.md +0 -132
  358. package/src/planner/framework/characteristics.ts +0 -503
  359. package/src/planner/framework/context.ts +0 -239
  360. package/src/planner/framework/pass.ts +0 -354
  361. package/src/planner/framework/physical-utils.ts +0 -210
  362. package/src/planner/framework/registry.ts +0 -261
  363. package/src/planner/framework/trace.ts +0 -259
  364. package/src/planner/nodes/add-constraint-node.ts +0 -62
  365. package/src/planner/nodes/aggregate-function.ts +0 -155
  366. package/src/planner/nodes/aggregate-node.ts +0 -267
  367. package/src/planner/nodes/array-index-node.ts +0 -50
  368. package/src/planner/nodes/block.ts +0 -80
  369. package/src/planner/nodes/cache-node.ts +0 -103
  370. package/src/planner/nodes/constraint-check-node.ts +0 -138
  371. package/src/planner/nodes/create-assertion-node.ts +0 -51
  372. package/src/planner/nodes/create-index-node.ts +0 -41
  373. package/src/planner/nodes/create-table-node.ts +0 -35
  374. package/src/planner/nodes/create-view-node.ts +0 -44
  375. package/src/planner/nodes/cte-node.ts +0 -168
  376. package/src/planner/nodes/cte-reference-node.ts +0 -125
  377. package/src/planner/nodes/declarative-schema.ts +0 -221
  378. package/src/planner/nodes/delete-node.ts +0 -102
  379. package/src/planner/nodes/distinct-node.ts +0 -107
  380. package/src/planner/nodes/dml-executor-node.ts +0 -104
  381. package/src/planner/nodes/drop-assertion-node.ts +0 -50
  382. package/src/planner/nodes/drop-table-node.ts +0 -36
  383. package/src/planner/nodes/drop-view-node.ts +0 -37
  384. package/src/planner/nodes/filter.ts +0 -144
  385. package/src/planner/nodes/function.ts +0 -98
  386. package/src/planner/nodes/insert-node.ts +0 -126
  387. package/src/planner/nodes/internal-recursive-cte-ref-node.ts +0 -61
  388. package/src/planner/nodes/join-node.ts +0 -336
  389. package/src/planner/nodes/limit-offset.ts +0 -144
  390. package/src/planner/nodes/plan-node-type.ts +0 -95
  391. package/src/planner/nodes/plan-node.ts +0 -503
  392. package/src/planner/nodes/pragma.ts +0 -98
  393. package/src/planner/nodes/project-node.ts +0 -337
  394. package/src/planner/nodes/recursive-cte-node.ts +0 -158
  395. package/src/planner/nodes/reference.ts +0 -334
  396. package/src/planner/nodes/remote-query-node.ts +0 -73
  397. package/src/planner/nodes/retrieve-node.ts +0 -86
  398. package/src/planner/nodes/returning-node.ts +0 -269
  399. package/src/planner/nodes/scalar.ts +0 -772
  400. package/src/planner/nodes/sequencing-node.ts +0 -113
  401. package/src/planner/nodes/set-operation-node.ts +0 -87
  402. package/src/planner/nodes/single-row.ts +0 -85
  403. package/src/planner/nodes/sink-node.ts +0 -61
  404. package/src/planner/nodes/sort.ts +0 -166
  405. package/src/planner/nodes/stream-aggregate.ts +0 -293
  406. package/src/planner/nodes/subquery.ts +0 -268
  407. package/src/planner/nodes/table-access-nodes.ts +0 -323
  408. package/src/planner/nodes/table-function-call.ts +0 -134
  409. package/src/planner/nodes/transaction-node.ts +0 -55
  410. package/src/planner/nodes/update-node.ts +0 -138
  411. package/src/planner/nodes/values-node.ts +0 -244
  412. package/src/planner/nodes/view-reference-node.ts +0 -97
  413. package/src/planner/nodes/window-function.ts +0 -73
  414. package/src/planner/nodes/window-node.ts +0 -199
  415. package/src/planner/optimizer-tuning.ts +0 -105
  416. package/src/planner/optimizer.ts +0 -332
  417. package/src/planner/planning-context.ts +0 -190
  418. package/src/planner/resolve.ts +0 -101
  419. package/src/planner/rules/README.md +0 -96
  420. package/src/planner/rules/access/rule-select-access-path.ts +0 -399
  421. package/src/planner/rules/aggregate/rule-aggregate-streaming.ts +0 -162
  422. package/src/planner/rules/cache/rule-cte-optimization.ts +0 -79
  423. package/src/planner/rules/cache/rule-materialization-advisory.ts +0 -77
  424. package/src/planner/rules/cache/rule-mutating-subquery-cache.ts +0 -104
  425. package/src/planner/rules/join/rule-join-greedy-commute.ts +0 -48
  426. package/src/planner/rules/join/rule-join-key-inference.ts +0 -35
  427. package/src/planner/rules/join/rule-quickpick-enumeration.ts +0 -267
  428. package/src/planner/rules/predicate/rule-predicate-pushdown.ts +0 -144
  429. package/src/planner/rules/retrieve/rule-grow-retrieve.ts +0 -337
  430. package/src/planner/scopes/aliased.ts +0 -50
  431. package/src/planner/scopes/base.ts +0 -10
  432. package/src/planner/scopes/empty.ts +0 -12
  433. package/src/planner/scopes/global.ts +0 -73
  434. package/src/planner/scopes/multi.ts +0 -40
  435. package/src/planner/scopes/param.ts +0 -95
  436. package/src/planner/scopes/registered.ts +0 -67
  437. package/src/planner/scopes/scope.ts +0 -16
  438. package/src/planner/stats/basic-estimates.ts +0 -107
  439. package/src/planner/stats/index.ts +0 -158
  440. package/src/planner/type-utils.ts +0 -87
  441. package/src/planner/util/key-utils.ts +0 -46
  442. package/src/planner/validation/determinism-validator.ts +0 -104
  443. package/src/planner/validation/plan-validator.ts +0 -335
  444. package/src/runtime/async-util.ts +0 -283
  445. package/src/runtime/cache/shared-cache.ts +0 -169
  446. package/src/runtime/context-helpers.ts +0 -191
  447. package/src/runtime/deferred-constraint-queue.ts +0 -196
  448. package/src/runtime/emission-context.ts +0 -319
  449. package/src/runtime/emit/add-constraint.ts +0 -78
  450. package/src/runtime/emit/aggregate.ts +0 -581
  451. package/src/runtime/emit/array-index.ts +0 -25
  452. package/src/runtime/emit/between.ts +0 -51
  453. package/src/runtime/emit/binary.ts +0 -357
  454. package/src/runtime/emit/block.ts +0 -23
  455. package/src/runtime/emit/cache.ts +0 -64
  456. package/src/runtime/emit/case.ts +0 -87
  457. package/src/runtime/emit/cast.ts +0 -151
  458. package/src/runtime/emit/collate.ts +0 -9
  459. package/src/runtime/emit/column-reference.ts +0 -17
  460. package/src/runtime/emit/constraint-check.ts +0 -290
  461. package/src/runtime/emit/create-assertion.ts +0 -82
  462. package/src/runtime/emit/create-index.ts +0 -15
  463. package/src/runtime/emit/create-table.ts +0 -15
  464. package/src/runtime/emit/create-view.ts +0 -52
  465. package/src/runtime/emit/cte-reference.ts +0 -38
  466. package/src/runtime/emit/cte.ts +0 -39
  467. package/src/runtime/emit/delete.ts +0 -24
  468. package/src/runtime/emit/distinct.ts +0 -40
  469. package/src/runtime/emit/dml-executor.ts +0 -198
  470. package/src/runtime/emit/drop-assertion.ts +0 -45
  471. package/src/runtime/emit/drop-table.ts +0 -27
  472. package/src/runtime/emit/drop-view.ts +0 -49
  473. package/src/runtime/emit/filter.ts +0 -30
  474. package/src/runtime/emit/insert.ts +0 -42
  475. package/src/runtime/emit/internal-recursive-cte-ref.ts +0 -37
  476. package/src/runtime/emit/join.ts +0 -148
  477. package/src/runtime/emit/limit-offset.ts +0 -73
  478. package/src/runtime/emit/literal.ts +0 -17
  479. package/src/runtime/emit/parameter.ts +0 -59
  480. package/src/runtime/emit/pragma.ts +0 -56
  481. package/src/runtime/emit/project.ts +0 -46
  482. package/src/runtime/emit/recursive-cte.ts +0 -111
  483. package/src/runtime/emit/remote-query.ts +0 -47
  484. package/src/runtime/emit/retrieve.ts +0 -15
  485. package/src/runtime/emit/returning.ts +0 -41
  486. package/src/runtime/emit/scalar-function.ts +0 -69
  487. package/src/runtime/emit/scan.ts +0 -106
  488. package/src/runtime/emit/schema-declarative.ts +0 -215
  489. package/src/runtime/emit/sequencing.ts +0 -24
  490. package/src/runtime/emit/set-operation.ts +0 -141
  491. package/src/runtime/emit/sink.ts +0 -27
  492. package/src/runtime/emit/sort.ts +0 -75
  493. package/src/runtime/emit/subquery.ts +0 -203
  494. package/src/runtime/emit/table-valued-function.ts +0 -106
  495. package/src/runtime/emit/temporal-arithmetic.ts +0 -302
  496. package/src/runtime/emit/transaction.ts +0 -205
  497. package/src/runtime/emit/unary.ts +0 -101
  498. package/src/runtime/emit/update.ts +0 -66
  499. package/src/runtime/emit/values.ts +0 -66
  500. package/src/runtime/emit/window-function.ts +0 -42
  501. package/src/runtime/emit/window.ts +0 -458
  502. package/src/runtime/emitters.ts +0 -183
  503. package/src/runtime/register.ts +0 -150
  504. package/src/runtime/scheduler.ts +0 -488
  505. package/src/runtime/types.ts +0 -242
  506. package/src/runtime/utils.ts +0 -177
  507. package/src/schema/assertion.ts +0 -21
  508. package/src/schema/catalog.ts +0 -269
  509. package/src/schema/change-events.ts +0 -80
  510. package/src/schema/column.ts +0 -51
  511. package/src/schema/declared-schema-manager.ts +0 -82
  512. package/src/schema/function.ts +0 -188
  513. package/src/schema/manager.ts +0 -1034
  514. package/src/schema/schema-differ.ts +0 -214
  515. package/src/schema/schema-hasher.ts +0 -26
  516. package/src/schema/schema.ts +0 -222
  517. package/src/schema/table.ts +0 -409
  518. package/src/schema/view.ts +0 -19
  519. package/src/schema/window-function.ts +0 -56
  520. package/src/types/builtin-types.ts +0 -350
  521. package/src/types/index.ts +0 -17
  522. package/src/types/json-type.ts +0 -152
  523. package/src/types/logical-type.ts +0 -91
  524. package/src/types/plugin-interface.ts +0 -10
  525. package/src/types/registry.ts +0 -204
  526. package/src/types/temporal-types.ts +0 -290
  527. package/src/types/validation.ts +0 -120
  528. package/src/util/affinity.ts +0 -151
  529. package/src/util/ast-stringify.ts +0 -887
  530. package/src/util/cached.ts +0 -25
  531. package/src/util/coercion.ts +0 -113
  532. package/src/util/comparison.ts +0 -510
  533. package/src/util/environment.ts +0 -52
  534. package/src/util/hash.ts +0 -90
  535. package/src/util/latches.ts +0 -47
  536. package/src/util/mutation-statement.ts +0 -135
  537. package/src/util/patterns.ts +0 -56
  538. package/src/util/plan-formatter.ts +0 -48
  539. package/src/util/plugin-helper.ts +0 -110
  540. package/src/util/row-descriptor.ts +0 -105
  541. package/src/util/serialization.ts +0 -47
  542. package/src/util/sql-literal.ts +0 -22
  543. package/src/util/working-table-iterable.ts +0 -38
  544. package/src/vtab/best-access-plan.ts +0 -244
  545. package/src/vtab/connection.ts +0 -36
  546. package/src/vtab/filter-info.ts +0 -23
  547. package/src/vtab/index-info.ts +0 -84
  548. package/src/vtab/manifest.ts +0 -86
  549. package/src/vtab/memory/connection.ts +0 -73
  550. package/src/vtab/memory/index.ts +0 -191
  551. package/src/vtab/memory/layer/base-cursor.ts +0 -124
  552. package/src/vtab/memory/layer/base.ts +0 -275
  553. package/src/vtab/memory/layer/connection.ts +0 -203
  554. package/src/vtab/memory/layer/interface.ts +0 -47
  555. package/src/vtab/memory/layer/manager.ts +0 -909
  556. package/src/vtab/memory/layer/safe-iterate.ts +0 -49
  557. package/src/vtab/memory/layer/scan-plan.ts +0 -84
  558. package/src/vtab/memory/layer/transaction-cursor.ts +0 -162
  559. package/src/vtab/memory/layer/transaction.ts +0 -229
  560. package/src/vtab/memory/module.ts +0 -667
  561. package/src/vtab/memory/table.ts +0 -251
  562. package/src/vtab/memory/types.ts +0 -23
  563. package/src/vtab/memory/utils/logging.ts +0 -36
  564. package/src/vtab/memory/utils/primary-key.ts +0 -163
  565. package/src/vtab/module.ts +0 -162
  566. package/src/vtab/table.ts +0 -177
@@ -1,1034 +0,0 @@
1
- import { Schema } from './schema.js';
2
- import type { IntegrityAssertionSchema } from './assertion.js';
3
- import type { Database } from '../core/database.js';
4
- import type { TableSchema, RowConstraintSchema, IndexSchema, IndexColumnSchema } from './table.js';
5
- import type { FunctionSchema } from './function.js';
6
- import { quereusError, QuereusError } from '../common/errors.js';
7
- import { StatusCode, type SqlValue } from '../common/types.js';
8
- import type { AnyVirtualTableModule, BaseModuleConfig } from '../vtab/module.js';
9
- import type { VirtualTable } from '../vtab/table.js';
10
- import type { ColumnSchema } from './column.js';
11
- import { buildColumnIndexMap, columnDefToSchema, findPKDefinition, opsToMask, mutationContextVarToSchema } from './table.js';
12
- import type { ViewSchema } from './view.js';
13
- import { createLogger } from '../common/logger.js';
14
- import type * as AST from '../parser/ast.js';
15
- import { Parser } from '../parser/parser.js';
16
- import { SchemaChangeNotifier } from './change-events.js';
17
- import { checkDeterministic } from '../planner/validation/determinism-validator.js';
18
- import { buildExpression } from '../planner/building/expression.js';
19
- import type { PlanningContext } from '../planner/planning-context.js';
20
- import { BuildTimeDependencyTracker } from '../planner/planning-context.js';
21
- import { GlobalScope } from '../planner/scopes/global.js';
22
- import { ParameterScope } from '../planner/scopes/param.js';
23
- import type { ScalarPlanNode } from '../planner/nodes/plan-node.js';
24
-
25
- const log = createLogger('schema:manager');
26
- const warnLog = log.extend('warn');
27
- const errorLog = log.extend('error');
28
-
29
- /**
30
- * Generic options passed to VTab modules during CREATE TABLE.
31
- * Modules are responsible for interpreting these.
32
- */
33
- export interface GenericModuleCallOptions extends BaseModuleConfig {
34
- moduleArgs?: readonly string[];
35
- statementColumns?: readonly AST.ColumnDef[];
36
- statementConstraints?: readonly AST.TableConstraint[];
37
- isTemporary?: boolean;
38
- }
39
-
40
- /**
41
- * Manages all schemas associated with a database connection (main, temp, attached).
42
- * Handles lookup resolution according to SQLite's rules.
43
- */
44
- export class SchemaManager {
45
- private schemas: Map<string, Schema> = new Map();
46
- private currentSchemaName: string = 'main';
47
- private modules: Map<string, { module: AnyVirtualTableModule, auxData?: unknown }> = new Map();
48
- private defaultVTabModuleName: string = 'memory';
49
- private defaultVTabModuleArgs: Record<string, SqlValue> = {};
50
- private db: Database;
51
- private changeNotifier = new SchemaChangeNotifier();
52
-
53
- /**
54
- * Creates a new schema manager
55
- *
56
- * @param db Reference to the parent Database instance
57
- */
58
- constructor(db: Database) {
59
- this.db = db;
60
- // Ensure 'main' and 'temp' schemas always exist
61
- this.schemas.set('main', new Schema('main'));
62
- this.schemas.set('temp', new Schema('temp'));
63
- }
64
-
65
- /**
66
- * Sets the current default schema for unqualified names
67
- *
68
- * @param name Schema name to set as current
69
- */
70
- setCurrentSchema(name: string): void {
71
- if (this.schemas.has(name.toLowerCase())) {
72
- this.currentSchemaName = name.toLowerCase();
73
- } else {
74
- warnLog(`Attempted to set current schema to non-existent schema: %s`, name);
75
- }
76
- }
77
-
78
- /**
79
- * Gets the name of the current default schema
80
- *
81
- * @returns Current schema name
82
- */
83
- getCurrentSchemaName(): string {
84
- return this.currentSchemaName;
85
- }
86
-
87
- /**
88
- * Registers a virtual table module
89
- *
90
- * @param name Module name
91
- * @param module Module implementation
92
- * @param auxData Optional client data associated with the module registration
93
- */
94
- registerModule(name: string, module: AnyVirtualTableModule, auxData?: unknown): void {
95
- const lowerName = name.toLowerCase();
96
- if (this.modules.has(lowerName)) {
97
- warnLog(`Replacing existing virtual table module: %s`, lowerName);
98
- }
99
- this.modules.set(lowerName, { module, auxData });
100
- log(`Registered VTab module: %s`, lowerName);
101
- }
102
-
103
- /**
104
- * Retrieves a registered virtual table module by name
105
- *
106
- * @param name Module name to look up
107
- * @returns The module and its auxData, or undefined if not found
108
- */
109
- getModule(name: string): { module: AnyVirtualTableModule, auxData?: unknown } | undefined {
110
- return this.modules.get(name.toLowerCase());
111
- }
112
-
113
- /**
114
- * Sets the default virtual table module to use when USING is omitted
115
- *
116
- * @param name Module name. Must be a registered module.
117
- * @throws QuereusError if the module name is not registered
118
- */
119
- setDefaultVTabModuleName(name: string): void {
120
- const lowerName = name.toLowerCase();
121
- if (this.modules.has(lowerName)) {
122
- this.defaultVTabModuleName = lowerName;
123
- log(`Default VTab module name set to: %s`, lowerName);
124
- } else {
125
- warnLog(`Setting default VTab module to '${lowerName}', which is not currently registered in SchemaManager. Ensure it gets registered.`);
126
- this.defaultVTabModuleName = lowerName;
127
- }
128
- }
129
-
130
- /**
131
- * Gets the currently configured default virtual table module name
132
- *
133
- * @returns The default module name
134
- */
135
- getDefaultVTabModuleName(): string {
136
- return this.defaultVTabModuleName;
137
- }
138
-
139
- /** @internal Sets the default VTab args directly */
140
- setDefaultVTabArgs(args: Record<string, SqlValue>): void {
141
- this.defaultVTabModuleArgs = args;
142
- log('Default VTab module args set to: %o', args);
143
- }
144
-
145
- /** @internal Sets the default VTab args by parsing a JSON string */
146
- setDefaultVTabArgsFromJson(argsJsonString: string): void {
147
- try {
148
- const parsedArgs = JSON.parse(argsJsonString);
149
- if (typeof parsedArgs !== 'object') {
150
- quereusError("JSON value must be an object.", StatusCode.MISUSE);
151
- }
152
- this.setDefaultVTabArgs(parsedArgs);
153
- } catch (e) {
154
- const msg = e instanceof Error ? e.message : String(e);
155
- quereusError(`Invalid JSON for default_vtab_args: ${msg}`, StatusCode.ERROR);
156
- }
157
- }
158
-
159
- /**
160
- * Gets the default virtual table module arguments.
161
- * @returns A copy of the default arguments array.
162
- */
163
- getDefaultVTabArgs(): Record<string, SqlValue> {
164
- return { ...this.defaultVTabModuleArgs };
165
- }
166
-
167
- /**
168
- * Gets the default virtual table module name and arguments.
169
- * @returns An object containing the module name and arguments.
170
- */
171
- getDefaultVTabModule(): { name: string; args: Record<string, SqlValue> } {
172
- return {
173
- name: this.defaultVTabModuleName,
174
- args: this.defaultVTabModuleArgs,
175
- };
176
- }
177
-
178
- /**
179
- * Gets a specific schema by name
180
- *
181
- * @param name Schema name to retrieve
182
- * @returns The schema or undefined if not found
183
- */
184
- getSchema(name: string): Schema | undefined {
185
- return this.schemas.get(name.toLowerCase());
186
- }
187
-
188
- /**
189
- * Gets the 'main' schema
190
- *
191
- * @returns The main schema
192
- */
193
- getMainSchema(): Schema {
194
- return this.schemas.get('main')!;
195
- }
196
-
197
- /**
198
- * Gets the 'temp' schema
199
- *
200
- * @returns The temp schema
201
- */
202
- getTempSchema(): Schema {
203
- return this.schemas.get('temp')!;
204
- }
205
-
206
- /**
207
- * @internal Returns iterator over all managed schemas
208
- */
209
- _getAllSchemas(): IterableIterator<Schema> {
210
- return this.schemas.values();
211
- }
212
-
213
- /**
214
- * Returns all assertions across all schemas
215
- */
216
- getAllAssertions(): IntegrityAssertionSchema[] {
217
- const result: IntegrityAssertionSchema[] = [];
218
- for (const schema of this._getAllSchemas()) {
219
- for (const a of schema.getAllAssertions()) {
220
- result.push(a);
221
- }
222
- }
223
- return result;
224
- }
225
-
226
- /**
227
- * Gets the schema change notifier for listening to schema changes
228
- */
229
- getChangeNotifier(): SchemaChangeNotifier {
230
- return this.changeNotifier;
231
- }
232
-
233
- /**
234
- * Adds a new schema (e.g., for ATTACH)
235
- *
236
- * @param name Name of the schema to add
237
- * @returns The newly created schema
238
- * @throws QuereusError if the name conflicts with an existing schema
239
- */
240
- addSchema(name: string): Schema {
241
- const lowerName = name.toLowerCase();
242
- if (this.schemas.has(lowerName)) {
243
- throw new QuereusError(`Schema '${name}' already exists`, StatusCode.ERROR);
244
- }
245
- const schema = new Schema(name);
246
- this.schemas.set(lowerName, schema);
247
- log(`Added schema '%s'`, name);
248
- return schema;
249
- }
250
-
251
- /**
252
- * Removes a schema (e.g., for DETACH)
253
- *
254
- * @param name Name of the schema to remove
255
- * @returns true if found and removed, false otherwise
256
- * @throws QuereusError if attempting to remove 'main' or 'temp'
257
- */
258
- removeSchema(name: string): boolean {
259
- const lowerName = name.toLowerCase();
260
- if (lowerName === 'main' || lowerName === 'temp') {
261
- throw new QuereusError(`Cannot detach schema '${name}'`, StatusCode.ERROR);
262
- }
263
- const schema = this.schemas.get(lowerName);
264
- if (schema) {
265
- schema.clearFunctions();
266
- schema.clearTables();
267
- schema.clearViews();
268
- this.schemas.delete(lowerName);
269
- log(`Removed schema '%s'`, name);
270
- return true;
271
- }
272
- return false;
273
- }
274
-
275
- /**
276
- * @internal Finds a table or virtual table by name across schemas
277
- */
278
- _findTable(tableName: string, dbName?: string): TableSchema | undefined {
279
- const lowerTableName = tableName.toLowerCase();
280
-
281
-
282
-
283
- if (dbName) {
284
- // Search specific schema
285
- const schema = this.schemas.get(dbName.toLowerCase());
286
- return schema?.getTable(lowerTableName);
287
- } else {
288
- // Search order: main, then temp (and attached later)
289
- const mainSchema = this.schemas.get('main');
290
- let table = mainSchema?.getTable(lowerTableName);
291
- if (table) return table;
292
-
293
- const tempSchema = this.schemas.get('temp');
294
- table = tempSchema?.getTable(lowerTableName);
295
- return table;
296
- }
297
- }
298
-
299
- /**
300
- * Finds a table by name, searching schemas according to SQLite rules
301
- *
302
- * @param tableName Name of the table
303
- * @param dbName Optional specific schema name to search
304
- * @returns The TableSchema or undefined if not found
305
- */
306
- findTable(tableName: string, dbName?: string): TableSchema | undefined {
307
- return this._findTable(tableName, dbName);
308
- }
309
-
310
- /**
311
- * Finds a function by name and arg count, searching schemas
312
- *
313
- * @param funcName Name of the function
314
- * @param nArg Number of arguments
315
- * @returns The FunctionSchema or undefined if not found
316
- */
317
- findFunction(funcName: string, nArg: number): FunctionSchema | undefined {
318
- return this.getMainSchema().getFunction(funcName, nArg);
319
- }
320
-
321
- /**
322
- * Retrieves a view schema definition
323
- *
324
- * @param schemaName The name of the schema ('main', 'temp', etc.). Defaults to current schema
325
- * @param viewName The name of the view
326
- * @returns The ViewSchema or undefined if not found
327
- */
328
- getView(schemaName: string | null, viewName: string): ViewSchema | undefined {
329
- const targetSchemaName = schemaName ?? this.currentSchemaName;
330
- const schema = this.schemas.get(targetSchemaName);
331
- return schema?.getView(viewName);
332
- }
333
-
334
- /**
335
- * Retrieves any schema item (table or view) by name. Checks views first
336
- *
337
- * @param schemaName The name of the schema ('main', 'temp', etc.). Defaults to current schema
338
- * @param itemName The name of the table or view
339
- * @returns The TableSchema or ViewSchema, or undefined if not found
340
- */
341
- getSchemaItem(schemaName: string | null, itemName: string): TableSchema | ViewSchema | undefined {
342
- const targetSchemaName = schemaName ?? this.currentSchemaName;
343
- const schema = this.schemas.get(targetSchemaName);
344
- if (!schema) return undefined;
345
-
346
- // Prioritize views over tables if names conflict
347
- const view = schema.getView(itemName);
348
- if (view) return view;
349
- return schema.getTable(itemName);
350
- }
351
-
352
- /**
353
- * Drops a table from the specified schema
354
- *
355
- * @param schemaName The name of the schema
356
- * @param tableName The name of the table to drop
357
- * @param ifExists If true, do not throw an error if the table does not exist.
358
- * @returns True if the table was found and dropped, false otherwise.
359
- */
360
- dropTable(schemaName: string, tableName: string, ifExists: boolean = false): boolean {
361
- const schema = this.schemas.get(schemaName.toLowerCase()); // Ensure schemaName is lowercased for lookup
362
- if (!schema) {
363
- if (ifExists) return false; // Schema not found, but IF EXISTS specified
364
- throw new QuereusError(`Schema not found: ${schemaName}`, StatusCode.ERROR);
365
- }
366
-
367
- const tableSchema = schema.getTable(tableName); // getTable should handle case-insensitivity
368
-
369
- if (!tableSchema) {
370
- if (ifExists) {
371
- log(`Table %s.%s not found, but IF EXISTS was specified.`, schemaName, tableName);
372
- return false; // Not found, but IF EXISTS means no error, not dropped.
373
- }
374
- throw new QuereusError(`Table ${tableName} not found in schema ${schemaName}`, StatusCode.NOTFOUND);
375
- }
376
-
377
- let destroyPromise: Promise<void> | null = null;
378
-
379
- // Call destroy on the module, providing table details
380
- if (tableSchema.vtabModuleName) { // tableSchema is guaranteed to be defined here
381
- const moduleRegistration = this.getModule(tableSchema.vtabModuleName);
382
- if (moduleRegistration && moduleRegistration.module && moduleRegistration.module.destroy) {
383
- log(`Calling destroy for VTab %s.%s via module %s`, schemaName, tableName, tableSchema.vtabModuleName);
384
- destroyPromise = moduleRegistration.module.destroy(
385
- this.db,
386
- moduleRegistration.auxData,
387
- tableSchema.vtabModuleName,
388
- schemaName,
389
- tableName
390
- ).catch(err => {
391
- errorLog(`Error during VTab module destroy for %s.%s: %O`, schemaName, tableName, err);
392
- // Potentially re-throw or handle as a critical error if destroy failure is problematic
393
- });
394
- } else {
395
- warnLog(`VTab module %s (for table %s.%s) or its destroy method not found during dropTable.`, tableSchema.vtabModuleName, schemaName, tableName);
396
- }
397
- }
398
-
399
- // Remove from schema map immediately
400
- const removed = schema.removeTable(tableName);
401
- if (!removed && !ifExists) {
402
- // This should ideally not be reached if tableSchema was found above.
403
- // But as a safeguard if removeTable could fail for other reasons.
404
- throw new QuereusError(`Failed to remove table ${tableName} from schema ${schemaName}, though it was initially found.`, StatusCode.INTERNAL);
405
- }
406
-
407
- // Notify schema change listeners if table was removed
408
- if (removed) {
409
- this.changeNotifier.notifyChange({
410
- type: 'table_removed',
411
- schemaName: schemaName,
412
- objectName: tableName,
413
- oldObject: tableSchema
414
- });
415
- }
416
-
417
- // Process destruction asynchronously
418
- if (destroyPromise) {
419
- void destroyPromise.then(() => log(`destroy completed for VTab %s.%s`, schemaName, tableName));
420
- }
421
-
422
- return removed; // True if removed from schema, false if not found and ifExists was true.
423
- }
424
-
425
- /**
426
- * Drops a view from the specified schema
427
- *
428
- * @param schemaName The name of the schema
429
- * @param viewName The name of the view to drop
430
- * @returns True if the view was found and dropped, false otherwise
431
- */
432
- dropView(schemaName: string, viewName: string): boolean {
433
- const schema = this.schemas.get(schemaName);
434
- if (!schema) return false;
435
- return schema.removeView(viewName);
436
- }
437
-
438
- /**
439
- * Clears all schema items (tables, functions, views)
440
- */
441
- clearAll(): void {
442
- this.schemas.forEach(schema => {
443
- schema.clearTables();
444
- schema.clearFunctions();
445
- schema.clearViews();
446
- });
447
- log("Cleared all schemas.");
448
- }
449
-
450
- /**
451
- * Retrieves a schema object, throwing if it doesn't exist
452
- *
453
- * @param name Schema name ('main', 'temp', or custom). Case-insensitive
454
- * @returns The Schema object
455
- * @throws QuereusError if the schema does not exist
456
- */
457
- getSchemaOrFail(name: string): Schema {
458
- const schema = this.schemas.get(name.toLowerCase());
459
- if (!schema) {
460
- throw new QuereusError(`Schema not found: ${name}`);
461
- }
462
- return schema;
463
- }
464
-
465
- /**
466
- * Retrieves a table from the specified schema
467
- *
468
- * @param schemaName The name of the schema ('main', 'temp', etc.). Defaults to current schema
469
- * @param tableName The name of the table
470
- * @returns The TableSchema or undefined if not found
471
- */
472
- getTable(schemaName: string | undefined, tableName: string): TableSchema | undefined {
473
- const targetSchemaName = schemaName ?? this.currentSchemaName;
474
- const schema = this.schemas.get(targetSchemaName);
475
- return schema?.getTable(tableName);
476
- }
477
-
478
- /**
479
- * Creates a new index on an existing table based on an AST.CreateIndexStmt.
480
- * This method validates the index definition and calls the virtual table's createIndex method.
481
- *
482
- * @param stmt The AST node for the CREATE INDEX statement.
483
- * @returns A Promise that resolves when the index is created.
484
- * @throws QuereusError on errors (e.g., table not found, column not found, createIndex fails).
485
- */
486
- async createIndex(stmt: AST.CreateIndexStmt): Promise<void> {
487
- const targetSchemaName = stmt.table.schema || this.getCurrentSchemaName();
488
- const tableName = stmt.table.name;
489
- const indexName = stmt.index.name;
490
-
491
- // Find the table schema
492
- const tableSchema = this.getTable(targetSchemaName, tableName);
493
- if (!tableSchema) {
494
- throw new QuereusError(`no such table: ${tableName}`, StatusCode.ERROR, undefined, stmt.table.loc?.start.line, stmt.table.loc?.start.column);
495
- }
496
-
497
- // Check if the virtual table module supports createIndex
498
- if (!tableSchema.vtabModule.createIndex) {
499
- throw new QuereusError(`Virtual table module '${tableSchema.vtabModuleName}' for table '${tableName}' does not support CREATE INDEX.`, StatusCode.ERROR, undefined, stmt.table.loc?.start.line, stmt.table.loc?.start.column);
500
- }
501
-
502
- // Check if index already exists (if not IF NOT EXISTS)
503
- const existingIndex = tableSchema.indexes?.find(idx => idx.name.toLowerCase() === indexName.toLowerCase());
504
- if (existingIndex) {
505
- if (stmt.ifNotExists) {
506
- log(`Skipping CREATE INDEX: Index %s.%s already exists (IF NOT EXISTS).`, targetSchemaName, indexName);
507
- return;
508
- } else {
509
- throw new QuereusError(`Index ${indexName} already exists on table ${tableName}`, StatusCode.CONSTRAINT, undefined, stmt.index.loc?.start.line, stmt.index.loc?.start.column);
510
- }
511
- }
512
-
513
- // Convert AST columns to IndexSchema columns
514
- const indexColumns = stmt.columns.map((indexedCol: AST.IndexedColumn) => {
515
- if (indexedCol.expr) {
516
- throw new QuereusError(`Indices on expressions are not supported yet.`, StatusCode.ERROR, undefined, indexedCol.expr.loc?.start.line, indexedCol.expr.loc?.start.column);
517
- }
518
- const colName = indexedCol.name;
519
- if (!colName) {
520
- // Should not happen if expr is checked first
521
- throw new QuereusError(`Indexed column must be a simple column name.`, StatusCode.ERROR);
522
- }
523
- const tableColIndex = tableSchema.columnIndexMap.get(colName.toLowerCase());
524
- if (tableColIndex === undefined) {
525
- throw new QuereusError(`Column '${colName}' not found in table '${tableName}'`, StatusCode.ERROR, undefined, stmt.loc?.start.line, stmt.loc?.start.column);
526
- }
527
- const tableColSchema = tableSchema.columns[tableColIndex];
528
- return {
529
- index: tableColIndex,
530
- desc: indexedCol.direction === 'desc',
531
- collation: indexedCol.collation || tableColSchema.collation // Use specified collation or inherit from table column
532
- };
533
- });
534
-
535
- // Construct the IndexSchema object
536
- const indexSchema: IndexSchema = {
537
- name: indexName,
538
- columns: Object.freeze(indexColumns),
539
- };
540
-
541
- try {
542
- // Call createIndex on the virtual table module
543
- await tableSchema.vtabModule.createIndex(
544
- this.db,
545
- targetSchemaName,
546
- tableName,
547
- indexSchema
548
- );
549
-
550
- // Update the table schema with the new index by creating a new schema object
551
- const updatedIndexes = [...(tableSchema.indexes || []), indexSchema];
552
- const updatedTableSchema: TableSchema = {
553
- ...tableSchema,
554
- indexes: Object.freeze(updatedIndexes),
555
- };
556
-
557
- // Replace the table schema in the schema
558
- const schema = this.getSchemaOrFail(targetSchemaName);
559
- schema.addTable(updatedTableSchema);
560
-
561
- // Notify schema change listeners that the table was modified
562
- this.changeNotifier.notifyChange({
563
- type: 'table_modified',
564
- schemaName: targetSchemaName,
565
- objectName: tableName,
566
- oldObject: tableSchema,
567
- newObject: updatedTableSchema
568
- });
569
-
570
- log(`Successfully created index %s on table %s.%s`, indexName, targetSchemaName, tableName);
571
- } catch (e: unknown) {
572
- const message = e instanceof Error ? e.message : String(e);
573
- const code = e instanceof QuereusError ? e.code : StatusCode.ERROR;
574
- throw new QuereusError(`createIndex failed for index '${indexName}' on table '${tableName}': ${message}`, code, e instanceof Error ? e : undefined, stmt.loc?.start.line, stmt.loc?.start.column);
575
- }
576
- }
577
-
578
- /**
579
- * Defines a new table in the schema based on an AST.CreateTableStmt.
580
- * This method encapsulates the logic for interacting with VTab modules (create)
581
- * and registering the new table schema.
582
- *
583
- * @param stmt The AST node for the CREATE TABLE statement.
584
- * @returns A Promise that resolves to the created TableSchema.
585
- * @throws QuereusError on errors (e.g., module not found, create fails, table exists).
586
- */
587
- async createTable(stmt: AST.CreateTableStmt): Promise<TableSchema> {
588
- const targetSchemaName = stmt.table.schema || this.getCurrentSchemaName();
589
- const tableName = stmt.table.name;
590
- let moduleName: string;
591
- let effectiveModuleArgs: Record<string, SqlValue>;
592
-
593
- if (stmt.moduleName) {
594
- moduleName = stmt.moduleName;
595
- effectiveModuleArgs = Object.freeze(stmt.moduleArgs || {});
596
- } else {
597
- const defaultVtab = this.getDefaultVTabModule();
598
- moduleName = defaultVtab.name;
599
- effectiveModuleArgs = Object.freeze(defaultVtab.args || {});
600
- }
601
-
602
- const moduleInfo = this.getModule(moduleName);
603
- if (!moduleInfo || !moduleInfo.module) {
604
- throw new QuereusError(`No virtual table module named '${moduleName}'`, StatusCode.ERROR, undefined, stmt.loc?.start.line, stmt.loc?.start.column);
605
- }
606
-
607
- const astColumnsToProcess = stmt.columns || [];
608
- const astConstraintsToProcess = stmt.constraints;
609
-
610
- // Get default nullability setting from database options
611
- const defaultNullability = this.db.options.getStringOption('default_column_nullability');
612
- const defaultNotNull = defaultNullability === 'not_null';
613
-
614
- const preliminaryColumnSchemas: ColumnSchema[] = astColumnsToProcess.map(colDef => columnDefToSchema(colDef, defaultNotNull));
615
- const pkDefinition = findPKDefinition(preliminaryColumnSchemas, astConstraintsToProcess);
616
-
617
- const finalColumnSchemas = preliminaryColumnSchemas.map((col, idx) => {
618
- const isPkColumn = pkDefinition.some(pkCol => pkCol.index === idx);
619
- let pkOrder = 0;
620
- if (isPkColumn) {
621
- pkOrder = pkDefinition.findIndex(pkC => pkC.index === idx) + 1;
622
- }
623
- return {
624
- ...col,
625
- primaryKey: isPkColumn,
626
- pkOrder: pkOrder,
627
- notNull: isPkColumn ? true : col.notNull,
628
- };
629
- });
630
-
631
- const checkConstraintsSchema: RowConstraintSchema[] = [];
632
- astColumnsToProcess.forEach(colDef => {
633
- colDef.constraints?.forEach(con => {
634
- if (con.type === 'check' && con.expr) {
635
- checkConstraintsSchema.push({
636
- name: con.name ?? `_check_${colDef.name}`,
637
- expr: con.expr,
638
- operations: opsToMask(con.operations),
639
- deferrable: con.deferrable,
640
- initiallyDeferred: con.initiallyDeferred
641
- });
642
- }
643
- });
644
- });
645
- (astConstraintsToProcess || []).forEach(con => {
646
- if (con.type === 'check' && con.expr) {
647
- checkConstraintsSchema.push({
648
- name: con.name,
649
- expr: con.expr,
650
- operations: opsToMask(con.operations),
651
- deferrable: con.deferrable,
652
- initiallyDeferred: con.initiallyDeferred
653
- });
654
- }
655
- });
656
-
657
- // Process mutation context definitions if present
658
- const mutationContextSchemas = stmt.contextDefinitions
659
- ? stmt.contextDefinitions.map(varDef => mutationContextVarToSchema(varDef, defaultNotNull))
660
- : undefined;
661
-
662
- // Validate that default expressions are deterministic
663
- // We need to build them temporarily to check their physical properties
664
- // Note: We only validate defaults here, not CHECK constraints, because CHECK constraints
665
- // may reference table columns which don't exist yet at CREATE TABLE time.
666
- // CHECK constraints are validated at INSERT/UPDATE time in constraint-builder.ts
667
- const globalScope = new GlobalScope(this.db.schemaManager);
668
- const parameterScope = new ParameterScope(globalScope);
669
- const planningCtx: PlanningContext = {
670
- db: this.db,
671
- schemaManager: this.db.schemaManager,
672
- parameters: {},
673
- scope: parameterScope,
674
- cteNodes: new Map(),
675
- schemaDependencies: new BuildTimeDependencyTracker(),
676
- schemaCache: new Map(),
677
- cteReferenceCache: new Map(),
678
- outputScopes: new Map()
679
- };
680
-
681
- // Validate default expressions
682
- // Note: We can only validate defaults that don't reference table columns,
683
- // since the table doesn't exist yet. Defaults that reference columns will be
684
- // validated at INSERT time in insert.ts
685
- for (const col of finalColumnSchemas) {
686
- if (col.defaultValue && typeof col.defaultValue === 'object' && col.defaultValue !== null && 'type' in col.defaultValue) {
687
- let defaultExpr: ScalarPlanNode | undefined;
688
- try {
689
- // Try to build the expression - may fail if it references columns that don't exist yet
690
- defaultExpr = buildExpression(planningCtx, col.defaultValue as AST.Expression) as ScalarPlanNode;
691
- } catch (e) {
692
- // If we can't build the expression (e.g., it references columns that don't exist yet),
693
- // skip validation here. It will be validated at INSERT time.
694
- log('Skipping determinism validation for default on column %s.%s at CREATE TABLE time (will validate at INSERT time): %s',
695
- tableName, col.name, (e as Error).message);
696
- }
697
-
698
- // If expression built successfully, check determinism (non-throwing)
699
- if (defaultExpr) {
700
- const result = checkDeterministic(defaultExpr);
701
- if (!result.valid) {
702
- throw new QuereusError(
703
- `Non-deterministic expression not allowed in DEFAULT for column '${col.name}' in table '${tableName}'. ` +
704
- `Expression: ${result.expression}. ` +
705
- `Use mutation context to pass non-deterministic values (e.g., WITH CONTEXT (timestamp = datetime('now'))).`,
706
- StatusCode.ERROR
707
- );
708
- }
709
- }
710
- }
711
- }
712
-
713
- const baseTableSchema: TableSchema = {
714
- name: tableName,
715
- schemaName: targetSchemaName,
716
- columns: Object.freeze(finalColumnSchemas),
717
- columnIndexMap: buildColumnIndexMap(finalColumnSchemas),
718
- primaryKeyDefinition: pkDefinition,
719
- checkConstraints: Object.freeze(checkConstraintsSchema),
720
- isTemporary: !!stmt.isTemporary,
721
- isView: false,
722
- vtabModuleName: moduleName,
723
- vtabArgs: effectiveModuleArgs,
724
- vtabModule: moduleInfo.module,
725
- vtabAuxData: moduleInfo.auxData,
726
- estimatedRows: 0,
727
- mutationContext: mutationContextSchemas ? Object.freeze(mutationContextSchemas) : undefined,
728
- };
729
-
730
- let tableInstance: VirtualTable;
731
- try {
732
- tableInstance = moduleInfo.module.create(
733
- this.db,
734
- baseTableSchema
735
- );
736
- } catch (e: unknown) {
737
- const message = e instanceof Error ? e.message : String(e);
738
- const code = e instanceof QuereusError ? e.code : StatusCode.ERROR;
739
- throw new QuereusError(`Module '${moduleName}' create failed for table '${tableName}': ${message}`, code, e instanceof Error ? e : undefined, stmt.loc?.start.line, stmt.loc?.start.column);
740
- }
741
-
742
- const schema = this.getSchema(targetSchemaName);
743
- if (!schema) {
744
- throw new QuereusError(`Internal error: Schema '${targetSchemaName}' not found.`, StatusCode.INTERNAL);
745
- }
746
-
747
- const finalRegisteredSchema = tableInstance.tableSchema;
748
- if (!finalRegisteredSchema) {
749
- throw new QuereusError(`Module '${moduleName}' create did not provide a tableSchema for '${tableName}'.`, StatusCode.INTERNAL);
750
- }
751
-
752
- // Create a properly typed schema object instead of mutating properties
753
- let correctedSchema = finalRegisteredSchema;
754
- if (finalRegisteredSchema.name.toLowerCase() !== tableName.toLowerCase() ||
755
- finalRegisteredSchema.schemaName.toLowerCase() !== targetSchemaName.toLowerCase()) {
756
- warnLog(`Module ${moduleName} returned schema for ${finalRegisteredSchema.schemaName}.${finalRegisteredSchema.name} but expected ${targetSchemaName}.${tableName}. Correcting name/schemaName.`);
757
- correctedSchema = {
758
- ...finalRegisteredSchema,
759
- name: tableName,
760
- schemaName: targetSchemaName,
761
- };
762
- }
763
-
764
- // Ensure all required properties are properly set
765
- const completeTableSchema: TableSchema = {
766
- ...correctedSchema,
767
- vtabModuleName: moduleName,
768
- vtabArgs: effectiveModuleArgs,
769
- vtabModule: moduleInfo.module,
770
- vtabAuxData: moduleInfo.auxData,
771
- estimatedRows: correctedSchema.estimatedRows ?? 0,
772
- };
773
-
774
- const existingTable = schema.getTable(tableName);
775
- const existingView = schema.getView(tableName);
776
-
777
- if (existingTable || existingView) {
778
- if (stmt.ifNotExists) {
779
- log(`Skipping CREATE TABLE: Item %s.%s already exists (IF NOT EXISTS).`, targetSchemaName, tableName);
780
- if (existingTable) return existingTable;
781
- throw new QuereusError(`Cannot CREATE TABLE ${targetSchemaName}.${tableName}: a VIEW with the same name already exists.`, StatusCode.CONSTRAINT, undefined, stmt.table.loc?.start.line, stmt.table.loc?.start.column);
782
- } else {
783
- const itemType = existingTable ? 'Table' : 'View';
784
- throw new QuereusError(`${itemType} ${targetSchemaName}.${tableName} already exists`, StatusCode.CONSTRAINT, undefined, stmt.table.loc?.start.line, stmt.table.loc?.start.column);
785
- }
786
- }
787
-
788
- schema.addTable(completeTableSchema);
789
- log(`Successfully created table %s.%s using module %s`, targetSchemaName, tableName, moduleName);
790
-
791
- // Notify schema change listeners
792
- this.changeNotifier.notifyChange({
793
- type: 'table_added',
794
- schemaName: targetSchemaName,
795
- objectName: tableName,
796
- newObject: completeTableSchema
797
- });
798
-
799
- return completeTableSchema;
800
- }
801
-
802
- /**
803
- * Import catalog objects from DDL statements without triggering storage creation.
804
- * Used when connecting to existing storage that already contains data.
805
- *
806
- * This method:
807
- * 1. Parses each DDL statement
808
- * 2. Registers the schema objects (tables, indexes)
809
- * 3. Calls module.connect() instead of module.create()
810
- * 4. Skips schema change hooks (since these are existing objects)
811
- *
812
- * @param ddlStatements Array of DDL strings (CREATE TABLE, CREATE INDEX, etc.)
813
- * @returns Array of imported object names
814
- */
815
- async importCatalog(ddlStatements: string[]): Promise<{ tables: string[]; indexes: string[] }> {
816
- const imported = { tables: [] as string[], indexes: [] as string[] };
817
-
818
- for (const ddl of ddlStatements) {
819
- try {
820
- const result = await this.importSingleDDL(ddl);
821
- if (result.type === 'table') {
822
- imported.tables.push(result.name);
823
- } else if (result.type === 'index') {
824
- imported.indexes.push(result.name);
825
- }
826
- } catch (e) {
827
- const message = e instanceof Error ? e.message : String(e);
828
- errorLog('Failed to import DDL: %s - Error: %s', ddl.substring(0, 100), message);
829
- throw e;
830
- }
831
- }
832
-
833
- log('Imported catalog: %d tables, %d indexes', imported.tables.length, imported.indexes.length);
834
- return imported;
835
- }
836
-
837
- /**
838
- * Import a single DDL statement without creating storage.
839
- */
840
- private async importSingleDDL(ddl: string): Promise<{ type: 'table' | 'index'; name: string }> {
841
- // Parse the DDL using the parser
842
- const parser = new Parser();
843
- const statements = parser.parseAll(ddl);
844
- if (statements.length !== 1) {
845
- throw new QuereusError(`importCatalog expects exactly one statement per DDL, got ${statements.length}`, StatusCode.ERROR);
846
- }
847
-
848
- const stmt = statements[0];
849
-
850
- if (stmt.type === 'createTable') {
851
- return this.importTable(stmt as AST.CreateTableStmt);
852
- } else if (stmt.type === 'createIndex') {
853
- return this.importIndex(stmt as AST.CreateIndexStmt);
854
- } else {
855
- throw new QuereusError(`importCatalog does not support statement type: ${stmt.type}`, StatusCode.ERROR);
856
- }
857
- }
858
-
859
- /**
860
- * Import a table schema without calling module.create().
861
- * Uses module.connect() to bind to existing storage.
862
- */
863
- private async importTable(stmt: AST.CreateTableStmt): Promise<{ type: 'table'; name: string }> {
864
- const targetSchemaName = stmt.table.schema || this.getCurrentSchemaName();
865
- const tableName = stmt.table.name;
866
-
867
- let moduleName: string;
868
- let effectiveModuleArgs: Record<string, SqlValue>;
869
-
870
- if (stmt.moduleName) {
871
- moduleName = stmt.moduleName;
872
- effectiveModuleArgs = Object.freeze(stmt.moduleArgs || {});
873
- } else {
874
- const defaultVtab = this.getDefaultVTabModule();
875
- moduleName = defaultVtab.name;
876
- effectiveModuleArgs = Object.freeze(defaultVtab.args || {});
877
- }
878
-
879
- const moduleInfo = this.getModule(moduleName);
880
- if (!moduleInfo || !moduleInfo.module) {
881
- throw new QuereusError(`No virtual table module named '${moduleName}'`, StatusCode.ERROR);
882
- }
883
-
884
- // Get default nullability setting from database options
885
- const defaultNullability = this.db.options.getStringOption('default_column_nullability');
886
- const defaultNotNull = defaultNullability === 'not_null';
887
-
888
- const astColumnsToProcess = stmt.columns || [];
889
- const astConstraintsToProcess = stmt.constraints;
890
-
891
- const preliminaryColumnSchemas: ColumnSchema[] = astColumnsToProcess.map(colDef => columnDefToSchema(colDef, defaultNotNull));
892
- const pkDefinition = findPKDefinition(preliminaryColumnSchemas, astConstraintsToProcess);
893
-
894
- const finalColumnSchemas = preliminaryColumnSchemas.map((col, idx) => {
895
- const isPkColumn = pkDefinition.some(pkCol => pkCol.index === idx);
896
- let pkOrder = 0;
897
- if (isPkColumn) {
898
- pkOrder = pkDefinition.findIndex(pkC => pkC.index === idx) + 1;
899
- }
900
- return {
901
- ...col,
902
- primaryKey: isPkColumn,
903
- pkOrder: pkOrder,
904
- notNull: isPkColumn ? true : col.notNull,
905
- };
906
- });
907
-
908
- const checkConstraintsSchema: RowConstraintSchema[] = [];
909
- astColumnsToProcess.forEach(colDef => {
910
- colDef.constraints?.forEach(con => {
911
- if (con.type === 'check' && con.expr) {
912
- checkConstraintsSchema.push({
913
- name: con.name ?? `_check_${colDef.name}`,
914
- expr: con.expr,
915
- operations: opsToMask(con.operations),
916
- deferrable: con.deferrable,
917
- initiallyDeferred: con.initiallyDeferred
918
- });
919
- }
920
- });
921
- });
922
- (astConstraintsToProcess || []).forEach(con => {
923
- if (con.type === 'check' && con.expr) {
924
- checkConstraintsSchema.push({
925
- name: con.name,
926
- expr: con.expr,
927
- operations: opsToMask(con.operations),
928
- deferrable: con.deferrable,
929
- initiallyDeferred: con.initiallyDeferred
930
- });
931
- }
932
- });
933
-
934
- // Process mutation context definitions if present
935
- const mutationContextSchemas = stmt.contextDefinitions
936
- ? stmt.contextDefinitions.map(varDef => mutationContextVarToSchema(varDef, defaultNotNull))
937
- : undefined;
938
-
939
- const tableSchema: TableSchema = {
940
- name: tableName,
941
- schemaName: targetSchemaName,
942
- columns: Object.freeze(finalColumnSchemas),
943
- columnIndexMap: buildColumnIndexMap(finalColumnSchemas),
944
- primaryKeyDefinition: pkDefinition,
945
- checkConstraints: Object.freeze(checkConstraintsSchema),
946
- isTemporary: !!stmt.isTemporary,
947
- isView: false,
948
- vtabModuleName: moduleName,
949
- vtabArgs: effectiveModuleArgs,
950
- vtabModule: moduleInfo.module,
951
- vtabAuxData: moduleInfo.auxData,
952
- estimatedRows: 0,
953
- mutationContext: mutationContextSchemas ? Object.freeze(mutationContextSchemas) : undefined,
954
- };
955
-
956
- // Use connect() instead of create() - the storage already exists
957
- try {
958
- moduleInfo.module.connect(
959
- this.db,
960
- moduleInfo.auxData,
961
- moduleName,
962
- targetSchemaName,
963
- tableName,
964
- effectiveModuleArgs as BaseModuleConfig,
965
- tableSchema // Pass the full schema so the module can use it
966
- );
967
- } catch (e: unknown) {
968
- const message = e instanceof Error ? e.message : String(e);
969
- throw new QuereusError(`Module '${moduleName}' connect failed during import for table '${tableName}': ${message}`, StatusCode.ERROR);
970
- }
971
-
972
- // Ensure schema exists
973
- let schema = this.getSchema(targetSchemaName);
974
- if (!schema) {
975
- schema = new Schema(targetSchemaName);
976
- this.schemas.set(targetSchemaName.toLowerCase(), schema);
977
- }
978
-
979
- // Register without notifying change listeners (this is an import, not a create)
980
- schema.addTable(tableSchema);
981
- log(`Imported table %s.%s using module %s`, targetSchemaName, tableName, moduleName);
982
-
983
- return { type: 'table', name: `${targetSchemaName}.${tableName}` };
984
- }
985
-
986
- /**
987
- * Import an index schema without calling module.createIndex().
988
- */
989
- private async importIndex(stmt: AST.CreateIndexStmt): Promise<{ type: 'index'; name: string }> {
990
- const targetSchemaName = stmt.table.schema || this.getCurrentSchemaName();
991
- const tableName = stmt.table.name;
992
- const indexName = stmt.index.name;
993
-
994
- // Find the table
995
- const tableSchema = this.findTable(tableName, targetSchemaName);
996
- if (!tableSchema) {
997
- throw new QuereusError(`Cannot import index '${indexName}': table '${tableName}' not found`, StatusCode.ERROR);
998
- }
999
-
1000
- // Build index columns schema
1001
- const indexColumns: IndexColumnSchema[] = stmt.columns.map(col => {
1002
- const colName = col.name;
1003
- if (!colName) {
1004
- throw new QuereusError(`Expression-based index columns are not supported during import`, StatusCode.ERROR);
1005
- }
1006
- const colIdx = tableSchema.columnIndexMap.get(colName.toLowerCase());
1007
- if (colIdx === undefined) {
1008
- throw new QuereusError(`Column '${colName}' not found in table '${tableName}'`, StatusCode.ERROR);
1009
- }
1010
- return {
1011
- index: colIdx,
1012
- desc: col.direction === 'desc',
1013
- };
1014
- });
1015
-
1016
- const indexSchema: IndexSchema = {
1017
- name: indexName,
1018
- columns: Object.freeze(indexColumns),
1019
- };
1020
-
1021
- // Add index to table without calling module.createIndex()
1022
- const updatedIndexes = [...(tableSchema.indexes || []), indexSchema];
1023
- const updatedTableSchema: TableSchema = {
1024
- ...tableSchema,
1025
- indexes: Object.freeze(updatedIndexes),
1026
- };
1027
-
1028
- const schema = this.getSchemaOrFail(targetSchemaName);
1029
- schema.addTable(updatedTableSchema);
1030
- log(`Imported index %s on table %s.%s`, indexName, targetSchemaName, tableName);
1031
-
1032
- return { type: 'index', name: `${targetSchemaName}.${tableName}.${indexName}` };
1033
- }
1034
- }