@johnhenry/mallory-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/bin/mallory.mjs +51 -0
- package/package.json +51 -4
- package/src/a2a/client.js +511 -0
- package/src/a2a/demo-agent.js +396 -0
- package/src/a2a/hub.js +578 -0
- package/src/a2a/settings.js +88 -0
- package/src/a2a/task.js +358 -0
- package/src/acp/client.js +573 -0
- package/src/acp/demo-agent.js +332 -0
- package/src/acp/hub.js +632 -0
- package/src/acp/settings.js +78 -0
- package/src/actions/map.js +524 -0
- package/src/agent/cloud.js +77 -0
- package/src/agent/compact.js +84 -0
- package/src/agent/constants.js +39 -0
- package/src/agent/diff.js +101 -0
- package/src/agent/fork.js +159 -0
- package/src/agent/grounding.js +73 -0
- package/src/agent/guards.js +129 -0
- package/src/agent/local-transport.js +152 -0
- package/src/agent/loop.js +479 -0
- package/src/agent/park-store.js +77 -0
- package/src/agent/park.js +76 -0
- package/src/agent/ports.js +28 -0
- package/src/agent/providers.js +591 -0
- package/src/agent/restart.js +51 -0
- package/src/agent/router.js +380 -0
- package/src/agent/run.js +861 -0
- package/src/agent/tools.js +247 -0
- package/src/agent-library/engine.js +43 -0
- package/src/ai/bridge.js +155 -0
- package/src/ai/policy.js +131 -0
- package/src/aimatey/vendor.js +18 -0
- package/src/audio/container-duration.js +35 -0
- package/src/audio/instruments.js +776 -0
- package/src/audio/lanes.js +230 -0
- package/src/audio/patch.js +1410 -0
- package/src/audio/plan.js +276 -0
- package/src/audio/rack.js +1006 -0
- package/src/audio/sample-trim.js +293 -0
- package/src/audio/soundfont.js +243 -0
- package/src/audio/take-store.js +87 -0
- package/src/audio/takes.js +129 -0
- package/src/audio/wav.js +170 -0
- package/src/audio/zzfx.js +333 -0
- package/src/autonomy/bundle.js +207 -0
- package/src/autonomy/confine.js +61 -0
- package/src/autonomy/enforce.js +155 -0
- package/src/autonomy/file-kv.js +88 -0
- package/src/autonomy/ledger.js +203 -0
- package/src/autonomy/pins.js +50 -0
- package/src/autonomy/psl/index.js +32 -0
- package/src/autonomy/psl/suffixes.json +1 -0
- package/src/autonomy/record.js +28 -0
- package/src/autonomy/routines.js +107 -0
- package/src/autonomy/server.js +175 -0
- package/src/autonomy/signer-node.js +167 -0
- package/src/autonomy/store.js +43 -0
- package/src/autonomy/unattended.js +13 -0
- package/src/bytes/bytes.js +378 -0
- package/src/calc/syntax.js +125 -0
- package/src/calc/tex.js +28 -0
- package/src/calendar/vendor.js +2 -0
- package/src/clipboard.js +130 -0
- package/src/clsh/clsh.js +3417 -0
- package/src/codec/capnp.js +1804 -0
- package/src/codec/core.js +2043 -0
- package/src/codec/vendor/avro.js +136 -0
- package/src/codec/vendor/cbor.js +25 -0
- package/src/codec/vendor/flatbuffers.js +206 -0
- package/src/codec/vendor/msgpack.js +9 -0
- package/src/codec/vendor/protobuf.js +53 -0
- package/src/delegation/caps.js +60 -0
- package/src/delegation/config.js +32 -0
- package/src/device/model.js +246 -0
- package/src/device/recording.js +198 -0
- package/src/device/stream-model.js +151 -0
- package/src/documents/documents.js +1224 -0
- package/src/effects/catalog.js +63 -0
- package/src/effects/extras.js +133 -0
- package/src/effects/parse.js +339 -0
- package/src/embed/protocol.js +131 -0
- package/src/env/env.js +159 -0
- package/src/exact/vendor.js +45 -0
- package/src/example-meta.js +164 -0
- package/src/examples.js +94 -0
- package/src/export/canvas-image.js +217 -0
- package/src/export/expr-latex-lazy.js +8 -0
- package/src/export/formats.js +322 -0
- package/src/export/latex.js +183 -0
- package/src/export/pane.js +184 -0
- package/src/export/value.js +452 -0
- package/src/export/zip.js +214 -0
- package/src/ext/access.js +58 -0
- package/src/ext/btasks.js +225 -0
- package/src/ext/client.js +209 -0
- package/src/ext/tools.js +69 -0
- package/src/ext/view.js +105 -0
- package/src/ext/webmcp-tabs.js +299 -0
- package/src/files/archive.js +232 -0
- package/src/files/files.js +317 -0
- package/src/formats/json.js +24 -0
- package/src/formats/jupyter.js +188 -0
- package/src/formats/markdown.js +254 -0
- package/src/formats/n8n.js +276 -0
- package/src/formats/node-red.js +363 -0
- package/src/formats/registry.js +177 -0
- package/src/formats/rivet.js +259 -0
- package/src/formats/shared.js +98 -0
- package/src/formats/structure.js +182 -0
- package/src/formats/yaml.js +127 -0
- package/src/frame/frame.js +962 -0
- package/src/frame/vendor.js +1484 -0
- package/src/gate/audit.js +116 -0
- package/src/gate/gate.js +365 -0
- package/src/gate/policy.js +295 -0
- package/src/gate/scripted.js +110 -0
- package/src/gate/seams.js +32 -0
- package/src/gate/store.js +66 -0
- package/src/geometry/model.js +533 -0
- package/src/grant-key.js +149 -0
- package/src/graph/model.js +381 -0
- package/src/headless/a2a-push.js +123 -0
- package/src/headless/channels/config.js +142 -0
- package/src/headless/channels/connectors.js +283 -0
- package/src/headless/channels/index.js +257 -0
- package/src/headless/channels/mail.js +197 -0
- package/src/headless/channels/mailnet.js +223 -0
- package/src/headless/channels/platforms.js +194 -0
- package/src/headless/channels/replay.js +49 -0
- package/src/headless/cli.js +1397 -0
- package/src/headless/companion-client.js +182 -0
- package/src/headless/cost-cli.js +177 -0
- package/src/headless/deprecations-cli.js +102 -0
- package/src/headless/examples.js +48 -0
- package/src/headless/ffmpeg-exec.js +217 -0
- package/src/headless/gateways/config.js +213 -0
- package/src/headless/gateways/homeassistant.js +159 -0
- package/src/headless/gateways/index.js +121 -0
- package/src/headless/gateways/matter.js +150 -0
- package/src/headless/gateways/mqtt-client.js +177 -0
- package/src/headless/gateways/mqtt.js +70 -0
- package/src/headless/gateways/netway.js +226 -0
- package/src/headless/gateways/serverpod-worker.mjs +16 -0
- package/src/headless/gateways/serverpod.js +71 -0
- package/src/headless/gateways/util.js +27 -0
- package/src/headless/grant-cli.js +208 -0
- package/src/headless/guard.js +125 -0
- package/src/headless/guards.js +124 -0
- package/src/headless/machine-cli.js +853 -0
- package/src/headless/mcp-endpoint.js +287 -0
- package/src/headless/mcp-roots.js +38 -0
- package/src/headless/model-endpoint.js +88 -0
- package/src/headless/net.js +151 -0
- package/src/headless/node.js +263 -0
- package/src/headless/npm-tarball.js +29 -0
- package/src/headless/operator-page.js +112 -0
- package/src/headless/operator.js +242 -0
- package/src/headless/people.js +34 -0
- package/src/headless/pkg-cli.js +1103 -0
- package/src/headless/pkg-serve.js +138 -0
- package/src/headless/process-worker.js +88 -0
- package/src/headless/runner-remote.js +477 -0
- package/src/headless/sandbox-child.mjs +21 -0
- package/src/headless/scheduled.js +557 -0
- package/src/headless/serve-stream.js +97 -0
- package/src/headless/serve.js +2238 -0
- package/src/headless/short-links.js +158 -0
- package/src/headless/static-dirs.js +207 -0
- package/src/headless/trust-file.js +51 -0
- package/src/headless/watch.js +291 -0
- package/src/headless/ws-connect.js +65 -0
- package/src/headless/ws-connections.js +44 -0
- package/src/headless/ws-echo.js +150 -0
- package/src/headless/ws-proxy.js +354 -0
- package/src/headless/ws-ticket.js +48 -0
- package/src/hooks/config.js +50 -0
- package/src/hooks/engine.js +189 -0
- package/src/input/log.js +613 -0
- package/src/input/player.js +217 -0
- package/src/input/replay.js +209 -0
- package/src/jth/vendor.js +28 -0
- package/src/ledger/tx.js +94 -0
- package/src/machine/apply.js +193 -0
- package/src/machine/diff.js +168 -0
- package/src/machine/drive.js +296 -0
- package/src/machine/engine.js +478 -0
- package/src/machine/files-tool.js +76 -0
- package/src/machine/lint.js +139 -0
- package/src/machine/llmtm-trace.js +117 -0
- package/src/machine/llmtm.js +475 -0
- package/src/machine/otel.js +80 -0
- package/src/machine/pane-provider.js +51 -0
- package/src/machine/propose.js +159 -0
- package/src/machine/random.js +52 -0
- package/src/machine/risk.js +107 -0
- package/src/machine/session.js +1017 -0
- package/src/machine/shell-tool.js +45 -0
- package/src/machine/tape.js +349 -0
- package/src/machine/templates.js +104 -0
- package/src/machine/trace.js +664 -0
- package/src/machine/view.js +73 -0
- package/src/machine/vm-tool.js +47 -0
- package/src/machine/watchdog.js +46 -0
- package/src/mcp/app-args.js +51 -0
- package/src/mcp/app-run.js +56 -0
- package/src/mcp/apps.js +468 -0
- package/src/mcp/cache.js +232 -0
- package/src/mcp/client.js +507 -0
- package/src/mcp/demo-app.js +183 -0
- package/src/mcp/demo-server.js +602 -0
- package/src/mcp/elicitation.js +116 -0
- package/src/mcp/hub.js +1326 -0
- package/src/mcp/roots.js +139 -0
- package/src/mcp/sampling.js +105 -0
- package/src/mcp/settings.js +125 -0
- package/src/mcp/tape.js +292 -0
- package/src/mcp/uri-template.js +156 -0
- package/src/mcp/wsh-client.js +164 -0
- package/src/media/animated-codec.js +7 -0
- package/src/media/animated.js +623 -0
- package/src/media/compare-agent.js +70 -0
- package/src/media/compare-job.js +63 -0
- package/src/media/compare-page.js +296 -0
- package/src/media/compare-worker.js +14 -0
- package/src/media/compare.js +600 -0
- package/src/media/contract.js +62 -0
- package/src/media/decode-frame.js +57 -0
- package/src/media/decode-pool.js +188 -0
- package/src/media/ffmpeg-edit.js +344 -0
- package/src/media/ffmpeg-wasm-client.js +121 -0
- package/src/media/ffmpeg-wasm-session.js +79 -0
- package/src/media/ffmpeg-wasm.js +139 -0
- package/src/media/ffmpeg-worker.js +23 -0
- package/src/media/ffmpeg.js +903 -0
- package/src/media/helpers.js +419 -0
- package/src/media/keep.js +108 -0
- package/src/media/metadata-worker.js +16 -0
- package/src/media/metadata.js +2518 -0
- package/src/media/mime.js +102 -0
- package/src/media/page-decode.js +74 -0
- package/src/media/persist.js +114 -0
- package/src/media/png.js +226 -0
- package/src/media/sample-input.js +67 -0
- package/src/media/store.js +86 -0
- package/src/media/wav.js +109 -0
- package/src/midi/mappings.js +250 -0
- package/src/midi/message.js +125 -0
- package/src/model/action-hub.js +143 -0
- package/src/model/adapters.js +284 -0
- package/src/model/agent-runs.js +12 -0
- package/src/model/arrange.js +308 -0
- package/src/model/automation-clock.js +494 -0
- package/src/model/automation.js +653 -0
- package/src/model/batches.js +78 -0
- package/src/model/binary-view.js +195 -0
- package/src/model/breakpoints.js +392 -0
- package/src/model/calc-settings.js +65 -0
- package/src/model/calendar.js +254 -0
- package/src/model/canvas-id.js +5 -0
- package/src/model/canvas.js +5048 -0
- package/src/model/channel-names.js +29 -0
- package/src/model/channels.js +692 -0
- package/src/model/chart-clock.js +631 -0
- package/src/model/chart-code.js +69 -0
- package/src/model/codecs.js +60 -0
- package/src/model/companion-access.js +271 -0
- package/src/model/companion-pane.js +50 -0
- package/src/model/composite.js +324 -0
- package/src/model/context.js +380 -0
- package/src/model/controls.js +231 -0
- package/src/model/converter-presets.js +368 -0
- package/src/model/cost.js +580 -0
- package/src/model/curve-transform.js +122 -0
- package/src/model/cycles.js +176 -0
- package/src/model/debug-log.js +168 -0
- package/src/model/decision-clock.js +100 -0
- package/src/model/decisions.js +265 -0
- package/src/model/desk.js +87 -0
- package/src/model/device-hub.js +400 -0
- package/src/model/diff.js +445 -0
- package/src/model/emit-events.js +179 -0
- package/src/model/errors.js +238 -0
- package/src/model/event-presets.js +297 -0
- package/src/model/events.js +1303 -0
- package/src/model/explicit-setters.js +139 -0
- package/src/model/field-mapping.js +623 -0
- package/src/model/files-pane.js +263 -0
- package/src/model/flow-idle.js +89 -0
- package/src/model/foreach.js +549 -0
- package/src/model/frame-loop.js +71 -0
- package/src/model/frame-pressure.js +180 -0
- package/src/model/function-scaffold.js +1000 -0
- package/src/model/geometry-settings.js +54 -0
- package/src/model/goals.js +176 -0
- package/src/model/graph-settings.js +76 -0
- package/src/model/grid-widget.js +175 -0
- package/src/model/groups.js +332 -0
- package/src/model/hash.js +21 -0
- package/src/model/history.js +259 -0
- package/src/model/http-copy.js +88 -0
- package/src/model/http-send-companion.js +110 -0
- package/src/model/http-send.js +163 -0
- package/src/model/http-tap.js +521 -0
- package/src/model/http-tools.js +1138 -0
- package/src/model/import-lock.js +78 -0
- package/src/model/imports.js +258 -0
- package/src/model/infer-outputs.js +822 -0
- package/src/model/ink-connect.js +150 -0
- package/src/model/ink-diff.js +75 -0
- package/src/model/ink-gone.js +71 -0
- package/src/model/ink-route.js +120 -0
- package/src/model/ink-svg.js +206 -0
- package/src/model/ink.js +739 -0
- package/src/model/input-log-hub.js +456 -0
- package/src/model/input-split.js +69 -0
- package/src/model/json-schema-host.js +9 -0
- package/src/model/json-schema.js +368 -0
- package/src/model/jth.js +78 -0
- package/src/model/latex-expr.js +528 -0
- package/src/model/layout-history.js +120 -0
- package/src/model/lazy-map.js +88 -0
- package/src/model/ledger-pane.js +101 -0
- package/src/model/legacy-viaframe.js +90 -0
- package/src/model/lessons.js +448 -0
- package/src/model/links.js +981 -0
- package/src/model/live.js +411 -0
- package/src/model/math-widget.js +53 -0
- package/src/model/memory-settings.js +33 -0
- package/src/model/midi-controls.js +350 -0
- package/src/model/nl-time.js +408 -0
- package/src/model/notebook.js +137 -0
- package/src/model/pane-view-store.js +15 -0
- package/src/model/partial.js +115 -0
- package/src/model/pause-clock.js +53 -0
- package/src/model/peer-pane.js +32 -0
- package/src/model/persist-state.js +290 -0
- package/src/model/person-only.js +122 -0
- package/src/model/pin.js +209 -0
- package/src/model/plot-3d.js +213 -0
- package/src/model/plot-series.js +157 -0
- package/src/model/plot-settings.js +531 -0
- package/src/model/ports.js +312 -0
- package/src/model/presentation.js +222 -0
- package/src/model/preset-apply.js +316 -0
- package/src/model/preset-banks.js +335 -0
- package/src/model/preset-morph.js +263 -0
- package/src/model/preset-ops.js +205 -0
- package/src/model/preset-player.js +283 -0
- package/src/model/preset-states.js +172 -0
- package/src/model/profile-settings.js +109 -0
- package/src/model/promote.js +103 -0
- package/src/model/protected.js +10 -0
- package/src/model/proxy-log.js +230 -0
- package/src/model/proxy.js +367 -0
- package/src/model/quantity-widget.js +61 -0
- package/src/model/queue-book.js +359 -0
- package/src/model/quick-add.js +224 -0
- package/src/model/rate-limit.js +313 -0
- package/src/model/rate.js +95 -0
- package/src/model/recovery.js +216 -0
- package/src/model/rename-follow.js +113 -0
- package/src/model/repeater.js +1126 -0
- package/src/model/retention.js +664 -0
- package/src/model/route-edit.js +132 -0
- package/src/model/router.js +155 -0
- package/src/model/runaway.js +232 -0
- package/src/model/runlog.js +1033 -0
- package/src/model/runners/a2a.js +2 -0
- package/src/model/runners/acp.js +2 -0
- package/src/model/runners/actions.js +4 -0
- package/src/model/runners/agent.js +4 -0
- package/src/model/runners/audio.js +21 -0
- package/src/model/runners/automation.js +2 -0
- package/src/model/runners/calc.js +23 -0
- package/src/model/runners/catch.js +10 -0
- package/src/model/runners/codec.js +24 -0
- package/src/model/runners/companion-run.js +2 -0
- package/src/model/runners/device.js +7 -0
- package/src/model/runners/dom.js +13 -0
- package/src/model/runners/effects.js +2 -0
- package/src/model/runners/embed.js +11 -0
- package/src/model/runners/eval.js +2 -0
- package/src/model/runners/files.js +19 -0
- package/src/model/runners/geometry.js +23 -0
- package/src/model/runners/goals.js +18 -0
- package/src/model/runners/graph.js +23 -0
- package/src/model/runners/html.js +2 -0
- package/src/model/runners/http-proxy.js +185 -0
- package/src/model/runners/http-send.js +61 -0
- package/src/model/runners/http-static.js +83 -0
- package/src/model/runners/http-tap.js +26 -0
- package/src/model/runners/http.js +40 -0
- package/src/model/runners/import.js +2 -0
- package/src/model/runners/index.js +74 -0
- package/src/model/runners/input.js +14 -0
- package/src/model/runners/inputlog.js +7 -0
- package/src/model/runners/ledger.js +15 -0
- package/src/model/runners/machine.js +4 -0
- package/src/model/runners/mcp.js +2 -0
- package/src/model/runners/mcpapp.js +2 -0
- package/src/model/runners/media.js +18 -0
- package/src/model/runners/memory.js +28 -0
- package/src/model/runners/mesh-inspect.js +13 -0
- package/src/model/runners/peer.js +14 -0
- package/src/model/runners/plot.js +22 -0
- package/src/model/runners/render.js +14 -0
- package/src/model/runners/respond.js +2 -0
- package/src/model/runners/sample-soundfont.js +85 -0
- package/src/model/runners/sample.js +159 -0
- package/src/model/runners/scene.js +8 -0
- package/src/model/runners/score.js +24 -0
- package/src/model/runners/secret.js +10 -0
- package/src/model/runners/select.js +2 -0
- package/src/model/runners/shared.js +4 -0
- package/src/model/runners/shares.js +15 -0
- package/src/model/runners/shell.js +7 -0
- package/src/model/runners/skill.js +26 -0
- package/src/model/runners/state.js +2 -0
- package/src/model/runners/statechart.js +4 -0
- package/src/model/runners/subgraph.js +9 -0
- package/src/model/runners/tabs.js +25 -0
- package/src/model/runners/terminal.js +5 -0
- package/src/model/runners/text.js +4 -0
- package/src/model/runners/timer.js +7 -0
- package/src/model/runners/traffic.js +65 -0
- package/src/model/runners/trigger.js +2 -0
- package/src/model/runners/verdict.js +29 -0
- package/src/model/runners/vm.js +7 -0
- package/src/model/runners/wait.js +4 -0
- package/src/model/runners/ws-client.js +57 -0
- package/src/model/safe-regex.js +719 -0
- package/src/model/sample-settings.js +43 -0
- package/src/model/sample-source.js +47 -0
- package/src/model/saved-mapping.js +153 -0
- package/src/model/score-controllers.js +87 -0
- package/src/model/score-edit.js +399 -0
- package/src/model/score-instruments.js +300 -0
- package/src/model/score-library.js +407 -0
- package/src/model/score-markup.js +235 -0
- package/src/model/score-mix.js +248 -0
- package/src/model/score-patterns.js +276 -0
- package/src/model/score-selection.js +34 -0
- package/src/model/score-time.js +139 -0
- package/src/model/score-transforms.js +336 -0
- package/src/model/score-transport.js +192 -0
- package/src/model/selection.js +351 -0
- package/src/model/serial-controls.js +328 -0
- package/src/model/shares-pane.js +17 -0
- package/src/model/shell-pane.js +106 -0
- package/src/model/signature.js +1122 -0
- package/src/model/size-hints.js +106 -0
- package/src/model/size-ratio.js +12 -0
- package/src/model/skill-settings.js +23 -0
- package/src/model/snapping.js +466 -0
- package/src/model/split.js +375 -0
- package/src/model/spring-player.js +222 -0
- package/src/model/statecharts.js +1369 -0
- package/src/model/states-preset.js +208 -0
- package/src/model/static-route.js +100 -0
- package/src/model/step-words.js +45 -0
- package/src/model/subgraph.js +1042 -0
- package/src/model/switch.js +98 -0
- package/src/model/tabs-store.js +10 -0
- package/src/model/tensor-view.js +146 -0
- package/src/model/timer-clock.js +361 -0
- package/src/model/timers.js +422 -0
- package/src/model/timing.js +212 -0
- package/src/model/traffic-agent.js +111 -0
- package/src/model/traffic-store.js +20 -0
- package/src/model/traffic.js +665 -0
- package/src/model/transport.js +364 -0
- package/src/model/turns.js +86 -0
- package/src/model/types.js +425 -0
- package/src/model/value-path.js +138 -0
- package/src/model/versions.js +535 -0
- package/src/model/view-outputs.js +144 -0
- package/src/model/viewport-bookmarks.js +194 -0
- package/src/model/virtual-clock.js +85 -0
- package/src/model/vm-pane.js +258 -0
- package/src/model/wait-clock.js +715 -0
- package/src/model/wait-persist.js +248 -0
- package/src/model/waits.js +431 -0
- package/src/model/watch.js +80 -0
- package/src/model/webhook.js +496 -0
- package/src/model/when.js +48 -0
- package/src/model/widget-values.js +392 -0
- package/src/model/window-commands.js +278 -0
- package/src/model/windows.js +348 -0
- package/src/model/wire-inspect.js +343 -0
- package/src/model/wire-ops.js +324 -0
- package/src/model/wire-pipeline.js +378 -0
- package/src/model/wire-route.js +637 -0
- package/src/model/workspaces.js +122 -0
- package/src/model/ws-client.js +155 -0
- package/src/model/ws-demo.js +31 -0
- package/src/model/ws-frames.js +141 -0
- package/src/model/ws-hub.js +219 -0
- package/src/model/ws-served.js +13 -0
- package/src/model/xstate.js +374 -0
- package/src/narrative/narrative.js +1557 -0
- package/src/network/auth.js +224 -0
- package/src/network/csp-frame.js +197 -0
- package/src/network/declarative-shadow.js +27 -0
- package/src/network/frame-net-shim.js +962 -0
- package/src/network/hosts.js +157 -0
- package/src/network/policy.js +520 -0
- package/src/network/rtc-shim.js +418 -0
- package/src/network/secret-gate.js +78 -0
- package/src/network/secrets.js +261 -0
- package/src/network/sockets.js +287 -0
- package/src/network/store.js +186 -0
- package/src/network/streams.js +99 -0
- package/src/packages/asset-values.js +50 -0
- package/src/packages/assets.js +99 -0
- package/src/packages/deprecation.js +203 -0
- package/src/packages/fetch.js +152 -0
- package/src/packages/function-canvas.js +73 -0
- package/src/packages/module.js +120 -0
- package/src/packages/package.js +474 -0
- package/src/packages/published.js +27 -0
- package/src/packages/requires.js +83 -0
- package/src/packages/signing.js +145 -0
- package/src/packages/trust.js +107 -0
- package/src/panes/a2a.js +51 -0
- package/src/panes/acp.js +60 -0
- package/src/panes/actions.js +54 -0
- package/src/panes/agent.js +83 -0
- package/src/panes/audio.js +103 -0
- package/src/panes/automation.js +112 -0
- package/src/panes/calc.js +67 -0
- package/src/panes/catch.js +52 -0
- package/src/panes/codec.js +59 -0
- package/src/panes/colors.js +12 -0
- package/src/panes/companion.js +54 -0
- package/src/panes/decision.js +65 -0
- package/src/panes/device.js +56 -0
- package/src/panes/dom.js +37 -0
- package/src/panes/effects.js +118 -0
- package/src/panes/embed.js +30 -0
- package/src/panes/eval.js +186 -0
- package/src/panes/fields.js +299 -0
- package/src/panes/files.js +45 -0
- package/src/panes/gate.js +70 -0
- package/src/panes/geometry.js +64 -0
- package/src/panes/goals.js +75 -0
- package/src/panes/graph.js +66 -0
- package/src/panes/html.js +54 -0
- package/src/panes/http.js +82 -0
- package/src/panes/import.js +38 -0
- package/src/panes/input.js +124 -0
- package/src/panes/inputlog.js +66 -0
- package/src/panes/ledger.js +56 -0
- package/src/panes/machine.js +138 -0
- package/src/panes/mcp.js +85 -0
- package/src/panes/mcpapp.js +64 -0
- package/src/panes/media.js +38 -0
- package/src/panes/memory.js +46 -0
- package/src/panes/mesh-inspect.js +49 -0
- package/src/panes/note.js +38 -0
- package/src/panes/peer.js +44 -0
- package/src/panes/plot.js +196 -0
- package/src/panes/registry.js +475 -0
- package/src/panes/render.js +87 -0
- package/src/panes/respond.js +44 -0
- package/src/panes/router.js +84 -0
- package/src/panes/sample.js +75 -0
- package/src/panes/scene.js +55 -0
- package/src/panes/score.js +87 -0
- package/src/panes/secret.js +38 -0
- package/src/panes/select.js +67 -0
- package/src/panes/shader.js +166 -0
- package/src/panes/shared.js +33 -0
- package/src/panes/shares.js +43 -0
- package/src/panes/shell.js +47 -0
- package/src/panes/skill.js +44 -0
- package/src/panes/state.js +91 -0
- package/src/panes/statechart.js +63 -0
- package/src/panes/story.js +33 -0
- package/src/panes/subgraph.js +94 -0
- package/src/panes/tabs.js +52 -0
- package/src/panes/terminal.js +57 -0
- package/src/panes/text.js +36 -0
- package/src/panes/timer.js +55 -0
- package/src/panes/traffic.js +59 -0
- package/src/panes/verdict.js +62 -0
- package/src/panes/vm.js +46 -0
- package/src/panes/wait.js +61 -0
- package/src/panes/watch.js +57 -0
- package/src/panes/webhook.js +67 -0
- package/src/panes/ws-client.js +67 -0
- package/src/persist.js +281 -0
- package/src/plot/tex.js +19 -0
- package/src/plot/vendor.js +59 -0
- package/src/plot/view-vendor.js +5 -0
- package/src/privacy/levels.js +108 -0
- package/src/protocol/devtools.js +116 -0
- package/src/protocol/inspector.js +368 -0
- package/src/render/time.js +381 -0
- package/src/rooms/mesh-metrics.js +162 -0
- package/src/run/companion.js +355 -0
- package/src/run/describe.js +114 -0
- package/src/run/local-model.js +150 -0
- package/src/run/monitor.js +208 -0
- package/src/run/publish.js +360 -0
- package/src/run/respond-outcome.js +12 -0
- package/src/run/run.js +820 -0
- package/src/run/runner-pairing.js +243 -0
- package/src/run/values.js +122 -0
- package/src/runtime/compile.js +122 -0
- package/src/runtime/console-tag.js +64 -0
- package/src/runtime/frame-signals.js +126 -0
- package/src/runtime/iteration-push.js +19 -0
- package/src/runtime/keys.js +474 -0
- package/src/runtime/midi-input.js +170 -0
- package/src/runtime/person-waits.js +140 -0
- package/src/runtime/resource-timing.js +56 -0
- package/src/runtime/runtime.js +2150 -0
- package/src/runtime/sandbox-modules.js +163 -0
- package/src/runtime/spring.js +246 -0
- package/src/runtime/strict.js +215 -0
- package/src/runtime/transfer.js +75 -0
- package/src/runtime/tween.js +158 -0
- package/src/runtime/wasm-fuel.js +596 -0
- package/src/runtime/worker/00-prelude.js +88 -0
- package/src/runtime/worker/10-helpers.js +295 -0
- package/src/runtime/worker/20-io.js +645 -0
- package/src/runtime/worker/30-previews.js +210 -0
- package/src/runtime/worker/40-profile-lineage.js +278 -0
- package/src/runtime/worker/50-own-worker.js +233 -0
- package/src/runtime/worker/60-timers.js +172 -0
- package/src/runtime/worker/70-state-keyed.js +193 -0
- package/src/runtime/worker/80-each-compile-generators.js +619 -0
- package/src/runtime/worker/90-events-operators.js +655 -0
- package/src/runtime/worker/95-agents-batches.js +1820 -0
- package/src/runtime/worker/96-plot.js +47 -0
- package/src/runtime/worker/97-calc.js +28 -0
- package/src/runtime/worker/98-geometry.js +24 -0
- package/src/runtime/worker/99-graph.js +30 -0
- package/src/runtime/worker/99-shell.js +30 -0
- package/src/safety/config.js +57 -0
- package/src/safety/engine.js +324 -0
- package/src/scene/pixi-scene.js +806 -0
- package/src/scene/scene-assets.js +241 -0
- package/src/scene/scene-edit.js +319 -0
- package/src/secret/settings.js +41 -0
- package/src/security/multipart.js +257 -0
- package/src/security/redact.js +261 -0
- package/src/serial/broker.js +473 -0
- package/src/serial/config.js +185 -0
- package/src/serial/framers.js +389 -0
- package/src/serial/packets.js +64 -0
- package/src/shader/audio-texture.js +87 -0
- package/src/shader/channels.js +496 -0
- package/src/shader/common.js +90 -0
- package/src/shader/model.js +867 -0
- package/src/shader/passes.js +150 -0
- package/src/shader/shadertoy.js +198 -0
- package/src/shell/hub.js +287 -0
- package/src/sim/checkpoints.js +850 -0
- package/src/sim/compile.js +37 -0
- package/src/sim/fixed.js +377 -0
- package/src/sim/headless.js +205 -0
- package/src/sim/physics.js +399 -0
- package/src/smf-helper/vendor.js +2 -0
- package/src/sources/config.js +435 -0
- package/src/storage.js +153 -0
- package/src/table/table-geo.js +2344 -0
- package/src/table/table-lineage.js +808 -0
- package/src/table/table-quality.js +355 -0
- package/src/table/table-schema.js +392 -0
- package/src/table/table-sql.js +1650 -0
- package/src/table/table-stats.js +480 -0
- package/src/table/table.js +2102 -0
- package/src/tensor/tensor.js +1153 -0
- package/src/terminal/hub.js +715 -0
- package/src/terminal/screen.js +516 -0
- package/src/tests/capture.js +88 -0
- package/src/tests/compare.js +480 -0
- package/src/tests/dataset.js +170 -0
- package/src/tests/evaluate.js +286 -0
- package/src/tests/from-runs.js +99 -0
- package/src/tests/judge.js +134 -0
- package/src/tests/matchers.js +263 -0
- package/src/tests/matrix-spec.js +87 -0
- package/src/tests/matrix.js +397 -0
- package/src/tests/metrics.js +369 -0
- package/src/tests/no-value.js +42 -0
- package/src/tests/pane-check.js +45 -0
- package/src/tests/report.js +124 -0
- package/src/tests/reporters.js +140 -0
- package/src/tests/run.js +155 -0
- package/src/tilemap/tilemap.js +1122 -0
- package/src/units/units.js +3 -0
- package/src/util/bytes-text.js +21 -0
- package/src/util/num.js +10 -0
- package/src/util/regexp.js +2 -0
- package/src/util/text.js +38 -0
- package/src/verdict/engine.js +154 -0
- package/src/vm/guest-wsh.js +108 -0
- package/src/vm/hub.js +457 -0
- package/src/vm/image-files.js +4 -0
- package/src/vm/image.js +33 -0
- package/src/vm/image.lock.json +13 -0
- package/src/vm/link.js +266 -0
- package/src/vm/mount.js +212 -0
- package/src/vm/net.js +85 -0
- package/src/vm/pipe-ws.js +187 -0
- package/src/vm/v86-loader.js +11 -0
- package/src/webmcp/args.js +212 -0
- package/src/webmcp/hidden.js +218 -0
- package/src/webmcp/text.js +250 -0
- package/src/webmcp/tools/bookmark-tools.js +106 -0
- package/src/webmcp/tools/breakpoint-tools.js +48 -0
- package/src/webmcp/tools/canvases.js +208 -0
- package/src/webmcp/tools/context-tools.js +84 -0
- package/src/webmcp/tools/core.js +170 -0
- package/src/webmcp/tools/devices.js +41 -0
- package/src/webmcp/tools/edit.js +357 -0
- package/src/webmcp/tools/event-tools.js +145 -0
- package/src/webmcp/tools/image-tools.js +173 -0
- package/src/webmcp/tools/ink-tools.js +247 -0
- package/src/webmcp/tools/input-log-tools.js +163 -0
- package/src/webmcp/tools/live.js +166 -0
- package/src/webmcp/tools/machine-tools.js +74 -0
- package/src/webmcp/tools/media.js +161 -0
- package/src/webmcp/tools/midi-tools.js +32 -0
- package/src/webmcp/tools/preset-tools.js +184 -0
- package/src/webmcp/tools/quick-add-tools.js +95 -0
- package/src/webmcp/tools/reshape.js +152 -0
- package/src/webmcp/tools/run-tools.js +309 -0
- package/src/webmcp/tools/runs.js +101 -0
- package/src/webmcp/tools/scaffold-tools.js +161 -0
- package/src/webmcp/tools/serial-tools.js +36 -0
- package/src/webmcp/tools/shared.js +338 -0
- package/src/webmcp/tools/subgraphs.js +360 -0
- package/src/webmcp/tools/tests.js +170 -0
- package/src/webmcp/tools/traffic-tools.js +70 -0
- package/src/webmcp/tools/transport-tools.js +65 -0
- package/src/webmcp/tools/version-tools.js +126 -0
- package/src/webmcp/tools/versions.js +11 -0
- package/src/webmcp/tools/wire-tools.js +90 -0
- package/src/webmcp/tools/workspace-tools.js +93 -0
- package/src/webmcp/tools.js +1323 -0
- package/src/wsh/connect.js +347 -0
- package/src/wsh/demo-host.js +361 -0
- package/src/wsh/e2e.js +27 -0
- package/src/wsh/keys.js +154 -0
- package/src/wsh/known-hosts.js +39 -0
- package/src/wsh/private-key.js +95 -0
- package/src/wsh/reverse.js +34 -0
- package/src/wsh/settings.js +118 -0
- package/src/wsh/transfer.js +62 -0
- package/src/wsh/vendor.js +5 -0
- package/src/x402/challenge.js +171 -0
- package/src/x402/demo-server.js +127 -0
- package/src/x402/pay.js +125 -0
- package/src/x402/retry.js +95 -0
- package/src/x402/store.js +76 -0
|
@@ -0,0 +1,1650 @@
|
|
|
1
|
+
// The table SQL engine: a small, pure-JS SQL subset over in-memory
|
|
2
|
+
// tables, and the expression language `derive`/`filter` strings use. Loaded as
|
|
3
|
+
// the module "mallory:table/sql" (src/runtime/sources.js) and installed into the
|
|
4
|
+
// `table` helper with `install(table)`. Self-contained: no imports, no
|
|
5
|
+
// eval/new Function (a query is parsed and interpreted, so it can only do what
|
|
6
|
+
// this file does), no network, no storage.
|
|
7
|
+
//
|
|
8
|
+
// SUPPORTED
|
|
9
|
+
// [WITH name AS (select) [, …]] select [{UNION | EXCEPT} [ALL] select | INTERSECT [ALL] select …]
|
|
10
|
+
// (INTERSECT binds tighter than UNION and EXCEPT; NULLs are equal; ALL counts occurrences)
|
|
11
|
+
// select := SELECT [DISTINCT] item [, …] [FROM source [join …]] [WHERE e]
|
|
12
|
+
// [GROUP BY e [, …]] [HAVING e] [ORDER BY e [ASC|DESC] [NULLS FIRST|LAST] [, …]]
|
|
13
|
+
// [LIMIT n [OFFSET n]]
|
|
14
|
+
// item := * | alias.* | e [[AS] name]
|
|
15
|
+
// source := table [[AS] alias] | (select) [AS] alias
|
|
16
|
+
// join := [INNER | LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER] | CROSS] JOIN source [ON e | USING (col, …)]
|
|
17
|
+
// e := literals ('text' with '' escape, numbers, TRUE, FALSE, NULL), columns
|
|
18
|
+
// (name, alias.name, "quoted name"), parameters (?, :name, $name),
|
|
19
|
+
// + - * / % ||, = == <> != < <= > >=, AND OR NOT, IS [NOT] NULL,
|
|
20
|
+
// [NOT] IN (list), [NOT] BETWEEN, [NOT] LIKE / ILIKE, CASE, CAST(e AS type),
|
|
21
|
+
// functions, aggregates (COUNT(*), and [DISTINCT] e in any of them: SUM, AVG, MIN, MAX, …),
|
|
22
|
+
// subqueries (select): a scalar one, [NOT] IN (select), [NOT] EXISTS (select),
|
|
23
|
+
// window functions: fn(…) OVER ([PARTITION BY e, …] [ORDER BY …] [ROWS|RANGE frame])
|
|
24
|
+
// window := ROW_NUMBER, RANK, DENSE_RANK, PERCENT_RANK, CUME_DIST, NTILE(n), LAG/LEAD(e [, n [, default]]),
|
|
25
|
+
// FIRST_VALUE, LAST_VALUE, NTH_VALUE(e, n), and any aggregate (SUM, AVG, COUNT, MIN, MAX, MEDIAN, …)
|
|
26
|
+
// frame := {ROWS | RANGE} {bound | BETWEEN bound AND bound}; bound := UNBOUNDED PRECEDING | n PRECEDING |
|
|
27
|
+
// CURRENT ROW | n FOLLOWING | UNBOUNDED FOLLOWING (RANGE takes no n: peers, not distances)
|
|
28
|
+
// Windows are computed after WHERE, GROUP BY and HAVING and before DISTINCT, ORDER BY and LIMIT; they are allowed in
|
|
29
|
+
// SELECT and ORDER BY. A subquery runs once, so it can't use the columns of the query around it (no correlated ones).
|
|
30
|
+
// NOT SUPPORTED (an error says so): correlated subqueries, named windows (WINDOW w AS …), GROUPS frames, DISTINCT
|
|
31
|
+
// in a window aggregate, NATURAL joins, INSERT/UPDATE/DELETE/DDL.
|
|
32
|
+
//
|
|
33
|
+
// SEMANTICS (documented in the README, tested in test/table-sql.test.mjs)
|
|
34
|
+
// - Three-valued logic: NULL = anything is NULL; WHERE keeps only TRUE.
|
|
35
|
+
// - Types are strict: 1 = '1' is FALSE, 1 < '1' is an error for that row
|
|
36
|
+
// (reported, never silently dropped); + needs numbers, || needs text.
|
|
37
|
+
// - A missing cell (undefined) reads as NULL.
|
|
38
|
+
// - Join keys: SQL's rule, a NULL never matches (use the `join` operation
|
|
39
|
+
// with nulls: "match" for the other policy).
|
|
40
|
+
// - ORDER BY puts NULLs last unless NULLS FIRST; text sorts by `options.locale` (default "en").
|
|
41
|
+
// - Names are case-sensitive (columns and tables); keywords and functions are not.
|
|
42
|
+
|
|
43
|
+
const KEYWORDS = new Set("select distinct from where group by having order limit offset as join inner left right full outer cross on using and or not is null in between like ilike case when then else end cast with natural union intersect except all asc desc nulls true false".split(" "));
|
|
44
|
+
|
|
45
|
+
export function install(t) {
|
|
46
|
+
const { TableError, functions, aggregates, inferSchema, compareCells, typeOfCell, convertCell, setExpressionEngine, defineOp, keyPart, normalizeSchema, mergeOrigin, sortYielding, LINEAGE_META } = t;
|
|
47
|
+
const fail = (code, message, detail) => new TableError(code, message, detail);
|
|
48
|
+
|
|
49
|
+
// ── tokenizer ─────────────────────────────────────────────────────────────
|
|
50
|
+
function tokenize(src) {
|
|
51
|
+
const tokens = [];
|
|
52
|
+
let i = 0;
|
|
53
|
+
const n = src.length;
|
|
54
|
+
while (i < n) {
|
|
55
|
+
const c = src[i];
|
|
56
|
+
if (/\s/.test(c)) {
|
|
57
|
+
i++;
|
|
58
|
+
} else if (c === "-" && src[i + 1] === "-") {
|
|
59
|
+
while (i < n && src[i] !== "\n") i++;
|
|
60
|
+
} else if (c === "/" && src[i + 1] === "*") {
|
|
61
|
+
const end = src.indexOf("*/", i + 2);
|
|
62
|
+
if (end < 0) throw fail("sql-syntax", `SQL: a comment is never closed (at ${i}).`);
|
|
63
|
+
i = end + 2;
|
|
64
|
+
} else if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(src[i + 1] ?? ""))) {
|
|
65
|
+
const m = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(src.slice(i));
|
|
66
|
+
tokens.push({ t: "num", v: Number(m[0]), s: i, e: i + m[0].length });
|
|
67
|
+
i += m[0].length;
|
|
68
|
+
} else if (c === "'") {
|
|
69
|
+
let v = "";
|
|
70
|
+
let j = i + 1;
|
|
71
|
+
for (;;) {
|
|
72
|
+
if (j >= n) throw fail("sql-syntax", `SQL: a text literal is never closed (it starts at ${i}).`);
|
|
73
|
+
if (src[j] === "'") {
|
|
74
|
+
if (src[j + 1] === "'") (v += "'", (j += 2));
|
|
75
|
+
else break;
|
|
76
|
+
} else v += src[j++];
|
|
77
|
+
}
|
|
78
|
+
tokens.push({ t: "str", v, s: i, e: j + 1 });
|
|
79
|
+
i = j + 1;
|
|
80
|
+
} else if (c === '"' || c === "`") {
|
|
81
|
+
const end = src.indexOf(c, i + 1);
|
|
82
|
+
if (end < 0) throw fail("sql-syntax", `SQL: a quoted name is never closed (it starts at ${i}).`);
|
|
83
|
+
tokens.push({ t: "id", v: src.slice(i + 1, end), q: true, s: i, e: end + 1 });
|
|
84
|
+
i = end + 1;
|
|
85
|
+
} else if (/[A-Za-z_]/.test(c)) {
|
|
86
|
+
let j = i + 1;
|
|
87
|
+
while (j < n && /[A-Za-z0-9_]/.test(src[j])) j++;
|
|
88
|
+
const word = src.slice(i, j);
|
|
89
|
+
tokens.push({ t: "id", v: word, k: word.toLowerCase(), s: i, e: j });
|
|
90
|
+
i = j;
|
|
91
|
+
} else if (c === "?") {
|
|
92
|
+
tokens.push({ t: "param", v: null, s: i, e: i + 1 });
|
|
93
|
+
i++;
|
|
94
|
+
} else if ((c === ":" || c === "$") && /[A-Za-z_0-9]/.test(src[i + 1] ?? "")) {
|
|
95
|
+
let j = i + 1;
|
|
96
|
+
while (j < n && /[A-Za-z0-9_]/.test(src[j])) j++;
|
|
97
|
+
tokens.push({ t: "param", v: src.slice(i + 1, j), s: i, e: j });
|
|
98
|
+
i = j;
|
|
99
|
+
} else {
|
|
100
|
+
const two = src.slice(i, i + 2);
|
|
101
|
+
if (["<=", ">=", "<>", "!=", "==", "||"].includes(two)) {
|
|
102
|
+
tokens.push({ t: "op", v: two, s: i, e: i + 2 });
|
|
103
|
+
i += 2;
|
|
104
|
+
} else if ("+-*/%=<>(),.;".includes(c)) {
|
|
105
|
+
tokens.push({ t: "op", v: c, s: i, e: i + 1 });
|
|
106
|
+
i++;
|
|
107
|
+
} else throw fail("sql-syntax", `SQL: unexpected character ${JSON.stringify(c)} at ${i}.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
tokens.push({ t: "eof", s: n, e: n });
|
|
111
|
+
return tokens;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── parser ────────────────────────────────────────────────────────────────
|
|
115
|
+
function parse(src) {
|
|
116
|
+
const toks = tokenize(src);
|
|
117
|
+
let p = 0;
|
|
118
|
+
let positional = 0;
|
|
119
|
+
const peek = (o = 0) => toks[Math.min(p + o, toks.length - 1)];
|
|
120
|
+
const kw = (word, o = 0) => peek(o).t === "id" && !peek(o).q && peek(o).k === word;
|
|
121
|
+
const op = (v, o = 0) => peek(o).t === "op" && peek(o).v === v;
|
|
122
|
+
const describe = (tok) => (tok.t === "eof" ? "the end of the query" : `"${src.slice(tok.s, tok.e)}"`);
|
|
123
|
+
const syntax = (msg) => fail("sql-syntax", `SQL: ${msg} (near ${describe(peek())}, position ${peek().s}).`);
|
|
124
|
+
const eatKw = (w) => (kw(w) ? (p++, true) : false);
|
|
125
|
+
const eatOp = (v) => (op(v) ? (p++, true) : false);
|
|
126
|
+
const needKw = (w) => {
|
|
127
|
+
if (!eatKw(w)) throw syntax(`expected ${w.toUpperCase()}`);
|
|
128
|
+
};
|
|
129
|
+
const needOp = (v) => {
|
|
130
|
+
if (!eatOp(v)) throw syntax(`expected "${v}"`);
|
|
131
|
+
};
|
|
132
|
+
const name = (what) => {
|
|
133
|
+
const tok = peek();
|
|
134
|
+
if (tok.t !== "id" || (!tok.q && KEYWORDS.has(tok.k))) throw syntax(`expected ${what}`);
|
|
135
|
+
p++;
|
|
136
|
+
return tok.v;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
function parseQuery() {
|
|
140
|
+
const ctes = [];
|
|
141
|
+
if (eatKw("with")) {
|
|
142
|
+
do {
|
|
143
|
+
const n = name("a table name");
|
|
144
|
+
needKw("as");
|
|
145
|
+
needOp("(");
|
|
146
|
+
const q = parseQuery();
|
|
147
|
+
needOp(")");
|
|
148
|
+
ctes.push({ name: n, query: q });
|
|
149
|
+
} while (eatOp(","));
|
|
150
|
+
}
|
|
151
|
+
// INTERSECT binds tighter than UNION and EXCEPT, which go left to right.
|
|
152
|
+
const term = () => {
|
|
153
|
+
let a = { sel: parseSelect() };
|
|
154
|
+
while (kw("intersect")) {
|
|
155
|
+
p++;
|
|
156
|
+
const all = eatKw("all");
|
|
157
|
+
a = { op: "intersect", all, left: a, right: { sel: parseSelect() } };
|
|
158
|
+
}
|
|
159
|
+
return a;
|
|
160
|
+
};
|
|
161
|
+
let body = term();
|
|
162
|
+
while (kw("union") || kw("except")) {
|
|
163
|
+
const o = peek().k;
|
|
164
|
+
p++;
|
|
165
|
+
const all = eatKw("all");
|
|
166
|
+
body = { op: o, all, left: body, right: term() };
|
|
167
|
+
}
|
|
168
|
+
// `parts`: the SELECTs in the order they were written (what the AST was before INTERSECT and EXCEPT: `body` is the tree).
|
|
169
|
+
const leaves = (n) => (n.sel ? [{ sel: n.sel }] : [...leaves(n.left), ...leaves(n.right)]);
|
|
170
|
+
return { ctes, body, parts: leaves(body) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function parseSelect() {
|
|
174
|
+
needKw("select");
|
|
175
|
+
const distinct = eatKw("distinct");
|
|
176
|
+
const items = [];
|
|
177
|
+
do {
|
|
178
|
+
if (op("*")) {
|
|
179
|
+
p++;
|
|
180
|
+
items.push({ star: true });
|
|
181
|
+
} else if (peek().t === "id" && op(".", 1) && op("*", 2)) {
|
|
182
|
+
const q = peek().v;
|
|
183
|
+
p += 3;
|
|
184
|
+
items.push({ star: true, q });
|
|
185
|
+
} else {
|
|
186
|
+
const start = peek().s;
|
|
187
|
+
const e = parseExpr();
|
|
188
|
+
const end = toks[p - 1].e;
|
|
189
|
+
let alias;
|
|
190
|
+
if (eatKw("as")) alias = name("a column name");
|
|
191
|
+
else if (peek().t === "id" && (peek().q || !KEYWORDS.has(peek().k))) alias = name("a column name");
|
|
192
|
+
items.push({ e, alias, text: src.slice(start, end).trim() });
|
|
193
|
+
}
|
|
194
|
+
} while (eatOp(","));
|
|
195
|
+
const sel = { distinct, items, from: null, joins: [], where: null, group: [], having: null, order: [], limit: null, offset: null };
|
|
196
|
+
if (eatKw("from")) {
|
|
197
|
+
sel.from = parseSource();
|
|
198
|
+
for (;;) {
|
|
199
|
+
let type = null;
|
|
200
|
+
if (kw("join")) type = "inner";
|
|
201
|
+
else if (kw("inner")) (p++, (type = "inner"));
|
|
202
|
+
else if (kw("left")) (p++, eatKw("outer"), (type = "left"));
|
|
203
|
+
else if (kw("right")) (p++, eatKw("outer"), (type = "right"));
|
|
204
|
+
else if (kw("full")) (p++, eatKw("outer"), (type = "full"));
|
|
205
|
+
else if (kw("cross")) (p++, (type = "cross"));
|
|
206
|
+
else if (kw("natural")) throw fail("sql-unsupported", "SQL: NATURAL joins aren't supported; name the columns with ON or USING.");
|
|
207
|
+
else if (op(",")) (p++, (type = "cross"));
|
|
208
|
+
else break;
|
|
209
|
+
if (type !== "cross" || kw("join")) needKw("join");
|
|
210
|
+
const source = parseSource();
|
|
211
|
+
let on = null;
|
|
212
|
+
let using = null;
|
|
213
|
+
if (eatKw("on")) on = parseExpr();
|
|
214
|
+
else if (eatKw("using")) {
|
|
215
|
+
needOp("(");
|
|
216
|
+
using = [];
|
|
217
|
+
do using.push(name("a column name"));
|
|
218
|
+
while (eatOp(","));
|
|
219
|
+
needOp(")");
|
|
220
|
+
} else if (type !== "cross") throw syntax("a join needs ON or USING");
|
|
221
|
+
sel.joins.push({ type, source, on, using });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (eatKw("where")) sel.where = parseExpr();
|
|
225
|
+
if (eatKw("group")) {
|
|
226
|
+
needKw("by");
|
|
227
|
+
do sel.group.push(parseExpr());
|
|
228
|
+
while (eatOp(","));
|
|
229
|
+
}
|
|
230
|
+
if (eatKw("having")) sel.having = parseExpr();
|
|
231
|
+
if (eatKw("order")) {
|
|
232
|
+
needKw("by");
|
|
233
|
+
sel.order = parseOrderItems();
|
|
234
|
+
}
|
|
235
|
+
if (eatKw("limit")) {
|
|
236
|
+
sel.limit = intLiteral("LIMIT");
|
|
237
|
+
if (eatKw("offset")) sel.offset = intLiteral("OFFSET");
|
|
238
|
+
}
|
|
239
|
+
return sel;
|
|
240
|
+
}
|
|
241
|
+
function parseOrderItems() {
|
|
242
|
+
const list = [];
|
|
243
|
+
do {
|
|
244
|
+
const e = parseExpr();
|
|
245
|
+
let dir = "asc";
|
|
246
|
+
if (eatKw("desc")) dir = "desc";
|
|
247
|
+
else eatKw("asc");
|
|
248
|
+
let nulls = null;
|
|
249
|
+
if (eatKw("nulls")) {
|
|
250
|
+
if (eatKw("first")) nulls = "first";
|
|
251
|
+
else if (eatKw("last")) nulls = "last";
|
|
252
|
+
else throw syntax("expected FIRST or LAST");
|
|
253
|
+
}
|
|
254
|
+
list.push({ e, dir, nulls });
|
|
255
|
+
} while (eatOp(","));
|
|
256
|
+
return list;
|
|
257
|
+
}
|
|
258
|
+
function intLiteral(what) {
|
|
259
|
+
const tok = peek();
|
|
260
|
+
if (tok.t === "num" && Number.isInteger(tok.v) && tok.v >= 0) return (p++, tok.v);
|
|
261
|
+
if (tok.t === "param") return (p++, { param: tok.v === null ? positional++ : tok.v });
|
|
262
|
+
throw syntax(`${what} takes a whole number`);
|
|
263
|
+
}
|
|
264
|
+
function parseSource() {
|
|
265
|
+
if (eatOp("(")) {
|
|
266
|
+
const q = parseQuery();
|
|
267
|
+
needOp(")");
|
|
268
|
+
eatKw("as");
|
|
269
|
+
return { query: q, alias: name("an alias for the subquery") };
|
|
270
|
+
}
|
|
271
|
+
const table = name("a table name");
|
|
272
|
+
let alias = table;
|
|
273
|
+
if (eatKw("as")) alias = name("an alias");
|
|
274
|
+
else if (peek().t === "id" && (peek().q || !KEYWORDS.has(peek().k))) alias = name("an alias");
|
|
275
|
+
return { table, alias };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// expressions, loosest to tightest
|
|
279
|
+
function parseExpr() {
|
|
280
|
+
return parseOr();
|
|
281
|
+
}
|
|
282
|
+
function parseOr() {
|
|
283
|
+
let a = parseAnd();
|
|
284
|
+
while (eatKw("or")) a = { t: "or", a, b: parseAnd() };
|
|
285
|
+
return a;
|
|
286
|
+
}
|
|
287
|
+
function parseAnd() {
|
|
288
|
+
let a = parseNot();
|
|
289
|
+
while (eatKw("and")) a = { t: "and", a, b: parseNot() };
|
|
290
|
+
return a;
|
|
291
|
+
}
|
|
292
|
+
function parseNot() {
|
|
293
|
+
if (eatKw("not")) return { t: "not", x: parseNot() };
|
|
294
|
+
return parseCompare();
|
|
295
|
+
}
|
|
296
|
+
function parseCompare() {
|
|
297
|
+
let a = parseConcat();
|
|
298
|
+
for (;;) {
|
|
299
|
+
const tok = peek();
|
|
300
|
+
if (tok.t === "op" && ["=", "==", "<>", "!=", "<", "<=", ">", ">="].includes(tok.v)) {
|
|
301
|
+
p++;
|
|
302
|
+
a = { t: "cmp", op: tok.v === "==" ? "=" : tok.v === "!=" ? "<>" : tok.v, a, b: parseConcat() };
|
|
303
|
+
} else if (kw("is")) {
|
|
304
|
+
p++;
|
|
305
|
+
const neg = eatKw("not");
|
|
306
|
+
needKw("null");
|
|
307
|
+
a = { t: "isnull", x: a, neg };
|
|
308
|
+
} else {
|
|
309
|
+
const neg = kw("not") && (kw("in", 1) || kw("between", 1) || kw("like", 1) || kw("ilike", 1));
|
|
310
|
+
if (neg) p++;
|
|
311
|
+
if (kw("in")) {
|
|
312
|
+
p++;
|
|
313
|
+
needOp("(");
|
|
314
|
+
if (kw("select") || kw("with")) {
|
|
315
|
+
const query = parseQuery();
|
|
316
|
+
needOp(")");
|
|
317
|
+
a = { t: "insub", x: a, query, neg };
|
|
318
|
+
} else {
|
|
319
|
+
const list = [];
|
|
320
|
+
do list.push(parseExpr());
|
|
321
|
+
while (eatOp(","));
|
|
322
|
+
needOp(")");
|
|
323
|
+
a = { t: "in", x: a, list, neg };
|
|
324
|
+
}
|
|
325
|
+
} else if (kw("between")) {
|
|
326
|
+
p++;
|
|
327
|
+
const lo = parseConcat();
|
|
328
|
+
needKw("and");
|
|
329
|
+
a = { t: "between", x: a, lo, hi: parseConcat(), neg };
|
|
330
|
+
} else if (kw("like") || kw("ilike")) {
|
|
331
|
+
const ci = kw("ilike");
|
|
332
|
+
p++;
|
|
333
|
+
a = { t: "like", x: a, pat: parseConcat(), neg, ci };
|
|
334
|
+
} else break;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return a;
|
|
338
|
+
}
|
|
339
|
+
function parseConcat() {
|
|
340
|
+
let a = parseAdd();
|
|
341
|
+
while (eatOp("||")) a = { t: "bin", op: "||", a, b: parseAdd() };
|
|
342
|
+
return a;
|
|
343
|
+
}
|
|
344
|
+
function parseAdd() {
|
|
345
|
+
let a = parseMul();
|
|
346
|
+
for (;;) {
|
|
347
|
+
if (op("+") || op("-")) {
|
|
348
|
+
const o = peek().v;
|
|
349
|
+
p++;
|
|
350
|
+
a = { t: "bin", op: o, a, b: parseMul() };
|
|
351
|
+
} else return a;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function parseMul() {
|
|
355
|
+
let a = parseUnary();
|
|
356
|
+
for (;;) {
|
|
357
|
+
if (op("*") || op("/") || op("%")) {
|
|
358
|
+
const o = peek().v;
|
|
359
|
+
p++;
|
|
360
|
+
a = { t: "bin", op: o, a, b: parseUnary() };
|
|
361
|
+
} else return a;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function parseUnary() {
|
|
365
|
+
if (eatOp("-")) return { t: "neg", x: parseUnary() };
|
|
366
|
+
if (eatOp("+")) return parseUnary();
|
|
367
|
+
return parsePrimary();
|
|
368
|
+
}
|
|
369
|
+
function parsePrimary() {
|
|
370
|
+
const tok = peek();
|
|
371
|
+
if (tok.t === "num") return (p++, { t: "lit", v: tok.v });
|
|
372
|
+
if (tok.t === "str") return (p++, { t: "lit", v: tok.v });
|
|
373
|
+
if (tok.t === "param") return (p++, { t: "param", k: tok.v === null ? positional++ : tok.v });
|
|
374
|
+
if (op("(")) {
|
|
375
|
+
p++;
|
|
376
|
+
if (kw("select") || kw("with")) {
|
|
377
|
+
const query = parseQuery();
|
|
378
|
+
needOp(")");
|
|
379
|
+
return { t: "scalar", query };
|
|
380
|
+
}
|
|
381
|
+
const e = parseExpr();
|
|
382
|
+
needOp(")");
|
|
383
|
+
return e;
|
|
384
|
+
}
|
|
385
|
+
if (tok.t === "id" && !tok.q) {
|
|
386
|
+
if (tok.k === "null") return (p++, { t: "lit", v: null });
|
|
387
|
+
if (tok.k === "true") return (p++, { t: "lit", v: true });
|
|
388
|
+
if (tok.k === "false") return (p++, { t: "lit", v: false });
|
|
389
|
+
if (tok.k === "case") return parseCase();
|
|
390
|
+
if (tok.k === "exists" && op("(", 1)) {
|
|
391
|
+
p += 2;
|
|
392
|
+
const query = parseQuery();
|
|
393
|
+
needOp(")");
|
|
394
|
+
return { t: "exists", query };
|
|
395
|
+
}
|
|
396
|
+
if (tok.k === "cast" && op("(", 1)) {
|
|
397
|
+
p += 2;
|
|
398
|
+
const x = parseExpr();
|
|
399
|
+
needKw("as");
|
|
400
|
+
const type = name("a type").toLowerCase();
|
|
401
|
+
needOp(")");
|
|
402
|
+
return { t: "cast", x, type };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (tok.t === "id" && (tok.q || !KEYWORDS.has(tok.k) || op("(", 1))) {
|
|
406
|
+
p++;
|
|
407
|
+
if (op("(")) {
|
|
408
|
+
p++;
|
|
409
|
+
const fname = tok.v.toLowerCase();
|
|
410
|
+
let star = false;
|
|
411
|
+
let distinct = false;
|
|
412
|
+
const args = [];
|
|
413
|
+
if (op("*")) (p++, (star = true));
|
|
414
|
+
else if (!op(")")) {
|
|
415
|
+
distinct = eatKw("distinct");
|
|
416
|
+
do args.push(parseExpr());
|
|
417
|
+
while (eatOp(","));
|
|
418
|
+
}
|
|
419
|
+
needOp(")");
|
|
420
|
+
if (kw("over")) {
|
|
421
|
+
p++;
|
|
422
|
+
return { t: "fn", name: fname, args, star, distinct, over: parseOver() };
|
|
423
|
+
}
|
|
424
|
+
return { t: "fn", name: fname, args, star, distinct };
|
|
425
|
+
}
|
|
426
|
+
if (op(".") && peek(1).t === "id") {
|
|
427
|
+
p++;
|
|
428
|
+
const col = peek().v;
|
|
429
|
+
p++;
|
|
430
|
+
return { t: "col", q: tok.v, n: col };
|
|
431
|
+
}
|
|
432
|
+
return { t: "col", q: null, n: tok.v };
|
|
433
|
+
}
|
|
434
|
+
throw syntax("expected a value");
|
|
435
|
+
}
|
|
436
|
+
// OVER ( [PARTITION BY e, …] [ORDER BY …] [ROWS|RANGE frame] )
|
|
437
|
+
function parseOver() {
|
|
438
|
+
if (!op("(")) throw fail("sql-unsupported", "SQL: named windows (OVER w, WINDOW w AS …) aren't supported; write the window out: OVER (PARTITION BY … ORDER BY …).");
|
|
439
|
+
p++;
|
|
440
|
+
const over = { partition: [], order: [], frame: null };
|
|
441
|
+
if (eatKw("partition")) {
|
|
442
|
+
needKw("by");
|
|
443
|
+
do over.partition.push(parseExpr());
|
|
444
|
+
while (eatOp(","));
|
|
445
|
+
}
|
|
446
|
+
if (eatKw("order")) {
|
|
447
|
+
needKw("by");
|
|
448
|
+
over.order = parseOrderItems();
|
|
449
|
+
}
|
|
450
|
+
if (kw("rows") || kw("range") || kw("groups")) {
|
|
451
|
+
const mode = peek().k;
|
|
452
|
+
if (mode === "groups") throw fail("sql-unsupported", "SQL: GROUPS frames aren't supported (ROWS and RANGE are).");
|
|
453
|
+
p++;
|
|
454
|
+
const bound = () => {
|
|
455
|
+
if (eatKw("unbounded")) return eatKw("preceding") ? { t: "up" } : (needKw("following"), { t: "uf" });
|
|
456
|
+
if (eatKw("current")) return (needKw("row"), { t: "cur" });
|
|
457
|
+
const tok = peek();
|
|
458
|
+
if (tok.t === "num" && Number.isInteger(tok.v) && tok.v >= 0) {
|
|
459
|
+
p++;
|
|
460
|
+
if (eatKw("preceding")) return { t: "p", n: tok.v };
|
|
461
|
+
needKw("following");
|
|
462
|
+
return { t: "f", n: tok.v };
|
|
463
|
+
}
|
|
464
|
+
throw syntax("expected a frame bound: UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING or UNBOUNDED FOLLOWING");
|
|
465
|
+
};
|
|
466
|
+
let start;
|
|
467
|
+
let end;
|
|
468
|
+
if (eatKw("between")) {
|
|
469
|
+
start = bound();
|
|
470
|
+
needKw("and");
|
|
471
|
+
end = bound();
|
|
472
|
+
} else (start = bound()), (end = { t: "cur" });
|
|
473
|
+
// A frame runs forwards: UNBOUNDED PRECEDING, n PRECEDING (largest n first), CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING.
|
|
474
|
+
const rank = (b) => ({ up: 0, p: 1, cur: 2, f: 3, uf: 4 })[b.t];
|
|
475
|
+
if (start.t === "uf" || end.t === "up" || rank(start) > rank(end) || (start.t === "p" && end.t === "p" && start.n < end.n) || (start.t === "f" && end.t === "f" && start.n > end.n)) throw fail("sql-syntax", "SQL: the window frame ends before it starts (it runs from its first bound to its second, in order: UNBOUNDED PRECEDING … n PRECEDING … CURRENT ROW … n FOLLOWING … UNBOUNDED FOLLOWING).");
|
|
476
|
+
if (mode === "range" && (start.t === "p" || start.t === "f" || end.t === "p" || end.t === "f")) throw fail("sql-unsupported", "SQL: RANGE with n PRECEDING or n FOLLOWING isn't supported; use ROWS (a number of rows), or RANGE with UNBOUNDED and CURRENT ROW.");
|
|
477
|
+
over.frame = { mode, start, end };
|
|
478
|
+
}
|
|
479
|
+
needOp(")");
|
|
480
|
+
return over;
|
|
481
|
+
}
|
|
482
|
+
function parseCase() {
|
|
483
|
+
p++; // CASE
|
|
484
|
+
let operand = null;
|
|
485
|
+
if (!kw("when")) operand = parseExpr();
|
|
486
|
+
const whens = [];
|
|
487
|
+
while (eatKw("when")) {
|
|
488
|
+
const w = parseExpr();
|
|
489
|
+
needKw("then");
|
|
490
|
+
whens.push({ w, r: parseExpr() });
|
|
491
|
+
}
|
|
492
|
+
if (!whens.length) throw syntax("CASE needs WHEN");
|
|
493
|
+
const els = eatKw("else") ? parseExpr() : null;
|
|
494
|
+
needKw("end");
|
|
495
|
+
return { t: "case", operand, whens, els };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const q = parseQuery();
|
|
499
|
+
eatOp(";");
|
|
500
|
+
if (peek().t !== "eof") throw syntax("unexpected input");
|
|
501
|
+
return q;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ── expression evaluation ─────────────────────────────────────────────────
|
|
505
|
+
const mismatch = (message) => fail("type-mismatch", message);
|
|
506
|
+
const show = (v) => (typeof v === "string" ? JSON.stringify(v) : String(v));
|
|
507
|
+
const isNum = (v) => typeof v === "number" || typeof v === "bigint";
|
|
508
|
+
const nul = (v) => v === null || v === undefined;
|
|
509
|
+
|
|
510
|
+
function equal(a, b) {
|
|
511
|
+
if (nul(a) || nul(b)) return null;
|
|
512
|
+
if (isNum(a) && isNum(b)) return a == b; // eslint-disable-line eqeqeq
|
|
513
|
+
if (typeof a !== typeof b) return false;
|
|
514
|
+
if (typeof a === "object") return keyPart(a) === keyPart(b);
|
|
515
|
+
return a === b;
|
|
516
|
+
}
|
|
517
|
+
function order(a, b, opts) {
|
|
518
|
+
if (typeOfCell(a) !== typeOfCell(b)) throw mismatch(`can't compare ${typeOfCell(a)} ${show(a)} with ${typeOfCell(b)} ${show(b)}; convert one with CAST`);
|
|
519
|
+
return compareCells(a, b, opts);
|
|
520
|
+
}
|
|
521
|
+
// LIKE is a pattern a query's author wrote too (`'%a%a%a%a%b'` backtracks as n^k on RegExp), so it runs on the linear-time matcher as well. A pattern the
|
|
522
|
+
// matcher can't take (over 200 characters of translated pattern) is an error saying so; text it can't answer for is an ERROR like REGEXP_LIKE's.
|
|
523
|
+
function likeRegex(pat, ci) {
|
|
524
|
+
let re = "^";
|
|
525
|
+
for (const ch of pat) re += ch === "%" ? "[\\s\\S]*" : ch === "_" ? "[\\s\\S]" : ch.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
|
|
526
|
+
if (!t.safeRegex) throw fail("bad-option", "LIKE can't run: no safe pattern matcher is installed");
|
|
527
|
+
const c = t.safeRegex.compileSafeRegex(`${re}$`, { ignoreCase: ci, patternLength: 1000 });
|
|
528
|
+
if (!c.ok) throw fail("bad-option", `LIKE: ${JSON.stringify(pat.length > 40 ? `${pat.slice(0, 40)}…` : pat)} can't be run safely: ${c.error}`);
|
|
529
|
+
return {
|
|
530
|
+
test(text) {
|
|
531
|
+
const answer = c.check(text);
|
|
532
|
+
if (answer === "match") return true;
|
|
533
|
+
if (answer === "none") return false;
|
|
534
|
+
throw fail("bad-option", `LIKE couldn't test ${JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}…` : text)} (${answer === "too-long" ? `text over ${c.limits.input} characters` : "the pattern costs too much on this text"}); the row was not tested`);
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
const likeCache = new Map();
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Compile an AST node to `(scope) => value`. `cx`: { col(q, n) -> getter,
|
|
542
|
+
* agg(node) -> getter (or null where aggregates aren't allowed), params, opts }.
|
|
543
|
+
*/
|
|
544
|
+
function compile(node, cx) {
|
|
545
|
+
const c = (x) => compile(x, cx);
|
|
546
|
+
switch (node.t) {
|
|
547
|
+
case "lit": {
|
|
548
|
+
const v = node.v;
|
|
549
|
+
return () => v;
|
|
550
|
+
}
|
|
551
|
+
case "param": {
|
|
552
|
+
// Looked up when the query is compiled, so a missing value is an error for the query, not for every row.
|
|
553
|
+
const params = cx.params;
|
|
554
|
+
const k = node.k;
|
|
555
|
+
const given = Array.isArray(params) ? k < params.length : params !== null && typeof params === "object" && k in params;
|
|
556
|
+
if (!given) throw fail("sql-param", `SQL: no value for parameter ${typeof k === "number" ? `#${k + 1}` : `:${k}`} (pass \`params\`: an array for ?, an object for :name).`);
|
|
557
|
+
const v = Array.isArray(params) ? params[k] : params[k];
|
|
558
|
+
return () => v;
|
|
559
|
+
}
|
|
560
|
+
case "col":
|
|
561
|
+
return cx.col(node.q, node.n);
|
|
562
|
+
case "neg": {
|
|
563
|
+
const x = c(node.x);
|
|
564
|
+
return (s) => {
|
|
565
|
+
const v = x(s);
|
|
566
|
+
if (nul(v)) return null;
|
|
567
|
+
if (!isNum(v)) throw mismatch(`can't negate ${typeOfCell(v)} ${show(v)}`);
|
|
568
|
+
return -v;
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
case "not": {
|
|
572
|
+
const x = c(node.x);
|
|
573
|
+
return (s) => {
|
|
574
|
+
const v = x(s);
|
|
575
|
+
if (nul(v)) return null;
|
|
576
|
+
if (typeof v !== "boolean") throw mismatch(`NOT needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
577
|
+
return !v;
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
case "and":
|
|
581
|
+
case "or": {
|
|
582
|
+
const a = c(node.a);
|
|
583
|
+
const b = c(node.b);
|
|
584
|
+
const isAnd = node.t === "and";
|
|
585
|
+
const bool = (v) => {
|
|
586
|
+
if (nul(v)) return null;
|
|
587
|
+
if (typeof v !== "boolean") throw mismatch(`${isAnd ? "AND" : "OR"} needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
588
|
+
return v;
|
|
589
|
+
};
|
|
590
|
+
return (s) => {
|
|
591
|
+
const x = bool(a(s));
|
|
592
|
+
if (isAnd ? x === false : x === true) return x;
|
|
593
|
+
const y = bool(b(s));
|
|
594
|
+
if (isAnd) return y === false ? false : x === null || y === null ? null : true;
|
|
595
|
+
return y === true ? true : x === null || y === null ? null : false;
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
case "cmp": {
|
|
599
|
+
const a = c(node.a);
|
|
600
|
+
const b = c(node.b);
|
|
601
|
+
const o = node.op;
|
|
602
|
+
return (s) => {
|
|
603
|
+
const x = a(s);
|
|
604
|
+
const y = b(s);
|
|
605
|
+
if (o === "=") return equal(x, y);
|
|
606
|
+
if (o === "<>") {
|
|
607
|
+
const e = equal(x, y);
|
|
608
|
+
return e === null ? null : !e;
|
|
609
|
+
}
|
|
610
|
+
if (nul(x) || nul(y)) return null;
|
|
611
|
+
const r = order(x, y, cx.opts);
|
|
612
|
+
return o === "<" ? r < 0 : o === "<=" ? r <= 0 : o === ">" ? r > 0 : r >= 0;
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
case "isnull": {
|
|
616
|
+
const x = c(node.x);
|
|
617
|
+
return (s) => nul(x(s)) !== node.neg;
|
|
618
|
+
}
|
|
619
|
+
case "in": {
|
|
620
|
+
const x = c(node.x);
|
|
621
|
+
const list = node.list.map(c);
|
|
622
|
+
return (s) => {
|
|
623
|
+
const v = x(s);
|
|
624
|
+
if (nul(v)) return null;
|
|
625
|
+
let unknown = false;
|
|
626
|
+
for (const f of list) {
|
|
627
|
+
const e = equal(v, f(s));
|
|
628
|
+
if (e === true) return !node.neg;
|
|
629
|
+
if (e === null) unknown = true;
|
|
630
|
+
}
|
|
631
|
+
return unknown ? null : node.neg;
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
case "insub": {
|
|
635
|
+
const x = c(node.x);
|
|
636
|
+
const got = subOf(cx, node, "IN (SELECT …)");
|
|
637
|
+
return (s) => {
|
|
638
|
+
const v = x(s);
|
|
639
|
+
if (nul(v)) return got.values.length ? null : node.neg; // NULL IN (empty) is false
|
|
640
|
+
const found = got.keys.has(keyPart(v));
|
|
641
|
+
if (found) return !node.neg;
|
|
642
|
+
return got.hasNull ? null : node.neg;
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
case "scalar": {
|
|
646
|
+
const got = subOf(cx, node, "a scalar subquery");
|
|
647
|
+
const v = got.values.length ? got.values[0] : null;
|
|
648
|
+
return () => v;
|
|
649
|
+
}
|
|
650
|
+
case "exists": {
|
|
651
|
+
const got = subOf(cx, node, "EXISTS (SELECT …)");
|
|
652
|
+
const v = got.rowCount > 0;
|
|
653
|
+
return () => v;
|
|
654
|
+
}
|
|
655
|
+
case "between": {
|
|
656
|
+
const x = c(node.x);
|
|
657
|
+
const lo = c(node.lo);
|
|
658
|
+
const hi = c(node.hi);
|
|
659
|
+
return (s) => {
|
|
660
|
+
const v = x(s);
|
|
661
|
+
const l = lo(s);
|
|
662
|
+
const h = hi(s);
|
|
663
|
+
if (nul(v) || nul(l) || nul(h)) return null;
|
|
664
|
+
const r = order(v, l, cx.opts) >= 0 && order(v, h, cx.opts) <= 0;
|
|
665
|
+
return node.neg ? !r : r;
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
case "like": {
|
|
669
|
+
const x = c(node.x);
|
|
670
|
+
const pat = c(node.pat);
|
|
671
|
+
return (s) => {
|
|
672
|
+
const v = x(s);
|
|
673
|
+
const pt = pat(s);
|
|
674
|
+
if (nul(v) || nul(pt)) return null;
|
|
675
|
+
if (typeof v !== "string" || typeof pt !== "string") throw mismatch(`LIKE compares text, not ${typeOfCell(typeof v !== "string" ? v : pt)}`);
|
|
676
|
+
const key = `${node.ci ? "i" : "s"}${pt}`;
|
|
677
|
+
let re = likeCache.get(key);
|
|
678
|
+
if (!re) {
|
|
679
|
+
if (likeCache.size > 200) likeCache.clear();
|
|
680
|
+
likeCache.set(key, (re = likeRegex(pt, node.ci)));
|
|
681
|
+
}
|
|
682
|
+
return re.test(v) !== node.neg;
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
case "bin": {
|
|
686
|
+
const a = c(node.a);
|
|
687
|
+
const b = c(node.b);
|
|
688
|
+
const o = node.op;
|
|
689
|
+
return (s) => {
|
|
690
|
+
const x = a(s);
|
|
691
|
+
const y = b(s);
|
|
692
|
+
if (nul(x) || nul(y)) return null;
|
|
693
|
+
if (o === "||") {
|
|
694
|
+
if (typeof x !== "string" || typeof y !== "string") throw mismatch(`|| joins text, not ${typeOfCell(typeof x !== "string" ? x : y)} ${show(typeof x !== "string" ? x : y)}; use CAST(… AS text) or CONCAT`);
|
|
695
|
+
return x + y;
|
|
696
|
+
}
|
|
697
|
+
if (!isNum(x) || !isNum(y)) throw mismatch(`${o} needs numbers, not ${typeOfCell(!isNum(x) ? x : y)} ${show(!isNum(x) ? x : y)}`);
|
|
698
|
+
switch (o) {
|
|
699
|
+
case "+":
|
|
700
|
+
return x + y;
|
|
701
|
+
case "-":
|
|
702
|
+
return x - y;
|
|
703
|
+
case "*":
|
|
704
|
+
return x * y;
|
|
705
|
+
case "/":
|
|
706
|
+
if (y == 0) throw fail("division-by-zero", "division by zero"); // eslint-disable-line eqeqeq
|
|
707
|
+
return x / y;
|
|
708
|
+
default:
|
|
709
|
+
if (y == 0) throw fail("division-by-zero", "division by zero"); // eslint-disable-line eqeqeq
|
|
710
|
+
return x % y;
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
case "case": {
|
|
715
|
+
const operand = node.operand ? c(node.operand) : null;
|
|
716
|
+
const whens = node.whens.map((w) => ({ w: c(w.w), r: c(w.r) }));
|
|
717
|
+
const els = node.els ? c(node.els) : () => null;
|
|
718
|
+
return (s) => {
|
|
719
|
+
const base = operand ? operand(s) : undefined;
|
|
720
|
+
for (const w of whens) {
|
|
721
|
+
const v = w.w(s);
|
|
722
|
+
if (operand ? equal(base, v) === true : v === true) return w.r(s);
|
|
723
|
+
if (!operand && !nul(v) && typeof v !== "boolean") throw mismatch(`CASE WHEN needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
724
|
+
}
|
|
725
|
+
return els(s);
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
case "cast": {
|
|
729
|
+
const x = c(node.x);
|
|
730
|
+
const map = { int: "integer", integer: "integer", bigint: "integer", number: "number", real: "number", float: "number", double: "number", numeric: "number", decimal: "number", text: "string", string: "string", varchar: "string", char: "string", boolean: "boolean", bool: "boolean", date: "date", timestamp: "datetime", datetime: "datetime", json: "json" };
|
|
731
|
+
const type = map[node.type];
|
|
732
|
+
if (!type) throw fail("sql-syntax", `SQL: CAST to "${node.type}" isn't supported (${Object.keys(map).join(", ")}).`);
|
|
733
|
+
return (s) => {
|
|
734
|
+
const v = x(s);
|
|
735
|
+
if (nul(v)) return null;
|
|
736
|
+
const r = convertCell(v, { type, round: node.type === "int" || node.type === "integer" || node.type === "bigint" ? false : undefined });
|
|
737
|
+
if (r.error) throw fail("conversion", `CAST(… AS ${node.type}): ${r.error}`);
|
|
738
|
+
return r.value;
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
case "fn": {
|
|
742
|
+
if (node.over) {
|
|
743
|
+
if (!cx.win) throw fail("sql-window", cx.inWindow ? `SQL: a window function can't be used inside another window function (${node.name.toUpperCase()} OVER …).` : "SQL: window functions (OVER) are allowed in SELECT and ORDER BY only, not in WHERE, GROUP BY, HAVING or ON (and not in derive or filter strings). To filter on one, select it in a subquery and filter outside.");
|
|
744
|
+
return cx.win(node);
|
|
745
|
+
}
|
|
746
|
+
if (aggregates.has(node.name) || (node.star && node.name === "count")) {
|
|
747
|
+
if (!cx.agg) throw fail("sql-aggregate", `SQL: the aggregate ${node.name.toUpperCase()} isn't allowed here (it belongs in SELECT, HAVING or ORDER BY, not WHERE or ON).`);
|
|
748
|
+
return cx.agg(node, c);
|
|
749
|
+
}
|
|
750
|
+
const fn = functions.get(node.name);
|
|
751
|
+
if (!fn) throw fail("sql-unknown-function", `SQL: unknown function ${node.name.toUpperCase()}. Functions: ${[...functions.keys()].map((k) => k.toUpperCase()).join(", ")}; aggregates: ${[...aggregates.keys()].map((k) => k.toUpperCase()).join(", ")}.`);
|
|
752
|
+
if (node.star || node.distinct) throw fail("sql-syntax", `SQL: ${node.name.toUpperCase()} isn't an aggregate.`);
|
|
753
|
+
const args = node.args.map(c);
|
|
754
|
+
const nullSafe = fn.nullSafe === true;
|
|
755
|
+
return (s) => {
|
|
756
|
+
const vals = args.map((a) => a(s));
|
|
757
|
+
if (!nullSafe && vals.some(nul)) return null;
|
|
758
|
+
return fn(...vals);
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
default:
|
|
762
|
+
throw fail("sql-syntax", `SQL: can't evaluate ${node.t}.`);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/** A subquery's result as the compile step needs it (it was run before the expressions were compiled: see `runSubqueries`). */
|
|
767
|
+
function subOf(cx, node, what) {
|
|
768
|
+
const got = cx.sub?.(node);
|
|
769
|
+
if (!got) throw fail("sql-unsupported", `SQL: ${what} isn't available in derive and filter strings; use the sql operation.`);
|
|
770
|
+
return got;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// Scalar functions (extension point: `functions.set(name, fn)`; set fn.nullSafe = true to see nulls).
|
|
774
|
+
const need = (name, v, type) => {
|
|
775
|
+
if (type === "string" ? typeof v !== "string" : !isNum(v)) throw mismatch(`${name.toUpperCase()} needs ${type === "string" ? "text" : "a number"}, not ${typeOfCell(v)} ${show(v)}`);
|
|
776
|
+
return v;
|
|
777
|
+
};
|
|
778
|
+
const def = (name, fn, nullSafe = false) => {
|
|
779
|
+
if (nullSafe) fn.nullSafe = true;
|
|
780
|
+
if (!functions.has(name)) functions.set(name, fn);
|
|
781
|
+
};
|
|
782
|
+
def("upper", (s) => need("upper", s, "string").toUpperCase());
|
|
783
|
+
def("lower", (s) => need("lower", s, "string").toLowerCase());
|
|
784
|
+
def("length", (s) => (typeof s === "string" ? [...s].length : Array.isArray(s) ? s.length : need("length", s, "string")));
|
|
785
|
+
def("trim", (s) => need("trim", s, "string").trim());
|
|
786
|
+
def("ltrim", (s) => need("ltrim", s, "string").trimStart());
|
|
787
|
+
def("rtrim", (s) => need("rtrim", s, "string").trimEnd());
|
|
788
|
+
const substr = (s, start, len) => {
|
|
789
|
+
need("substr", s, "string");
|
|
790
|
+
const from = Math.max(0, need("substr", start, "number") - 1);
|
|
791
|
+
return len === undefined ? [...s].slice(from).join("") : [...s].slice(from, from + Math.max(0, need("substr", len, "number"))).join("");
|
|
792
|
+
};
|
|
793
|
+
def("substr", substr);
|
|
794
|
+
def("substring", substr);
|
|
795
|
+
def("replace", (s, a, b) => need("replace", s, "string").split(need("replace", a, "string")).join(need("replace", b, "string")));
|
|
796
|
+
def("concat", (...a) => a.map((v) => (nul(v) ? "" : typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v))).join(""), true);
|
|
797
|
+
def("coalesce", (...a) => a.find((v) => !nul(v)) ?? null, true);
|
|
798
|
+
def("ifnull", (a, b) => (nul(a) ? b ?? null : a), true);
|
|
799
|
+
def("nullif", (a, b) => (equal(a, b) === true ? null : a), true);
|
|
800
|
+
def("abs", (x) => Math.abs(need("abs", x, "number")));
|
|
801
|
+
def("round", (x, d = 0) => {
|
|
802
|
+
const f = 10 ** need("round", d, "number");
|
|
803
|
+
return Math.round((need("round", x, "number") + Number.EPSILON * Math.sign(x)) * f) / f;
|
|
804
|
+
});
|
|
805
|
+
def("floor", (x) => Math.floor(need("floor", x, "number")));
|
|
806
|
+
def("ceil", (x) => Math.ceil(need("ceil", x, "number")));
|
|
807
|
+
def("ceiling", (x) => Math.ceil(need("ceiling", x, "number")));
|
|
808
|
+
def("sqrt", (x) => {
|
|
809
|
+
if (need("sqrt", x, "number") < 0) throw fail("domain", "SQRT of a negative number");
|
|
810
|
+
return Math.sqrt(x);
|
|
811
|
+
});
|
|
812
|
+
def("power", (a, b) => need("power", a, "number") ** need("power", b, "number"));
|
|
813
|
+
def("pow", (a, b) => need("pow", a, "number") ** need("pow", b, "number"));
|
|
814
|
+
def("mod", (a, b) => need("mod", a, "number") % need("mod", b, "number"));
|
|
815
|
+
def("sign", (x) => Math.sign(need("sign", x, "number")));
|
|
816
|
+
def("least", (...a) => a.reduce((m, v) => (order(v, m) < 0 ? v : m)));
|
|
817
|
+
def("greatest", (...a) => a.reduce((m, v) => (order(v, m) > 0 ? v : m)));
|
|
818
|
+
def("instr", (s, sub) => need("instr", s, "string").indexOf(need("instr", sub, "string")) + 1);
|
|
819
|
+
def("starts_with", (s, p) => need("starts_with", s, "string").startsWith(need("starts_with", p, "string")));
|
|
820
|
+
def("ends_with", (s, p) => need("ends_with", s, "string").endsWith(need("ends_with", p, "string")));
|
|
821
|
+
def("contains", (s, p) => need("contains", s, "string").includes(need("contains", p, "string")));
|
|
822
|
+
def("split_part", (s, sep, n) => need("split_part", s, "string").split(need("split_part", sep, "string"))[need("split_part", n, "number") - 1] ?? "");
|
|
823
|
+
def("typeof", (v) => typeOfCell(v), true);
|
|
824
|
+
// REGEXP_LIKE runs the pattern on the linear-time matcher (`t.safeRegex`, src/model/safe-regex.js), never on RegExp: a query's pattern is text from a person or an
|
|
825
|
+
// agent. A pattern outside the supported subset is an error that says why. Text the matcher can't answer for (over its length, or a pattern too costly on it)
|
|
826
|
+
// is an ERROR too (a row error: the row is left out of the result and `errors` says why, as for any failing function), not NULL: NULL would drop the row from a WHERE as if it had been tested and rejected.
|
|
827
|
+
const patterns = new Map();
|
|
828
|
+
def("regexp_like", (s, re) => {
|
|
829
|
+
const text = need("regexp_like", s, "string");
|
|
830
|
+
const source = need("regexp_like", re, "string");
|
|
831
|
+
let c = patterns.get(source);
|
|
832
|
+
if (!c) {
|
|
833
|
+
if (!t.safeRegex) throw fail("bad-option", "REGEXP_LIKE can't run: no safe pattern matcher is installed");
|
|
834
|
+
c = t.safeRegex.compileSafeRegex(source);
|
|
835
|
+
if (patterns.size > 200) patterns.clear();
|
|
836
|
+
patterns.set(source, c);
|
|
837
|
+
}
|
|
838
|
+
if (!c.ok) throw fail("bad-option", `REGEXP_LIKE: ${JSON.stringify(source)} isn't a pattern this helper can run safely: ${c.error}`);
|
|
839
|
+
const answer = c.check(text);
|
|
840
|
+
if (answer === "match") return true;
|
|
841
|
+
if (answer === "none") return false;
|
|
842
|
+
throw fail("bad-option", `REGEXP_LIKE couldn't test ${JSON.stringify(text.length > 40 ? `${text.slice(0, 40)}…` : text)} against ${JSON.stringify(source)} (${answer === "too-long" ? `text over ${c.limits.input} characters` : "the pattern costs too much on this text"}); the row was not tested`);
|
|
843
|
+
});
|
|
844
|
+
const datePart = (name, pick) =>
|
|
845
|
+
def(name, (v) => {
|
|
846
|
+
const ms = typeof v === "string" ? t.parseIso(v) : NaN;
|
|
847
|
+
if (Number.isNaN(ms)) throw fail("conversion", `${name.toUpperCase()}: ${show(v)} isn't an ISO 8601 date`);
|
|
848
|
+
return pick(new Date(ms));
|
|
849
|
+
});
|
|
850
|
+
datePart("year", (d) => d.getUTCFullYear());
|
|
851
|
+
datePart("month", (d) => d.getUTCMonth() + 1);
|
|
852
|
+
datePart("day", (d) => d.getUTCDate());
|
|
853
|
+
datePart("hour", (d) => d.getUTCHours());
|
|
854
|
+
|
|
855
|
+
// ── single-row expressions (derive, filter) ───────────────────────────────
|
|
856
|
+
|
|
857
|
+
/** Compile an expression string to `(row, index) => value`. `columns` (names) makes an unknown name an error up front. */
|
|
858
|
+
function compileExpression(text, { params, columns, locale } = {}) {
|
|
859
|
+
const q = parse(`SELECT ${text} FROM t`);
|
|
860
|
+
const sel = q.body.sel;
|
|
861
|
+
if (!sel || q.ctes.length || sel.items.length !== 1 || sel.items[0].star || sel.where || sel.joins.length || sel.group.length || sel.order.length || sel.limit !== null) throw fail("sql-syntax", `Expression ${JSON.stringify(text)} isn't a single expression.`);
|
|
862
|
+
const known = columns ? new Set(columns) : null;
|
|
863
|
+
const fn = compile(sel.items[0].e, {
|
|
864
|
+
params,
|
|
865
|
+
opts: { locale },
|
|
866
|
+
col(qual, n) {
|
|
867
|
+
if (known && !known.has(n)) throw fail("unknown-column", `No column "${n}" in the expression ${JSON.stringify(text)}. Columns: ${[...known].map((x) => JSON.stringify(x)).join(", ")}.`, { column: n });
|
|
868
|
+
return (s) => s.row[n] ?? null;
|
|
869
|
+
},
|
|
870
|
+
agg: null,
|
|
871
|
+
});
|
|
872
|
+
const scope = { row: null };
|
|
873
|
+
return (row, i) => {
|
|
874
|
+
scope.row = row;
|
|
875
|
+
scope.i = i;
|
|
876
|
+
return fn(scope);
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// ── queries ───────────────────────────────────────────────────────────────
|
|
881
|
+
|
|
882
|
+
function findTable(tables, ctes, name) {
|
|
883
|
+
if (ctes.has(name)) return ctes.get(name);
|
|
884
|
+
if (Object.prototype.hasOwnProperty.call(tables, name)) return { rows: tables[name], declared: tables.__schemas?.[name], base: name };
|
|
885
|
+
const lower = Object.keys(tables).find((k) => k.toLowerCase() === name.toLowerCase());
|
|
886
|
+
throw fail("sql-unknown-table", `SQL: no table "${name}"${lower ? ` (did you mean "${lower}"? names are case-sensitive)` : ""}. Tables: ${[...Object.keys(tables).filter((k) => k !== "__schemas"), ...ctes.keys()].map((k) => JSON.stringify(k)).join(", ") || "(none given)"}.`, { table: name });
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** A row that was cut on one path but is in the result through another is not "excluded": take it out of the lists. */
|
|
890
|
+
function keepOnlyMissing(ctx, origin) {
|
|
891
|
+
const present = new Map();
|
|
892
|
+
for (const entry of origin) {
|
|
893
|
+
for (const [input, list] of Object.entries(entry)) {
|
|
894
|
+
if (input === LINEAGE_META) continue;
|
|
895
|
+
if (!present.has(input)) present.set(input, new Set());
|
|
896
|
+
for (const p of list) present.get(input).add(p);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
for (const [key, g] of ctx.excluded) {
|
|
900
|
+
const here = present.get(g.input);
|
|
901
|
+
const seen = new Set();
|
|
902
|
+
const rows = g.rows.filter((p) => !here?.has(p) && !seen.has(p) && seen.add(p));
|
|
903
|
+
g.count -= g.rows.length - rows.length; // a row cut by several pairs counts once
|
|
904
|
+
g.rows = rows;
|
|
905
|
+
if (!g.count) ctx.excluded.delete(key);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function* runQuery(ast, env, outer) {
|
|
910
|
+
const ctes = new Map(outer?.ctes ?? []);
|
|
911
|
+
for (const c of ast.ctes) {
|
|
912
|
+
const done = yield* runQuery(c.query, env, { ctes });
|
|
913
|
+
ctes.set(c.name, { rows: done.rows, origin: done.origin });
|
|
914
|
+
}
|
|
915
|
+
const scoped = { ...env, ctes };
|
|
916
|
+
const run = function* (node) {
|
|
917
|
+
if (node.sel) return yield* runSelect(node.sel, scoped);
|
|
918
|
+
const left = yield* run(node.left);
|
|
919
|
+
const right = yield* run(node.right);
|
|
920
|
+
return combine(node, left, right, env.ctx);
|
|
921
|
+
};
|
|
922
|
+
return yield* run(ast.body);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/** UNION, INTERSECT and EXCEPT of two results: the right side's columns line up with the left's by position, and the rows are compared as whole rows (NULL equals NULL). */
|
|
926
|
+
function combine(node, left, right, ctx) {
|
|
927
|
+
const what = node.op.toUpperCase();
|
|
928
|
+
if (left.columns.length !== right.columns.length) throw fail("sql-union", `SQL: ${what} needs the same number of columns on both sides (${left.columns.length} and ${right.columns.length}).`);
|
|
929
|
+
const names = left.columns;
|
|
930
|
+
const mapped = right.rows.map((r) => Object.fromEntries(names.map((c, i) => [c, r[right.columns[i]]])));
|
|
931
|
+
const keyOf = (r) => names.map((c) => keyPart(r[c])).join("\u0001");
|
|
932
|
+
const trace = Boolean(ctx.trace);
|
|
933
|
+
const merge = (list) => (list.length === 1 ? list[0] : mergeOrigin(list, ctx.maxLinks));
|
|
934
|
+
let rows;
|
|
935
|
+
let origin;
|
|
936
|
+
// `groups`: Map key -> { n: the first row's position, from: every origin that makes this row }
|
|
937
|
+
const distinct = (entries) => {
|
|
938
|
+
const seen = new Map();
|
|
939
|
+
for (const e of entries) {
|
|
940
|
+
const have = seen.get(e.key);
|
|
941
|
+
if (have) have.from.push(...e.from);
|
|
942
|
+
else seen.set(e.key, { row: e.row, from: [...e.from] });
|
|
943
|
+
}
|
|
944
|
+
return [...seen.values()];
|
|
945
|
+
};
|
|
946
|
+
const lefts = left.rows.map((row, i) => ({ row, key: keyOf(row), from: trace ? [left.origin[i]] : [] }));
|
|
947
|
+
const rights = mapped.map((row, i) => ({ row, key: keyOf(row), from: trace ? [right.origin[i]] : [] }));
|
|
948
|
+
if (node.op === "union") {
|
|
949
|
+
if (node.all) {
|
|
950
|
+
rows = [...left.rows, ...mapped];
|
|
951
|
+
origin = trace ? [...left.origin, ...right.origin] : undefined;
|
|
952
|
+
} else {
|
|
953
|
+
const out = distinct([...lefts, ...rights]);
|
|
954
|
+
rows = out.map((o) => o.row);
|
|
955
|
+
origin = trace ? out.map((o) => merge(o.from)) : undefined;
|
|
956
|
+
}
|
|
957
|
+
} else {
|
|
958
|
+
const inRight = new Map();
|
|
959
|
+
for (const r of rights) {
|
|
960
|
+
const list = inRight.get(r.key);
|
|
961
|
+
if (list) list.push(r);
|
|
962
|
+
else inRight.set(r.key, [r]);
|
|
963
|
+
}
|
|
964
|
+
if (node.op === "intersect") {
|
|
965
|
+
if (node.all) {
|
|
966
|
+
// min(left count, right count) occurrences: the k-th left row with the k-th right row it pairs with.
|
|
967
|
+
const used = new Map();
|
|
968
|
+
const out = [];
|
|
969
|
+
for (const l of lefts) {
|
|
970
|
+
const k = used.get(l.key) ?? 0;
|
|
971
|
+
const partner = inRight.get(l.key)?.[k];
|
|
972
|
+
if (!partner) continue;
|
|
973
|
+
used.set(l.key, k + 1);
|
|
974
|
+
out.push({ row: l.row, from: [...l.from, ...partner.from] });
|
|
975
|
+
}
|
|
976
|
+
rows = out.map((o) => o.row);
|
|
977
|
+
origin = trace ? out.map((o) => merge(o.from)) : undefined;
|
|
978
|
+
} else {
|
|
979
|
+
const out = distinct(lefts.filter((l) => inRight.has(l.key)).map((l) => ({ ...l, from: [...l.from, ...inRight.get(l.key).flatMap((r) => r.from)] })));
|
|
980
|
+
rows = out.map((o) => o.row);
|
|
981
|
+
origin = trace ? out.map((o) => merge(o.from)) : undefined;
|
|
982
|
+
}
|
|
983
|
+
} else if (node.all) {
|
|
984
|
+
// left count - right count occurrences: the first right-count occurrences of each row are the ones taken away.
|
|
985
|
+
const skipped = new Map();
|
|
986
|
+
const out = [];
|
|
987
|
+
for (const l of lefts) {
|
|
988
|
+
const take = inRight.get(l.key)?.length ?? 0;
|
|
989
|
+
const k = skipped.get(l.key) ?? 0;
|
|
990
|
+
if (k < take) skipped.set(l.key, k + 1);
|
|
991
|
+
else out.push({ row: l.row, from: l.from });
|
|
992
|
+
}
|
|
993
|
+
rows = out.map((o) => o.row);
|
|
994
|
+
origin = trace ? out.map((o) => merge(o.from)) : undefined;
|
|
995
|
+
} else {
|
|
996
|
+
const out = distinct(lefts.filter((l) => !inRight.has(l.key)));
|
|
997
|
+
rows = out.map((o) => o.row);
|
|
998
|
+
origin = trace ? out.map((o) => merge(o.from)) : undefined;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
ctx.checkRows(rows.length, `the ${what}`);
|
|
1002
|
+
return { columns: names, rows, ...(trace ? { origin } : {}) };
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/** Compare two lists of ORDER BY values by the specs (`dir`, `nulls`): <0, 0, >0. A pair that can't be compared is handed to `onError` and counts as equal. */
|
|
1006
|
+
function compareOrder(specs, ka, kb, onError, opts) {
|
|
1007
|
+
for (let q = 0; q < specs.length; q++) {
|
|
1008
|
+
const a = ka[q];
|
|
1009
|
+
const b = kb[q];
|
|
1010
|
+
const an = nul(a);
|
|
1011
|
+
const bn = nul(b);
|
|
1012
|
+
const nullsFirst = (specs[q].nulls ?? "last") === "first";
|
|
1013
|
+
if (an || bn) {
|
|
1014
|
+
if (an && bn) continue;
|
|
1015
|
+
return (an ? 1 : -1) * (nullsFirst ? -1 : 1);
|
|
1016
|
+
}
|
|
1017
|
+
let c;
|
|
1018
|
+
try {
|
|
1019
|
+
c = order(a, b, opts);
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
onError?.(error);
|
|
1022
|
+
c = 0;
|
|
1023
|
+
}
|
|
1024
|
+
if (c) return specs[q].dir === "desc" ? -c : c;
|
|
1025
|
+
}
|
|
1026
|
+
return 0;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/** The subquery nodes (scalar, IN, EXISTS) among the expressions `list`, not looking inside them (each runs its own). */
|
|
1030
|
+
function collectSubqueries(node, out) {
|
|
1031
|
+
if (Array.isArray(node)) for (const x of node) collectSubqueries(x, out);
|
|
1032
|
+
else if (node && typeof node === "object") {
|
|
1033
|
+
if (node.t === "scalar" || node.t === "exists") out.push(node);
|
|
1034
|
+
else if (node.t === "insub") (collectSubqueries(node.x, out), out.push(node));
|
|
1035
|
+
else for (const v of Object.values(node)) collectSubqueries(v, out);
|
|
1036
|
+
}
|
|
1037
|
+
return out;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/** Run the subqueries of one SELECT's expressions (once each, before its rows are looked at) and keep what the expressions need of them. */
|
|
1041
|
+
function* runSubqueries(sel, env) {
|
|
1042
|
+
const nodes = collectSubqueries([sel.items, sel.where, sel.group, sel.having, sel.order, sel.joins.map((j) => j.on)], []);
|
|
1043
|
+
for (const node of nodes) {
|
|
1044
|
+
if (env.subs.has(node)) continue;
|
|
1045
|
+
let done;
|
|
1046
|
+
try {
|
|
1047
|
+
done = yield* runQuery(node.query, env, env);
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
if (error?.code === "unknown-column") throw fail("unknown-column", `${error.message} A subquery runs once, on its own, so it can't use the columns of the query around it (correlated subqueries aren't supported): join the tables instead, or compare in the outer query.`, error.detail);
|
|
1050
|
+
throw error;
|
|
1051
|
+
}
|
|
1052
|
+
if (node.t !== "exists" && done.columns.length !== 1) throw fail("sql-subquery", `SQL: a subquery used as a value must return one column (this one returns ${done.columns.length}: ${done.columns.map((c) => JSON.stringify(c)).join(", ")}).`);
|
|
1053
|
+
if (node.t === "scalar" && done.rows.length > 1) throw fail("sql-subquery", `SQL: a scalar subquery returned ${done.rows.length} rows; it must return at most one (add LIMIT 1, or aggregate).`);
|
|
1054
|
+
const values = node.t === "exists" ? [] : done.rows.map((r) => r[done.columns[0]] ?? null);
|
|
1055
|
+
const keys = new Set();
|
|
1056
|
+
let hasNull = false;
|
|
1057
|
+
for (const v of values) (nul(v) ? (hasNull = true) : keys.add(keyPart(v)));
|
|
1058
|
+
env.subs.set(node, { values, keys, hasNull, rowCount: done.rows.length });
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// Window functions that aren't aggregates: argument counts (the aggregates take one, or * for COUNT).
|
|
1063
|
+
const WINDOW_FNS = new Map([
|
|
1064
|
+
["row_number", [0, 0]], ["rank", [0, 0]], ["dense_rank", [0, 0]], ["percent_rank", [0, 0]], ["cume_dist", [0, 0]],
|
|
1065
|
+
["ntile", [1, 1]], ["lag", [1, 3]], ["lead", [1, 3]], ["first_value", [1, 1]], ["last_value", [1, 1]], ["nth_value", [2, 2]],
|
|
1066
|
+
]);
|
|
1067
|
+
const wholeNumber = (what, v, min) => {
|
|
1068
|
+
if (!Number.isInteger(v) || v < min) throw fail("sql-window", `SQL: ${what} needs a whole number ${min === 0 ? "of 0 or more" : "of 1 or more"} (got ${show(v)}).`);
|
|
1069
|
+
return v;
|
|
1070
|
+
};
|
|
1071
|
+
|
|
1072
|
+
/**
|
|
1073
|
+
* One window function over the rows the query produced (after WHERE, GROUP BY and HAVING): the value for each
|
|
1074
|
+
* row goes in its scope's `w[k]`. A row whose keys or arguments can't be computed gets `wErr`, which the row's
|
|
1075
|
+
* projection then throws (the usual per-row error); the other rows are computed without it.
|
|
1076
|
+
*/
|
|
1077
|
+
function* computeWindow(w, k, produced, ctx, opts) {
|
|
1078
|
+
const parts = new Map();
|
|
1079
|
+
for (let idx = 0; idx < produced.length; idx++) {
|
|
1080
|
+
if (ctx.tick()) yield;
|
|
1081
|
+
const { scope } = produced[idx];
|
|
1082
|
+
if (scope.wErr) continue;
|
|
1083
|
+
try {
|
|
1084
|
+
const key = w.partition.map((f) => keyPart(f(scope))).join("\u0001");
|
|
1085
|
+
const entry = { idx, ok: w.order.map((o) => o.f(scope)), args: w.args.map((f) => f(scope)) };
|
|
1086
|
+
const list = parts.get(key);
|
|
1087
|
+
if (list) list.push(entry);
|
|
1088
|
+
else parts.set(key, [entry]);
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
scope.wErr = error;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
const NAME = w.node.name.toUpperCase();
|
|
1094
|
+
const reported = new Set();
|
|
1095
|
+
let cells = 0;
|
|
1096
|
+
for (const m of parts.values()) {
|
|
1097
|
+
const L = m.length;
|
|
1098
|
+
const rowOf = (i) => produced[m[i].idx].tp.i;
|
|
1099
|
+
const set = (i, v) => void (produced[m[i].idx].scope.w[k] = v);
|
|
1100
|
+
if (w.order.length) {
|
|
1101
|
+
yield* sortYielding(ctx, m, (x, y) => compareOrder(w.order, x.ok, y.ok, (error) => ctx.error({ row: produced[x.idx].tp.i, code: error.code ?? "expression", message: `window ORDER BY: ${error.message}` }), opts) || x.idx - y.idx);
|
|
1102
|
+
}
|
|
1103
|
+
// Peers: the rows an ORDER BY doesn't tell apart (without one, the whole partition).
|
|
1104
|
+
const peerStart = new Array(L);
|
|
1105
|
+
const peerEnd = new Array(L);
|
|
1106
|
+
const same = (i, j) => compareOrder(w.order, m[i].ok, m[j].ok, null, opts) === 0;
|
|
1107
|
+
for (let i = 0; i < L; i++) peerStart[i] = !w.order.length ? 0 : i > 0 && same(i, i - 1) ? peerStart[i - 1] : i;
|
|
1108
|
+
for (let i = L - 1; i >= 0; i--) peerEnd[i] = !w.order.length ? L - 1 : i < L - 1 && same(i, i + 1) ? peerEnd[i + 1] : i;
|
|
1109
|
+
const frame = w.frame ?? { mode: "range", start: { t: "up" }, end: { t: "cur" } };
|
|
1110
|
+
const lo = (i) => {
|
|
1111
|
+
const b = frame.start;
|
|
1112
|
+
return b.t === "up" ? 0 : b.t === "p" ? i - b.n : b.t === "f" ? i + b.n : frame.mode === "range" ? peerStart[i] : i;
|
|
1113
|
+
};
|
|
1114
|
+
const hi = (i) => {
|
|
1115
|
+
const b = frame.end;
|
|
1116
|
+
return b.t === "uf" ? L - 1 : b.t === "p" ? i - b.n : b.t === "f" ? i + b.n : frame.mode === "range" ? peerEnd[i] : i;
|
|
1117
|
+
};
|
|
1118
|
+
const span = (i) => [Math.max(0, lo(i)), Math.min(L - 1, hi(i))];
|
|
1119
|
+
const arg = (i, n = 0) => m[i].args[n] ?? null;
|
|
1120
|
+
switch (w.known) {
|
|
1121
|
+
case "row_number":
|
|
1122
|
+
for (let i = 0; i < L; i++) set(i, i + 1);
|
|
1123
|
+
break;
|
|
1124
|
+
case "rank":
|
|
1125
|
+
for (let i = 0; i < L; i++) set(i, peerStart[i] + 1);
|
|
1126
|
+
break;
|
|
1127
|
+
case "dense_rank": {
|
|
1128
|
+
let d = 0;
|
|
1129
|
+
for (let i = 0; i < L; i++) {
|
|
1130
|
+
if (peerStart[i] === i) d++;
|
|
1131
|
+
set(i, d);
|
|
1132
|
+
}
|
|
1133
|
+
break;
|
|
1134
|
+
}
|
|
1135
|
+
case "percent_rank":
|
|
1136
|
+
for (let i = 0; i < L; i++) set(i, L > 1 ? peerStart[i] / (L - 1) : 0);
|
|
1137
|
+
break;
|
|
1138
|
+
case "cume_dist":
|
|
1139
|
+
for (let i = 0; i < L; i++) set(i, (peerEnd[i] + 1) / L);
|
|
1140
|
+
break;
|
|
1141
|
+
case "ntile":
|
|
1142
|
+
for (let i = 0; i < L; i++) {
|
|
1143
|
+
const n = wholeNumber("NTILE", arg(i), 1);
|
|
1144
|
+
const base = Math.floor(L / n);
|
|
1145
|
+
const rem = L % n;
|
|
1146
|
+
const cut = rem * (base + 1);
|
|
1147
|
+
set(i, i < cut ? Math.floor(i / (base + 1)) + 1 : rem + Math.floor((i - cut) / base) + 1);
|
|
1148
|
+
}
|
|
1149
|
+
break;
|
|
1150
|
+
case "lag":
|
|
1151
|
+
case "lead":
|
|
1152
|
+
for (let i = 0; i < L; i++) {
|
|
1153
|
+
const off = m[i].args.length > 1 ? wholeNumber(NAME, arg(i, 1), 0) : 1;
|
|
1154
|
+
const at = w.known === "lag" ? i - off : i + off;
|
|
1155
|
+
set(i, at >= 0 && at < L ? arg(at) : m[i].args.length > 2 ? arg(i, 2) : null);
|
|
1156
|
+
}
|
|
1157
|
+
break;
|
|
1158
|
+
case "first_value":
|
|
1159
|
+
case "last_value":
|
|
1160
|
+
case "nth_value":
|
|
1161
|
+
for (let i = 0; i < L; i++) {
|
|
1162
|
+
const [l, h] = span(i);
|
|
1163
|
+
const n = w.known === "nth_value" ? wholeNumber(NAME, arg(i, 1), 1) : 1;
|
|
1164
|
+
const at = w.known === "last_value" ? h : l + n - 1;
|
|
1165
|
+
set(i, l <= h && at >= l && at <= h ? arg(at) : null);
|
|
1166
|
+
}
|
|
1167
|
+
break;
|
|
1168
|
+
default: {
|
|
1169
|
+
const spec = w.spec;
|
|
1170
|
+
const step = (state, j) => {
|
|
1171
|
+
const v = w.star ? 1 : arg(j);
|
|
1172
|
+
if (!spec.nulls && nul(v)) return;
|
|
1173
|
+
spec.step(state, v, {
|
|
1174
|
+
star: w.star,
|
|
1175
|
+
row: rowOf(j),
|
|
1176
|
+
compare: opts,
|
|
1177
|
+
bad: (message) => {
|
|
1178
|
+
if (reported.has(m[j].idx)) return;
|
|
1179
|
+
reported.add(m[j].idx);
|
|
1180
|
+
ctx.error({ row: rowOf(j), code: "aggregate-type", message: `${w.node.name}(): ${message}; the cell was ignored` });
|
|
1181
|
+
},
|
|
1182
|
+
});
|
|
1183
|
+
};
|
|
1184
|
+
// A value an aggregate hands out (a list) is copied: the running state goes on growing.
|
|
1185
|
+
const done = (state) => {
|
|
1186
|
+
const v = spec.done(state);
|
|
1187
|
+
if (v === null || typeof v !== "object") return v;
|
|
1188
|
+
try {
|
|
1189
|
+
return structuredClone(v);
|
|
1190
|
+
} catch {
|
|
1191
|
+
return v;
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
if (frame.start.t === "up") {
|
|
1195
|
+
// The frame only grows: one pass, reading each row once.
|
|
1196
|
+
const state = spec.init();
|
|
1197
|
+
let added = -1;
|
|
1198
|
+
for (let i = 0; i < L; i++) {
|
|
1199
|
+
if (ctx.tick()) yield;
|
|
1200
|
+
const h = Math.min(L - 1, hi(i));
|
|
1201
|
+
while (added < h) step(state, ++added);
|
|
1202
|
+
set(i, done(state));
|
|
1203
|
+
}
|
|
1204
|
+
} else {
|
|
1205
|
+
for (let i = 0; i < L; i++) {
|
|
1206
|
+
if (ctx.tick()) yield;
|
|
1207
|
+
const [l, h] = span(i);
|
|
1208
|
+
const state = spec.init();
|
|
1209
|
+
if (l <= h) {
|
|
1210
|
+
cells += h - l + 1;
|
|
1211
|
+
if (cells > ctx.limits.maxCells) throw fail("limit", `SQL: the window frames of ${NAME} would read over limits.maxCells (${ctx.limits.maxCells}) values. Use a smaller frame, or raise limits.maxCells.`);
|
|
1212
|
+
for (let j = l; j <= h; j++) step(state, j);
|
|
1213
|
+
}
|
|
1214
|
+
set(i, done(state));
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
const paramNum = (v, params, what) => {
|
|
1223
|
+
const n = v !== null && typeof v === "object" ? (Array.isArray(params) ? params[v.param] : params?.[v.param]) : v;
|
|
1224
|
+
if (!Number.isInteger(n) || n < 0) throw fail("sql-param", `SQL: ${what} needs a whole number (got ${show(n)}).`);
|
|
1225
|
+
return n;
|
|
1226
|
+
};
|
|
1227
|
+
|
|
1228
|
+
function* runSelect(sel, env) {
|
|
1229
|
+
const { ctx, tables, params, opts } = env;
|
|
1230
|
+
yield* runSubqueries(sel, env);
|
|
1231
|
+
// Sources.
|
|
1232
|
+
const sources = [];
|
|
1233
|
+
const addSource = function* (src) {
|
|
1234
|
+
let rows;
|
|
1235
|
+
let declared;
|
|
1236
|
+
let origin;
|
|
1237
|
+
let base;
|
|
1238
|
+
if (src.query) ({ rows, origin } = yield* runQuery(src.query, env, env));
|
|
1239
|
+
else ({ rows, declared, origin, base } = findTable(tables, env.ctes, src.table));
|
|
1240
|
+
t.checkInput(ctx, rows, `table ${src.table ?? src.alias}`);
|
|
1241
|
+
const cols = inferSchema(rows, { declared }).columns.map((c) => c.name);
|
|
1242
|
+
if (sources.some((s) => s.alias === src.alias)) throw fail("sql-alias", `SQL: the name "${src.alias}" is used for two tables; give one an alias (FROM t AS u).`);
|
|
1243
|
+
// `origin`: per row, the base-table rows it came from (a subquery or CTE); `base`: this is a named table itself.
|
|
1244
|
+
sources.push({ alias: src.alias, rows, cols: new Set(cols), colList: cols, origin, base });
|
|
1245
|
+
};
|
|
1246
|
+
if (sel.from) {
|
|
1247
|
+
yield* addSource(sel.from);
|
|
1248
|
+
for (const j of sel.joins) yield* addSource(j.source);
|
|
1249
|
+
}
|
|
1250
|
+
const resolve = (qual, n, upTo = sources.length) => {
|
|
1251
|
+
if (qual !== null) {
|
|
1252
|
+
const idx = sources.findIndex((s) => s.alias === qual);
|
|
1253
|
+
if (idx < 0 || idx >= upTo) throw fail("unknown-column", `SQL: no table or alias "${qual}" here (tables: ${sources.slice(0, upTo).map((s) => JSON.stringify(s.alias)).join(", ")}).`);
|
|
1254
|
+
if (!sources[idx].cols.has(n)) throw fail("unknown-column", `SQL: no column "${n}" in ${qual}. Columns: ${sources[idx].colList.map((x) => JSON.stringify(x)).join(", ")}.`, { column: n });
|
|
1255
|
+
return idx;
|
|
1256
|
+
}
|
|
1257
|
+
const hits = sources.slice(0, upTo).map((s, i) => (s.cols.has(n) ? i : -1)).filter((i) => i >= 0);
|
|
1258
|
+
if (hits.length === 1) return hits[0];
|
|
1259
|
+
if (hits.length > 1) throw fail("sql-ambiguous", `SQL: column "${n}" is in ${hits.map((i) => JSON.stringify(sources[i].alias)).join(" and ")}; write ${sources[hits[0]].alias}.${n} or ${sources[hits[1]].alias}.${n}.`, { column: n });
|
|
1260
|
+
return -1;
|
|
1261
|
+
};
|
|
1262
|
+
const baseCx = (upTo, outAlias) => ({
|
|
1263
|
+
params,
|
|
1264
|
+
opts,
|
|
1265
|
+
sub: (node) => env.subs.get(node),
|
|
1266
|
+
col(qual, n) {
|
|
1267
|
+
const idx = resolve(qual, n, upTo);
|
|
1268
|
+
if (idx < 0) {
|
|
1269
|
+
if (outAlias && qual === null && outAlias.has(n)) return (s) => s.out?.[n] ?? null;
|
|
1270
|
+
const all = sources.slice(0, upTo).flatMap((s) => s.colList);
|
|
1271
|
+
throw fail("unknown-column", `SQL: no column "${n}". Columns: ${all.map((x) => JSON.stringify(x)).join(", ") || "(none: the table has no rows and no declared schema)"}.`, { column: n });
|
|
1272
|
+
}
|
|
1273
|
+
return (s) => {
|
|
1274
|
+
const r = s.r[idx];
|
|
1275
|
+
return r === null || r === undefined ? null : r[n] ?? null;
|
|
1276
|
+
};
|
|
1277
|
+
},
|
|
1278
|
+
agg: null,
|
|
1279
|
+
});
|
|
1280
|
+
|
|
1281
|
+
// Joins build tuples: arrays of one row (or null) per source. With `trace`, `s` is the position of each in its source (-1: none).
|
|
1282
|
+
const trace = ctx.trace;
|
|
1283
|
+
const sourceOrigin = (k, pos) => (pos < 0 ? undefined : sources[k].origin ? sources[k].origin[pos] : sources[k].base !== undefined ? { [sources[k].base]: [pos] } : undefined);
|
|
1284
|
+
const tupleOrigin = (tps) => mergeOrigin(tps.flatMap((tp) => tp.s.map((pos, k) => sourceOrigin(k, pos))), ctx.maxLinks);
|
|
1285
|
+
// The named-table rows behind source `k`'s row `pos` (itself for a named table, its origin for a subquery or CTE).
|
|
1286
|
+
const baseRows = (k, pos) => {
|
|
1287
|
+
if (pos < 0) return [];
|
|
1288
|
+
if (sources[k].base !== undefined) return [[sources[k].base, pos]];
|
|
1289
|
+
const entry = sources[k].origin?.[pos];
|
|
1290
|
+
return entry ? Object.entries(entry).flatMap(([input, list]) => list.map((p) => [input, p])) : [];
|
|
1291
|
+
};
|
|
1292
|
+
// With trace: every named-table row behind this tuple is out of the result for `why` (one still in it through another tuple is dropped from the list at the end).
|
|
1293
|
+
const excludeTuple = (tp, why) => {
|
|
1294
|
+
if (trace) tp.s.forEach((pos, k) => baseRows(k, pos).forEach(([input, p]) => ctx.exclude({ ...why, input }, p)));
|
|
1295
|
+
};
|
|
1296
|
+
let tuples;
|
|
1297
|
+
if (!sel.from) tuples = [{ r: [], i: 0, ...(trace ? { s: [] } : {}) }];
|
|
1298
|
+
else {
|
|
1299
|
+
tuples = sources[0].rows.map((r, i) => ({ r: [r], i, ...(trace ? { s: [i] } : {}) }));
|
|
1300
|
+
for (let jn = 0; jn < sel.joins.length; jn++) {
|
|
1301
|
+
const j = sel.joins[jn];
|
|
1302
|
+
const k = jn + 1;
|
|
1303
|
+
const right = sources[k].rows;
|
|
1304
|
+
const jcx = baseCx(k + 1);
|
|
1305
|
+
let on = null;
|
|
1306
|
+
if (j.using) {
|
|
1307
|
+
const parts = j.using.map((n) => {
|
|
1308
|
+
const li = sources.slice(0, k).findIndex((s) => s.cols.has(n));
|
|
1309
|
+
if (li < 0 || !sources[k].cols.has(n)) throw fail("unknown-column", `SQL: USING (${n}) needs the column in both tables.`);
|
|
1310
|
+
return { li, n };
|
|
1311
|
+
});
|
|
1312
|
+
on = { using: parts };
|
|
1313
|
+
} else if (j.on) on = { expr: compile(j.on, jcx), ast: j.on };
|
|
1314
|
+
// Equality pairs for a hash join: a.x = b.y with one side in the new table.
|
|
1315
|
+
const pairs = [];
|
|
1316
|
+
const conj = (e) => (e.t === "and" ? [...conj(e.a), ...conj(e.b)] : [e]);
|
|
1317
|
+
if (on?.using) for (const u of on.using) pairs.push({ left: (tp) => tp.r[u.li]?.[u.n], right: (r) => r[u.n], n: u.n, li: u.li });
|
|
1318
|
+
else if (on)
|
|
1319
|
+
for (const e of conj(on.ast)) {
|
|
1320
|
+
if (e.t === "cmp" && e.op === "=" && e.a.t === "col" && e.b.t === "col") {
|
|
1321
|
+
let ai;
|
|
1322
|
+
let bi;
|
|
1323
|
+
try {
|
|
1324
|
+
ai = resolve(e.a.q, e.a.n, k + 1);
|
|
1325
|
+
bi = resolve(e.b.q, e.b.n, k + 1);
|
|
1326
|
+
} catch {
|
|
1327
|
+
continue;
|
|
1328
|
+
}
|
|
1329
|
+
if (ai === k && bi < k) pairs.push({ left: (tp) => tp.r[bi]?.[e.b.n], right: (r) => r[e.a.n] });
|
|
1330
|
+
else if (bi === k && ai < k) pairs.push({ left: (tp) => tp.r[ai]?.[e.a.n], right: (r) => r[e.b.n] });
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
const test = (tp, r) => {
|
|
1334
|
+
if (on?.using) return true; // pairs decided it
|
|
1335
|
+
if (!on) return true;
|
|
1336
|
+
const tuple = { r: [...tp.r, r], i: tp.i };
|
|
1337
|
+
const v = on.expr(tuple);
|
|
1338
|
+
if (v !== null && typeof v !== "boolean") throw mismatch(`ON needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
1339
|
+
return v === true;
|
|
1340
|
+
};
|
|
1341
|
+
let index = null;
|
|
1342
|
+
if (pairs.length) {
|
|
1343
|
+
index = new Map();
|
|
1344
|
+
for (let ri = 0; ri < right.length; ri++) {
|
|
1345
|
+
if (ctx.tick()) yield;
|
|
1346
|
+
const vals = pairs.map((pr) => pr.right(right[ri]));
|
|
1347
|
+
if (vals.some(nul)) continue; // SQL: a NULL key never matches
|
|
1348
|
+
const key = vals.map((v) => keyPart(v)).join("\u0001");
|
|
1349
|
+
const list = index.get(key);
|
|
1350
|
+
if (list) list.push(ri);
|
|
1351
|
+
else index.set(key, [ri]);
|
|
1352
|
+
}
|
|
1353
|
+
} else if (tuples.length * right.length > ctx.limits.maxCells) throw fail("limit", `SQL: this join without an equality condition would compare ${tuples.length * right.length} pairs, over limits.maxCells (${ctx.limits.maxCells}). Join on a key (ON a.id = b.id), or filter first.`);
|
|
1354
|
+
const out = [];
|
|
1355
|
+
const rightUsed = new Uint8Array(right.length);
|
|
1356
|
+
for (const tp of tuples) {
|
|
1357
|
+
if (ctx.tick()) yield;
|
|
1358
|
+
let found = false;
|
|
1359
|
+
let candidates;
|
|
1360
|
+
if (index) {
|
|
1361
|
+
const vals = pairs.map((pr) => pr.left(tp));
|
|
1362
|
+
candidates = vals.some(nul) ? [] : index.get(vals.map((v) => keyPart(v)).join("\u0001")) ?? [];
|
|
1363
|
+
} else candidates = right.map((_, ri) => ri);
|
|
1364
|
+
for (const ri of candidates) {
|
|
1365
|
+
if (ctx.tick()) yield;
|
|
1366
|
+
let ok;
|
|
1367
|
+
try {
|
|
1368
|
+
ok = test(tp, right[ri]);
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
ctx.error({ row: tp.i, code: error.code ?? "expression", message: `join ON: ${error.message}` });
|
|
1371
|
+
ok = false;
|
|
1372
|
+
}
|
|
1373
|
+
if (ok) {
|
|
1374
|
+
found = true;
|
|
1375
|
+
rightUsed[ri] = 1;
|
|
1376
|
+
ctx.checkRows(out.length + 1, "the join");
|
|
1377
|
+
out.push({ r: [...tp.r, right[ri]], i: tp.i, ...(trace ? { s: [...tp.s, ri] } : {}) });
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
if (!found && (j.type === "left" || j.type === "full")) out.push({ r: [...tp.r, null], i: tp.i, ...(trace ? { s: [...tp.s, -1] } : {}) });
|
|
1381
|
+
else if (!found) excludeTuple(tp, { kind: "unmatched", reason: `no row of ${JSON.stringify(sources[k].alias)} matched its ${j.type.toUpperCase()} JOIN condition` });
|
|
1382
|
+
}
|
|
1383
|
+
if (trace && (j.type === "inner" || j.type === "left"))
|
|
1384
|
+
right.forEach((_, ri) => {
|
|
1385
|
+
if (!rightUsed[ri]) baseRows(k, ri).forEach(([input, p]) => ctx.exclude({ input, kind: "unmatched", reason: `no row on the left matched its ${j.type.toUpperCase()} JOIN condition` }, p));
|
|
1386
|
+
});
|
|
1387
|
+
if (j.type === "right" || j.type === "full") {
|
|
1388
|
+
right.forEach((r, ri) => {
|
|
1389
|
+
if (!rightUsed[ri]) out.push({ r: [...Array(k).fill(null), r], i: -1, ...(trace ? { s: [...Array(k).fill(-1), ri] } : {}) });
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
tuples = out;
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
// Projection items.
|
|
1396
|
+
const items = [];
|
|
1397
|
+
for (const it of sel.items) {
|
|
1398
|
+
if (it.star) {
|
|
1399
|
+
const from = it.q === undefined ? sources.map((_, i) => i) : [sources.findIndex((s) => s.alias === it.q)];
|
|
1400
|
+
if (from[0] < 0) throw fail("unknown-column", `SQL: no table or alias "${it.q}" for ${it.q}.*.`);
|
|
1401
|
+
for (const idx of from) for (const n of sources[idx].colList) items.push({ star: true, idx, n });
|
|
1402
|
+
} else items.push(it);
|
|
1403
|
+
}
|
|
1404
|
+
if (!sel.from && items.some((i) => i.star)) throw fail("sql-syntax", "SQL: * needs a FROM.");
|
|
1405
|
+
// Output names.
|
|
1406
|
+
const names = [];
|
|
1407
|
+
const taken = new Set();
|
|
1408
|
+
const nameFor = (base, preferred) => {
|
|
1409
|
+
let nme = base;
|
|
1410
|
+
let k = 2;
|
|
1411
|
+
if (taken.has(nme) && preferred) nme = preferred;
|
|
1412
|
+
while (taken.has(nme)) nme = `${base}_${k++}`;
|
|
1413
|
+
if (nme !== base) ctx.note(`Two result columns were named "${base}": the later one is "${nme}". Give one an alias (AS).`);
|
|
1414
|
+
taken.add(nme);
|
|
1415
|
+
return nme;
|
|
1416
|
+
};
|
|
1417
|
+
for (const it of items) {
|
|
1418
|
+
if (it.star) names.push(nameFor(it.n, `${sources[it.idx].alias}_${it.n}`));
|
|
1419
|
+
else names.push(nameFor(it.alias ?? (it.e.t === "col" ? it.e.n : it.text)));
|
|
1420
|
+
}
|
|
1421
|
+
const aliasSet = new Set(items.filter((i) => !i.star && i.alias).map((i) => i.alias));
|
|
1422
|
+
|
|
1423
|
+
// Aggregates.
|
|
1424
|
+
const aggNodes = [];
|
|
1425
|
+
const aggCx = {
|
|
1426
|
+
...baseCx(sources.length, aliasSet),
|
|
1427
|
+
agg(node, c) {
|
|
1428
|
+
const spec = aggregates.get(node.name === "count" && node.distinct ? "count_distinct" : node.name);
|
|
1429
|
+
if (node.args.length > 1 || (!node.star && node.args.length === 0)) throw fail("sql-syntax", `SQL: ${node.name.toUpperCase()} takes one argument${node.name === "count" ? " (or *)" : ""}.`);
|
|
1430
|
+
if (node.distinct && node.star) throw fail("sql-syntax", `SQL: ${node.name.toUpperCase()}(DISTINCT *) isn't valid; DISTINCT takes a column or an expression.`);
|
|
1431
|
+
const innerCx = { ...aggCx, agg: null };
|
|
1432
|
+
const arg = node.star ? null : compile(node.args[0], innerCx);
|
|
1433
|
+
const k = aggNodes.length;
|
|
1434
|
+
// COUNT(DISTINCT e) is its own aggregate; for every other one DISTINCT feeds each different value once.
|
|
1435
|
+
aggNodes.push({ node, spec, arg, star: node.star, distinct: node.distinct && node.name !== "count" });
|
|
1436
|
+
return (s) => s.a[k];
|
|
1437
|
+
},
|
|
1438
|
+
};
|
|
1439
|
+
const hasAgg = (e) => {
|
|
1440
|
+
if (Array.isArray(e)) return e.some(hasAgg);
|
|
1441
|
+
if (!e || typeof e !== "object") return false;
|
|
1442
|
+
if (e.t === "scalar" || e.t === "exists") return false; // a subquery's own aggregates are its own
|
|
1443
|
+
if (e.t === "insub") return hasAgg(e.x);
|
|
1444
|
+
if (e.t === "fn" && e.over) return hasAgg([e.args, e.over.partition, e.over.order.map((o) => o.e)]); // SUM(x) OVER (…) is a window, not a group: its arguments may hold aggregates
|
|
1445
|
+
if (e.t === "fn" && (aggregates.has(e.name) || e.star)) return true;
|
|
1446
|
+
return Object.values(e).some(hasAgg);
|
|
1447
|
+
};
|
|
1448
|
+
const grouped = sel.group.length > 0 || items.some((i) => !i.star && hasAgg(i.e)) || hasAgg(sel.having) || sel.order.some((o) => hasAgg(o.e));
|
|
1449
|
+
const plain = baseCx(sources.length, aliasSet);
|
|
1450
|
+
// Window functions (SELECT and ORDER BY only): what they read is the grouped or plain row, never a select alias (the select list isn't computed yet).
|
|
1451
|
+
const winNodes = [];
|
|
1452
|
+
const winInner = { ...baseCx(sources.length), ...(grouped ? { agg: aggCx.agg } : {}), inWindow: true };
|
|
1453
|
+
const win = (node) => {
|
|
1454
|
+
const NAME = node.name.toUpperCase();
|
|
1455
|
+
const known = WINDOW_FNS.get(node.name);
|
|
1456
|
+
if (!known && !aggregates.has(node.name)) throw fail("sql-unknown-function", `SQL: ${NAME} isn't a window function. Window functions: ${[...WINDOW_FNS.keys()].map((n) => n.toUpperCase()).join(", ")}, and the aggregates (${[...aggregates.keys()].map((n) => n.toUpperCase()).join(", ")}).`);
|
|
1457
|
+
if (node.distinct) throw fail("sql-unsupported", `SQL: DISTINCT isn't supported inside a window function (${NAME}(DISTINCT …) OVER …).`);
|
|
1458
|
+
if (known) {
|
|
1459
|
+
const [min, max] = known;
|
|
1460
|
+
if (node.star || node.args.length < min || node.args.length > max) throw fail("sql-syntax", max === 0 ? `SQL: ${NAME} takes no argument.` : `SQL: ${NAME} takes ${min === max ? `${min} argument${min === 1 ? "" : "s"}` : `${min} to ${max} arguments`}.`);
|
|
1461
|
+
} else if (node.star ? node.name !== "count" : node.args.length !== 1) throw fail("sql-syntax", `SQL: ${NAME} takes one argument${node.name === "count" ? " (or *)" : ""}.`);
|
|
1462
|
+
const k = winNodes.length;
|
|
1463
|
+
winNodes.push({
|
|
1464
|
+
node,
|
|
1465
|
+
known: known ? node.name : null,
|
|
1466
|
+
spec: known ? null : aggregates.get(node.name),
|
|
1467
|
+
star: node.star,
|
|
1468
|
+
args: node.args.map((a) => compile(a, winInner)),
|
|
1469
|
+
partition: node.over.partition.map((e) => compile(e, winInner)),
|
|
1470
|
+
order: node.over.order.map((o) => ({ ...o, f: compile(o.e, winInner) })),
|
|
1471
|
+
frame: node.over.frame,
|
|
1472
|
+
});
|
|
1473
|
+
return (sc) => {
|
|
1474
|
+
if (sc.wErr) throw sc.wErr;
|
|
1475
|
+
return sc.w[k];
|
|
1476
|
+
};
|
|
1477
|
+
};
|
|
1478
|
+
const where = sel.where ? compile(sel.where, plain) : null;
|
|
1479
|
+
const projCx = { ...(grouped ? aggCx : plain), win };
|
|
1480
|
+
const projections = items.map((it) => (it.star ? (s) => s.r[it.idx]?.[it.n] ?? null : compile(it.e, projCx)));
|
|
1481
|
+
const groupKeys = sel.group.map((e) => compile(e, plain));
|
|
1482
|
+
const having = sel.having ? compile(sel.having, aggCx) : null;
|
|
1483
|
+
const orderKeys = sel.order.map((o) => ({ ...o, f: compile(o.e, projCx) }));
|
|
1484
|
+
|
|
1485
|
+
// WHERE.
|
|
1486
|
+
const rowFail = (tp, error) => ctx.error({ row: tp.i, code: error.code ?? "expression", message: error.message });
|
|
1487
|
+
if (where) {
|
|
1488
|
+
const kept = [];
|
|
1489
|
+
for (const tp of tuples) {
|
|
1490
|
+
if (ctx.tick()) yield;
|
|
1491
|
+
try {
|
|
1492
|
+
const v = where({ r: tp.r });
|
|
1493
|
+
if (v !== null && typeof v !== "boolean") throw mismatch(`WHERE needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
1494
|
+
if (v !== true) excludeTuple(tp, { kind: "filtered", reason: "WHERE was not true" });
|
|
1495
|
+
if (v === true) kept.push(tp);
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
rowFail(tp, error);
|
|
1498
|
+
excludeTuple(tp, { kind: "filtered", code: error.code ?? "expression", reason: `WHERE could not be evaluated: ${error.message}` });
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
tuples = kept;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// Group or project.
|
|
1505
|
+
let produced = []; // { out, scope }
|
|
1506
|
+
if (grouped) {
|
|
1507
|
+
const groups = new Map();
|
|
1508
|
+
for (const tp of tuples) {
|
|
1509
|
+
if (ctx.tick()) yield;
|
|
1510
|
+
let key;
|
|
1511
|
+
try {
|
|
1512
|
+
key = groupKeys.map((g) => g({ r: tp.r })).map((v) => keyPart(v)).join("\u0001");
|
|
1513
|
+
} catch (error) {
|
|
1514
|
+
rowFail(tp, error);
|
|
1515
|
+
excludeTuple(tp, { kind: "rejected", code: error.code ?? "expression", reason: `GROUP BY could not be evaluated: ${error.message}` });
|
|
1516
|
+
continue;
|
|
1517
|
+
}
|
|
1518
|
+
let g = groups.get(key);
|
|
1519
|
+
if (!g) groups.set(key, (g = []));
|
|
1520
|
+
g.push(tp);
|
|
1521
|
+
}
|
|
1522
|
+
if (!sel.group.length && !groups.size) groups.set("", []);
|
|
1523
|
+
for (const members of groups.values()) {
|
|
1524
|
+
const states = aggNodes.map((a) => a.spec.init());
|
|
1525
|
+
const seen = aggNodes.map((a) => (a.distinct ? new Set() : null));
|
|
1526
|
+
for (const tp of members) {
|
|
1527
|
+
if (ctx.tick()) yield;
|
|
1528
|
+
aggNodes.forEach((a, k) => {
|
|
1529
|
+
try {
|
|
1530
|
+
const v = a.star ? 1 : a.arg({ r: tp.r }) ?? null;
|
|
1531
|
+
if (!a.spec.nulls && nul(v)) return;
|
|
1532
|
+
if (a.distinct) {
|
|
1533
|
+
if (nul(v)) return; // DISTINCT never feeds a NULL
|
|
1534
|
+
const key = keyPart(v);
|
|
1535
|
+
if (seen[k].has(key)) return;
|
|
1536
|
+
seen[k].add(key);
|
|
1537
|
+
}
|
|
1538
|
+
a.spec.step(states[k], v, { star: a.star, row: tp.i, compare: opts, bad: (message) => ctx.error({ row: tp.i, code: "aggregate-type", message: `${a.node.name}(): ${message}; the cell was ignored` }) });
|
|
1539
|
+
} catch (error) {
|
|
1540
|
+
rowFail(tp, error);
|
|
1541
|
+
}
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
const scope = { r: members[0]?.r ?? sources.map(() => null), a: aggNodes.map((a, k) => a.spec.done(states[k])), i: members[0]?.i ?? 0 };
|
|
1545
|
+
produced.push({ scope, tp: members[0] ?? { i: 0 }, members });
|
|
1546
|
+
}
|
|
1547
|
+
if (having)
|
|
1548
|
+
produced = produced.filter(({ scope, tp, members }) => {
|
|
1549
|
+
try {
|
|
1550
|
+
const v = having(scope);
|
|
1551
|
+
if (v !== null && typeof v !== "boolean") throw mismatch(`HAVING needs true or false, not ${typeOfCell(v)} ${show(v)}`);
|
|
1552
|
+
if (v !== true) members.forEach((m) => excludeTuple(m, { kind: "filtered", reason: "HAVING was not true" }));
|
|
1553
|
+
return v === true;
|
|
1554
|
+
} catch (error) {
|
|
1555
|
+
rowFail(tp, error);
|
|
1556
|
+
members.forEach((m) => excludeTuple(m, { kind: "filtered", code: error.code ?? "expression", reason: `HAVING could not be evaluated: ${error.message}` }));
|
|
1557
|
+
return false;
|
|
1558
|
+
}
|
|
1559
|
+
});
|
|
1560
|
+
} else {
|
|
1561
|
+
if (sel.having) throw fail("sql-syntax", "SQL: HAVING needs GROUP BY or an aggregate.");
|
|
1562
|
+
produced = tuples.map((tp) => ({ scope: { r: tp.r, a: [], i: tp.i }, tp, members: [tp] }));
|
|
1563
|
+
}
|
|
1564
|
+
if (winNodes.length) {
|
|
1565
|
+
for (const { scope } of produced) scope.w = [];
|
|
1566
|
+
for (let k = 0; k < winNodes.length; k++) yield* computeWindow(winNodes[k], k, produced, ctx, opts);
|
|
1567
|
+
}
|
|
1568
|
+
let outs = [];
|
|
1569
|
+
for (const { scope, tp, members } of produced) {
|
|
1570
|
+
if (ctx.tick()) yield;
|
|
1571
|
+
try {
|
|
1572
|
+
const out = {};
|
|
1573
|
+
projections.forEach((f, k) => (out[names[k]] = f(scope)));
|
|
1574
|
+
scope.out = out;
|
|
1575
|
+
outs.push({ out, scope, i: tp.i, ups: trace ? [members] : undefined });
|
|
1576
|
+
} catch (error) {
|
|
1577
|
+
rowFail(tp, error);
|
|
1578
|
+
members.forEach((m) => excludeTuple(m, { kind: "rejected", code: error.code ?? "expression", reason: `SELECT could not be evaluated: ${error.message}` }));
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
ctx.checkRows(outs.length, "the result");
|
|
1582
|
+
if (sel.distinct) {
|
|
1583
|
+
const seen = new Map();
|
|
1584
|
+
outs = outs.filter((o) => {
|
|
1585
|
+
const key = names.map((n) => keyPart(o.out[n])).join("\u0001");
|
|
1586
|
+
if (seen.has(key)) {
|
|
1587
|
+
seen.get(key).ups?.push(...o.ups); // a repeated row is one row with all its ancestors
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
1590
|
+
seen.set(key, o);
|
|
1591
|
+
return true;
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
if (orderKeys.length) {
|
|
1595
|
+
const keyed = outs.map((o, idx) => {
|
|
1596
|
+
try {
|
|
1597
|
+
return { o, idx, k: orderKeys.map((ok) => ok.f(o.scope)) };
|
|
1598
|
+
} catch (error) {
|
|
1599
|
+
rowFail({ i: o.i }, error);
|
|
1600
|
+
return { o, idx, k: orderKeys.map(() => null) };
|
|
1601
|
+
}
|
|
1602
|
+
});
|
|
1603
|
+
yield* sortYielding(ctx, keyed, (x, y) => compareOrder(orderKeys, x.k, y.k, (error) => ctx.error({ row: x.o.i, code: error.code ?? "expression", message: `ORDER BY: ${error.message}` }), opts) || x.idx - y.idx);
|
|
1604
|
+
outs = keyed.map((k) => k.o);
|
|
1605
|
+
}
|
|
1606
|
+
const offset = sel.offset === null ? 0 : paramNum(sel.offset, params, "OFFSET");
|
|
1607
|
+
const limit = sel.limit === null ? Infinity : paramNum(sel.limit, params, "LIMIT");
|
|
1608
|
+
if (trace) {
|
|
1609
|
+
const cut = (list, reason) => list.forEach((o) => o.ups.flat().forEach((m) => excludeTuple(m, { kind: "dropped", reason })));
|
|
1610
|
+
cut(outs.slice(0, offset), "cut by OFFSET");
|
|
1611
|
+
cut(outs.slice(offset + limit), "cut by LIMIT");
|
|
1612
|
+
}
|
|
1613
|
+
outs = outs.slice(offset, offset + limit);
|
|
1614
|
+
return { columns: names, rows: outs.map((o) => o.out), ...(trace ? { origin: outs.map((o) => tupleOrigin(o.ups.flat())) } : {}) };
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Run a query over named tables: `sql("SELECT … FROM orders o JOIN users u ON …", { orders, users }, options)`.
|
|
1619
|
+
* `options`: params (array for ?, object for :name / $name), locale, schemas
|
|
1620
|
+
* ({ table: declared schema } so columns exist without rows), plus the
|
|
1621
|
+
* shared ones (onError, limits, signal, trace). Returns the usual result; an
|
|
1622
|
+
* error in one row (a type mismatch in WHERE, say) is an entry in `errors` and
|
|
1623
|
+
* excludes that row, and syntax or unknown names throw.
|
|
1624
|
+
*/
|
|
1625
|
+
const sqlOp = defineOp(
|
|
1626
|
+
"sql",
|
|
1627
|
+
function* ({ query, tables }, o, ctx) {
|
|
1628
|
+
if (typeof query !== "string" || !query.trim()) throw fail("sql-syntax", "SQL: the query is empty.");
|
|
1629
|
+
if (!tables || typeof tables !== "object" || Array.isArray(tables)) throw fail("bad-input", "SQL: tables is an object of named tables: { orders: rows, users: rows }.");
|
|
1630
|
+
for (const [name, rows] of Object.entries(tables)) {
|
|
1631
|
+
if (!Array.isArray(rows)) throw fail("bad-input", `SQL: table "${name}" isn't a table (an array of row objects).`);
|
|
1632
|
+
}
|
|
1633
|
+
const ast = parse(query);
|
|
1634
|
+
const schemas = o.schemas ? Object.fromEntries(Object.entries(o.schemas).map(([k, v]) => [k, normalizeSchema(v)])) : undefined;
|
|
1635
|
+
const env = { ctx, tables: schemas ? Object.assign(Object.create(null), tables, { __schemas: schemas }) : tables, params: o.params, opts: { locale: o.locale ?? "en", numeric: o.numeric, sensitivity: o.sensitivity }, ctes: new Map(), subs: new Map() };
|
|
1636
|
+
if (ctx.trace && Object.prototype.hasOwnProperty.call(tables, LINEAGE_META)) throw fail("bad-input", `SQL: a table can't be called "${LINEAGE_META}" when trace is on (it is the key of lineage metadata).`);
|
|
1637
|
+
const { columns, rows, origin } = yield* runQuery(ast, env, null);
|
|
1638
|
+
if (ctx.trace) keepOnlyMissing(ctx, origin);
|
|
1639
|
+
return { rows, origin, schema: inferSchema(rows, { declared: columns.map((name) => ({ name, type: "any" })) }) };
|
|
1640
|
+
},
|
|
1641
|
+
{ inputs: "none" },
|
|
1642
|
+
);
|
|
1643
|
+
|
|
1644
|
+
t.sql = (query, tables, options = {}) => sqlOp({ query, tables }, options);
|
|
1645
|
+
t.async.sql = (query, tables, options = {}) => sqlOp.async({ query, tables }, options);
|
|
1646
|
+
t.parseSql = (query) => parse(query);
|
|
1647
|
+
t.compileExpression = compileExpression;
|
|
1648
|
+
setExpressionEngine(compileExpression, 1);
|
|
1649
|
+
t.sqlSubset = "SELECT/WITH/UNION/INTERSECT/EXCEPT, JOINs, GROUP BY/HAVING, ORDER BY, LIMIT, CASE, CAST, LIKE, IN, BETWEEN, aggregates (DISTINCT), subqueries (scalar, IN, EXISTS), window functions";
|
|
1650
|
+
}
|