mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-02 22:31:17 +00:00
Compare commits
219
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
687ecd3a12 | ||
|
|
0f8a55b580 | ||
|
|
ee8f7a5668 | ||
|
|
47055d4f58 | ||
|
|
73da9c65c8 | ||
|
|
71ec2b9aa0 | ||
|
|
a4d025e778 | ||
|
|
79c31a6a9f | ||
|
|
80e5bf2857 | ||
|
|
52276ad881 | ||
|
|
7f8a981d8a | ||
|
|
9d00fe9cca | ||
|
|
4e8d4f2d80 | ||
|
|
505e303d13 | ||
|
|
4434e3bd05 | ||
|
|
7960441bca | ||
|
|
a09cd4fa30 | ||
|
|
3547cd1593 | ||
|
|
e605ad4e69 | ||
|
|
4eb8e3e38d | ||
|
|
d176602488 | ||
|
|
14493aa259 | ||
|
|
d4ef6064a4 | ||
|
|
60c72b77a6 | ||
|
|
226a5d3d26 | ||
|
|
585970c542 | ||
|
|
9ed28ba9ea | ||
|
|
4d94d3e27c | ||
|
|
9a1e05f442 | ||
|
|
be7732912b | ||
|
|
c869fdb23c | ||
|
|
d0661f8505 | ||
|
|
be07bd69fd | ||
|
|
5f22c7c01c | ||
|
|
838c9104c0 | ||
|
|
ade107ab73 | ||
|
|
44b8fc5b52 | ||
|
|
331486148e | ||
|
|
28bd4b42d0 | ||
|
|
684d86b78d | ||
|
|
5b43c2abc8 | ||
|
|
01c94182f5 | ||
|
|
0ff6f02485 | ||
|
|
f2934fd009 | ||
|
|
ba597305a1 | ||
|
|
0e57a9d37d | ||
|
|
b15dde1795 | ||
|
|
b742816737 | ||
|
|
2b71cf261f | ||
|
|
500f380504 | ||
|
|
a608301540 | ||
|
|
97f2754c1d | ||
|
|
6357908c69 | ||
|
|
3bed16aea8 | ||
|
|
dd6a17d239 | ||
|
|
296a4bf9a6 | ||
|
|
8cc5022abb | ||
|
|
4d5c8f2a4d | ||
|
|
1af87a37c5 | ||
|
|
401041f00c | ||
|
|
959497cad6 | ||
|
|
c10f94fcd3 | ||
|
|
5c4fcc65bd | ||
|
|
86a0c41e8f | ||
|
|
c159362b95 | ||
|
|
93d8e97d16 | ||
|
|
55d6879a94 | ||
|
|
791beee9f4 | ||
|
|
f45c122e79 | ||
|
|
3c9fc0d7c2 | ||
|
|
6868b7eb7b | ||
|
|
39dacab93a | ||
|
|
989a267cb0 | ||
|
|
8192019564 | ||
|
|
bc43e71e5b | ||
|
|
42abed0978 | ||
|
|
9d9c9cdf83 | ||
|
|
c00fb9b67e | ||
|
|
e86b2ef0ef | ||
|
|
1e087adf28 | ||
|
|
50a6ea444a | ||
|
|
7bd4c2d17b | ||
|
|
0a642f86eb | ||
|
|
7e05f4e57e | ||
|
|
0329de4388 | ||
|
|
c77d94f07d | ||
|
|
bc320680e1 | ||
|
|
36a932c933 | ||
|
|
5e75ffe429 | ||
|
|
67bea056d5 | ||
|
|
e6f5de7e42 | ||
|
|
14bc675778 | ||
|
|
e59c6dfda2 | ||
|
|
ef124ce4a9 | ||
|
|
e4d0388944 | ||
|
|
69a36a3b37 | ||
|
|
33eaca4524 | ||
|
|
dd1ba0e33d | ||
|
|
810b95bf68 | ||
|
|
a85ee924d6 | ||
|
|
0d868b83df | ||
|
|
05b883379a | ||
|
|
ba6385b388 | ||
|
|
989782f1a0 | ||
|
|
e2174a9595 | ||
|
|
50e660c119 | ||
|
|
5f5dda7249 | ||
|
|
c7e254c372 | ||
|
|
38e98cbe9b | ||
|
|
98d7238838 | ||
|
|
77c6bfb286 | ||
|
|
9fab68fd8f | ||
|
|
f9921b99c8 | ||
|
|
ccb757dff2 | ||
|
|
2464b4f6aa | ||
|
|
0ade51f7aa | ||
|
|
94bdc71889 | ||
|
|
8662072a92 | ||
|
|
1198e1ddf9 | ||
|
|
a8b9913c31 | ||
|
|
682d777b85 | ||
|
|
0f074e4702 | ||
|
|
6f965710c0 | ||
|
|
581b085e9b | ||
|
|
68389e865b | ||
|
|
c040089f8d | ||
|
|
10a2c02378 | ||
|
|
39ece863d8 | ||
|
|
b3e25437cc | ||
|
|
88717cd5ac | ||
|
|
b4c8238594 | ||
|
|
707cbc0742 | ||
|
|
a8e8bd70c6 | ||
|
|
d24debac57 | ||
|
|
2af770def2 | ||
|
|
14916f64af | ||
|
|
f00e1da135 | ||
|
|
c37fa6a799 | ||
|
|
292f0a3447 | ||
|
|
5e1b519955 | ||
|
|
278f95e26a | ||
|
|
6dbb9e3c8e | ||
|
|
9e7497210b | ||
|
|
e96107dae5 | ||
|
|
934561c3ae | ||
|
|
3f5c55a052 | ||
|
|
d1cc151fc7 | ||
|
|
21212be16a | ||
|
|
5a73c66a1f | ||
|
|
7332a12c17 | ||
|
|
eebfbf5d66 | ||
|
|
40350bad7a | ||
|
|
c24fe0d105 | ||
|
|
4e2fe3206e | ||
|
|
faab395ce4 | ||
|
|
4ff74072db | ||
|
|
a7abddee7d | ||
|
|
81a593dbcf | ||
|
|
a89acaa9a6 | ||
|
|
5c0e27c556 | ||
|
|
4f6500320d | ||
|
|
d049f1a595 | ||
|
|
3131f30f5c | ||
|
|
b006c956eb | ||
|
|
8ad676b85c | ||
|
|
b1a1eee435 | ||
|
|
61e3275c42 | ||
|
|
4ae322a973 | ||
|
|
f954ca72b2 | ||
|
|
b815f11184 | ||
|
|
a1fc982132 | ||
|
|
8c0f60ec96 | ||
|
|
8e0d621a0f | ||
|
|
5f55b755fa | ||
|
|
17abd46b97 | ||
|
|
9187049f7f | ||
|
|
47c5e3b816 | ||
|
|
9777459eb6 | ||
|
|
1ccc95d846 | ||
|
|
b83f717a39 | ||
|
|
efac07d32f | ||
|
|
7369738a28 | ||
|
|
8af1e4fd84 | ||
|
|
9319fb44b4 | ||
|
|
b56d13da75 | ||
|
|
fbb33c42ee | ||
|
|
55e73b2564 | ||
|
|
07600d3523 | ||
|
|
b4feff7be2 | ||
|
|
2051a15c30 | ||
|
|
e3f6c66a6a | ||
|
|
8513c584cb | ||
|
|
7e4f2c4a0d | ||
|
|
76433d99a6 | ||
|
|
b2a2e74316 | ||
|
|
b321e50197 | ||
|
|
c2362ccff5 | ||
|
|
826ba30f5e | ||
|
|
c77b8ac3cb | ||
|
|
270995c299 | ||
|
|
6f8c4d09c7 | ||
|
|
1e865962dc | ||
|
|
9f224b6ca9 | ||
|
|
a5bcbe5c05 | ||
|
|
e07b5e39b0 | ||
|
|
d38ebe3853 | ||
|
|
21672fea59 | ||
|
|
3bbd2afb0f | ||
|
|
871b025921 | ||
|
|
51a6d64c23 | ||
|
|
4629c063ab | ||
|
|
e765690c18 | ||
|
|
0d0e6d5e39 | ||
|
|
c39fcd884e | ||
|
|
8d495f9ce0 | ||
|
|
85ab340ccd | ||
|
|
27fc0e828f | ||
|
|
c0f4480504 | ||
|
|
669f9cc53d |
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1408285582,
|
||||
"producer_workflow_id": 429713469,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "6bde9f8b9ba76635d00f6369d58313d1269b4191",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -83,7 +83,9 @@
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"automatic_signer_actors": [
|
||||
"github-actions[bot]"
|
||||
],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
@@ -95,7 +97,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "browser-print-probe"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
craft-print = { path = "../../shared/crates/print" }
|
||||
wasm-bindgen = "=0.2.129"
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Use real Chrome print preview on an isolated runner, then inspect the saved PDFs."""
|
||||
import functools
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageGrab
|
||||
from reportlab.pdfgen import canvas
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.firefox.service import Service as FirefoxService
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
|
||||
|
||||
SITE = Path(__file__).resolve().parent
|
||||
RESULTS = Path("browser-capture").resolve()
|
||||
COLORS = {"first": [(220, 40, 50), (25, 55, 215)], "second": [(0, 160, 45)]}
|
||||
|
||||
|
||||
def fixture(name, colors):
|
||||
doc = canvas.Canvas(str(SITE / f"{name}.pdf"), pagesize=(612, 792))
|
||||
for index, rgb in enumerate(colors):
|
||||
doc.drawString(72, 690, f"{name} document page {index + 1}")
|
||||
doc.setFillColorRGB(*(v / 255 for v in rgb))
|
||||
doc.rect(145, 245, 322, 302, fill=1, stroke=0)
|
||||
doc.showPage()
|
||||
doc.save()
|
||||
|
||||
|
||||
def wait_for_pdf(before, name):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
found = set(RESULTS.glob("*.pdf")) - before
|
||||
if len(found) > 1:
|
||||
raise RuntimeError(f"multiple outputs for {name}: {found}")
|
||||
if found:
|
||||
path = next(iter(found))
|
||||
if path.read_bytes().rstrip().endswith(b"%%EOF"):
|
||||
return path.rename(RESULTS / f"{name}-captured.pdf")
|
||||
time.sleep(0.25)
|
||||
raise TimeoutError(f"{name} produced no complete PDF")
|
||||
|
||||
|
||||
def inspect_pdf(path, colors):
|
||||
info = subprocess.check_output(["pdfinfo", path], text=True)
|
||||
pages = next(int(line.split()[1]) for line in info.splitlines() if line.startswith("Pages:"))
|
||||
assert pages == len(colors), (path, pages, colors)
|
||||
prefix = path.with_suffix("")
|
||||
subprocess.run(["pdftoppm", "-r", "36", "-png", path, prefix], check=True)
|
||||
for index, rgb in enumerate(colors, start=1):
|
||||
with Image.open(f"{prefix}-{index}.png") as image:
|
||||
actual = image.convert("RGB").getpixel((image.width // 2, image.height // 2))
|
||||
assert max(abs(a - b) for a, b in zip(actual, rgb)) < 20, (index, actual, rgb)
|
||||
print(f"{path.name} page {index}: {actual}", flush=True)
|
||||
|
||||
|
||||
def wait_preview(name, color, visible):
|
||||
"""Observe the actual X11 surface. The host page contains no colour marks."""
|
||||
deadline = time.monotonic() + 40
|
||||
while True:
|
||||
image = ImageGrab.grab().convert("RGB")
|
||||
# A half-page solid rectangle survives Chrome's print-preview scaling.
|
||||
pixels = image.resize((320, 240)).getdata()
|
||||
count = sum(max(abs(a - b) for a, b in zip(pixel, color)) < 18 for pixel in pixels)
|
||||
if (count > 300) == visible:
|
||||
image.save(RESULTS / f"{name}.png")
|
||||
print(f"{name}: {count} matching preview pixels", flush=True)
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
image.save(RESULTS / f"{name}-timeout.png")
|
||||
raise TimeoutError(f"{name}: matching preview pixels = {count}")
|
||||
time.sleep(0.35)
|
||||
|
||||
|
||||
def cancel_then_save(driver, *, gtk_picker=False):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "first"))).click()
|
||||
wait_preview("before-cancel", COLORS["first"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("after-cancel", COLORS["first"][0], False)
|
||||
assert set(RESULTS.glob("*.pdf")) == before, "cancel created a PDF"
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, "second"))).click()
|
||||
wait_preview("next-document", COLORS["second"][0], True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
if gtk_picker:
|
||||
# Firefox's GTK dialog has already focused the filename when it covers
|
||||
# the green preview. The selected filename stem excludes its extension.
|
||||
wait_preview("gtk-file-picker", COLORS["second"][0], False)
|
||||
subprocess.run(["xdotool", "key", "ctrl+a"], check=True)
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
# Chrome's Save as PDF destination opens the native Save File dialog.
|
||||
deadline = time.monotonic() + 25
|
||||
while not gtk_picker and time.monotonic() < deadline:
|
||||
if set(RESULTS.glob("*.pdf")) != before:
|
||||
break
|
||||
title = subprocess.run(["xdotool", "getwindowfocus", "getwindowname"], capture_output=True, text=True)
|
||||
# Firefox's GTK picker can be a transient without a separate window title.
|
||||
image = io.BytesIO()
|
||||
ImageGrab.grab().save(image, format="PNG")
|
||||
words = subprocess.run(["tesseract", "stdin", "stdout", "--psm", "6"], input=image.getvalue(), capture_output=True, check=True).stdout.decode()
|
||||
if "save" in title.stdout.lower() or ("Name:" in words and "Save" in words):
|
||||
print("Native Save File dialog is visible", flush=True)
|
||||
subprocess.run(["xdotool", "key", "ctrl+l"], check=True)
|
||||
subprocess.run(["xdotool", "type", "--clearmodifiers", str(RESULTS / "retry.pdf")], check=True)
|
||||
subprocess.run(["xdotool", "key", "Return"], check=True)
|
||||
break
|
||||
time.sleep(0.25)
|
||||
pdf = wait_for_pdf(before, "after-cancel")
|
||||
inspect_pdf(pdf, COLORS["second"])
|
||||
assert set(RESULTS.glob("*.pdf")) == before | {pdf}
|
||||
|
||||
|
||||
def firefox_probe(url):
|
||||
options = webdriver.FirefoxOptions()
|
||||
options.set_preference("print_printer", "Mozilla Save to PDF")
|
||||
options.set_preference("print.save_print_settings", True)
|
||||
with webdriver.Firefox(options=options, service=FirefoxService(shutil.which("geckodriver"))) as driver:
|
||||
print("Firefox", driver.capabilities["browserVersion"], flush=True)
|
||||
driver.get(url)
|
||||
try:
|
||||
driver.find_element(By.ID, "control").click()
|
||||
yellow = (240, 185, 20)
|
||||
wait_preview("firefox-parent-preview", yellow, True)
|
||||
subprocess.run(["xdotool", "key", "Escape"], check=True)
|
||||
wait_preview("firefox-parent-dismissed", yellow, False)
|
||||
cancel_then_save(driver, gtk_picker=True)
|
||||
finally:
|
||||
ImageGrab.grab().save(RESULTS / "firefox-last-screen.png")
|
||||
|
||||
|
||||
def main():
|
||||
RESULTS.mkdir()
|
||||
for name, colors in COLORS.items():
|
||||
fixture(name, colors)
|
||||
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=SITE)
|
||||
with http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) as server:
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
url = f"http://127.0.0.1:{server.server_port}/"
|
||||
# This disposable browser cannot contact the system CUPS server.
|
||||
os.environ["CUPS_SERVER"] = str(RESULTS / "absent-cups.sock")
|
||||
if "--firefox" in sys.argv:
|
||||
firefox_probe(url)
|
||||
return
|
||||
options = webdriver.ChromeOptions()
|
||||
cancellation = "--cancel" in sys.argv
|
||||
if not cancellation:
|
||||
options.add_argument("--kiosk-printing")
|
||||
options.add_argument("--no-first-run")
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": str(RESULTS),
|
||||
"savefile.default_directory": str(RESULTS),
|
||||
"printing.print_preview_sticky_settings.appState": json.dumps({
|
||||
"version": 2, "recentDestinations": [{"id": "Save as PDF", "origin": "local"}],
|
||||
"selectedDestinationId": "Save as PDF",
|
||||
}),
|
||||
})
|
||||
options.set_capability("goog:loggingPrefs", {"browser": "ALL"})
|
||||
with webdriver.Chrome(options=options, service=Service(shutil.which("chromedriver"))) as driver:
|
||||
print("Chrome", driver.capabilities["browserVersion"], flush=True)
|
||||
driver.get(url)
|
||||
try:
|
||||
if cancellation:
|
||||
cancel_then_save(driver)
|
||||
return
|
||||
for name in ("control", "first", "second"):
|
||||
before = set(RESULTS.glob("*.pdf"))
|
||||
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, name))).click()
|
||||
pdf = wait_for_pdf(before, name)
|
||||
if name == "control":
|
||||
text = subprocess.check_output(["pdftotext", pdf, "-"], text=True)
|
||||
assert "Parent page control only" in text, text
|
||||
else:
|
||||
inspect_pdf(pdf, COLORS[name])
|
||||
finally:
|
||||
(RESULTS / "browser-log.json").write_text(json.dumps(driver.get_log("browser"), indent=2))
|
||||
driver.save_screenshot(str(RESULTS / "last-view.png"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>Parent page control</title>
|
||||
<style>
|
||||
#control-marker { display: none; }
|
||||
@media print { #control-marker { display: block; } }
|
||||
</style>
|
||||
<p>Parent page control only</p>
|
||||
<svg id="control-marker" width="360" height="340"><rect width="360" height="340" fill="rgb(240,185,20)"/></svg>
|
||||
<button id="control" onclick="setTimeout(() => window.print(), 0)">Print parent</button>
|
||||
<button id="first" disabled>Print first PDF</button>
|
||||
<button id="second" disabled>Print second PDF</button>
|
||||
<script type="module">
|
||||
import init, { print_document } from "./pkg/browser_print_probe.js";
|
||||
await init();
|
||||
for (const id of ["first", "second"]) {
|
||||
const pdf = new Uint8Array(await (await fetch("./" + id + ".pdf")).arrayBuffer());
|
||||
const button = document.getElementById(id);
|
||||
button.addEventListener("click", () => print_document(pdf));
|
||||
button.disabled = false;
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,7 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Exercise the same shared entry point as the GridCraft web print service.
|
||||
#[wasm_bindgen]
|
||||
pub fn print_document(bytes: &[u8]) -> Result<(), JsValue> {
|
||||
craft_print::browser::print_pdf(bytes).map_err(|error| JsValue::from_str(&error))
|
||||
}
|
||||
@@ -9,6 +9,7 @@ workflows:
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/[email protected]'
|
||||
- 'step-security/[email protected]'
|
||||
'.github/workflows/nightly-dispatch.yml': []
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [GridCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
if: >-
|
||||
github.repository == 'storytold/gridcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/gridcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/gridcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/gridcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'gridcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
name: GridCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -22,12 +23,13 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: 6bde9f8b9ba76635d00f6369d58313d1269b4191
|
||||
tooling-revision: main
|
||||
app-name: gridcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
|
||||
# A push to main is the run that publishes coverage; superseded runs there would never finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Verify browser print output
|
||||
on:
|
||||
push:
|
||||
branches: [verify/gridcraft-browser-output-4859]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
browser-print:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
repository: storytold/craft-libs
|
||||
ref: e0646e91ad432c43358137d0d894877216fa91ed
|
||||
path: shared
|
||||
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
packages: xvfb xauth xdotool tesseract-ocr poppler-utils python3-selenium python3-reportlab python3-pil
|
||||
- name: Build the shared browser entry point as WebAssembly
|
||||
working-directory: .github/print-probe
|
||||
env:
|
||||
CARGO_PROFILE_DEV_DEBUG: 0
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cp ../../shared/Cargo.lock Cargo.lock
|
||||
cargo build --target wasm32-unknown-unknown
|
||||
archive="$RUNNER_TEMP/wasm-bindgen.tar.gz"
|
||||
curl --fail --location --silent --show-error https://github.com/wasm-bindgen/wasm-bindgen/releases/download/0.2.129/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl.tar.gz -o "$archive"
|
||||
echo "82d12bb940e2d4e72e0d5605387fc1b8ca179044e012b620f0ce4e7440e8320e $archive" | sha256sum --check
|
||||
tar -xf "$archive" -C "$RUNNER_TEMP" wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen
|
||||
"$RUNNER_TEMP/wasm-bindgen-0.2.129-x86_64-unknown-linux-musl/wasm-bindgen" --target web --out-dir pkg target/wasm32-unknown-unknown/debug/browser_print_probe.wasm
|
||||
- name: Verify the Firefox print dialog and inspect its output
|
||||
run: |
|
||||
firefox --version
|
||||
geckodriver --version
|
||||
xvfb-run -a /usr/bin/python3 .github/print-probe/capture.py --firefox
|
||||
- name: Preserve output and diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
with:
|
||||
name: firefox-print-output
|
||||
path: browser-capture
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
@@ -81,4 +81,5 @@ Paths and conventions:
|
||||
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
|
||||
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
|
||||
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
|
||||
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
|
||||
|
||||
@@ -13,6 +13,7 @@ Generated-in-code art is original and has no file to list: the UI icon set (`cra
|
||||
| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | The Noto Project Authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Noto Emoji](https://fonts.google.com/noto/specimen/Noto+Emoji) | SIL Open Font License 1.1 (full upstream text in `NOTICE`) | NotoEmoji-Regular.ttf is enabled by egui's `monochrome_emoji_fonts` feature and used as the monochrome emoji fallback. Dependency asset unmodified here, no font file copied into this repository. |
|
||||
| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Canonical Ltd. and the Ubuntu Font Family authors | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [Ubuntu font](https://design.ubuntu.com/font) | Ubuntu Font Licence 1.0 (full upstream text in `NOTICE`) | Ubuntu-Light.ttf is egui's default proportional face. Dependency asset unmodified here, no font file copied into this repository. |
|
||||
| Regional format data in `crates/core/src/region.rs` (data, no file of its own) | Unicode, Inc. (Unicode CLDR) | [cldr-json](https://github.com/unicode-org/cldr-json) (`cldr-numbers-full`, `cldr-dates-full`) and ICU's CLDR 48 data | Unicode License v3 (`Unicode-3.0`; full text in `NOTICE`) | Separators, month and weekday names, AM/PM words, currency symbols and date order of the built-in regions. No CLDR file is copied into this repository. |
|
||||
| Polish formula function names in `crates/formula/src/input/pl.rs` (data, no file of its own) | PhpSpreadsheet Authors | [PhpSpreadsheet `locale/pl/functions`](https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions) | MIT (Copyright (c) 2019-2026 PhpSpreadsheet Authors; full upstream text in `NOTICE`) | The English-to-Polish function name table (`FUNCTIONS`). Names not in that table come from Microsoft's pl-pl support pages and #1678's Excel for the web observation. No PhpSpreadsheet file is copied into this repository. |
|
||||
| `docs/brand/artcraft-logo.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms (`docs/brand/LICENSE-brand.txt`) | Trademark, not open source |
|
||||
| `docs/brand/artcraft-logo.png` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | ArtCraft brand kit | ArtCraft brand terms | Trademark |
|
||||
|
||||
Generated
+41
-20
@@ -1216,6 +1216,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-odf"
|
||||
version = "0.1.0"
|
||||
@@ -2841,10 +2849,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"chrono",
|
||||
"craft-nightly",
|
||||
"craft-print",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
@@ -2870,7 +2879,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-calc"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
@@ -2882,7 +2891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-chart"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-calc",
|
||||
"gridcraft-core",
|
||||
@@ -2893,20 +2902,31 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-cli"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"gridcraft-mcp",
|
||||
"gridcraft-sandbox",
|
||||
"log",
|
||||
"quick-xml 0.41.0",
|
||||
"quick-xml 0.42.0",
|
||||
"serde_json",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-core"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"js-sys",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-dax"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"js-sys",
|
||||
@@ -2917,7 +2937,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-engine"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-csv",
|
||||
"craft-gridcraft-format",
|
||||
@@ -2943,7 +2963,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-formula"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"serde",
|
||||
@@ -2952,7 +2972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-functions"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"regex",
|
||||
@@ -2960,7 +2980,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-math"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"ratex-font",
|
||||
"ratex-layout",
|
||||
@@ -2970,7 +2990,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-mcp"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-mcp-server",
|
||||
"gridcraft-engine",
|
||||
@@ -2980,7 +3000,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-model"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
@@ -2994,14 +3014,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-numfmt"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-pdf"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"craft-stream-codecs",
|
||||
@@ -3013,7 +3033,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-sandbox"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"landlock",
|
||||
"libc",
|
||||
@@ -3024,7 +3044,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-ui-egui"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -3056,8 +3076,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-web"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
@@ -3075,7 +3096,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "gridcraft-xlsx"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-cfb",
|
||||
"craft-csv",
|
||||
@@ -3092,7 +3113,7 @@ dependencies = [
|
||||
"gridcraft-functions",
|
||||
"gridcraft-math",
|
||||
"gridcraft-model",
|
||||
"quick-xml 0.41.0",
|
||||
"quick-xml 0.42.0",
|
||||
"sha2 0.11.1",
|
||||
"thiserror 2.0.21",
|
||||
"zip",
|
||||
@@ -8249,7 +8270,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"gridcraft-engine",
|
||||
"serde_json",
|
||||
|
||||
+4
-2
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.19.1"
|
||||
version = "0.20.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -16,6 +16,7 @@ gridcraft-core = { path = "crates/core" }
|
||||
gridcraft-numfmt = { path = "crates/numfmt" }
|
||||
gridcraft-sandbox = { path = "crates/sandbox" }
|
||||
gridcraft-formula = { path = "crates/formula" }
|
||||
gridcraft-dax = { path = "crates/dax" }
|
||||
gridcraft-functions = { path = "crates/functions" }
|
||||
gridcraft-model = { path = "crates/model" }
|
||||
gridcraft-calc = { path = "crates/calc" }
|
||||
@@ -53,6 +54,7 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
|
||||
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
thiserror = "2"
|
||||
@@ -64,7 +66,7 @@ chrono = { version = "0.4.45", default-features = false, features = ["std", "clo
|
||||
web-time = "1.1.0"
|
||||
rayon = "1"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode", "perf"] }
|
||||
quick-xml = "0.41"
|
||||
quick-xml = "0.42"
|
||||
zip = { version = "9.8.2", default-features = false, features = ["deflate"] }
|
||||
sha2 = { version = "0.11", default-features = false }
|
||||
# Verifying SHA-1 iterated protection hashes (`crates/model/src/password.rs`).
|
||||
|
||||
@@ -324,6 +324,35 @@ authorization of the copyright holder.
|
||||
|
||||
SPDX-License-Identifier: Unicode-3.0
|
||||
|
||||
The Polish formula function names in crates/formula/src/input/pl.rs (the English-to-Polish
|
||||
name table) are taken from PhpSpreadsheet's locale/pl/functions table, under the MIT License.
|
||||
Source: https://github.com/PHPOffice/PhpSpreadsheet/blob/master/src/PhpSpreadsheet/Calculation/locale/pl/functions
|
||||
The following text is reproduced verbatim from PhpSpreadsheet's LICENSE:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2026 PhpSpreadsheet Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
SPDX-License-Identifier: MIT
|
||||
|
||||
Linux Wayland window decorations
|
||||
-------------------------------
|
||||
sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita,
|
||||
|
||||
+2
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~25 points of "ready for real work" and ~160–240 h away
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-16 · **Change:** minor (Polish formula language; earlier: File › Print › Settings: Print Selection; earlier: XLSX password to modify is kept and enforced; earlier: IRR's Newton solver checks its scaled residual before accepting a small step; earlier: XLSX keeps PivotTables on a data connection, the Data Model or another workbook on save; earlier: a selected chart outlines its names, categories and values in Excel's colours, and dragging the values outline's corner changes the chart's data, #4389, #4390; earlier: performance: formula entry and XLSX save win back time lost since 23829d8c (#2654), 465 → 420 ms and 540 → 488 ms on the 100k-row benchmark; Sandbox refuses fcntl's asynchronous notification and the socket ioctls that notify another process on Linux (#3846); CI provisions pinned fonts for coverage tests; the oversized pivot-cache warning's test names the part limit; readiness estimates unchanged) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
> **Last reviewed:** 2026-11-01 · **Last updated:** 2026-11-05 · **Change:** minor (CJK fallback text shares the Latin baseline; earlier: form controls: buttons, sliders and spin buttons; earlier: RefEdit reference boxes in dialogs: Goal Seek, Solver and Data Analysis take ranges by selection on the grid; earlier: Python mode in the formula bar; earlier: Python cells stored and kept in files; earlier: equations: Insert › Equation, editor, gridcraft-math; earlier: What-if and analysis: Solver Sensitivity report for Simplex LP and GRG Nonlinear; earlier: floating objects: one selection, eight resize handles, keyboard delete; earlier: Chart data tables: live source values beneath column, bar, line, area and compatible combo charts; legend keys and borders; XLSX round-trip and print/PDF; earlier: Formulas › Function Library as labelled buttons with category menus; Recently Used and Insert Function categories; XLSX workbook-view selection, bounded tab ratios and sheet-edit regressions; readiness estimates unchanged; earlier: CSV and text open detects each column's date order, so day-first dates are not silently swapped; earlier: searchable data validation dropdown) · **Target:** Microsoft Excel (Microsoft 365)
|
||||
|
||||
|
||||
@@ -301,6 +301,7 @@ Ranked; estimates in Opus 5.5 agent-hours. Detail and the full beta-gate list in
|
||||
| 2026-11-06 | trivial | Progress log: scroll positions follow their sheet through sheet inserts, deletes and moves (#3485) |
|
||||
| 2026-11-05 | minor | Reconcile upstream form-control progress with the CJK baseline update |
|
||||
| 2026-11-02 | minor | Form controls; catalog 277 / 292 → 281 / 296 (Developer › Controls); progress log row |
|
||||
| 2026-11-02 | minor | Polish formula language (`FormulaLocale::Pl`: 434 function names, PRAWDA/FAŁSZ, error values, table specifiers, `;` arguments, decimal comma) |
|
||||
| 2026-11-02 | minor | Progress log: RefEdit reference boxes in dialogs |
|
||||
| 2026-11-02 | minor | Progress log: Python mode in the formula bar |
|
||||
| 2026-11-02 | minor | Progress log: Python cells as data |
|
||||
|
||||
@@ -16,11 +16,8 @@ pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
|
||||
|
||||
// ---------------------------------------------------------------- package validation
|
||||
|
||||
fn local_name(name: &[u8]) -> &[u8] {
|
||||
match name.iter().rposition(|&b| b == b':') {
|
||||
Some(i) => name.get(i + 1..).unwrap_or(name),
|
||||
None => name,
|
||||
}
|
||||
fn local_name(name: &str) -> &str {
|
||||
name.rsplit(':').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
/// `(element local name, attributes)` for every start/empty element of an XML part.
|
||||
@@ -41,12 +38,12 @@ fn xml_elements(xml: &[u8]) -> Result<Vec<XmlElement>, String> {
|
||||
.map(|a| {
|
||||
let v = match a.normalized_value(quick_xml::XmlVersion::Explicit1_0) {
|
||||
Ok(v) => v.into_owned(),
|
||||
Err(_) => String::from_utf8_lossy(&a.value).into_owned(),
|
||||
Err(_) => a.value.to_string(),
|
||||
};
|
||||
(String::from_utf8_lossy(local_name(a.key.as_ref())).into_owned(), v)
|
||||
(local_name(a.key.as_ref()).to_string(), v)
|
||||
})
|
||||
.collect();
|
||||
out.push((String::from_utf8_lossy(local_name(e.name().as_ref())).into_owned(), attrs));
|
||||
out.push((local_name(e.name().as_ref()).to_string(), attrs));
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Ok(_) => {}
|
||||
@@ -350,9 +347,9 @@ fn holds_something_uncached(zip: &mut Zip<'_>, index: usize, marker: &'static st
|
||||
let take = f.size().min(MAX_XML_PART).min(*budget);
|
||||
*budget -= take;
|
||||
let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(f.take(take)));
|
||||
let wanted: Option<&'static [u8]> = match marker {
|
||||
"comment" => Some(b"comment"),
|
||||
"shape" => Some(b"shape"),
|
||||
let wanted: Option<&'static str> = match marker {
|
||||
"comment" => Some("comment"),
|
||||
"shape" => Some("shape"),
|
||||
_ => None,
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
|
||||
@@ -187,7 +187,7 @@ impl Args {
|
||||
|
||||
fn exec(s: &mut Session, id: &str, params: Value) -> Result<Value, String> {
|
||||
let r = s.execute_headless(id, params).map_err(|e| e.to_string());
|
||||
if id == "file.open"
|
||||
if matches!(id, "file.open" | "file.save" | "file.saveAs" | "file.saveBytes")
|
||||
&& let Ok(value) = &r
|
||||
&& let Some(warnings) = value.get("warnings").and_then(Value::as_array)
|
||||
{
|
||||
@@ -328,6 +328,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
eprintln!("wrote {out} ({} bytes, {} pages)", result["bytes"], result["pages"]);
|
||||
return Ok(());
|
||||
}
|
||||
for warning in gridcraft_engine::cmd::file::save_losses(&s, "file.save", &json!({"path": out})).messages() {
|
||||
eprintln!("Warning: {warning}");
|
||||
}
|
||||
let d = s.doc().map_err(|e| e.to_string())?;
|
||||
let bytes = gridcraft_engine::io::save_file_bytes(&d.wb, out).map_err(|e| e.to_string())?;
|
||||
gridcraft_engine::io::write_file(out, &bytes).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -25,9 +25,10 @@ log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
rfd = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
@@ -228,7 +228,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
if let Err(e) = craft_print::browser::print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
@@ -280,75 +280,6 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
if let Err(e) = body.append_child(&iframe) {
|
||||
cleanup_print(&iframe, &url);
|
||||
return Err(js(e));
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
iframe_for_load.set_onload(None);
|
||||
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
|
||||
cleanup_print(&iframe_for_load, &url_for_cleanup);
|
||||
log::error!("print failed: {e:?}");
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
|
||||
// Both operations are idempotent: print can fail after dispatching `afterprint`.
|
||||
web_sys::Url::revoke_object_url(url).ok();
|
||||
iframe.remove();
|
||||
}
|
||||
|
||||
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
|
||||
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
|
||||
let iframe_for_cleanup = iframe.clone();
|
||||
let url_for_cleanup = url.to_owned();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
|
||||
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
|
||||
});
|
||||
// Listen before `print()`, which can dispatch `afterprint` before it returns.
|
||||
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
|
||||
let options = web_sys::AddEventListenerOptions::new();
|
||||
options.set_once(true);
|
||||
let callback = on_after_print.as_ref().unchecked_ref();
|
||||
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
|
||||
if let Err(e) = content_window.print() {
|
||||
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = on_after_print.into_js_value();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
|
||||
@@ -30,6 +30,8 @@ winresource = "0.1"
|
||||
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
|
||||
craft-nightly = { workspace = true }
|
||||
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
|
||||
# Cargo.toml).
|
||||
craft-print = { workspace = true }
|
||||
@@ -43,6 +45,10 @@ getrandom = "0.4"
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies]
|
||||
arboard = { workspace = true, features = ["image-data", "wayland-data-control"] }
|
||||
|
||||
# GNOME does not provide server-side decorations on Wayland. Keep the Adwaita frame
|
||||
# and buttons without embedding its fallback title font; the ribbon shows the name (#54).
|
||||
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Blocks on the start-up DirectX 12 adapter probe (`graphics.rs`); already in the tree via eframe.
|
||||
pollster = "1"
|
||||
|
||||
@@ -1,24 +1,12 @@
|
||||
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
|
||||
//! stable build, and a nightly build cannot be talked out of its profile.
|
||||
use crate::launch_profile::Profile;
|
||||
//! stable build, and a nightly build always stays isolated in its nightly profile.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
pub use craft_nightly::BuildFlavor;
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
@@ -36,7 +24,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use super::{BuildFlavor, needs_native_error, version, version_query};
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
@@ -45,22 +34,6 @@ mod tests {
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
|
||||
|
||||
@@ -1,131 +1,43 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches keep their original arguments and directory policy. No environment mutation.
|
||||
//!
|
||||
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
|
||||
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
|
||||
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
|
||||
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
|
||||
//! of this can create a directory, open a log or start a window.
|
||||
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
|
||||
//! state. Direct launches of a nightly build self-isolate into
|
||||
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
|
||||
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
|
||||
//! their original arguments and directory policy.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
pub use craft_nightly::Profile;
|
||||
|
||||
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
|
||||
/// [`Profile::Stable`] before startup selection.
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
craft_nightly::current().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
|
||||
/// runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
|
||||
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
|
||||
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
|
||||
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
|
||||
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
|
||||
if let Some(index) = separator_index
|
||||
&& raw_args.get(index).is_some_and(|arg| arg == "--")
|
||||
{
|
||||
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
|
||||
passthrough_args
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use craft_nightly::{
|
||||
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
|
||||
};
|
||||
|
||||
use super::restore_launcher_separator;
|
||||
use crate::profile_root;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
@@ -136,88 +48,88 @@ mod tests {
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
launch_arguments(Path::new(absolute()), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::Stable);
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
|
||||
let spec = profile_root::app_spec();
|
||||
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
|
||||
let argv = args(&["sales.xlsx", "--sample", "budget"]);
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
|
||||
assert!(launch.profile.is_nightly());
|
||||
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let spec = profile_root::app_spec();
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
|
||||
assert_eq!(
|
||||
restore_launcher_separator(&argv, launch.passthrough_args),
|
||||
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
fn stable_build_refuses_nightly_launch_flags() {
|
||||
let spec = profile_root::app_spec();
|
||||
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
|
||||
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv.clone()).is_err(), "{argv:?}");
|
||||
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
|
||||
}
|
||||
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
|
||||
let spec = profile_root::app_spec();
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
args(&["-V"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
|
||||
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["--version"])),
|
||||
launch_arguments(Path::new(absolute()), &args(&["-V"])),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
for argv in [
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
|
||||
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
|
||||
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
|
||||
] {
|
||||
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
|
||||
assert!(!launch.is_version_query(), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
|
||||
+47
-31
@@ -214,8 +214,13 @@ fn services() -> Services {
|
||||
let path = std::path::Path::new(suggested);
|
||||
let stem = path.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("Book1").to_string();
|
||||
// The suggested name's type (an export asks for .pdf, .csv or .html) comes first.
|
||||
const TYPES: [(&str, &str); 4] =
|
||||
[("Excel Workbook (.xlsx)", "xlsx"), ("CSV UTF-8 (.csv)", "csv"), ("Web Page (.html)", "html"), ("PDF (.pdf)", "pdf")];
|
||||
const TYPES: [(&str, &str); 5] = [
|
||||
("Excel Workbook (.xlsx)", "xlsx"),
|
||||
("CSV UTF-8 (.csv)", "csv"),
|
||||
("Web Page (.html)", "html"),
|
||||
("PDF (.pdf)", "pdf"),
|
||||
("GridCraft Workbook (.json)", "json"),
|
||||
];
|
||||
let ext = path.extension().and_then(std::ffi::OsStr::to_str).map(str::to_ascii_lowercase).filter(|e| TYPES.iter().any(|(_, x)| x == e));
|
||||
let ext = ext.unwrap_or_else(|| "xlsx".to_string());
|
||||
let mut dialog = rfd::FileDialog::new().set_file_name(format!("{stem}.{ext}"));
|
||||
@@ -304,46 +309,47 @@ fn report_launch_profile_error(error: &str) {
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
|
||||
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window (a dialog
|
||||
// here would hang a headless runner and fail a Linux build).
|
||||
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
|
||||
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
|
||||
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
|
||||
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
|
||||
if nightly_build && build_flavor::version_query(&argv) {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| {
|
||||
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
|
||||
})
|
||||
})
|
||||
let spec = profile_root::app_spec();
|
||||
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2)
|
||||
});
|
||||
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
|
||||
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
|
||||
if nightly_build && launch.is_version_query() {
|
||||
use std::io::Write as _;
|
||||
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
|
||||
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
|
||||
return None;
|
||||
}
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
report_launch_profile_error(&error.to_string());
|
||||
std::process::exit(2);
|
||||
}
|
||||
let channel =
|
||||
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) =
|
||||
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
|
||||
{
|
||||
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
|
||||
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
Some(early.args)
|
||||
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
|
||||
}
|
||||
|
||||
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
|
||||
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
|
||||
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
|
||||
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
|
||||
/// opened as a file.
|
||||
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
|
||||
/// separator itself is never opened as a file.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
struct DesktopArgs {
|
||||
control_port: Option<u16>,
|
||||
@@ -660,8 +666,9 @@ mod launch_separator_tests {
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
|
||||
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
|
||||
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
|
||||
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
|
||||
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
|
||||
/// these tests too.
|
||||
fn launcher_root() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
|
||||
}
|
||||
@@ -671,15 +678,24 @@ mod launch_separator_tests {
|
||||
let mut argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
argv.extend(tail.iter().map(std::ffi::OsString::from));
|
||||
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
let launch = craft_nightly::parse_startup(
|
||||
BuildFlavor::NightlyV1,
|
||||
&profile_root::app_spec(),
|
||||
argv.iter().cloned(),
|
||||
&craft_nightly::StartupOptions::default(),
|
||||
)
|
||||
.unwrap();
|
||||
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_platforms_root_spelling_is_refused_as_relative() {
|
||||
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
|
||||
let argv: Vec<std::ffi::OsString> =
|
||||
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
|
||||
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
|
||||
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
|
||||
assert!(
|
||||
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
|
||||
"a root that is not absolute on this platform must be refused"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+209
-419
@@ -1,35 +1,91 @@
|
||||
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
|
||||
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
|
||||
//! nightly root, in both directions, so the two channels can never share a file.
|
||||
//! GridCraft's nightly profile specification and control-directory boundary, backed by
|
||||
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
|
||||
//! so the two channels can never share a file.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
|
||||
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
|
||||
use craft_nightly::AppProfileSpec;
|
||||
|
||||
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
|
||||
pub const CONTROL_DIR: &str = "Control";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
|
||||
|
||||
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
|
||||
/// token, Flatpak, and installer boundary.
|
||||
pub fn app_spec() -> AppProfileSpec {
|
||||
AppProfileSpec {
|
||||
app_id: "gridcraft",
|
||||
display_name: "GridCraft",
|
||||
stable_dir_names: &["gridcraft", "GridCraft"],
|
||||
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
|
||||
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
profile_root_env: None,
|
||||
forbidden_env_vars: &[],
|
||||
portable_markers: &[],
|
||||
folder_only_entries: &PROFILE_FOLDERS,
|
||||
extra_forbidden_roots: extra_forbidden_roots(|key| std::env::var_os(key)),
|
||||
}
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
// FreeBSD, the BSDs and anything else have no nightly channel.
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
|
||||
let value = env(key)?;
|
||||
if value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = PathBuf::from(value);
|
||||
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
|
||||
}
|
||||
|
||||
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
|
||||
/// config/data/cache directories already fenced by `craft-nightly`.
|
||||
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
|
||||
// (`install-policy.wxi`).
|
||||
let mut roots = Vec::new();
|
||||
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
|
||||
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
|
||||
roots.push(profile.join(".gridcraft"));
|
||||
}
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = non_empty_abs(&env, key) {
|
||||
roots.push(base.join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
|
||||
if let Some(home) = non_empty_abs(&env, "HOME") {
|
||||
let library = home.join("Library");
|
||||
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
|
||||
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
|
||||
roots.push(home.join("Applications/GridCraft.app"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, target_os = "windows")))]
|
||||
{
|
||||
let _ = env;
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,18 +96,6 @@ fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
|
||||
/// ancestor is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
@@ -74,102 +118,21 @@ fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
|
||||
// token folder, plus both MSI install folders (`install-policy.wxi`).
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
|
||||
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
|
||||
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
|
||||
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/GridCraft"),
|
||||
library.join("Caches/GridCraft"),
|
||||
library.join("Caches/ai.storyteller.gridcraft"),
|
||||
library.join("Preferences/GridCraft"),
|
||||
library.join("Preferences/ai.storyteller.gridcraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
|
||||
home.join("Applications/GridCraft.app"),
|
||||
PathBuf::from("/Applications/GridCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
|
||||
/// so a link there cannot point Nightly's writes at the stable app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
match std::fs::symlink_metadata(&child) {
|
||||
Ok(metadata) if !metadata.file_type().is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(())
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
|
||||
@@ -178,351 +141,178 @@ pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
|
||||
private_subdirectory(root, CONTROL_DIR, "control folder")
|
||||
}
|
||||
|
||||
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
|
||||
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
// A crashed launch can leave a probe with this name behind: take the next one instead of
|
||||
// failing, and remove only the file this call created, never someone else's.
|
||||
loop {
|
||||
let probe =
|
||||
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
|
||||
Ok(_) => return std::fs::remove_file(&probe),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
|
||||
/// starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
|
||||
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
|
||||
{
|
||||
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
|
||||
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
|
||||
// instance may carry a profile. Any other, the stable app's included, could point it at
|
||||
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
|
||||
return Err(format!(
|
||||
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
|
||||
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
|
||||
id.to_string_lossy()
|
||||
));
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect a subfolder elsewhere.
|
||||
control_directory(&chosen)?;
|
||||
entries_stay_inside(&chosen)?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
control_directory(&confirmed)?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
use craft_nightly::{ProfileError, validate_and_prepare_root};
|
||||
|
||||
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
|
||||
|
||||
struct TempDir {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/gridcraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
Self { root }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
self.check_with(platform, root, |_| Ok(()))
|
||||
}
|
||||
|
||||
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
|
||||
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
fn path(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_stable_data_root_is_refused_on_its_own_platform() {
|
||||
let mut fixture = Fixture::new();
|
||||
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
|
||||
// and per-machine install folders and the control-token folder.
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
|
||||
for candidate in [stable.clone(), stable.join("nightly")] {
|
||||
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
|
||||
}
|
||||
assert!(!stable.exists());
|
||||
fn failed_profile_preparation_does_not_start_with_stable() {
|
||||
let tmp = TempDir::new("file-root");
|
||||
let root = tmp.path().join("not-a-directory");
|
||||
std::fs::write(&root, b"an ordinary file").unwrap();
|
||||
let argv = craft_nightly::launch_arguments(&root, &[]);
|
||||
let result =
|
||||
craft_nightly::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, &app_spec(), argv, &craft_nightly::StartupOptions::default());
|
||||
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
|
||||
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
|
||||
let spec = app_spec();
|
||||
assert_eq!(spec.app_id, "gridcraft");
|
||||
assert_eq!(spec.display_name, "GridCraft");
|
||||
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
|
||||
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
|
||||
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
|
||||
assert_eq!(spec.profile_root_env, None);
|
||||
assert!(spec.forbidden_env_vars.is_empty());
|
||||
assert!(spec.portable_markers.is_empty());
|
||||
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
|
||||
let tmp = TempDir::new("extra-roots");
|
||||
let home = tmp.path().join("home");
|
||||
let local = tmp.path().join("local");
|
||||
let program_files = tmp.path().join("program-files");
|
||||
let env: BTreeMap<&str, OsString> = [
|
||||
("HOME", home.clone().into_os_string()),
|
||||
("USERPROFILE", home.clone().into_os_string()),
|
||||
("LOCALAPPDATA", local.clone().into_os_string()),
|
||||
("ProgramFiles", program_files.clone().into_os_string()),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
|
||||
assert!(roots.contains(&home.join(".gridcraft")));
|
||||
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
|
||||
}
|
||||
assert!(
|
||||
fixture
|
||||
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
|
||||
.is_err()
|
||||
);
|
||||
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
|
||||
assert!(!base.join("ArtCraft/GridCraft").exists());
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
|
||||
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
|
||||
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
|
||||
}
|
||||
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
|
||||
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
|
||||
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
|
||||
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
let _ = (&local, &program_files);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
|
||||
let tmp = TempDir::new("reopen");
|
||||
let private = tmp.path().join("nightly-profile");
|
||||
let spec = app_spec();
|
||||
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
|
||||
// macOS: the four Library rows and the bundle itself.
|
||||
for suffix in [
|
||||
"Application Support/GridCraft",
|
||||
"Caches/GridCraft",
|
||||
"Preferences/GridCraft",
|
||||
"Saved Application State/ai.storyteller.gridcraft.savedState",
|
||||
] {
|
||||
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
|
||||
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(
|
||||
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
|
||||
"{name} must stay a directory"
|
||||
);
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_profile_row_is_accepted_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert_eq!(fixture.check(platform, &data).unwrap(), data);
|
||||
}
|
||||
assert!(
|
||||
fixture
|
||||
.check(
|
||||
Platform::Linux,
|
||||
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
|
||||
)
|
||||
.is_ok(),
|
||||
"the Launcher's own folder is not GridCraft's install"
|
||||
);
|
||||
}
|
||||
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
|
||||
let tmp = TempDir::new("forbidden");
|
||||
let forbidden = tmp.path().join("stable-boundary");
|
||||
let mut spec = app_spec();
|
||||
spec.extra_forbidden_roots.push(forbidden.clone());
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/gridcraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Control"), platform));
|
||||
assert!(overlaps(&root.join("Control"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
|
||||
}
|
||||
}
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
|
||||
assert!(!forbidden.exists());
|
||||
|
||||
#[test]
|
||||
fn the_install_folder_of_the_running_build_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/gridcraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
|
||||
let mut fixture = Fixture::new();
|
||||
let root = fixture.root.join("flatpak profile");
|
||||
for (id, accepted) in [
|
||||
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
|
||||
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
|
||||
("ai.storyteller.gridcraft", false),
|
||||
("ai.storyteller.gridcraft.nightly-v1", false),
|
||||
("io.github.other.Gridcraft", false),
|
||||
] {
|
||||
fixture.env.insert("FLATPAK_ID".into(), id.into());
|
||||
let result = fixture.check(Platform::Linux, &root);
|
||||
assert_eq!(result.is_ok(), accepted, "{id}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_write_probe_never_falls_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/gridcraft");
|
||||
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
|
||||
assert!(!fixture.home().join(".config/gridcraft").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_in_place_of_the_profile_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let candidate = fixture.root.join("not-a-directory");
|
||||
std::fs::write(&candidate, b"a file, not a profile").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &candidate).is_err());
|
||||
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn profile_entry_aliases_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/gridcraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
|
||||
for name in ["ui.json", "logs", "Control", "profile"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = fixture.check_with(Platform::Linux, &private, |_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-logs")).unwrap();
|
||||
std::fs::write(private.join("ui.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let outside = fixture.home().join("shared-tokens");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = fixture.root.join("nightly-control");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
|
||||
assert!(control_directory(&private).is_err());
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err());
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
|
||||
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_control_folder_is_a_private_lazy_subfolder() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
|
||||
let tmp = TempDir::new("control");
|
||||
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
|
||||
let control = control_directory(&private).unwrap();
|
||||
assert!(control.starts_with(&private) && control != private);
|
||||
assert!(!control.exists(), "resolving it must not create it");
|
||||
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_writable_probe_leaves_nothing_behind() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
|
||||
ensure_writable(&private).unwrap();
|
||||
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
|
||||
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
|
||||
let tmp = TempDir::new("control-symlink");
|
||||
let outside = tmp.path().join("shared-tokens");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
let private = tmp.path().join("nightly-control");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
|
||||
|
||||
assert!(control_directory(&private).is_err());
|
||||
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
+44
-8
@@ -18,7 +18,7 @@ mod lambda;
|
||||
mod reference_fns;
|
||||
mod special;
|
||||
|
||||
use array::map_unary;
|
||||
use array::{binary_scalar_snapped, map_unary};
|
||||
pub use array::{binary_values, zip2};
|
||||
pub use format::r1c1_to_a1;
|
||||
pub use special::{SPECIAL_FUNCTIONS, is_known_function, precedents, resized_sum_range};
|
||||
@@ -332,6 +332,27 @@ impl<'h> Evaluator<'h> {
|
||||
self.deref(ev)
|
||||
}
|
||||
|
||||
/// Evaluates the root of a formula. Excel snaps a near-cancelling add or subtract to exactly 0
|
||||
/// only here (and in the last addition of a `SUM`), never inside parentheses, unary signs,
|
||||
/// `IF` branches or an inner step: `=A1-B1` is 0 over two numbers one ulp apart, `=(A1-B1)` is not.
|
||||
pub fn value_root(&mut self, e: &Expr) -> Value {
|
||||
match e {
|
||||
Expr::Binary(op @ (BinOp::Add | BinOp::Sub), a, b) => {
|
||||
// The root skips `eval`, so it must pass `eval`'s guards itself: a name that refers to
|
||||
// itself (directly or through cells) is bounded only by them.
|
||||
if let Err(x) = self.enter() {
|
||||
return Value::Error(x);
|
||||
}
|
||||
let x = self.value(a);
|
||||
let y = self.value(b);
|
||||
self.depth -= 1;
|
||||
let sys = self.host.workbook().date_system;
|
||||
zip2(&x, &y, |l, r| binary_scalar_snapped(*op, l, r, sys))
|
||||
}
|
||||
_ => self.value(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_sheet(&self, s: &SheetSel) -> Result<Vec<usize>, CellError> {
|
||||
let wb = self.host.workbook();
|
||||
match s {
|
||||
@@ -418,25 +439,34 @@ impl<'h> Evaluator<'h> {
|
||||
}
|
||||
|
||||
pub fn eval(&mut self, e: &Expr) -> Ev {
|
||||
if let Err(x) = self.enter() {
|
||||
return err(x);
|
||||
}
|
||||
let r = self.eval_inner(e);
|
||||
self.depth -= 1;
|
||||
r
|
||||
}
|
||||
|
||||
/// `eval`'s guards, shared with [`Self::value_root`]: the stack budget and the nesting depth.
|
||||
/// On `Ok` the depth is one level deeper, and the caller steps it back.
|
||||
fn enter(&mut self) -> Result<(), CellError> {
|
||||
let here = stack_position();
|
||||
if self.depth == 0 {
|
||||
self.stack_top = self.host.stack_top().unwrap_or(here);
|
||||
}
|
||||
if self.stack_top.abs_diff(here) > STACK_BUDGET {
|
||||
self.host.stack_exhausted();
|
||||
return err(CellError::Num);
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
if !self.spend(1) {
|
||||
return err(CellError::Calc);
|
||||
return Err(CellError::Calc);
|
||||
}
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
self.depth -= 1;
|
||||
return err(CellError::Num);
|
||||
return Err(CellError::Num);
|
||||
}
|
||||
let r = self.eval_inner(e);
|
||||
self.depth -= 1;
|
||||
r
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn eval_inner(&mut self, e: &Expr) -> Ev {
|
||||
@@ -518,7 +548,13 @@ impl<'h> Evaluator<'h> {
|
||||
let saved = self.sheet;
|
||||
// Unqualified references in a name refer to the scope sheet.
|
||||
self.sheet = scope;
|
||||
let r = self.eval(&expr);
|
||||
// A name's body is a formula of its own, so Excel snaps it by the root rule wherever
|
||||
// the name is used (name probe, observed on Windows Excel 16.0.20430). Only a
|
||||
// value-producing add or subtract needs it; any other body, a range included, stays as it is.
|
||||
let r = match &expr {
|
||||
Expr::Binary(BinOp::Add | BinOp::Sub, ..) => Ev::V(self.value_root(&expr)),
|
||||
_ => self.eval(&expr),
|
||||
};
|
||||
self.sheet = saved;
|
||||
r
|
||||
}
|
||||
|
||||
@@ -22,17 +22,32 @@ impl Agg {
|
||||
/// What a folded aggregate carries from one value to the next.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Acc {
|
||||
pub(super) sum: f64,
|
||||
/// The sum of every number but the last, left to right.
|
||||
sum: f64,
|
||||
/// The last number seen: `SUM` snaps only its last addition (see `gridcraft_core::arith::sum_snapped`).
|
||||
last: Option<f64>,
|
||||
pub(super) count: u64,
|
||||
}
|
||||
|
||||
impl Acc {
|
||||
pub(super) fn add(&mut self, n: f64) {
|
||||
if let Some(prev) = self.last.replace(n) {
|
||||
self.sum += prev;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold a precomputed range sum into an empty accumulator.
|
||||
pub(super) fn add_range_sum(&mut self, sum: f64, count: u64) {
|
||||
self.sum = sum;
|
||||
self.count = self.count.saturating_add(count);
|
||||
}
|
||||
|
||||
/// Takes a value found inside a reference: only numbers count. `Err` is an error value that
|
||||
/// ends `SUM` and `AVERAGE`; `COUNT` skips errors.
|
||||
pub(super) fn add_cell(&mut self, kind: Agg, v: &Value) -> Result<(), CellError> {
|
||||
match v {
|
||||
Value::Number(n) => {
|
||||
self.sum += n;
|
||||
self.add(*n);
|
||||
self.count = self.count.saturating_add(1);
|
||||
Ok(())
|
||||
}
|
||||
@@ -42,11 +57,12 @@ impl Acc {
|
||||
}
|
||||
|
||||
pub(super) fn finish(&self, kind: Agg) -> Value {
|
||||
let plain = self.sum + self.last.unwrap_or(0.0);
|
||||
match kind {
|
||||
Agg::Sum => Value::number(self.sum),
|
||||
Agg::Sum => Value::number(self.last.map_or(self.sum, |l| gridcraft_core::arith::snap_add(self.sum, l))),
|
||||
Agg::Count => Value::number(self.count as f64),
|
||||
Agg::Average if self.count == 0 => Value::Error(CellError::Div0),
|
||||
Agg::Average => Value::number(self.sum / self.count as f64),
|
||||
Agg::Average => Value::number(plain / self.count as f64),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,6 +188,17 @@ pub fn binary_values(op: BinOp, x: &Value, y: &Value, sys: gridcraft_core::DateS
|
||||
zip2(x, y, |a, b| binary_scalar(op, a, b, sys))
|
||||
}
|
||||
|
||||
/// `a + b` or `a - b` with Excel's snap to zero (see [`super::Evaluator::value_root`]).
|
||||
pub(super) fn binary_scalar_snapped(op: BinOp, a: &Value, b: &Value, sys: gridcraft_core::DateSystem) -> Value {
|
||||
match (a, b) {
|
||||
(Value::Error(_), _) | (_, Value::Error(_)) => binary_scalar(op, a, b, sys),
|
||||
_ => match (a.to_number_in(sys), b.to_number_in(sys)) {
|
||||
(Ok(x), Ok(y)) => Value::number(gridcraft_core::arith::snap_add(x, if op == BinOp::Sub { -y } else { y })),
|
||||
(Err(e), _) | (_, Err(e)) => Value::Error(e),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `x & y` with at least one array operand, giving `#NUM!` once the texts built so far pass `budget`
|
||||
/// bytes.
|
||||
fn concat_arrays(x: &Value, y: &Value, sys: gridcraft_core::DateSystem, budget: usize) -> Value {
|
||||
|
||||
@@ -413,13 +413,13 @@ impl<'h> Evaluator<'h> {
|
||||
/// Adds one area to `acc`; `Err` is the result the function ends with.
|
||||
fn aggregate_area(&mut self, kind: Agg, a: &Area, acc: &mut Acc) -> Result<(), Ev> {
|
||||
if !a.range.is_single() {
|
||||
// Adding the block's remembered sum to anything but +0.0 would add in another order.
|
||||
// COUNT never reads the sum, so it may reuse every block.
|
||||
if (kind == Agg::Count || acc.sum.to_bits() == 0)
|
||||
&& let Some((sum, count)) = self.host.range_sum(a.sheet, a.range)
|
||||
// COUNT never reads the sum, so it may reuse every block's remembered count.
|
||||
// SUM and AVERAGE must walk so SUM can snap only its last addition (the remembered
|
||||
// block sum does not keep that last add).
|
||||
if kind == Agg::Count
|
||||
&& let Some((_sum, count)) = self.host.range_sum(a.sheet, a.range)
|
||||
{
|
||||
acc.sum = sum;
|
||||
acc.count = acc.count.saturating_add(count);
|
||||
acc.add_range_sum(0.0, count);
|
||||
return Ok(());
|
||||
}
|
||||
// Folded without building an array, but still walked: the part inside the used
|
||||
@@ -444,20 +444,21 @@ impl<'h> Evaluator<'h> {
|
||||
self.aggregate_value(kind, value, true, acc)
|
||||
}
|
||||
|
||||
/// Adds one argument's value by calling `SUM` and `COUNT` on it, so coercion and error rules
|
||||
/// stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`).
|
||||
/// Adds one argument's value with `SUM`'s numbers and a call to `COUNT`, so coercion and error
|
||||
/// rules stay in one place (`AVERAGE` of an argument is its `SUM` over its `COUNT`). The numbers
|
||||
/// are added one by one so `SUM` can snap only its last addition.
|
||||
fn aggregate_value(&mut self, kind: Agg, value: Value, from_ref: bool, acc: &mut Acc) -> Result<(), Ev> {
|
||||
if !from_ref && !self.spend_on(&value) {
|
||||
return Err(err(CellError::Calc));
|
||||
}
|
||||
let (Some(sum), Some(count)) = (gridcraft_functions::lookup("SUM"), gridcraft_functions::lookup("COUNT")) else {
|
||||
let Some(count) = gridcraft_functions::lookup("COUNT") else {
|
||||
return Err(err(CellError::Name));
|
||||
};
|
||||
let args = [Arg { value, from_ref, blank_value: false }];
|
||||
if kind != Agg::Count {
|
||||
match gridcraft_functions::call(sum, &args, &mut FnCtx { ev: self, criteria: None, lambda: None }) {
|
||||
Value::Number(n) => acc.sum += n,
|
||||
other => return Err(Ev::V(other)),
|
||||
match gridcraft_functions::numbers(&args) {
|
||||
Ok(ns) => ns.into_iter().for_each(|n| acc.add(n)),
|
||||
Err(e) => return Err(err(e)),
|
||||
}
|
||||
}
|
||||
if kind != Agg::Sum {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::MAX_LAMBDA_CALLS;
|
||||
use super::array::{broadcast_len, single};
|
||||
use super::special::is_special;
|
||||
use super::{Array, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
|
||||
use super::{Array, BinOp, CellError, Ev, Evaluator, Expr, Lambda, MAX_CELLS, MAX_TAIL_CALLS, Tail, Value, err};
|
||||
use std::sync::Arc;
|
||||
|
||||
impl<'h> Evaluator<'h> {
|
||||
@@ -96,10 +96,14 @@ impl<'h> Evaluator<'h> {
|
||||
self.calls += 1;
|
||||
let saved = std::mem::replace(&mut self.env, l.env.clone());
|
||||
self.env.extend(bound);
|
||||
// A LAMBDA body is a formula of its own, so Excel snaps it by the root rule in every context
|
||||
// (named, inline, LET-bound, MAP, REDUCE, SCAN, MAKEARRAY, BYROW, BYCOL; LAMBDA probe, observed
|
||||
// on Windows Excel 16.0.20430). A LET, IF, parenthesis or unary sign at the root of the body does not.
|
||||
// A call in tail position replaces this one instead of nesting under it, so a tail recursion
|
||||
// uses no more native stack at 5,000 deep than at 5. Each link still spends fuel.
|
||||
let snap_root = |body: &Expr| matches!(body, Expr::Binary(BinOp::Add | BinOp::Sub, ..));
|
||||
let mut tails = 0;
|
||||
let mut step = self.tail_step(&l.body);
|
||||
let mut step = if snap_root(&l.body) { Tail::Done(Ev::V(self.value_root(&l.body))) } else { self.tail_step(&l.body) };
|
||||
let r = loop {
|
||||
match step {
|
||||
Tail::Done(v) => break v,
|
||||
@@ -115,7 +119,7 @@ impl<'h> Evaluator<'h> {
|
||||
self.env.clear();
|
||||
self.env.extend(next.env.iter().cloned());
|
||||
self.env.extend(bound);
|
||||
step = self.tail_step(&next.body);
|
||||
step = if snap_root(&next.body) { Tail::Done(Ev::V(self.value_root(&next.body))) } else { self.tail_step(&next.body) };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -825,11 +825,21 @@ pub fn evaluate(wb: &Workbook, sheet: usize, at: CellRef, formula: &str) -> Valu
|
||||
}
|
||||
|
||||
pub fn evaluate_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
|
||||
evaluate_expr_at(wb, sheet, at, expr, true)
|
||||
}
|
||||
|
||||
/// Like [`evaluate_expr`] for a sub-expression of a larger formula (Evaluate Formula's steps): Excel's
|
||||
/// snap to zero applies at a formula's root only, so an inner `A1-B1` keeps its IEEE residue.
|
||||
pub fn evaluate_inner_expr(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr) -> Value {
|
||||
evaluate_expr_at(wb, sheet, at, expr, false)
|
||||
}
|
||||
|
||||
fn evaluate_expr_at(wb: &Workbook, sheet: usize, at: CellRef, expr: &Expr, root: bool) -> Value {
|
||||
let exprs = HashMap::default();
|
||||
let mut rng = 0x1234_5678_9ABC_DEF0u64;
|
||||
let mut host = PassHost::new(wb, &exprs, &mut rng, now_serial());
|
||||
let mut ev = Evaluator::new(&mut host, sheet, at);
|
||||
ev.value(expr)
|
||||
if root { ev.value_root(expr) } else { ev.value(expr) }
|
||||
}
|
||||
|
||||
/// What [`evaluate_bounded`] found: the formula's reference (not read), its value, or that it ran
|
||||
|
||||
@@ -332,7 +332,7 @@ impl PassHost<'_> {
|
||||
let outer_out_of_stack = std::mem::replace(&mut self.out_of_stack, false);
|
||||
let v = {
|
||||
let mut ev = Evaluator::new(self, k.0, k.1);
|
||||
ev.value(&expr)
|
||||
ev.value_root(&expr)
|
||||
};
|
||||
let out_of_stack = std::mem::replace(&mut self.out_of_stack, outer_out_of_stack);
|
||||
if out_of_stack && self.depth > 1 && self.suspend.is_none() {
|
||||
|
||||
+483
-4
@@ -1718,6 +1718,478 @@ fn sumif_resized_sum_range_on_another_sheet_and_through_a_name() {
|
||||
assert_eq!(t.num("C2"), 5.0);
|
||||
}
|
||||
|
||||
// ---- Excel's snap to zero (observed on Windows Excel 16.0.20430; suite rows cancel-ulps, cancel-band, decimal-sum, excel-probe) ----
|
||||
|
||||
impl T {
|
||||
/// Stores an exact double, bypassing input parsing.
|
||||
fn put(&mut self, at: &str, x: f64) {
|
||||
self.wb.sheet_mut(0).unwrap().cells.set(c(at), Cell::value(Value::Number(x)));
|
||||
self.calc.cells_changed(&mut self.wb, &[(0, c(at))]);
|
||||
}
|
||||
}
|
||||
|
||||
const ULP1: f64 = f64::EPSILON; // the spacing of doubles just above 1.0
|
||||
|
||||
#[test]
|
||||
fn a_bare_root_add_or_sub_snaps_a_near_cancellation_to_zero() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1); // one ulp apart: Excel shows 0, not -2.22e-16
|
||||
t.set("C1", "=A1-B1");
|
||||
t.set("C2", "=B1-A1");
|
||||
t.set("C3", "=A1+-B1");
|
||||
t.set("C4", "=0+A1-B1"); // the end of =0+A-B snaps too
|
||||
t.set("C5", "=SUM(A1,-B1)*1"); // the last addition of a SUM snaps even when SUM isn't the root
|
||||
t.put("D1", -(1.0 + ULP1));
|
||||
t.set("C6", "=SUM(A1,D1)");
|
||||
t.set("C7", "=A1+D1");
|
||||
for at in ["C1", "C2", "C3", "C4", "C5", "C6", "C7"] {
|
||||
assert_eq!(t.get(at), Value::Number(0.0), "{at}");
|
||||
}
|
||||
// The classic: 0.1+0.2-0.3 is 0 in Excel (5.55e-17 in IEEE).
|
||||
t.put("E1", 0.1);
|
||||
t.put("E2", 0.2);
|
||||
t.put("E3", 0.3);
|
||||
t.set("E4", "=E1+E2-E3");
|
||||
assert_eq!(t.get("E4"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_snaps_its_last_addition_when_it_folds_a_range_in_place() {
|
||||
// SUM, COUNT and AVERAGE fold ranges over the stored cells instead of calling SUM; the fold must
|
||||
// keep SUM's rule: only the last number added snaps, and a blank cell adds no number.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("A2", -(1.0 + ULP1));
|
||||
t.set("C1", "=SUM(A1:A2)");
|
||||
t.set("C2", "=SUM(A1:A2,Z9)");
|
||||
t.set("C3", "=SUM(A1:A2,0)"); // the last addition is residue + 0: no snap
|
||||
t.set("C4", "=AVERAGE(A1:A2)"); // AVERAGE does not snap
|
||||
assert_eq!(t.get("C1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C2"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C3"), Value::Number(-ULP1));
|
||||
assert_eq!(t.get("C4"), Value::Number(-ULP1 / 2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_threshold_is_two_to_the_e_minus_49_of_the_left_operand() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
// 7 ulps below the threshold of 8 ulps (2^-49): snaps. Exactly 8: does not.
|
||||
t.put("B1", 1.0 + 7.0 * ULP1);
|
||||
t.put("B2", 1.0 + 8.0 * ULP1);
|
||||
t.set("C1", "=A1-B1");
|
||||
t.set("C2", "=A1-B2");
|
||||
assert_eq!(t.get("C1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("C2"), Value::Number(-8.0 * ULP1));
|
||||
// The binade is the LEFT operand's (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046).
|
||||
t.put("A3", 0.4999999999999998);
|
||||
t.put("B3", 0.5000000000000002);
|
||||
t.set("C3", "=A3-B3");
|
||||
t.set("C4", "=B3-A3");
|
||||
assert_eq!(t.get("C3"), Value::Number(-4.440892098500626e-16));
|
||||
assert_eq!(t.get("C4"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_does_not_apply_inside_parentheses_unary_if_or_inner_steps() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
let residue = 1.0 - (1.0 + ULP1);
|
||||
for (at, f) in [
|
||||
("C1", "=(A1-B1)"),
|
||||
("C2", "=+(A1-B1)"),
|
||||
("C3", "=-(B1-A1)"),
|
||||
("C4", "=IF(TRUE,A1-B1)"),
|
||||
("C5", "=A1-B1+0"), // the root is the +0; the inner subtraction is not a root
|
||||
("C6", "=SUM(A1,-B1,0)"), // the last addition is residue+0
|
||||
] {
|
||||
t.set(at, f);
|
||||
assert_eq!(t.get(at), Value::Number(residue), "{f}");
|
||||
}
|
||||
// Observed on Windows Excel 16.0.20430: =SUM(A-B) does not snap (the subtraction is an inner step, the SUM's
|
||||
// last addition is residue + 0), and neither does a root that adds a zero.
|
||||
t.set("C7", "=SUM(A1-B1)");
|
||||
t.set("C8", "=A1-B1-0");
|
||||
assert_eq!(t.get("C7"), Value::Number(residue));
|
||||
assert_eq!(t.get("C8"), Value::Number(residue));
|
||||
// Only the LAST addition of a SUM snaps: 3+1e16-1e16 is 4, not 0.
|
||||
t.put("D1", 3.0);
|
||||
t.put("D2", 1e16);
|
||||
t.put("D3", -1e16);
|
||||
t.put("D4", 0.0);
|
||||
t.set("E1", "=SUM(D1:D4)");
|
||||
assert_eq!(t.get("E1"), Value::Number(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_sign_and_exact_arithmetic_never_snap() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1e-20);
|
||||
t.put("B1", 2e-20);
|
||||
t.set("C1", "=A1+B1"); // a tiny sum of small numbers is not a cancellation
|
||||
t.set("C2", "=A1-B1");
|
||||
t.put("A2", 3.0);
|
||||
t.put("B2", 2.0);
|
||||
t.set("C3", "=A2-B2");
|
||||
assert_eq!(t.num("C1"), 1e-20 + 2e-20);
|
||||
assert_eq!(t.num("C2"), 1e-20 - 2e-20);
|
||||
assert_eq!(t.num("C3"), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_threshold_follows_the_left_operand_across_a_binade_boundary() {
|
||||
// Observed on Windows Excel 16.0.20430, snap probe rows 226, 231 and 236 (=A-B, A just below 1.0): the
|
||||
// threshold is 2^-50 (A's binade), not 2^-49 (B's), so 7.8e-16 snaps and 9.99e-16 does not.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 0.9999999999999999);
|
||||
t.put("B1", 1.0000000000000004);
|
||||
t.put("B2", 1.0000000000000007);
|
||||
t.put("B3", 1.0000000000000009);
|
||||
t.set("D1", "=A1-B1");
|
||||
t.set("D2", "=A1-B2");
|
||||
t.set("D3", "=A1-B3");
|
||||
assert_eq!(t.get("D1"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D2"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D3"), Value::Number(-9.992007221626409e-16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snap_leaves_error_and_text_operands_alone() {
|
||||
let mut t = T::new();
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
t.set("A1", "=1/0");
|
||||
t.set("C1", "=A1-B1");
|
||||
assert_eq!(t.get("C1"), Value::Error(CellError::Div0));
|
||||
t.set("A2", "abc");
|
||||
t.set("C2", "=A2-B1");
|
||||
assert_eq!(t.get("C2"), Value::Error(CellError::Value));
|
||||
t.set("A3", "1"); // numeric text still converts, then the subtraction snaps like any other
|
||||
t.put("B3", 1.0);
|
||||
t.set("C3", "=A3-B3");
|
||||
assert_eq!(t.get("C3"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
// ---- the snap in a defined name's body (observed on Windows Excel 16.0.20430, name probe: 8 bodies x 12 positions) ----
|
||||
|
||||
impl T {
|
||||
fn name(&mut self, name: &str, body: &str) {
|
||||
self.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: name.into(),
|
||||
scope: None,
|
||||
formula: body.into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_defined_name_is_a_formula_of_its_own_so_its_body_snaps_wherever_it_is_used() {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
// (body, does Excel snap it?) Only the shape of the BODY matters, not where the name is used.
|
||||
let bodies = [
|
||||
("N_sub", "Sheet1!$A$1-Sheet1!$B$1", true),
|
||||
("N_par", "(Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
("N_plus0", "Sheet1!$A$1-Sheet1!$B$1+0", false),
|
||||
("N_sum", "SUM(Sheet1!$A$1,-Sheet1!$B$1)", true),
|
||||
("N_neg", "-(Sheet1!$B$1-Sheet1!$A$1)", false),
|
||||
("N_ref", "N_sub", true), // a name that is a name inherits it
|
||||
("N_if", "IF(TRUE,Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
("N_sumsub", "SUM(Sheet1!$A$1-Sheet1!$B$1)", false),
|
||||
];
|
||||
for (name, body, _) in bodies {
|
||||
t.name(name, body);
|
||||
}
|
||||
// All 12 positions of the Excel probe.
|
||||
let uses = ["{n}", "{n}*1", "{n}+0", "0+{n}", "({n})", "-{n}", "+{n}", "SUM({n})", "IF(TRUE,{n})", "ABS({n})", "1*{n}", "{n}-0"];
|
||||
let mut row = 2;
|
||||
for (name, body, snaps) in bodies {
|
||||
for u in uses {
|
||||
let at = format!("D{row}");
|
||||
t.set(&at, &format!("={}", u.replace("{n}", name)));
|
||||
// Every body is -1 ulp (A1-B1) or exactly 0; a minus sign or ABS flips the residue.
|
||||
let flips = u.starts_with('-') || u.starts_with("ABS");
|
||||
let want = if snaps {
|
||||
0.0
|
||||
} else if flips {
|
||||
ULP1
|
||||
} else {
|
||||
-ULP1
|
||||
};
|
||||
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excels_own_gap_shapes_from_lookup_shapes_xlsx() {
|
||||
// excel-evidence/request-3/files/lookup-shapes.xlsx, Sheet1!H15:H26: the gaps of 1, 4 and 7 ulps
|
||||
// snap to 0 as =Gap, =Gap*1 and =Gap+0; the gap of 8 ulps keeps its residue.
|
||||
let mut t = T::new();
|
||||
for (cell, v) in [("A1", 1.0000000000000002), ("A2", 1.0000000000000009), ("A3", 1.0000000000000016), ("A4", 1.0000000000000018)] {
|
||||
t.put(cell, v);
|
||||
}
|
||||
for (cell, v) in [("B1", 1.0), ("B2", 1.0), ("B3", 1.0), ("B4", 1.0)] {
|
||||
t.put(cell, v);
|
||||
}
|
||||
for (name, row) in [("Gap_1", 1), ("Gap_4", 2), ("Gap_7", 3), ("Gap_8", 4)] {
|
||||
t.name(name, &format!("Sheet1!$A${row}-Sheet1!$B${row}"));
|
||||
}
|
||||
let mut r = 10;
|
||||
for (name, residue) in [("Gap_1", 0.0), ("Gap_4", 0.0), ("Gap_7", 0.0), ("Gap_8", 1.7763568394002505e-15)] {
|
||||
for f in ["{n}", "{n}*1", "{n}+0"] {
|
||||
let at = format!("F{r}");
|
||||
t.set(&at, &format!("={}", f.replace("{n}", name)));
|
||||
assert_eq!(t.get(&at), Value::Number(residue), "{f} over {name}");
|
||||
r += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_refers_to_a_range_still_refers_to_it() {
|
||||
// Only a reference answers these: ISREF, ROW and OFFSET over a name. Wrapping every name
|
||||
// body in value_root would turn the range into an array and fail all three.
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("A2", 2.0);
|
||||
t.put("B1", 3.0);
|
||||
t.put("B2", 4.0);
|
||||
t.name("Block", "Sheet1!$A$1:$B$2");
|
||||
t.set("D1", "=ISREF(Block)");
|
||||
t.set("D2", "=MIN(ROW(Block))");
|
||||
t.set("D3", "=SUM(OFFSET(Block,0,1))");
|
||||
assert_eq!(t.get("D1"), Value::Bool(true));
|
||||
assert_eq!(t.num("D2"), 1.0);
|
||||
assert_eq!(t.num("D3"), 7.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_whose_body_is_an_array_difference_snaps_element_wise() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): INDEX(Arr,1)*1 and INDEX(Arr,2)*1 are 0 for Arr = A1:A2-B1:B2.
|
||||
let mut t = T::new();
|
||||
for (a, b) in [("A1", "B1"), ("A2", "B2")] {
|
||||
t.put(a, 1.0);
|
||||
t.put(b, 1.0 + ULP1);
|
||||
}
|
||||
t.name("Arr", "Sheet1!$A$1:$A$2-Sheet1!$B$1:$B$2");
|
||||
t.set("D1", "=INDEX(Arr,1)*1");
|
||||
t.set("D2", "=INDEX(Arr,2)*1");
|
||||
t.set("D3", "=SUM(Arr)");
|
||||
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
|
||||
assert_eq!(t.get("D3"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sheet_scoped_name_snaps_on_its_own_sheet() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): a sheet-scoped Loc = S2!$A$1-S2!$B$1 gives 0 as =S2!Loc*1.
|
||||
let mut t = T::new();
|
||||
t.wb.sheets.push(std::sync::Arc::new(gridcraft_model::Sheet::new("S2")));
|
||||
t.wb.sheet_mut(1).unwrap().cells.set(c("A1"), Cell::value(Value::Number(1.0)));
|
||||
t.wb.sheet_mut(1).unwrap().cells.set(c("B1"), Cell::value(Value::Number(1.0 + ULP1)));
|
||||
t.wb.names.push(gridcraft_model::DefinedName {
|
||||
name: "Loc".into(),
|
||||
scope: Some(1),
|
||||
formula: "S2!$A$1-S2!$B$1".into(),
|
||||
comment: String::new(),
|
||||
hidden: false,
|
||||
});
|
||||
t.set("D1", "=S2!Loc*1");
|
||||
t.set("D2", "=S2!Loc");
|
||||
assert_eq!((t.get("D1"), t.get("D2")), (Value::Number(0.0), Value::Number(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_names_stay_bounded_and_cost_the_same_depth_as_before_the_snap() {
|
||||
let mut t = T::new();
|
||||
// A name that refers to itself ends in the depth limit's #NUM!, not a stack overflow.
|
||||
t.name("Rec", "Rec-1");
|
||||
t.set("A1", "=Rec");
|
||||
assert_eq!(t.get("A1"), Value::Error(CellError::Num));
|
||||
// A long chain of names, each one `-0` over the last, runs out of depth at the same place as it did
|
||||
// before names were snapped (value_root must charge its own level, or each link would be cheaper
|
||||
// and a chain through cells could overflow the stack).
|
||||
t.name("Nm_0", "1");
|
||||
for i in 1..=250 {
|
||||
t.name(&format!("Nm_{i}"), &format!("Nm_{}-0", i - 1));
|
||||
}
|
||||
t.set("A2", "=Nm_250");
|
||||
assert_eq!(t.get("A2"), Value::Error(CellError::Num));
|
||||
t.set("A3", "=Nm_20");
|
||||
assert_eq!(t.get("A3"), Value::Number(1.0));
|
||||
}
|
||||
|
||||
// ---- the snap in a LAMBDA body (observed on Windows Excel 16.0.20430, LAMBDA probe: 126 formulas) ----
|
||||
// A LAMBDA body is a formula of its own, like a defined name's: Excel snaps it by the root rule in every
|
||||
// context (named, inline, LET-bound, and under MAP, REDUCE, SCAN, MAKEARRAY, BYROW and BYCOL).
|
||||
|
||||
fn lambda_t() -> T {
|
||||
let mut t = T::new();
|
||||
t.put("A1", 1.0);
|
||||
t.put("B1", 1.0 + ULP1);
|
||||
t.put("A2", 1.0 + ULP1);
|
||||
t.put("B2", 1.0 + ULP1);
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_snaps_by_its_own_root_wherever_the_lambda_is_called() {
|
||||
let mut t = lambda_t();
|
||||
// (name, body, does Excel snap it?)
|
||||
let lambdas = [
|
||||
("L_sub", "LAMBDA(x,y,x-y)", true),
|
||||
("L_par", "LAMBDA(x,y,(x-y))", false),
|
||||
("L_plus0", "LAMBDA(x,y,x-y+0)", false),
|
||||
("L_sum", "LAMBDA(x,y,SUM(x,-y))", true),
|
||||
("L_neg", "LAMBDA(x,y,-(y-x))", false),
|
||||
("L_if", "LAMBDA(x,y,IF(TRUE,x-y))", false),
|
||||
("L_sumsub", "LAMBDA(x,y,SUM(x-y))", false),
|
||||
("L_let", "LAMBDA(x,y,LET(d,x-y,d))", false), // a LET inside the body does not snap
|
||||
("L_letroot", "LAMBDA(x,y,LET(a,x,a-y))", false),
|
||||
("L_ref", "LAMBDA(x,y,L_sub(x,y))", true), // a lambda that calls one inherits it
|
||||
];
|
||||
for (name, body, _) in lambdas {
|
||||
t.name(name, body);
|
||||
}
|
||||
let uses = ["{c}", "{c}*1", "{c}+0", "0+{c}", "({c})", "-{c}", "SUM({c})", "IF(TRUE,{c})", "ABS({c})"];
|
||||
let mut row = 5;
|
||||
for (name, body, snaps) in lambdas {
|
||||
for u in uses {
|
||||
let at = format!("D{row}");
|
||||
t.set(&at, &format!("={}", u.replace("{c}", &format!("{name}(Sheet1!$A$1,Sheet1!$B$1)"))));
|
||||
let flips = u.starts_with('-') || u.starts_with("ABS");
|
||||
let want = if snaps {
|
||||
0.0
|
||||
} else if flips {
|
||||
ULP1
|
||||
} else {
|
||||
-ULP1
|
||||
};
|
||||
assert_eq!(t.get(&at), Value::Number(want), "{u} over {name} = {body}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_and_let_bound_lambdas_snap_the_same_way() {
|
||||
let mut t = lambda_t();
|
||||
for (i, (f, snaps)) in [
|
||||
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)", true),
|
||||
("LAMBDA(x,y,x-y)(Sheet1!$A$1,Sheet1!$B$1)*1", true),
|
||||
("LAMBDA(x,y,(x-y))(Sheet1!$A$1,Sheet1!$B$1)", false),
|
||||
("LAMBDA(x,y,x-y+0)(Sheet1!$A$1,Sheet1!$B$1)", false),
|
||||
("LAMBDA(x,y,SUM(x,-y))(Sheet1!$A$1,Sheet1!$B$1)", true),
|
||||
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))", true),
|
||||
("LET(f,LAMBDA(x,y,x-y),f(Sheet1!$A$1,Sheet1!$B$1))*1", true),
|
||||
("LET(f,LAMBDA(x,y,(x-y)),f(Sheet1!$A$1,Sheet1!$B$1))", false),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = format!("D{}", i + 5);
|
||||
t.set(&at, &format!("={f}"));
|
||||
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_order_functions_snap_their_lambda_body() {
|
||||
let mut t = lambda_t();
|
||||
// The cell is INDEX(<result>,1,1), bare and times 1. A is (1, 1+ulp), B is (1+ulp, 1+ulp).
|
||||
let cases = [
|
||||
("MAP(Sheet1!$A$1:$A$2,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("REDUCE(Sheet1!$A$1,Sheet1!$B$1,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("SCAN(Sheet1!$A$1,Sheet1!$B$1:$B$2,LAMBDA(x,y,{b}))", "x-y"),
|
||||
("MAKEARRAY(1,1,LAMBDA(x,y,{b}))", "Sheet1!$A$1-Sheet1!$B$1"),
|
||||
("BYROW(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,1,2)"),
|
||||
("BYCOL(Sheet1!$A$1:$B$2,LAMBDA(r,{b}))", "INDEX(r,1,1)-INDEX(r,2,1)"),
|
||||
];
|
||||
let mut row = 5;
|
||||
for (f, bare) in cases {
|
||||
for (b, snaps) in [(bare.to_string(), true), (format!("({bare})"), false)] {
|
||||
for u in ["INDEX({c},1,1)", "INDEX({c},1,1)*1"] {
|
||||
let at = format!("D{row}");
|
||||
let formula = u.replace("{c}", &f.replace("{b}", &b));
|
||||
t.set(&at, &format!("={formula}"));
|
||||
assert_eq!(t.get(&at), Value::Number(if snaps { 0.0 } else { -ULP1 }), "{formula}");
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_that_returns_a_reference_still_returns_one() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): a body that returns a reference is still a reference, so only an
|
||||
// add or subtract root takes the snapping path. ISREF and OFFSET need the reference; wrapping every
|
||||
// body in value_root would turn it into a value.
|
||||
let mut t = lambda_t();
|
||||
t.set("D5", "=ISREF(LAMBDA(x,x)(Sheet1!$A$1))");
|
||||
t.set("D6", "=ISREF(LAMBDA(x,IF(TRUE,x))(Sheet1!$A$1))");
|
||||
t.set("D7", "=ROW(LAMBDA(x,OFFSET(x,1,0))(Sheet1!$A$1))");
|
||||
assert_eq!(t.get("D5"), Value::Bool(true));
|
||||
assert_eq!(t.get("D6"), Value::Bool(true));
|
||||
assert_eq!(t.num("D7"), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_curried_and_closed_over_lambda_bodies_snap_by_the_root_of_the_inner_body() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): each of these is exactly 0.
|
||||
let mut t = lambda_t();
|
||||
for (i, f) in [
|
||||
"LAMBDA(x,LAMBDA(y,x-y))(Sheet1!$A$1)(Sheet1!$B$1)", // curried
|
||||
"LAMBDA(x,y,LAMBDA(p,q,p-q)(x,y))(Sheet1!$A$1,Sheet1!$B$1)", // a body that calls an inner lambda
|
||||
"LAMBDA(x,y,0+x-y)(Sheet1!$A$1,Sheet1!$B$1)", // the end of 0+x-y snaps like =0+A-B
|
||||
"LET(a,Sheet1!$A$1,LAMBDA(y,a-y)(Sheet1!$B$1))", // a closure over a LET variable
|
||||
"LAMBDA(x,y,x-y)(Sheet1!$A$1+0,Sheet1!$B$1+0)",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = format!("D{}", i + 5);
|
||||
t.set(&at, &format!("={f}"));
|
||||
assert_eq!(t.get(&at), Value::Number(0.0), "{f}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_body_uses_the_same_threshold_and_snaps_array_arguments_element_wise() {
|
||||
// Observed on Windows Excel 16.0.20430 (review probe): 7 ulps snap, 8 ulps keep the residue, inside a body as in a cell.
|
||||
let mut t = lambda_t();
|
||||
t.put("G1", 1.0);
|
||||
t.put("G2", 1.0 + 7.0 * ULP1);
|
||||
t.put("G3", 1.0 + 8.0 * ULP1);
|
||||
t.set("D5", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$2)");
|
||||
t.set("D6", "=LAMBDA(x,y,x-y)(Sheet1!$G$1,Sheet1!$G$3)");
|
||||
assert_eq!(t.get("D5"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D6"), Value::Number(-8.0 * ULP1));
|
||||
// Array arguments: each element snaps by its own left operand (1 and 3 are different binades).
|
||||
t.put("E1", 1.0);
|
||||
t.put("E2", 3.0);
|
||||
t.put("F1", 1.0 + ULP1);
|
||||
t.put("F2", 3.0 + 2.0 * ULP1);
|
||||
t.set("D8", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),1,1)");
|
||||
t.set("D9", "=INDEX(LAMBDA(x,y,x-y)(Sheet1!$E$1:$E$2,Sheet1!$F$1:$F$2),2,1)");
|
||||
assert_eq!(t.get("D8"), Value::Number(0.0));
|
||||
assert_eq!(t.get("D9"), Value::Number(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lambda_that_calls_itself_ends_in_an_error_not_a_crash() {
|
||||
// Which error depends on where the depth runs out first (#CALC! or #NAME?); what matters is that
|
||||
// it ends. A recursion through cells is a separate, existing limit.
|
||||
let mut t = lambda_t();
|
||||
t.name("Loop", "LAMBDA(x,Loop(x)-1)");
|
||||
t.set("D5", "=Loop(1)");
|
||||
assert!(matches!(t.get("D5"), Value::Error(_)), "{:?}", t.get("D5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimrange() {
|
||||
let mut t = T::new();
|
||||
@@ -3038,13 +3510,17 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
|
||||
let check = |wb: &Workbook, when: &str| {
|
||||
let sh = wb.sheet(0).unwrap();
|
||||
for (cell, f, lead, blocks) in &oracle {
|
||||
let (mut sum, mut count, mut error) = (lead.unwrap_or(0.0), u64::from(lead.is_some()), None);
|
||||
let (mut nums, mut count, mut error) = (Vec::new(), 0u64, None);
|
||||
if let Some(l) = *lead {
|
||||
nums.push(l);
|
||||
count += 1;
|
||||
}
|
||||
for &(r0, c0, r1, c1) in blocks {
|
||||
for r in r0..=r1 {
|
||||
for col in c0..=c1 {
|
||||
match sh.value(CellRef::new(r, col)) {
|
||||
Value::Number(n) => {
|
||||
sum += n;
|
||||
nums.push(n);
|
||||
count += 1;
|
||||
}
|
||||
Value::Error(e) if *f != "COUNT" => error = error.or(Some(e)),
|
||||
@@ -3053,12 +3529,15 @@ fn aggregates_over_ranges_match_a_plain_fold_bit_for_bit() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// SUM snaps only its last addition, matching Acc::finish. AVERAGE and the
|
||||
// running total use the unsapped left-to-right fold.
|
||||
let plain = nums.iter().fold(0.0, |a, n| a + n);
|
||||
let want = match (error, *f) {
|
||||
(Some(e), _) => Value::Error(e),
|
||||
(_, "SUM") => Value::number(sum),
|
||||
(_, "SUM") => Value::number(gridcraft_core::arith::sum_snapped(&nums)),
|
||||
(_, "COUNT") => Value::number(count as f64),
|
||||
(_, _) if count == 0 => Value::Error(CellError::Div0),
|
||||
_ => Value::number(sum / count as f64),
|
||||
_ => Value::number(plain / count as f64),
|
||||
};
|
||||
let got = sh.value(*cell);
|
||||
let same = match (&got, &want) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use gridcraft_calc::is_known_function;
|
||||
use gridcraft_formula::FormulaLocale;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn every_polish_name_belongs_to_a_known_function() {
|
||||
let names = FormulaLocale::Pl.aliases();
|
||||
assert!(names.len() > 400, "{}", names.len());
|
||||
let mut seen = HashSet::new();
|
||||
for (en, pl) in names {
|
||||
assert!(is_known_function(en), "{en} is not a GridCraft function");
|
||||
assert_ne!(en, pl, "{en} needs no alias");
|
||||
// A Polish name that is another function's English name would call the wrong function.
|
||||
assert!(!is_known_function(pl), "{pl} ({en}) shadows an English function");
|
||||
assert!(seen.insert(pl.to_uppercase()), "{pl} is listed twice");
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,15 @@ fn has_markers(k: ChartKind) -> bool {
|
||||
matches!(k, ChartKind::LineMarkers | ChartKind::LineStacked100Markers)
|
||||
}
|
||||
|
||||
/// Stroke widths for explicitly selected Excel chart styles.
|
||||
fn line_style_width(style: u32) -> f32 {
|
||||
match style {
|
||||
1 => 3.0,
|
||||
9 => 5.0,
|
||||
_ => 2.25,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bars that fall into one pixel column, merged: extent along the category axis (`a0..=a1`, the
|
||||
/// bars' start positions) and along the value axis (`lo..hi`).
|
||||
struct BarRun {
|
||||
@@ -71,6 +80,7 @@ struct BarRun {
|
||||
}
|
||||
|
||||
impl BarRun {
|
||||
/// Starts a single-bar run at `pos` spanning `lo..hi`.
|
||||
fn new(pos: f32, lo: f32, hi: f32) -> Self {
|
||||
BarRun { bucket: pos.floor(), a0: pos, a1: pos, lo, hi, merged: false }
|
||||
}
|
||||
@@ -78,6 +88,7 @@ impl BarRun {
|
||||
fn touches(&self, lo: f32, hi: f32) -> bool {
|
||||
lo <= self.hi && hi >= self.lo
|
||||
}
|
||||
/// Extends the merged run to cover `pos` and `lo..hi`.
|
||||
fn add(&mut self, pos: f32, lo: f32, hi: f32) {
|
||||
self.merged = true;
|
||||
self.a0 = self.a0.min(pos);
|
||||
@@ -112,13 +123,15 @@ struct BarSink {
|
||||
bw: f32,
|
||||
horizontal: bool,
|
||||
color: Rgba,
|
||||
stroke: Option<(Rgba, f32)>,
|
||||
nslots: f32,
|
||||
k: f32,
|
||||
}
|
||||
|
||||
impl BarSink {
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, nslots, k }
|
||||
/// Creates a bar emitter for series slot `k` of `nslots`.
|
||||
fn new(bw: f32, horizontal: bool, color: Rgba, stroke: Option<(Rgba, f32)>, nslots: f32, k: f32) -> Self {
|
||||
BarSink { run: None, bw, horizontal, color, stroke, nslots, k }
|
||||
}
|
||||
/// Start of this series' slot along the category axis, for the category centered at `c`.
|
||||
fn pos(&self, c: f32) -> f32 {
|
||||
@@ -138,11 +151,10 @@ impl BarSink {
|
||||
let pos = self.pos(c);
|
||||
let band = self.band();
|
||||
if !merge {
|
||||
if self.horizontal {
|
||||
ctx.rect(lo, pos, len, self.bw, self.color, None);
|
||||
} else {
|
||||
ctx.rect(pos, lo, self.bw, len, self.color, None);
|
||||
}
|
||||
let (x, y, w, h) = if self.horizontal { (lo, pos, len, self.bw) } else { (pos, lo, self.bw, len) };
|
||||
// Omit the outline when a bar is no wider/taller than the stroke, so the inner fill never disappears.
|
||||
let stroke = self.stroke.filter(|(_, sw)| w > *sw && h > *sw);
|
||||
ctx.rect(x, y, w, h, self.color, stroke);
|
||||
return;
|
||||
}
|
||||
match &mut self.run {
|
||||
@@ -154,6 +166,7 @@ impl BarSink {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Flushes any pending hairline bar run at the end of the series.
|
||||
fn finish(self, ctx: &mut Ctx) {
|
||||
let band = self.band();
|
||||
if let Some(m) = self.run {
|
||||
@@ -294,6 +307,12 @@ fn column_slots(fams: &[Fam], sec: &[bool]) -> (Vec<usize>, f32) {
|
||||
(slot_of, slot_keys.len().max(1) as f32)
|
||||
}
|
||||
|
||||
/// Renders Cartesian column, bar, line, area, and combination charts.
|
||||
///
|
||||
/// Resolves series families and their axes, calculates stacking and
|
||||
/// category positions, and draws the corresponding primitives.
|
||||
/// Explicit chart style 9 adds white outlines to column and bar
|
||||
/// rectangles, including stacked and 100%-stacked variants.
|
||||
pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx, horizontal: bool) {
|
||||
let ncat = data.categories.len().max(data.series.iter().map(|s| s.values.len()).max().unwrap_or(0)).min(MAX_CATS);
|
||||
if ncat == 0 {
|
||||
@@ -392,7 +411,8 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
let k = slot_of.get(i).copied().unwrap_or(0) as f32;
|
||||
// Hairline bars are merged per pixel column (their envelope is what shows).
|
||||
let cull = merge_hairlines(bw, labels_on);
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, nslots, k);
|
||||
let stroke = (chart.style == 9).then_some((WHITE, 1.0));
|
||||
let mut sink = BarSink::new(bw, horizontal, s.color, stroke, nslots, k);
|
||||
for (j, sp) in row.iter().enumerate() {
|
||||
let Some((b, t)) = sp else { continue };
|
||||
let (pb, pt) = (vpos(*b, &sc), vpos(*t, &sc));
|
||||
@@ -429,7 +449,7 @@ pub(super) fn cartesian(ctx: &mut Ctx, chart: &Chart, data: &ChartData, area: Bx
|
||||
}
|
||||
_ => {
|
||||
let pts: Vec<Option<[f32; 2]>> = row.iter().enumerate().map(|(j, sp)| sp.map(|(_, t)| [center(j), vpos(t, &sc)])).collect();
|
||||
draw_runs(ctx, &pts, s.color, 2.25, s.smooth.then_some(plot));
|
||||
draw_runs(ctx, &pts, s.color, line_style_width(chart.style), s.smooth.then_some(plot));
|
||||
let k = kinds.get(i).copied().unwrap_or(ChartKind::Line);
|
||||
if has_markers(k) && cw >= 3.0 {
|
||||
draw_markers(ctx, pts.iter().flatten().copied(), 3.5, s.color);
|
||||
|
||||
@@ -39,6 +39,28 @@ pub fn series_color(theme: &Theme, i: usize) -> Rgba {
|
||||
[r, g, b, 0xFF]
|
||||
}
|
||||
|
||||
/// Excel reference colours for explicit styles 1 and 9.
|
||||
///
|
||||
/// These palettes cover measured default-theme examples.
|
||||
/// Other counts still use the existing theme-based fallback.
|
||||
fn chart_style_series_color(theme: &Theme, style: u32, index: usize, count: usize) -> Rgba {
|
||||
if !matches!(style, 1 | 9) {
|
||||
return series_color(theme, index);
|
||||
}
|
||||
|
||||
const SMALL: [u8; 4] = [0x61, 0xB3, 0x81, 0x50];
|
||||
const MEDIUM: [u8; 8] = [0x55, 0x9E, 0x72, 0x46, 0x83, 0xC1, 0x9A, 0xC8];
|
||||
const LARGE: [u8; 16] = [0x4F, 0x93, 0x6A, 0x40, 0x7A, 0xB4, 0x61, 0xB3, 0x81, 0x50, 0x95, 0xDA, 0xAF, 0xD2, 0xBA, 0xAA];
|
||||
|
||||
let shades: &[u8] = match count {
|
||||
1..=4 => &SMALL,
|
||||
5..=8 => &MEDIUM,
|
||||
9..=16 => &LARGE,
|
||||
_ => return series_color(theme, index),
|
||||
};
|
||||
|
||||
shades.get(index).map_or_else(|| series_color(theme, index), |shade| [*shade, *shade, *shade, 0xFF])
|
||||
}
|
||||
/// The first `n` series colours for `theme`.
|
||||
pub fn default_palette(theme: &Theme, n: usize) -> Vec<Rgba> {
|
||||
(0..n.min(4096)).map(|i| series_color(theme, i)).collect()
|
||||
@@ -470,8 +492,12 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
for (i, s) in chart.series.iter().take(MAX_SERIES).enumerate() {
|
||||
let values = nums(wb, sheet, &s.values, limit);
|
||||
let name = s.name.as_deref().map(|n| series_name(wb, sheet, n)).filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series{}", i + 1));
|
||||
let color =
|
||||
s.color.as_ref().and_then(|c| c.resolve(&wb.theme)).map(|[r, g, b]| [r, g, b, 0xFF]).unwrap_or_else(|| series_color(&wb.theme, i));
|
||||
let color = s
|
||||
.color
|
||||
.as_ref()
|
||||
.and_then(|c| c.resolve(&wb.theme))
|
||||
.map(|[r, g, b]| [r, g, b, 0xFF])
|
||||
.unwrap_or_else(|| chart_style_series_color(&wb.theme, chart.style, i, chart.series.len().min(MAX_SERIES)));
|
||||
let kind = chart.series_kind(i);
|
||||
let x = match (&s.categories, numeric_x || matches!(kind, ChartKind::Scatter | ChartKind::ScatterLines | ChartKind::Bubble)) {
|
||||
// X values with text in them (labels) are ignored: the points are numbered 1..n.
|
||||
@@ -519,10 +545,51 @@ pub fn resolve(wb: &Workbook, sheet: usize, chart: &Chart) -> ChartData {
|
||||
}
|
||||
let n = series.iter().map(|s| s.values.len()).max().unwrap_or(0);
|
||||
let categories = categories.unwrap_or_else(|| (1..=n).map(|i| i.to_string()).collect());
|
||||
let palette = default_palette(&wb.theme, n.min(PALETTE_CYCLE));
|
||||
let palette = if matches!(chart.style, 1 | 9) {
|
||||
(0..n.min(PALETTE_CYCLE)).map(|i| chart_style_series_color(&wb.theme, chart.style, i, n)).collect()
|
||||
} else {
|
||||
default_palette(&wb.theme, n.min(PALETTE_CYCLE))
|
||||
};
|
||||
ChartData { categories, category_levels, series, palette }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod explicit_style_palette_tests {
|
||||
use super::*;
|
||||
|
||||
/// Verifies grayscale palette selection and fallback boundaries for explicit styles 1 and 9.
|
||||
#[test]
|
||||
fn explicit_style_palette_boundaries() {
|
||||
let theme = Workbook::default().theme;
|
||||
|
||||
for style in [1, 9] {
|
||||
for count in [0, 17, 255] {
|
||||
for index in [0, 1, 4, 8, 16] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, index, count), series_color(&theme, index));
|
||||
}
|
||||
}
|
||||
|
||||
for (count, expected_first) in [(1, 0x61), (4, 0x61), (5, 0x55), (8, 0x55), (9, 0x4F), (16, 0x4F)] {
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 0, count),
|
||||
[expected_first, expected_first, expected_first, 255],
|
||||
"style {style}, count {count}",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
chart_style_series_color(&theme, style, 16, count),
|
||||
series_color(&theme, 16),
|
||||
"out-of-range index for style {style}, count {count}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for style in [0, 2, 10, 48] {
|
||||
assert_eq!(chart_style_series_color(&theme, style, 0, 4), series_color(&theme, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod label_budget_tests {
|
||||
use gridcraft_model::Workbook;
|
||||
|
||||
@@ -1743,6 +1743,7 @@ fn box_whisker_draws_each_series_quartile_method() {
|
||||
assert!((heights[0] / heights[1] - 1.4).abs() < 0.001);
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets with apostrophes resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
// #2012: `'Bob''s'!Title` kept the doubled quote, so the sheet wasn't found and the series
|
||||
@@ -1780,6 +1781,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_an_apostrophe_resolves() {
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Defined-name series titles on sheets whose names contain `!` resolve properly.
|
||||
#[test]
|
||||
fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
// `'a!b'!Title`: the sheet name holds a `!`, so the evaluator must split the parsed name at
|
||||
@@ -1817,6 +1819,7 @@ fn a_series_named_by_a_name_on_a_sheet_with_a_bang_resolves() {
|
||||
assert_eq!(d.series.first().map(|s| s.name.as_str()), Some("Takings"));
|
||||
}
|
||||
|
||||
/// Volatile functions in series values or names mark the chart as volatile.
|
||||
#[test]
|
||||
fn volatile_series_formulas_are_detected() {
|
||||
let wb = Workbook::new();
|
||||
@@ -1849,6 +1852,7 @@ fn volatile_series_formulas_are_detected() {
|
||||
assert!(!has_volatile_series(&wb, 0, &chart(ChartKind::Line)));
|
||||
}
|
||||
|
||||
/// Defined names referenced by series formulas are followed for volatility checks.
|
||||
#[test]
|
||||
fn volatile_defined_names_are_followed() {
|
||||
let with = |values: &str| {
|
||||
@@ -1913,3 +1917,204 @@ fn volatile_defined_names_are_followed() {
|
||||
assert!(!has_volatile_series(&wb, 1, &with("=Dice")));
|
||||
assert!(has_volatile_series(&wb, 1, &with("=FreshClock")));
|
||||
}
|
||||
|
||||
/// Explicit Excel chart styles should affect default series colours,
|
||||
/// without changing the workbook theme.
|
||||
#[test]
|
||||
fn explicit_chart_styles_use_distinct_default_colors() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.series.push(Series { values: "{10,20,30}".into(), ..Series::default() });
|
||||
|
||||
c.style = 2;
|
||||
let style2 = resolve(&wb, 0, &c).series[0].color;
|
||||
assert_eq!(style2, series_color(&wb.theme, 0));
|
||||
|
||||
c.style = 1;
|
||||
let style1 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
c.style = 9;
|
||||
let style9 = resolve(&wb, 0, &c).series[0].color;
|
||||
|
||||
assert_ne!(style1, style2, "style 1 should differ from style 2");
|
||||
assert_ne!(style9, style2, "style 9 should differ from style 2");
|
||||
}
|
||||
|
||||
/// Excel chart styles must not override explicitly assigned series colours.
|
||||
#[test]
|
||||
fn explicit_chart_styles_preserve_custom_series_colors() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30}".into(), color: Some(Color::rgb(12, 34, 56)), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series[0].color, [12, 34, 56, 255], "explicit series colour changed under chart style {style}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the first four point colours measured in Excel for styles 1 and 9.
|
||||
#[test]
|
||||
fn excel_chart_styles_use_measured_point_palette() {
|
||||
let wb = Workbook::default();
|
||||
let mut c = chart(ChartKind::Pie);
|
||||
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
let expected = [[0x61, 0x61, 0x61, 0xFF], [0xB3, 0xB3, 0xB3, 0xFF], [0x81, 0x81, 0x81, 0xFF], [0x50, 0x50, 0x50, 0xFF]];
|
||||
|
||||
for style in [1, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(&data.palette[..4], &expected);
|
||||
assert_eq!(data.series[0].color, expected[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default-theme chart colours depend on the total series count.
|
||||
#[test]
|
||||
fn excel_chart_styles_depend_on_series_count() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
let base_series = Series { values: "{10,20,30,40}".into(), ..Series::default() };
|
||||
|
||||
let cases: &[(usize, [[u8; 4]; 3])] = &[
|
||||
(6, [[0x55, 0x55, 0x55, 0xFF], [0x9E, 0x9E, 0x9E, 0xFF], [0x72, 0x72, 0x72, 0xFF]]),
|
||||
(12, [[0x4F, 0x4F, 0x4F, 0xFF], [0x93, 0x93, 0x93, 0xFF], [0x6A, 0x6A, 0x6A, 0xFF]]),
|
||||
];
|
||||
|
||||
for (count, expected) in cases {
|
||||
for style in [1, 9] {
|
||||
let mut c = chart(ChartKind::ColumnClustered);
|
||||
c.style = style;
|
||||
c.series = vec![base_series.clone(); *count];
|
||||
|
||||
let data = resolve(&wb, 0, &c);
|
||||
|
||||
assert_eq!(data.series.len(), *count);
|
||||
|
||||
for (i, color) in expected.iter().enumerate() {
|
||||
assert_eq!(data.series[i].color, *color, "style {style}, {count} series, index {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Style 9 uses white outlines on column and bar data rectangles.
|
||||
#[test]
|
||||
fn explicit_style_nine_draws_white_column_outlines() {
|
||||
let wb = Workbook::default();
|
||||
|
||||
for kind in [
|
||||
ChartKind::ColumnClustered,
|
||||
ChartKind::BarClustered,
|
||||
ChartKind::ColumnStacked,
|
||||
ChartKind::BarStacked,
|
||||
ChartKind::ColumnStacked100,
|
||||
ChartKind::BarStacked100,
|
||||
] {
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.series.push(Series { values: "{10,20,30,40}".into(), ..Series::default() });
|
||||
|
||||
for style in [1, 2, 9] {
|
||||
c.style = style;
|
||||
let data = resolve(&wb, 0, &c);
|
||||
let color = data.series[0].color;
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let outlines: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { fill: Some(fill), stroke, .. } if *fill == color => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert!(!outlines.is_empty(), "No data rectangles for {kind:?}, style {style}");
|
||||
|
||||
let expected = if style == 9 { Some(([255, 255, 255, 255], 1.0)) } else { None };
|
||||
|
||||
assert!(outlines.iter().all(|stroke| *stroke == expected), "Unexpected outline for {kind:?}, style {style}: {outlines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Excel's default line weights are 3 pt for style 1 and 5 pt for style 9.
|
||||
/// Other styles retain GridCraft's existing stroke width.
|
||||
#[test]
|
||||
fn explicit_excel_styles_set_line_stroke_width() {
|
||||
let color: Rgba = [17, 73, 131, 255];
|
||||
|
||||
for kind in [ChartKind::Line, ChartKind::LineMarkers, ChartKind::LineStacked] {
|
||||
let data = ChartData {
|
||||
categories: ["Jan", "Feb", "Mar", "Apr"].map(String::from).to_vec(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("North", &[12.0, 19.0, 25.0, 30.0], color, kind)],
|
||||
};
|
||||
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
c.data_labels = false;
|
||||
|
||||
for (style, expected_width) in [(0, 2.25_f32), (1, 3.0), (2, 2.25), (9, 5.0), (48, 2.25)] {
|
||||
c.style = style;
|
||||
|
||||
let prims = render(&c, &data, 640.0, 400.0, &ApproxMeasure);
|
||||
|
||||
let widths: Vec<f32> = prims
|
||||
.iter()
|
||||
.filter_map(|primitive| match primitive {
|
||||
Prim::Line { color: line_color, width, .. } if *line_color == color => Some(*width),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(widths, vec![expected_width], "Unexpected stroke width for {kind:?}, style {style}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrow style 9 bars (at or below the 1 px outline width) omit the white stroke so their gray fill stays visible.
|
||||
#[test]
|
||||
fn narrow_style_9_bars_retain_visible_fill() {
|
||||
let fill_color: Rgba = [0x61, 0x61, 0x61, 0xFF];
|
||||
// Stay within MAX_LABELS (200) so data labels remain active on the direct unmerged path,
|
||||
// while keeping each single-series slot <= 0.88 px inside the 220 px chart.
|
||||
let count = 100usize;
|
||||
let categories: Vec<String> = (0..count).map(|i| format!("C{i}")).collect();
|
||||
let values = vec![50.0; count];
|
||||
|
||||
for kind in [ChartKind::ColumnClustered, ChartKind::BarClustered] {
|
||||
let data = ChartData {
|
||||
categories: categories.clone(),
|
||||
category_levels: vec![],
|
||||
palette: vec![],
|
||||
series: vec![series("S1", &values, fill_color, kind)],
|
||||
};
|
||||
let mut c = chart(kind);
|
||||
c.legend = LegendPos::None;
|
||||
// Data labels keep bars on the unmerged direct path even when narrower than 1 px.
|
||||
c.data_labels = true;
|
||||
c.gridlines = false;
|
||||
c.style = 9;
|
||||
|
||||
let prims = render(&c, &data, 220.0, 220.0, &ApproxMeasure);
|
||||
let narrow_bars: Vec<_> = prims
|
||||
.iter()
|
||||
.filter_map(|p| match p {
|
||||
Prim::Rect { w, h, fill: Some(fill), stroke, .. } if *fill == fill_color && (*w <= 1.0 || *h <= 1.0) => Some(*stroke),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(narrow_bars.len(), count, "Direct unmerged path must emit all {count} bars individually for {kind:?}");
|
||||
assert!(narrow_bars.iter().all(Option::is_none), "Narrow style 9 bars must omit the 1 px white outline: {narrow_bars:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,11 +123,27 @@ pub fn letters_to_col(s: &str) -> Option<u32> {
|
||||
|
||||
/// A rectangular block of cells, inclusive on both ends. Always normalised (`start <= end`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
#[serde(from = "RangeRefFields")]
|
||||
pub struct RangeRef {
|
||||
pub start: CellRef,
|
||||
pub end: CellRef,
|
||||
}
|
||||
|
||||
/// A range as stored (`{start, end}`). A file may hold any numbers there, so loading puts the
|
||||
/// corners in order and on the sheet: `height()` and `width()` subtract them unchecked (#2160).
|
||||
#[derive(Deserialize)]
|
||||
struct RangeRefFields {
|
||||
start: CellRef,
|
||||
end: CellRef,
|
||||
}
|
||||
|
||||
impl From<RangeRefFields> for RangeRef {
|
||||
fn from(r: RangeRefFields) -> Self {
|
||||
let on_sheet = |c: CellRef| CellRef::new(c.row.min(MAX_ROWS - 1), c.col.min(MAX_COLS - 1));
|
||||
RangeRef::new(on_sheet(r.start), on_sheet(r.end))
|
||||
}
|
||||
}
|
||||
|
||||
impl RangeRef {
|
||||
pub fn new(a: CellRef, b: CellRef) -> Self {
|
||||
RangeRef { start: CellRef::new(a.row.min(b.row), a.col.min(b.col)), end: CellRef::new(a.row.max(b.row), a.col.max(b.col)) }
|
||||
@@ -337,6 +353,19 @@ mod tests {
|
||||
assert_eq!(split_areas(""), [""]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loaded_range_is_ordered_and_on_the_sheet() {
|
||||
// #2160: a file can hold any corners; `height()` subtracts them unchecked.
|
||||
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":4000000000,"col":5},"end":{"row":2,"col":1}}"#).unwrap();
|
||||
assert_eq!(r, RangeRef::new(CellRef::new(2, 1), CellRef::new(MAX_ROWS - 1, 5)));
|
||||
assert_eq!((r.height(), r.width()), (MAX_ROWS - 2, 5));
|
||||
let r: RangeRef = serde_json::from_str(r#"{"start":{"row":9,"col":99999},"end":{"row":3,"col":0}}"#).unwrap();
|
||||
assert_eq!(r, RangeRef::new(CellRef::new(3, 0), CellRef::new(9, MAX_COLS - 1)));
|
||||
// What is saved loads back unchanged.
|
||||
let ok = RangeRef::new(CellRef::new(1, 2), CellRef::new(7, 3));
|
||||
assert_eq!(serde_json::from_str::<RangeRef>(&serde_json::to_string(&ok).unwrap()).unwrap(), ok);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_parse_rejects_signed_rows() -> Result<(), std::io::Error> {
|
||||
assert!(RangeRef::parse("+1:+3").is_none());
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Arithmetic that follows Excel's bits rather than IEEE's: the snap to zero.
|
||||
|
||||
/// 2^-49: the snap threshold is this fraction of the left operand's binade.
|
||||
const SNAP: f64 = 1.0 / 562_949_953_421_312.0;
|
||||
|
||||
/// The power of two at the bottom of `x`'s binade (`x` with its mantissa cleared); 0 for zero,
|
||||
/// subnormal and non-finite values.
|
||||
fn binade(x: f64) -> f64 {
|
||||
if x.is_finite() { f64::from_bits(x.to_bits() & 0x7FF0_0000_0000_0000) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// `x + y` as Excel computes it at the root of a formula or as the last addition of a `SUM`:
|
||||
/// when the operands have opposite signs and `|x + y| < 2^(e-49)`, `e` the binary exponent of
|
||||
/// the LEFT operand `x`, the result is exactly 0. A subtraction passes `-y`.
|
||||
///
|
||||
/// Excel does this only at those places, not at every add or subtract (observed on Windows Excel 16.0.20430; see
|
||||
/// `EXCEL-BEHAVIOUR.md` of the Spreadsheet Accuracy Suite, "The snap to zero").
|
||||
pub fn snap_add(x: f64, y: f64) -> f64 {
|
||||
let s = x + y;
|
||||
let opposite = (x > 0.0 && y < 0.0) || (x < 0.0 && y > 0.0);
|
||||
if opposite && s.abs() < binade(x) * SNAP { 0.0 } else { s }
|
||||
}
|
||||
|
||||
/// The sum of `values` left to right, each addition rounded, with the LAST addition snapped.
|
||||
/// This is `SUM`'s arithmetic: `SUM(a, -b)` is 0 for a near-cancellation, but `SUM(a, -b, 0)` keeps
|
||||
/// the residue because its last addition is residue + 0.
|
||||
pub fn sum_snapped(values: &[f64]) -> f64 {
|
||||
let Some((last, head)) = values.split_last() else { return 0.0 };
|
||||
snap_add(head.iter().fold(0.0, |acc, v| acc + v), *last)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ULP1: f64 = f64::EPSILON;
|
||||
|
||||
#[test]
|
||||
fn snaps_below_two_to_the_e_minus_49_of_the_left_operand() {
|
||||
assert_eq!(snap_add(1.0, -(1.0 + ULP1)), 0.0);
|
||||
assert_eq!(snap_add(1.0, -(1.0 + 7.0 * ULP1)), 0.0);
|
||||
// Exactly 2^-49 (8 ulps of 1.0) does not snap.
|
||||
assert_eq!(snap_add(1.0, -(1.0 + 8.0 * ULP1)), -8.0 * ULP1);
|
||||
// The left operand's binade decides (observed on Windows Excel 16.0.20430, excel-probe-4.00044 to 00046):
|
||||
// 0.4999999999999998 - 0.5000000000000002 keeps -4.44e-16 (threshold 2^-51 is not beaten),
|
||||
// the other way round it is 0 (threshold 2^-50).
|
||||
assert_eq!(snap_add(0.4999999999999998, -0.5000000000000002), -4.440892098500626e-16);
|
||||
assert_eq!(snap_add(0.5000000000000002, -0.4999999999999998), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_snaps_same_sign_zero_or_hostile_operands() {
|
||||
assert_eq!(snap_add(1e-20, 2e-20), 1e-20 + 2e-20);
|
||||
assert_eq!(snap_add(3.0, 0.0), 3.0);
|
||||
assert_eq!(snap_add(0.0, -1e-300), -1e-300);
|
||||
// A subnormal left operand has no binade to measure against: it never snaps.
|
||||
assert_eq!(snap_add(5e-324, -1e-323), -5e-324);
|
||||
assert!(snap_add(f64::INFINITY, -f64::INFINITY).is_nan());
|
||||
assert_eq!(snap_add(-1.0, 1.0 + ULP1), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_snaps_only_its_last_addition() {
|
||||
assert_eq!(sum_snapped(&[]), 0.0);
|
||||
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1)]), 0.0);
|
||||
assert_eq!(sum_snapped(&[1.0, -(1.0 + ULP1), 0.0]), 1.0 - (1.0 + ULP1));
|
||||
assert_eq!(sum_snapped(&[3.0, 1e16, -1e16, 0.0]), 4.0);
|
||||
// Left to right, each addition rounded: ten 0.1s do not make 1.
|
||||
assert_eq!(sum_snapped(&[0.1; 10]), 0.999_999_999_999_999_9);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod addr;
|
||||
pub mod arith;
|
||||
pub mod color;
|
||||
pub mod date;
|
||||
pub mod parse;
|
||||
|
||||
@@ -103,6 +103,10 @@ impl fmt::Display for CellError {
|
||||
}
|
||||
|
||||
/// A 2-D array of values (row-major). Always at least 1×1.
|
||||
///
|
||||
/// Indexing assumes `data` holds `rows × cols` values. Loading doesn't check that (the fields are
|
||||
/// public, so a file can say anything): whoever loads values from a file checks them with
|
||||
/// [`Value::is_well_formed`] and repairs what fails (#2160).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Array {
|
||||
pub rows: usize,
|
||||
@@ -208,6 +212,23 @@ impl From<Array> for Value {
|
||||
}
|
||||
|
||||
impl Value {
|
||||
/// Whether every array in this value, including arrays nested in another array's values, is
|
||||
/// at least 1×1 and holds exactly `rows × cols` values, as indexing assumes. Values built in
|
||||
/// code always are; values loaded from a file may not be (#2160). Walks without recursion,
|
||||
/// so a deeply nested value can't overflow the stack.
|
||||
pub fn is_well_formed(&self) -> bool {
|
||||
let mut pending = vec![self];
|
||||
while let Some(v) = pending.pop() {
|
||||
if let Value::Array(a) = v {
|
||||
if a.rows == 0 || a.cols == 0 || a.rows.checked_mul(a.cols) != Some(a.data.len()) {
|
||||
return false;
|
||||
}
|
||||
pending.extend(a.data.iter().filter(|x| matches!(x, Value::Array(_))));
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A number, or `#NUM!` when it is NaN or infinite (Excel never stores those).
|
||||
pub fn number(v: f64) -> Value {
|
||||
if v.is_finite() { Value::Number(if v == 0.0 { 0.0 } else { v }) } else { Value::Error(CellError::Num) }
|
||||
@@ -530,6 +551,27 @@ pub fn cap_value(v: Value) -> Value {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_loaded_array_is_checked_by_is_well_formed() {
|
||||
// #2160: indexing assumes `data.len() == rows * cols`. A file can say otherwise; loading
|
||||
// keeps what it says and `is_well_formed` tells the loader to repair it.
|
||||
let number = |n: f64| Value::Number(n);
|
||||
let loaded = |json: &str| serde_json::from_str::<Value>(json).unwrap();
|
||||
for bad in [
|
||||
r#"{"t":"Array","v":{"rows":3,"cols":2,"data":[{"t":"Number","v":1.0}]}}"#,
|
||||
r#"{"t":"Array","v":{"rows":0,"cols":1,"data":[]}}"#,
|
||||
r#"{"t":"Array","v":{"rows":18446744073709551615,"cols":2,"data":[]}}"#,
|
||||
// Nested in a well-formed array.
|
||||
r#"{"t":"Array","v":{"rows":1,"cols":2,"data":[{"t":"Number","v":1.0},{"t":"Array","v":{"rows":2,"cols":2,"data":[]}}]}}"#,
|
||||
] {
|
||||
assert!(!loaded(bad).is_well_formed(), "{bad}");
|
||||
}
|
||||
let ok = Value::from(Array::new(1, 2, vec![number(1.0), Value::from(Array::scalar(number(2.0)))]).unwrap());
|
||||
let back = loaded(&serde_json::to_string(&ok).unwrap());
|
||||
assert_eq!(back, ok, "what is saved loads back unchanged");
|
||||
assert!(back.is_well_formed() && number(1.0).is_well_formed() && Value::Empty.is_well_formed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_text() {
|
||||
assert_eq!(number_to_text(1.0), "1");
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "gridcraft-dax"
|
||||
# A first release of this crate, not the workspace release line: nothing depends on a published
|
||||
# version of it yet, and 0.1.0 says what it is — new.
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "GridCraft DAX language: lexer, Pratt parser, syntax tree and canonical printer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# Calendar arithmetic (date serials, month lengths, leap years) goes through chrono on every
|
||||
# target, as AGENTS.md requires. The web build has no clock and uses the fixed fallback in
|
||||
# `eval/support.rs`, but the date types it needs build for wasm too (`gridcraft-core` does the
|
||||
# same with the same workspace dependency).
|
||||
chrono = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# The browser clock for NOW/TODAY under wasm, the same dependency `crates/core` uses: the standard
|
||||
# library clock traps there, and `eval/support.rs` would otherwise freeze at 1970.
|
||||
js-sys = "0.3"
|
||||
|
||||
[[example]]
|
||||
name = "parse"
|
||||
# Cargo does not test examples by default; this one carries assertions on the query-to-expression
|
||||
# fallback, so it has to run under `cargo test`.
|
||||
test = true
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,430 @@
|
||||
# gridcraft-dax
|
||||
|
||||
The DAX language for GridCraft: a tokenizer, a Pratt parser, a syntax tree, a canonical printer,
|
||||
the function catalog for every dax.guide category with static call validation, the static type surface (types,
|
||||
literals, inference and operator result tables), the full DAX statement/query grammar, a model
|
||||
evaluator, a columnar model store and a model-backed PivotTable renderer. It has no dependency on
|
||||
the GridCraft engine.
|
||||
|
||||
```rust
|
||||
use gridcraft_dax::{ParseError, parse_expression, print_expression};
|
||||
|
||||
fn main() -> Result<(), ParseError> {
|
||||
let expr = parse_expression("1 + 2 * 3")?;
|
||||
assert_eq!(print_expression(&expr), "1 + 2 * 3");
|
||||
|
||||
let query = gridcraft_dax::parse_query(
|
||||
"DEFINE MEASURE Sales[Margin] = [Sales Amount] - [Total Cost] EVALUATE Sales ORDER BY [Margin] DESC",
|
||||
)?;
|
||||
assert!(gridcraft_dax::print_query(&query).starts_with("DEFINE\n MEASURE Sales[Margin] ="));
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Public API
|
||||
|
||||
| Item | Meaning |
|
||||
| --- | --- |
|
||||
| `parse_expression(&str) -> Result<Expr, ParseError>` | Parse one expression. One leading `=` (as typed in some editors) is accepted and ignored. |
|
||||
| `print_expression(&Expr) -> String` | Canonical text. |
|
||||
| `parse_query(&str) -> Result<Query, ParseError>` | Parse a query: optional `DEFINE`, then one or more `EVALUATE` statements. `EVALUATE <expr>` alone keeps working. |
|
||||
| `print_query(&Query) -> String` | Canonical multi-line query text. |
|
||||
| `tokenize(&str) -> Result<Vec<Token>, LexError>` | Tokens with byte spans, including `Eof`. |
|
||||
| `ParseError { message, span }` / `LexError { message, span }` | `Display + std::error::Error`; the lexer error converts with `From`. |
|
||||
| `ast::{Expr, ExprKind, Literal, DateTimeLiteral, Name, NameRef, NameStyle, Call, UnaryOp, BinaryOp, Span}` | Expression syntax tree. |
|
||||
| `ast::{Query, Define, Definition, MeasureDef, ColumnDef, TableDef, VarDef, FunctionDef, MParameterDef}` | Query/`DEFINE` tree. |
|
||||
| `ast::{Evaluate, OrderItem, StartValue, SortDirection}` | `EVALUATE`, `ORDER BY` and `START AT`. |
|
||||
| `ast::{FunctionParam, ParameterType, ParameterSubtype, PassingMode}` | `FUNCTION` parameters and annotations. |
|
||||
| `ast::{VisualShape, Axis, AxisKind, AxisGroup, AxisOrderItem}` | `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`. |
|
||||
| `functions::{catalog, lookup}` | Every catalogued function, looked up case-insensitively. |
|
||||
| `functions::{FunctionSpec, FunctionCategory, ParamKind, ReturnType, BlankPolicy, FunctionFlags, Parameter, Overload}` | Catalog record types. |
|
||||
| `validate_call(&Call) -> Vec<ValidationError>` | Arity/kind checks for one call; empty for valid or unknown functions. |
|
||||
| `validate_expression(&Expr) -> Vec<ValidationError>` | Walks the tree and reports every invalid known-function call with its span. |
|
||||
| `types::{DataType, PseudoType, InferredType, TypeMetadata, TypeError}` | The eight DAX types, the BLANK/Table pseudo-types, inference results and static type errors. |
|
||||
| `types::{literal_type, infer_type, unary_type, binary_type, arithmetic_type, comparison_coercion, comparison_compatible, comparison_type}` | Literal classification, static inference and the documented operator/coercion tables. |
|
||||
| `model::{DataModel, ModelTable, ModelColumn, Measure, Relationship, parse_measure}` | Metadata + inline-row model, formula parsing and name validation. |
|
||||
| `binder::{Binder, BoundExpr, BoundMeasure, bind_formula}` | Name/measure/column resolution, dependency graph and cycle rejection. |
|
||||
| `eval::{Evaluator, FilterContext}` | Expression/measure evaluator over `DataModel`; a catalogued function whose family is not linked reports "not implemented". |
|
||||
| `pivot::{pivot, pivot_cross, pivot_fields}` | Row/column grouping helpers. |
|
||||
| `pivot_table::PivotTable` | Power Pivot-style row/column/filter/value layout with subtotals and grand totals. |
|
||||
| `storage::{ModelStorage, TableStorage, ColumnStorage, ColumnData}` | Columnar, dictionary-encoded model store with filter/aggregate/relationship indexes. |
|
||||
| `MAX_INPUT_LEN` (8192 bytes, expressions) / `MAX_QUERY_LEN` (1 MiB, queries) / `MAX_DEPTH` (256) | Limits enforced with errors. |
|
||||
|
||||
### Syntax tree
|
||||
|
||||
```text
|
||||
Expr { kind: ExprKind, span: Span }
|
||||
ExprKind =
|
||||
Literal(Literal) Integer(i64) | Decimal(f64)
|
||||
| DateTime(DateTimeLiteral)
|
||||
| String(String) | Boolean(bool)
|
||||
| Name(NameRef) table: Option<Name>, name: Name
|
||||
| Call(Call) name: Name, args: Vec<Expr>
|
||||
| Unary { op, expr } op: UnaryOp (Plus | Neg | Not)
|
||||
| Binary { op, left, right } op: BinaryOp
|
||||
| Table(Vec<Expr>) { value, ... }
|
||||
| Tuple(Vec<Expr>) (value, ...)
|
||||
| VarReturn { vars, body } VAR a = 1 ... RETURN body
|
||||
|
||||
Query { define: Option<Define>, evaluates: Vec<Evaluate> }
|
||||
Define { items: Vec<Definition> }
|
||||
Definition =
|
||||
Measure(MeasureDef) name: NameRef, expr: Expr
|
||||
| Column(ColumnDef) name: NameRef, expr: Expr
|
||||
| Table(TableDef) name: Name, expr: Expr, visual_shape: Option<VisualShape>
|
||||
| Var(VarDef) name: Name, expr: Expr
|
||||
| Function(FunctionDef) name: Name, params: Vec<FunctionParam>, body: Expr
|
||||
| MParameter(MParameterDef) name: Name, expr: Expr
|
||||
|
||||
Evaluate { table: Expr, order_by: Vec<OrderItem>, start_at: Vec<StartValue> }
|
||||
OrderItem { expr: Expr, direction: SortDirection }
|
||||
StartValue = Literal(Literal) | Parameter(Name) -- @name
|
||||
FunctionParam { name, ty, subtype, passing, default }
|
||||
VisualShape { axes: Vec<Axis>, densify: Option<String> }
|
||||
Axis { kind: AxisKind (Rows | Columns), groups: Vec<AxisGroup>, order_by: Vec<AxisOrderItem> }
|
||||
AxisGroup { columns: Vec<NameRef>, total: NameRef }
|
||||
AxisOrderItem { column: NameRef, direction: SortDirection }
|
||||
```
|
||||
|
||||
`Span` is a half-open byte range into the source. `Expr::walk` visits nodes depth-first with an
|
||||
explicit stack. `Expr` equality compares `ExprKind` only: spans are ignored, so
|
||||
`parse(print(e)) == e` for every expression the parser produces.
|
||||
|
||||
`Name` keeps the source spelling and quoting style (`Bare`, `Quoted`, `Bracketed`); the printer
|
||||
reproduces that style. A `NameRef` is a table-qualified reference (`'Sales'[Amount]`) or an
|
||||
unqualified name (`[Amount]`, `Total`, `'Sales'`). `Call` also keeps the spelling (`Sum` stays
|
||||
`Sum`).
|
||||
|
||||
Parentheses are grouping, not AST nodes. A parenthesised comma list is a `Tuple`; inside
|
||||
`{ ... }` those tuples are the rows of a `Table`.
|
||||
|
||||
## Grammar
|
||||
|
||||
```text
|
||||
expression := prefix (binary_operator prefix)* -- precedence-climbing, see the table
|
||||
prefix := "+" prefix | "-" prefix | NOT prefix | primary
|
||||
primary := INTEGER | DECIMAL | STRING | TRUE | FALSE
|
||||
| dt STRING -- validated date/time literal
|
||||
| name
|
||||
| name "(" [ expression ("," expression)* ] ")"
|
||||
| table-qualified-name
|
||||
| "(" expression ")"
|
||||
| "(" expression "," expression ("," expression)* ")"
|
||||
| "{" [ expression ("," expression)* ] "}"
|
||||
| VAR var_name "=" expression { VAR var_name "=" expression } RETURN expression
|
||||
name := IDENT | "[" column "]" | "'" table "'"
|
||||
qualified := (IDENT | "'" table "'") "[" column "]"
|
||||
|
||||
query := [ define ] evaluate { evaluate } [ ";" ]
|
||||
define := DEFINE definition { definition }
|
||||
definition := MEASURE table '[' name ']' "=" expression
|
||||
| COLUMN table '[' name ']' "=" expression
|
||||
| TABLE table_name "=" expression [ visual_shape ]
|
||||
| VAR var_name "=" expression
|
||||
| FUNCTION function_name "=" "(" [ param { "," param } ] ")" "=>" expression
|
||||
| MPARAMETER mparameter_name "=" expression
|
||||
param := param_name [ ":" [ type ] [ subtype ] [ passing_mode ] ] [ "=" expression ]
|
||||
evaluate := EVALUATE expression [ order_by ] [ start_at ]
|
||||
order_by := ORDER BY order_item { "," order_item }
|
||||
order_item := expression [ ASC | DESC ]
|
||||
start_at := START AT start_value { "," start_value }
|
||||
start_value := literal | [ "+" | "-" ] number | "@" name
|
||||
visual_shape := WITH VISUAL SHAPE axis { axis } [ DENSIFY STRING ]
|
||||
axis := AXIS ( ROWS | COLUMNS )
|
||||
group { group }
|
||||
ORDER BY column_ref [ ASC | DESC ] { "," column_ref [ ASC | DESC ] }
|
||||
group := GROUP column_ref { "," column_ref } TOTAL column_ref
|
||||
column_ref := "[" name "]" | table "[" name "]"
|
||||
```
|
||||
|
||||
Statement keywords are matched case-insensitively. There are no statement terminators in the
|
||||
documented grammar: `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `FUNCTION`, `MPARAMETER` and the
|
||||
`EVALUATE` token bound definition bodies and separate statements, so no newline is needed.
|
||||
One or more trailing `;` are accepted as a recovery extension. The `DEFINE` block is optional but
|
||||
requires at least one entry and must be followed by at least one `EVALUATE`. Duplicate definition
|
||||
names and forward/backward references are accepted; resolution is a semantic concern.
|
||||
|
||||
The shape above is illustrative: the Pratt parser applies the precedence and associativity
|
||||
table below rather than a fixed grammar cascade.
|
||||
|
||||
`*` is not a wildcard token: it is only the multiplication operator.
|
||||
|
||||
### Statements
|
||||
|
||||
- `EVALUATE` takes any table expression. `ORDER BY` sorts the result and defaults to `ASC`;
|
||||
`START AT` requires `ORDER BY`, takes literals or `@parameter` references, and may not have
|
||||
more values than `ORDER BY` items.
|
||||
- `DEFINE MEASURE`/`COLUMN` names are `<table>[<name>]`; `TABLE`, `FUNCTION` and `MPARAMETER`
|
||||
names are bare or single-quoted. `VAR` names are bare only. A query-scoped `VAR` has no
|
||||
`RETURN`; an expression-level `VAR ... RETURN ...` requires one. `RETURN` without a preceding
|
||||
`VAR` is an error.
|
||||
- `FUNCTION` parameters may declare a type (`ANYVAL`, `SCALAR`, `TABLE`, `ANYREF`,
|
||||
`CALENDARREF`, `COLUMNREF`, `MEASUREREF`, `TABLEREF`), a scalar subtype (`BOOLEAN`,
|
||||
`DATETIME`, `DECIMAL`, `DOUBLE`, `INT64`, `NUMERIC`, `STRING`, `VARIANT`), a passing mode
|
||||
(`VAL`/`EXPR`) and a default expression. Only `SCALAR` (or an omitted type) accepts a subtype.
|
||||
- `WITH VISUAL SHAPE` is valid only as the suffix of a `DEFINE TABLE`. It needs one or two axes
|
||||
(`AXIS ROWS`, `AXIS COLUMNS`, no duplicates), each with at least one `GROUP ... TOTAL` level
|
||||
and an `ORDER BY` list. `DENSIFY "column"` is optional and last, and takes a double-quoted
|
||||
string, not a bracketed reference. `AXIS ROWPAGES` is not part of the grammar.
|
||||
- `MPARAMETER` is the Power BI dynamic M-parameter binding and is accepted as a `DEFINE` entry
|
||||
even though Microsoft's `DEFINE` grammar omits it.
|
||||
|
||||
### Case and escapes
|
||||
|
||||
- Keywords (`NOT`, `IN`, `EVALUATE`, `TRUE`, `FALSE`, and every statement keyword) are
|
||||
case-insensitive. `TRUE`/`FALSE` are literals unless followed by `(` (then they are calls to a
|
||||
function of that name). The printer writes statement keywords uppercase and keeps identifier
|
||||
spelling.
|
||||
- Bare identifiers keep their spelling. Function names may contain `.` (`STDEV.P`).
|
||||
- Single-quoted table identifiers double an embedded quote: `'It''s'`.
|
||||
- Bracketed columns double an embedded `]`: `[A]]B]`.
|
||||
- String literals double an embedded quote: `"a""b"`.
|
||||
- Number literals are typed: a digit-only literal is an `Integer` (`42`, parsed as `i64`), while
|
||||
a decimal point or exponent is a `Decimal` (`3.14`, `.5`, `1.`, `1e3`, `1.5E-3`, parsed as
|
||||
`f64`). The sign is the unary operator, never part of the token. Values must be finite; an
|
||||
integer that does not fit `i64`, or a decimal that overflows `f64`, is a lexer error with a
|
||||
span. `Decimal` printing always keeps a decimal point or exponent (`1000.0`, `1e-6`) so the
|
||||
text re-lexes as a `Decimal`.
|
||||
- Date/time literals are `dt"YYYY-MM-DD"`, `dt"YYYY-MM-DDThh:mm:ss"` and
|
||||
`dt"YYYY-MM-DD hh:mm:ss"`. The `dt` prefix is matched case-insensitively but must be adjacent
|
||||
to the quote; the printer emits lowercase `dt` and padded components. Unpadded month/day/time
|
||||
components are accepted (`dt"2015-1-9T2:3:0"`). Timezone offsets, fractional seconds,
|
||||
time-only forms, wrong-case `t`, and invalid calendar dates (including non-leap `1900-02-29`)
|
||||
are lexer errors.
|
||||
- `BLANK` is an ordinary identifier. `BLANK()` is a zero-argument call; there is no BLANK literal.
|
||||
- Comments: `// line`, `-- line`, and `/* block */` (blocks do not nest).
|
||||
|
||||
## Operators
|
||||
|
||||
Precedence from the operator table (tighter first); operators of equal precedence evaluate left to
|
||||
right, including `^`:
|
||||
|
||||
| Level | Operators | Associativity |
|
||||
| --- | --- | --- |
|
||||
| 1 | grouping `()`, function calls | — |
|
||||
| 2 | `^` | left |
|
||||
| 3 | unary `+`, `-` | prefix |
|
||||
| 4 | `*`, `/` | left |
|
||||
| 5 | binary `+`, `-` | left |
|
||||
| 6 | `&` | left |
|
||||
| 7 | `=`, `==`, `<>`, `<`, `>`, `<=`, `>=`, `IN` | left |
|
||||
| 8 | `NOT` | prefix |
|
||||
| 9 | `&&` | left |
|
||||
| 10 | `\|\|` | left |
|
||||
|
||||
`=` coerces types at evaluation time; `==` is strict equality. This crate only records which
|
||||
operator was written. `IN` is a comparison at the same level as `=`, so `1 + 2 IN { 3 }` parses as
|
||||
`(1 + 2) IN { 3 }`, and it takes a list (`expr IN { v1, v2 }`) or a table expression
|
||||
(`expr IN VALUES(T[Col])`).
|
||||
|
||||
Microsoft's operator reference states that operators of equal precedence are ordered from left to
|
||||
right, and `^` shares no tier with another operator, so a chain groups left: `2^3^2` is `(2^3)^2` =
|
||||
64, the value Excel and Power Pivot produce as well. Unary minus binds looser than `^`: `-2^2` parses
|
||||
as `-(2^2)`.
|
||||
|
||||
## Data types and static inference
|
||||
|
||||
`types::DataType` is exactly the eight dax.guide types: `Binary`, `Boolean`, `Currency`,
|
||||
`DateTime`, `Decimal`, `Integer`, `String`, `Variant`. `PseudoType` adds the two Microsoft DAX
|
||||
types that are not in that list, `Blank` and `Table`; they are inference results, not
|
||||
`DataType` variants. Each type (including the pseudo-types) has a `TypeMetadata` row with its
|
||||
internal representation, literal syntax (or `None`), range, precision and notes. Literal
|
||||
availability is `Boolean`, `DateTime`, `Decimal`, `Integer`, `String`; `Binary`, `Currency` and
|
||||
`Variant` have no literal, and neither does BLANK (`BLANK()` is a function).
|
||||
|
||||
`literal_type(&Literal)` maps a literal to its `DataType`. `infer_type(&Expr) ->
|
||||
Result<InferredType, TypeError>` infers literals, unary `+`/`-`/`NOT`, binary operators,
|
||||
`TRUE()`/`FALSE()`/`BLANK()` calls, table constructors, and every catalogued function's documented
|
||||
`ReturnType` (`Table` for table functions, `Blank` for BLANK, `Unknown` for `Any`/unknown names).
|
||||
Name references still return `InferredType::Unknown` because they need the model. `Unknown` is not
|
||||
a DAX type; it is the absence of static information.
|
||||
|
||||
The arithmetic and comparison result tables are transcribed from the published DAX operator
|
||||
reference for `Integer`, `Currency`, `Decimal` ("Real") and `DateTime`:
|
||||
`arithmetic_type` implements `+`, `-`, `*`, `/` and `^` (a double). The quirks are preserved
|
||||
rather than normalised: `Integer * DateTime -> Integer`, `Currency * Currency -> Decimal`,
|
||||
`DateTime - DateTime -> DateTime`, and a `DateTime` on the left of `*` has no published row and is
|
||||
a `TypeError`. `&` yields `String`; `&&`, `||`, comparisons and `IN` yield `Boolean`; unary `+`
|
||||
and `-` preserve the numeric type. `Variant` propagates, and BLANK stays polymorphic (for example
|
||||
`BLANK() + 5` is `Integer` while `BLANK() * 5` is `Blank`).
|
||||
|
||||
`comparison_coercion` models `=`, `<>` and ordering: BLANK is coerced to `0`, `""` or `FALSE` for
|
||||
the other operand's type, and String/Boolean compared with a numeric type is a `TypeError` (the
|
||||
engine errors; dax.guide also documents a conflicting type rank). `comparison_compatible` and
|
||||
`comparison_type` also cover `==`, which is strict and does not coerce BLANK. Excel's embedded
|
||||
engine rejects `==` altogether, but dax.guide documents it and this crate parses it.
|
||||
|
||||
This is static typing only. Text-to-number/date/Boolean parsing, BLANK substitution and truth
|
||||
tables, `5/BLANK()` (Infinity), `0/BLANK()` (NaN), Currency rounding, runtime integer overflow,
|
||||
IEEE equality and string collation belong to the evaluator. The module documentation lists the
|
||||
documented conflicts (Currency/Integer endpoints, the DateTime minimum, mixed-type comparisons,
|
||||
and `dt` literal engine support) instead of hiding them behind one total order.
|
||||
|
||||
## Limits, errors and printing
|
||||
|
||||
Expressions are capped at 8192 bytes, queries at 1 MiB, and expression nesting at 256 levels; each
|
||||
limit produces an error, never a stack overflow. The printer and `Expr::walk` use explicit stacks, and
|
||||
the parser's binary loop is iterative, so a left-associated chain does not recurse — but the chain
|
||||
still grows the tree one level per operator, and the depth check applies to it: a flat
|
||||
`1 + 1 + ... + 1` with more than about 256 terms is rejected as too deeply nested (asserted for a
|
||||
1,000-term chain in `src/tests.rs`). Long generated `&&`, `||` or `&` chains hit the same limit.
|
||||
|
||||
Numeric literal overflow (an integer outside `i64`, or a decimal outside finite `f64`) and invalid
|
||||
date/time literals are lexer errors with the literal's span. Errors carry `message` and a byte
|
||||
`span`; `Display` includes both. The canonical printer uses
|
||||
spaces around binary operators, `, ` between arguments/items, and adds parentheses only where
|
||||
precedence or associativity requires them. Re-parsing canonical text yields the same AST.
|
||||
|
||||
`print_query` prints `DEFINE` entries indented one level, each following `EVALUATE` on its own
|
||||
line with indented `ORDER BY`/`START AT` clauses, and visual-shape axes, groups and `DENSIFY`
|
||||
indented under their `TABLE`. The simple `EVALUATE <expression>` form stays on one line, so
|
||||
`print_query(parse_query("EVALUATE 1 + 2"))` is still `EVALUATE 1 + 2`. An expression-level
|
||||
`VAR ... RETURN ...` prints on one line and is parenthesised when it is an operand, because it
|
||||
binds looser than every operator. All printing remains iterative.
|
||||
|
||||
## Function catalog
|
||||
|
||||
`functions::catalog()` returns every function of every
|
||||
[dax.guide function category](https://dax.guide/functions/), in category order. Each
|
||||
`FunctionSpec` records the exact arity, parameter kinds, overloads (including variadic
|
||||
functions), return type, iterator/volatile/not-recommended/Excel flags, description and
|
||||
parseable examples. Each record carries its descriptive signature (`params`, with `optional`
|
||||
markers), exact `overloads` (fixed or variadic), `return_type`, `flags` (`iterator`, `volatile`,
|
||||
`not_recommended`, `excel_compatible`, `direct_query_limited`), `sugar_of`, `blank_policy`,
|
||||
`description` and `examples`. Every example in the catalog parses with `parse_expression`.
|
||||
|
||||
Descriptions and examples are original summaries written for GridCraft. Microsoft's DAX function
|
||||
documentation is a behavioural reference only: no sentence, definition or sample argument list is
|
||||
copied from it (or from dax.guide, which republishes Microsoft's wording). Write what the function
|
||||
returns, what its arguments mean and which edge case it handles, in the project's own voice.
|
||||
|
||||
| Category | Functions |
|
||||
| --- | ---: |
|
||||
| Aggregation | 22 |
|
||||
| Date and Time | 24 |
|
||||
| Filter | 29 |
|
||||
| Financial | 51 |
|
||||
| Information | 114 |
|
||||
| Logical | 13 |
|
||||
| Math and Trig | 49 |
|
||||
| Other | 16 |
|
||||
| Parent-child | 5 |
|
||||
| Relationship management | 4 |
|
||||
| Statistical | 43 |
|
||||
| Table manipulation | 35 |
|
||||
| Text | 23 |
|
||||
| Time Intelligence | 45 |
|
||||
| Visual calculations | 11 |
|
||||
| **Total** | **484** |
|
||||
|
||||
| Function | Arity | Iterator | Sugar of | Blank | Excel | Notes |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| `APPROXIMATEDISTINCTCOUNT` | 1 | no | — | BLANK | no | HyperLogLog / DirectQuery pushdown; column reference only. |
|
||||
| `AVERAGE` | 1 | no | `AVERAGEX` | unspecified | yes | Ignores blanks, includes zero; sources disagree on the empty/all-blank result. |
|
||||
| `AVERAGEA` | 1 | no | — | unspecified | yes | Booleans are 1/0, any text is 0 and a BLANK cell is 0 in the denominator (Microsoft's 22/5 example); dax.guide marks it not recommended. |
|
||||
| `AVERAGEX` | 2 | yes | — | BLANK | yes | Row context; blanks ignored, zeros included; empty set observed BLANK. |
|
||||
| `COUNT` | 1 | no | `COUNTX` | BLANK | yes | Counts numbers, dates and strings; empty strings count, booleans do not. |
|
||||
| `COUNTA` | 1 | no | `COUNTAX` | BLANK | yes | Counts non-blank values including booleans. |
|
||||
| `COUNTAX` | 2 | yes | — | BLANK | yes | Row context; booleans count. |
|
||||
| `COUNTBLANK` | 1 | no | — | unspecified | yes | Empty string counts as blank; dax.guide says never 0, Microsoft Learn says 0 when rows exist. |
|
||||
| `COUNTROWS` | 0–1 | no | — | BLANK | yes\* | \*The zero-argument form is rejected by Excel's embedded engine; pass a table there. |
|
||||
| `COUNTX` | 2 | yes | — | BLANK | yes | Row context; booleans are not counted. |
|
||||
| `DISTINCTCOUNT` | 1 | no | — | BLANK | yes | BLANK is one distinct value; totals are non-additive. |
|
||||
| `DISTINCTCOUNTNOBLANK` | 1 | no | `DISTINCTCOUNT` | unspecified | no | Excludes BLANK; rejected by Excel's embedded engine. |
|
||||
| `MAX` | 1–2 | no | `MAXX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars treat BLANK as significant per dax.guide, as 0 per Microsoft Learn. |
|
||||
| `MAXA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
|
||||
| `MAXX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY DESC`. |
|
||||
| `MIN` | 1–2 | no | `MINX`\* | unspecified | yes | \*Only the one-argument column overload is sugar. Two scalars have the same BLANK conflict as `MAX`. |
|
||||
| `MINA` | 1 | no | — | unspecified | yes | TRUE/FALSE become 1/0; empty result conflicts across sources. |
|
||||
| `MINX` | 2–3 | yes | — | unspecified | yes | Optional third `Variant` compares mixed types per `ORDER BY ASC`. |
|
||||
| `PRODUCT` | 1 | no | `PRODUCTX` | BLANK | yes | Multiplies numeric cells, ignoring blanks, logical values and text. |
|
||||
| `PRODUCTX` | 2 | yes | — | BLANK | yes | Row context; ignores blank results, unlike the `*` operator. |
|
||||
| `SUM` | 1 | no | `SUMX` | BLANK | yes | Adds numeric cells, ignoring blanks, logical values and text. |
|
||||
| `SUMX` | 2 | yes | — | BLANK | yes | Row context; blanks, logical values and text ignored. |
|
||||
|
||||
`AVERAGEA`, `MAXA` and `MINA` use the X function internally but are not pure sugar: their
|
||||
boolean/text coercions differ, so `sugar_of` is `None`. `direct_query_limited` is `true` for all
|
||||
22 functions because Microsoft Learn excludes them from calculated columns and RLS rules in
|
||||
DirectQuery mode; `APPROXIMATEDISTINCTCOUNT` still supports DirectQuery pushdown in measures.
|
||||
|
||||
### Blank policies
|
||||
|
||||
- `BlankWhenEmpty` — the result is BLANK when there are no rows or no qualifying value. Used
|
||||
where dax.guide and the observed engine agree, including the observed empty-set results of
|
||||
`SUMX`, `AVERAGEX`, `COUNTX` and `PRODUCTX`.
|
||||
- `Unspecified` — dax.guide and Microsoft Learn disagree, or the sources are silent. This is
|
||||
deliberate: the catalog does not pick a winner for `AVERAGE`/`AVERAGEA`, `COUNTBLANK`,
|
||||
`MAX`/`MIN`/`MAXA`/`MINA` or `MAXX`/`MINX`.
|
||||
- `ZeroWhenRowsButNoMatch` — documents the Microsoft Learn rule. No function uses it today
|
||||
because no engine observation supported it; it stays in the enum for a future evaluator that
|
||||
needs to model the conflicting rule explicitly.
|
||||
|
||||
### Static validation
|
||||
|
||||
`validate_expression` walks the AST and reports every argument-count or argument-kind error for a
|
||||
catalogued function. Spans point at the offending argument for kind errors and at the whole call
|
||||
for arity errors; unknown functions are ignored but their arguments are still visited.
|
||||
|
||||
A `ParamKind::Column` argument must be a bracketed `NameRef` (`Sales[Amount]` or `[Amount]`), so
|
||||
`SUM ( 1 )` and `AVERAGE ( 1 + 1 )` are rejected. A `ParamKind::Table` argument is rejected when
|
||||
it is certainly not a table — a literal, an operator expression or a bracketed column reference —
|
||||
so `COUNTROWS ( 1 )` and `COUNTROWS ( Sales[Amount] )` fail while
|
||||
`COUNTROWS ( DISTINCT ( Sales[Region] ) )`, table variables and `{ 1, 2 }` are accepted.
|
||||
`COUNTROWS ()` is valid in the catalog (the Excel limitation is recorded on the function, not
|
||||
enforced here). `Date`, `Text`, `Number`, `Boolean`, `Function`, `Reference`, `Json`, `Variant`,
|
||||
`Expression`, `Scalar`, `Logical` and `Any` are not statically decidable: DAX's implicit
|
||||
coercions need the model, so they are recorded for documentation and future type checking only.
|
||||
Variadic overloads repeat their last parameter kind for every additional argument; the third
|
||||
`Variant` argument of `MAXX`/`MINX` accepts any expression.
|
||||
|
||||
## Model, binder and evaluator
|
||||
|
||||
`model::DataModel` is the metadata + inline-row view used by the binder and evaluator. JSON shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"tables": [{"name": "Sales", "columns": [{"name": "Region"}, {"name": "Amount"}],
|
||||
"rows": [["East", 10], ["West", 20]]}],
|
||||
"relationships": [],
|
||||
"measures": [{"name": "Total Sales", "formula": "SUM(Sales[Amount])", "table": "Sales"}]
|
||||
}
|
||||
```
|
||||
|
||||
`DataModel::parse_formulas` parses each measure and validates table/column/relationship names.
|
||||
`Binder::bind_expression` resolves `Table[Column]`, measures, variables and function calls;
|
||||
`Binder::bind_measure` and `Binder::dependency_graph` expose direct measure dependencies and reject
|
||||
cycles. `Evaluator::new` pre-binds the measures and evaluates scalar or table expressions with a
|
||||
`FilterContext`; `pivot::pivot` groups a measure by row fields.
|
||||
|
||||
The evaluator's core switch implements the scalar spine — literals, operators, `VAR`/`RETURN`,
|
||||
context transition, `CALCULATE`/`FILTER`/`ALL`/`VALUES`/`DISTINCT`/`SELECTEDVALUE`, the
|
||||
aggregations and their `*X` iterators, and the logical functions that need lazy arguments — over
|
||||
a columnar store (`storage`: typed columns, dictionary strings, null bitmaps, relationship
|
||||
indexes). `Evaluator::new` materializes the store once and uses it for filters, aggregates,
|
||||
`VALUES`/`DISTINCT`, `COUNTROWS` and `RELATED*` when `ModelStorage::is_faithful` holds; other
|
||||
models keep the row scan. The remaining catalogued functions arrive in family modules under
|
||||
`src/eval/`, one module per family, each registering itself through the evaluator's dispatch
|
||||
array; a family that is not linked reports the catalogued call as not implemented.
|
||||
|
||||
## Extending in later PRs
|
||||
|
||||
- Statement semantics (name resolution, duplicate-name shadowing, `START AT` value types,
|
||||
function overloading and recursion rules, visual-shape evaluation) are not checked here; the
|
||||
parser accepts what the grammar accepts. Query-defined tables/columns and `MPARAMETER` are
|
||||
engine-specific, and the crate records them without validating a model.
|
||||
- `Call`, `NameRef` and `NameStyle` keep spelling/quoting so catalog and type work can resolve
|
||||
names without re-lexing.
|
||||
- `types::infer_type` resolves every catalogued call through its documented `ReturnType`, plus
|
||||
literals, operators, `TRUE()`/`FALSE()`/`BLANK()` and `VAR`/`RETURN` blocks. `InferredType::Unknown`
|
||||
remains for names and functions whose return type is `Any`/unknown.
|
||||
- The binder resolves tables, columns, measures, variables and documented keyword parameters.
|
||||
Each evaluator family ships with its own integration suite under `tests/eval_*.rs`.
|
||||
|
||||
## Example
|
||||
|
||||
```sh
|
||||
cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
|
||||
cargo run -p gridcraft-dax --example parse -- "EVALUATE SUM('Sales'[Amount])"
|
||||
cargo run -p gridcraft-dax --example parse -- "DEFINE MEASURE Sales[M] = SUM(Sales[Amount]) EVALUATE Sales ORDER BY [M] DESC"
|
||||
echo 'NOT TRUE || FALSE && TRUE' | cargo run -p gridcraft-dax --example parse
|
||||
```
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Parse DAX from the command line (or stdin), print its syntax tree and canonical text.
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo run -p gridcraft-dax --example parse -- "1 + 2 * 3"
|
||||
//! echo "EVALUATE SUM('Sales'[Amount])" | cargo run -p gridcraft-dax --example parse
|
||||
//! ```
|
||||
|
||||
use std::io::{self, Read};
|
||||
|
||||
use gridcraft_dax::{TokenKind, parse_expression, parse_query, print_expression, print_query, tokenize};
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut text = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
|
||||
if text.trim().is_empty() {
|
||||
io::stdin().read_to_string(&mut text)?;
|
||||
}
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err("no DAX expression supplied; pass it as an argument or on stdin".into());
|
||||
}
|
||||
print!("{}", render(text)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parses and renders one input. Queries are preferred; when the query parser fails, a valid
|
||||
/// expression is still accepted (`DEFINE` is a legal bare name), and the query diagnostic is kept
|
||||
/// only when both parsers fail for input that starts with a query keyword.
|
||||
fn render(text: &str) -> Result<String, String> {
|
||||
match parse_query(text) {
|
||||
Ok(query) => Ok(format!("Query\n{query:#?}\nCanonical: {}\n", print_query(&query))),
|
||||
Err(query_error) => {
|
||||
let expr = match parse_expression(text) {
|
||||
Ok(expr) => expr,
|
||||
Err(expr_error) => {
|
||||
if starts_with_query_keyword(text) {
|
||||
return Err(query_error.to_string());
|
||||
}
|
||||
return Err(expr_error.to_string());
|
||||
}
|
||||
};
|
||||
Ok(format!("AST\n{expr:#?}\nCanonical: {}\n", print_expression(&expr)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn starts_with_query_keyword(text: &str) -> bool {
|
||||
tokenize(text).is_ok_and(|tokens| match tokens.first().map(|token| &token.kind) {
|
||||
Some(TokenKind::Evaluate) => true,
|
||||
Some(TokenKind::Ident(word)) => word.eq_ignore_ascii_case("DEFINE"),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn query_only_keywords_stay_on_the_query_parser() {
|
||||
assert!(starts_with_query_keyword("EVALUATE Sales"));
|
||||
assert!(starts_with_query_keyword("DEFINE MEASURE Sales[M] = 1 EVALUATE Sales"));
|
||||
assert!(starts_with_query_keyword(" define measure Sales[M] = 1"));
|
||||
assert!(!starts_with_query_keyword("SUM(Sales[Amount])"));
|
||||
// `DEFINE` alone is a valid expression, so the expression parser wins.
|
||||
assert!(render("DEFINE").expect("bare name expression").starts_with("AST"));
|
||||
let error = render("DEFINE MEASURE").expect_err("malformed query");
|
||||
assert!(error.contains("measure name"), "{error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
//! DAX syntax tree.
|
||||
//!
|
||||
//! Every expression node carries a [`Span`] in byte offsets into the source text. Statement
|
||||
//! nodes (`DEFINE` entries, `EVALUATE`, `ORDER BY`, visual shapes) group expressions and names.
|
||||
//! [`Expr`] equality deliberately ignores spans (`PartialEq` compares [`ExprKind`] only), which
|
||||
//! makes the parser/printer round-trip invariant expressible as `parse(print(e)) == e`.
|
||||
|
||||
/// A half-open byte range `start..end` into the source text.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Span {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
pub const fn new(start: usize, end: usize) -> Self {
|
||||
Span { start, end }
|
||||
}
|
||||
|
||||
/// An empty span at byte offset 0.
|
||||
pub const fn empty() -> Self {
|
||||
Span { start: 0, end: 0 }
|
||||
}
|
||||
|
||||
pub const fn len(self) -> usize {
|
||||
self.end.saturating_sub(self.start)
|
||||
}
|
||||
|
||||
pub const fn is_empty(self) -> bool {
|
||||
self.start >= self.end
|
||||
}
|
||||
|
||||
/// The smallest span covering both operands.
|
||||
pub fn to(self, other: Span) -> Span {
|
||||
Span { start: self.start.min(other.start), end: self.end.max(other.end) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dt"..."` date/time literal.
|
||||
///
|
||||
/// Components are validated when the literal is lexed. The `has_time` flag distinguishes
|
||||
/// `dt"2023-05-19"` from `dt"2023-05-19T00:00:00"`, which are different literal forms even
|
||||
/// though they denote the same serial value.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct DateTimeLiteral {
|
||||
pub year: u32,
|
||||
pub month: u32,
|
||||
pub day: u32,
|
||||
pub hour: u32,
|
||||
pub minute: u32,
|
||||
pub second: u32,
|
||||
pub has_time: bool,
|
||||
}
|
||||
|
||||
impl DateTimeLiteral {
|
||||
/// Canonical `YYYY-MM-DD` / `YYYY-MM-DDThh:mm:ss` text, without the `dt` prefix or quotes.
|
||||
pub fn canonical(self) -> String {
|
||||
format!("{self}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DateTimeLiteral {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)?;
|
||||
if self.has_time {
|
||||
write!(f, "T{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A DAX literal value.
|
||||
///
|
||||
/// Integer and Decimal are distinct literal kinds (not one numeric kind): `42` is an
|
||||
/// [`Literal::Integer`] and `42.0`, `42e0` are [`Literal::Decimal`] values. The sign of a
|
||||
/// negative number is the unary `-` operator, never part of the literal.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Literal {
|
||||
/// A 64-bit signed integer literal such as `42`.
|
||||
Integer(i64),
|
||||
/// An IEEE-754 double literal written with a decimal point or exponent: `3.14`, `.5`, `1e3`.
|
||||
Decimal(f64),
|
||||
/// A `dt"..."` literal.
|
||||
DateTime(DateTimeLiteral),
|
||||
String(String),
|
||||
Boolean(bool),
|
||||
}
|
||||
|
||||
/// How an identifier was written, so the printer can reproduce it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum NameStyle {
|
||||
/// `Sales`
|
||||
Bare,
|
||||
/// `'Sales Table'`
|
||||
Quoted,
|
||||
/// `[Amount]`
|
||||
Bracketed,
|
||||
}
|
||||
|
||||
/// A single identifier, preserving its source spelling and quoting style.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Name {
|
||||
/// Text with quoting removed and doubled quote/bracket escapes resolved.
|
||||
pub text: String,
|
||||
pub style: NameStyle,
|
||||
}
|
||||
|
||||
impl Name {
|
||||
pub fn bare(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Bare }
|
||||
}
|
||||
|
||||
pub fn quoted(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Quoted }
|
||||
}
|
||||
|
||||
pub fn bracketed(text: impl Into<String>) -> Self {
|
||||
Name { text: text.into(), style: NameStyle::Bracketed }
|
||||
}
|
||||
}
|
||||
|
||||
/// A name, optionally table-qualified: `'Sales'[Amount]`, `Sales[Amount]` or `[Amount]`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct NameRef {
|
||||
/// Table part of a column/measure reference.
|
||||
pub table: Option<Name>,
|
||||
pub name: Name,
|
||||
}
|
||||
|
||||
impl NameRef {
|
||||
pub fn unqualified(name: Name) -> Self {
|
||||
NameRef { table: None, name }
|
||||
}
|
||||
|
||||
pub fn qualified(table: Name, name: Name) -> Self {
|
||||
NameRef { table: Some(table), name }
|
||||
}
|
||||
}
|
||||
|
||||
/// A function call. The name keeps the spelling used in the source (`Sum`, `SUM`).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Call {
|
||||
pub name: Name,
|
||||
pub args: Vec<Expr>,
|
||||
}
|
||||
|
||||
/// Prefix operators. `Not` is the keyword operator, not a function call.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum UnaryOp {
|
||||
Plus,
|
||||
Neg,
|
||||
Not,
|
||||
}
|
||||
|
||||
impl UnaryOp {
|
||||
/// Binding power, higher binds tighter (DAX precedence levels 3 and 8).
|
||||
pub const fn precedence(self) -> u8 {
|
||||
match self {
|
||||
UnaryOp::Plus | UnaryOp::Neg => 80,
|
||||
UnaryOp::Not => 30,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
UnaryOp::Plus => "+",
|
||||
UnaryOp::Neg => "-",
|
||||
UnaryOp::Not => "NOT",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary operators, in the precedence order of <https://dax.guide/operators/>.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Pow,
|
||||
Concat,
|
||||
Eq,
|
||||
StrictEq,
|
||||
Ne,
|
||||
Lt,
|
||||
Gt,
|
||||
Le,
|
||||
Ge,
|
||||
And,
|
||||
Or,
|
||||
In,
|
||||
}
|
||||
|
||||
impl BinaryOp {
|
||||
pub const fn symbol(self) -> &'static str {
|
||||
match self {
|
||||
BinaryOp::Add => "+",
|
||||
BinaryOp::Sub => "-",
|
||||
BinaryOp::Mul => "*",
|
||||
BinaryOp::Div => "/",
|
||||
BinaryOp::Pow => "^",
|
||||
BinaryOp::Concat => "&",
|
||||
BinaryOp::Eq => "=",
|
||||
BinaryOp::StrictEq => "==",
|
||||
BinaryOp::Ne => "<>",
|
||||
BinaryOp::Lt => "<",
|
||||
BinaryOp::Gt => ">",
|
||||
BinaryOp::Le => "<=",
|
||||
BinaryOp::Ge => ">=",
|
||||
BinaryOp::And => "&&",
|
||||
BinaryOp::Or => "||",
|
||||
BinaryOp::In => "IN",
|
||||
}
|
||||
}
|
||||
|
||||
/// Binding power, higher binds tighter. The values encode the ten precedence levels
|
||||
/// from the operator table: parentheses/calls, `^`, unary sign, `* /`, `+ -`, `&`,
|
||||
/// comparisons (including `IN`), `NOT`, `&&`, `||`.
|
||||
pub const fn precedence(self) -> u8 {
|
||||
match self {
|
||||
BinaryOp::Pow => 90,
|
||||
BinaryOp::Mul | BinaryOp::Div => 70,
|
||||
BinaryOp::Add | BinaryOp::Sub => 60,
|
||||
BinaryOp::Concat => 50,
|
||||
// `IN` is a comparison, at the same tier as `=`/`<` (Microsoft's operator table).
|
||||
BinaryOp::In | BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => 40,
|
||||
BinaryOp::And => 20,
|
||||
BinaryOp::Or => 10,
|
||||
}
|
||||
}
|
||||
|
||||
/// DAX binary operators all associate to the left. Microsoft's operator reference puts `^` in
|
||||
/// its own precedence tier and states that operators of equal precedence are ordered from left
|
||||
/// to right, so `2^3^2` is `(2^3)^2` = 64 — the same value Excel and Power Pivot produce.
|
||||
pub const fn is_left_associative(self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub const fn is_right_associative(self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub const fn is_comparison(self) -> bool {
|
||||
matches!(self, BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge)
|
||||
}
|
||||
|
||||
pub const fn is_logical(self) -> bool {
|
||||
matches!(self, BinaryOp::And | BinaryOp::Or)
|
||||
}
|
||||
}
|
||||
|
||||
/// The shape of an expression, without its span.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ExprKind {
|
||||
Literal(Literal),
|
||||
/// A bare, quoted or table-qualified name.
|
||||
Name(NameRef),
|
||||
/// `SUM(1, 2)`.
|
||||
Call(Call),
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
expr: Box<Expr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
/// A table constructor `{ 1, 2 }`. Rows are [`ExprKind::Tuple`] values.
|
||||
Table(Vec<Expr>),
|
||||
/// A row constructor / parenthesised comma list `(1, "a")`.
|
||||
Tuple(Vec<Expr>),
|
||||
/// An expression-level `VAR <name> = <expr> ... RETURN <expr>` block.
|
||||
VarReturn {
|
||||
vars: Vec<VarDecl>,
|
||||
body: Box<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
/// One `VAR <name> = <expression>` declaration inside an [`ExprKind::VarReturn`].
|
||||
///
|
||||
/// The name is a plain identifier: DAX variable names cannot be quoted or bracketed. Declarations
|
||||
/// are sequential, so `nameN` is visible only to `expressionN+1` and to the `RETURN` body.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VarDecl {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// A DAX expression with its source span.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Expr {
|
||||
pub kind: ExprKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Expr {
|
||||
pub fn new(kind: ExprKind, span: Span) -> Self {
|
||||
Expr { kind, span }
|
||||
}
|
||||
|
||||
pub fn literal(value: Literal, span: Span) -> Self {
|
||||
Expr::new(ExprKind::Literal(value), span)
|
||||
}
|
||||
|
||||
/// The tree depth (a leaf is 1), computed iteratively so it is safe on any shape the
|
||||
/// parser accepts. The parser uses this to bound the AST that recursive `Debug`,
|
||||
/// `PartialEq` and drop glue would otherwise walk.
|
||||
pub fn depth(&self) -> usize {
|
||||
let mut max = 0;
|
||||
let mut stack = vec![(self, 1usize)];
|
||||
while let Some((node, depth)) = stack.pop() {
|
||||
max = max.max(depth);
|
||||
match &node.kind {
|
||||
ExprKind::Call(call) => stack.extend(call.args.iter().map(|e| (e, depth + 1))),
|
||||
ExprKind::Unary { expr, .. } => stack.push((expr, depth + 1)),
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
stack.push((right, depth + 1));
|
||||
stack.push((left, depth + 1));
|
||||
}
|
||||
ExprKind::Table(items) | ExprKind::Tuple(items) => {
|
||||
stack.extend(items.iter().map(|e| (e, depth + 1)));
|
||||
}
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
stack.push((body, depth + 1));
|
||||
stack.extend(vars.iter().map(|var| (&var.expr, depth + 1)));
|
||||
}
|
||||
ExprKind::Literal(_) | ExprKind::Name(_) => {}
|
||||
}
|
||||
}
|
||||
max
|
||||
}
|
||||
|
||||
/// Visits every node depth-first, parents before children. Iterative, so deeply nested
|
||||
/// (but within the parser limits) trees cannot overflow the stack.
|
||||
pub fn walk<'a>(&'a self, f: &mut dyn FnMut(&'a Expr)) {
|
||||
let mut stack = vec![self];
|
||||
while let Some(node) = stack.pop() {
|
||||
f(node);
|
||||
match &node.kind {
|
||||
ExprKind::Call(call) => stack.extend(call.args.iter().rev()),
|
||||
ExprKind::Unary { expr, .. } => stack.push(expr),
|
||||
ExprKind::Binary { left, right, .. } => {
|
||||
stack.push(right);
|
||||
stack.push(left);
|
||||
}
|
||||
ExprKind::Table(items) | ExprKind::Tuple(items) => stack.extend(items.iter().rev()),
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
stack.push(body);
|
||||
stack.extend(vars.iter().rev().map(|var| &var.expr));
|
||||
}
|
||||
ExprKind::Literal(_) | ExprKind::Name(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Spans do not participate in equality: reparsing printed text produces the same AST.
|
||||
impl PartialEq for Expr {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.kind == other.kind
|
||||
}
|
||||
}
|
||||
|
||||
/// A complete DAX query: an optional `DEFINE` block followed by one or more `EVALUATE`
|
||||
/// statements.
|
||||
///
|
||||
/// A query always has at least one [`Evaluate`]; the parser rejects `DEFINE` without a following
|
||||
/// `EVALUATE`. For the simple form `EVALUATE <expression>` the `define` field is `None` and
|
||||
/// `evaluates` holds exactly one entry with no clauses.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Query {
|
||||
pub define: Option<Define>,
|
||||
pub evaluates: Vec<Evaluate>,
|
||||
}
|
||||
|
||||
/// The `DEFINE` block of a query. One block applies to every `EVALUATE` statement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Define {
|
||||
pub items: Vec<Definition>,
|
||||
}
|
||||
|
||||
/// One entry of a `DEFINE` block.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Definition {
|
||||
Measure(MeasureDef),
|
||||
Column(ColumnDef),
|
||||
Table(TableDef),
|
||||
Var(VarDef),
|
||||
Function(FunctionDef),
|
||||
MParameter(MParameterDef),
|
||||
}
|
||||
|
||||
/// `MEASURE <table>[<measure>] = <scalar expression>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MeasureDef {
|
||||
pub name: NameRef,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `COLUMN <table>[<column>] = <scalar expression>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColumnDef {
|
||||
pub name: NameRef,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `VAR <name> = <expression>` in a `DEFINE` block. Unlike an expression-level
|
||||
/// [`ExprKind::VarReturn`], a query-scoped variable has no `RETURN`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VarDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// `TABLE <name> = <table expression> [WITH VISUAL SHAPE ...]`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TableDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
pub visual_shape: Option<VisualShape>,
|
||||
}
|
||||
|
||||
/// `MPARAMETER <name> = <expression>`: a Power BI dynamic M parameter binding.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MParameterDef {
|
||||
pub name: Name,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
/// A query-defined function: `FUNCTION <name> = (<param>, ...) => <body>`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FunctionDef {
|
||||
pub name: Name,
|
||||
pub params: Vec<FunctionParam>,
|
||||
pub body: Expr,
|
||||
}
|
||||
|
||||
/// One parameter of a [`FunctionDef`].
|
||||
///
|
||||
/// Every annotation is optional: `p`, `p : INT64`, `p : SCALAR INT64 VAL` and `p = 1` are all
|
||||
/// valid parameter declarations.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FunctionParam {
|
||||
pub name: Name,
|
||||
pub ty: Option<ParameterType>,
|
||||
pub subtype: Option<ParameterSubtype>,
|
||||
pub passing: Option<PassingMode>,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
/// The DAX user-defined-function parameter types.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParameterType {
|
||||
AnyVal,
|
||||
Scalar,
|
||||
Table,
|
||||
AnyRef,
|
||||
CalendarRef,
|
||||
ColumnRef,
|
||||
MeasureRef,
|
||||
TableRef,
|
||||
}
|
||||
|
||||
impl ParameterType {
|
||||
/// The canonical uppercase keyword.
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
ParameterType::AnyVal => "ANYVAL",
|
||||
ParameterType::Scalar => "SCALAR",
|
||||
ParameterType::Table => "TABLE",
|
||||
ParameterType::AnyRef => "ANYREF",
|
||||
ParameterType::CalendarRef => "CALENDARREF",
|
||||
ParameterType::ColumnRef => "COLUMNREF",
|
||||
ParameterType::MeasureRef => "MEASUREREF",
|
||||
ParameterType::TableRef => "TABLEREF",
|
||||
}
|
||||
}
|
||||
|
||||
/// Recognises a type keyword case-insensitively.
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
Some(match word.to_ascii_uppercase().as_str() {
|
||||
"ANYVAL" => ParameterType::AnyVal,
|
||||
"SCALAR" => ParameterType::Scalar,
|
||||
"TABLE" => ParameterType::Table,
|
||||
"ANYREF" => ParameterType::AnyRef,
|
||||
"CALENDARREF" => ParameterType::CalendarRef,
|
||||
"COLUMNREF" => ParameterType::ColumnRef,
|
||||
"MEASUREREF" => ParameterType::MeasureRef,
|
||||
"TABLEREF" => ParameterType::TableRef,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The scalar subtypes, which are only valid together with [`ParameterType::Scalar`] (or alone,
|
||||
/// as in the documented `p : INT64` shorthand).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParameterSubtype {
|
||||
Boolean,
|
||||
DateTime,
|
||||
Decimal,
|
||||
Double,
|
||||
Int64,
|
||||
Numeric,
|
||||
String,
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ParameterSubtype {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
ParameterSubtype::Boolean => "BOOLEAN",
|
||||
ParameterSubtype::DateTime => "DATETIME",
|
||||
ParameterSubtype::Decimal => "DECIMAL",
|
||||
ParameterSubtype::Double => "DOUBLE",
|
||||
ParameterSubtype::Int64 => "INT64",
|
||||
ParameterSubtype::Numeric => "NUMERIC",
|
||||
ParameterSubtype::String => "STRING",
|
||||
ParameterSubtype::Variant => "VARIANT",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
Some(match word.to_ascii_uppercase().as_str() {
|
||||
"BOOLEAN" => ParameterSubtype::Boolean,
|
||||
"DATETIME" => ParameterSubtype::DateTime,
|
||||
"DECIMAL" => ParameterSubtype::Decimal,
|
||||
"DOUBLE" => ParameterSubtype::Double,
|
||||
"INT64" => ParameterSubtype::Int64,
|
||||
"NUMERIC" => ParameterSubtype::Numeric,
|
||||
"STRING" => ParameterSubtype::String,
|
||||
"VARIANT" => ParameterSubtype::Variant,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// How a function argument is passed: `VAL` (eagerly) or `EXPR` (lazily).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PassingMode {
|
||||
Val,
|
||||
Expr,
|
||||
}
|
||||
|
||||
impl PassingMode {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
PassingMode::Val => "VAL",
|
||||
PassingMode::Expr => "EXPR",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_keyword(word: &str) -> Option<Self> {
|
||||
match word.to_ascii_uppercase().as_str() {
|
||||
"VAL" => Some(PassingMode::Val),
|
||||
"EXPR" => Some(PassingMode::Expr),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `EVALUATE <table expression> [ORDER BY ...] [START AT ...]` statement.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Evaluate {
|
||||
pub table: Expr,
|
||||
pub order_by: Vec<OrderItem>,
|
||||
pub start_at: Vec<StartValue>,
|
||||
}
|
||||
|
||||
/// One item of a query-level `ORDER BY` clause.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OrderItem {
|
||||
pub expr: Expr,
|
||||
pub direction: SortDirection,
|
||||
}
|
||||
|
||||
/// The sort direction of an `ORDER BY` item. An omitted direction parses as
|
||||
/// [`SortDirection::Asc`], and the printer writes the keyword explicitly.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum SortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
impl SortDirection {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
SortDirection::Asc => "ASC",
|
||||
SortDirection::Desc => "DESC",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_ascending(self) -> bool {
|
||||
matches!(self, SortDirection::Asc)
|
||||
}
|
||||
}
|
||||
|
||||
/// One value of a `START AT` clause: a constant or an XMLA `@parameter` reference.
|
||||
///
|
||||
/// Start values are constants, not expressions. A sign in front of a numeric literal is folded
|
||||
/// into the literal (`START AT -1`); everything else must be a literal or `@name`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum StartValue {
|
||||
Literal(Literal),
|
||||
Parameter(Name),
|
||||
}
|
||||
|
||||
/// The `WITH VISUAL SHAPE` clause of a query-defined table.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct VisualShape {
|
||||
pub axes: Vec<Axis>,
|
||||
/// The optional `DENSIFY "<column>"` clause, always last.
|
||||
pub densify: Option<String>,
|
||||
}
|
||||
|
||||
/// One `AXIS ROWS` / `AXIS COLUMNS` clause of a visual shape.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Axis {
|
||||
pub kind: AxisKind,
|
||||
pub groups: Vec<AxisGroup>,
|
||||
pub order_by: Vec<AxisOrderItem>,
|
||||
}
|
||||
|
||||
/// The axis of a visual shape. Only these two are documented.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum AxisKind {
|
||||
Rows,
|
||||
Columns,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
pub const fn keyword(self) -> &'static str {
|
||||
match self {
|
||||
AxisKind::Rows => "ROWS",
|
||||
AxisKind::Columns => "COLUMNS",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `GROUP <column>, ... TOTAL <column>` level of an axis.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AxisGroup {
|
||||
pub columns: Vec<NameRef>,
|
||||
pub total: NameRef,
|
||||
}
|
||||
|
||||
/// One column of an axis `ORDER BY` clause.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AxisOrderItem {
|
||||
pub column: NameRef,
|
||||
pub direction: SortDirection,
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Name binding for DAX expressions and measures.
|
||||
//!
|
||||
//! The binder resolves table names, `Table[Column]` references, measures and expression-level
|
||||
//! `VAR` names against a [`DataModel`]. It validates catalogued function calls with the same
|
||||
//! arity/kind rules as [`crate::validate`], and builds the measure dependency graph.
|
||||
//!
|
||||
//! It is deliberately static: row context and filter context are evaluator concerns. A bracketed
|
||||
//! column that is not qualified by a table is left as [`BoundExpr::UnqualifiedColumn`] so the
|
||||
//! evaluator can resolve it from the current row context.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use crate::ast::{BinaryOp, Literal, NameRef, UnaryOp};
|
||||
use crate::model::DataModel;
|
||||
use crate::{Call, Expr, ExprKind, FunctionSpec, ParamKind, lookup, parse_expression, validate_call};
|
||||
|
||||
/// A name-resolution error with the source span.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct BindError {
|
||||
pub message: String,
|
||||
pub span: crate::Span,
|
||||
}
|
||||
|
||||
impl BindError {
|
||||
fn new(message: impl Into<String>, span: crate::Span) -> Self {
|
||||
BindError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
/// The bound form of an expression.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum BoundExpr {
|
||||
Literal(Literal),
|
||||
/// A resolved `Table[Column]` reference.
|
||||
Column {
|
||||
table: usize,
|
||||
column: usize,
|
||||
},
|
||||
/// `[Column]` without a table qualifier: resolved from the evaluator's row context.
|
||||
UnqualifiedColumn {
|
||||
name: String,
|
||||
},
|
||||
/// A model measure reference.
|
||||
Measure(usize),
|
||||
/// A table reference.
|
||||
Table(usize),
|
||||
/// A catalogued function call with bound arguments.
|
||||
Call {
|
||||
spec: &'static FunctionSpec,
|
||||
args: Vec<BoundExpr>,
|
||||
},
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
expr: Box<BoundExpr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<BoundExpr>,
|
||||
right: Box<BoundExpr>,
|
||||
},
|
||||
/// `{ value, ... }`.
|
||||
TableConstructor(Vec<BoundExpr>),
|
||||
/// `( value, ... )`.
|
||||
Tuple(Vec<BoundExpr>),
|
||||
/// A variable reference.
|
||||
///
|
||||
/// `index` is the variable's absolute slot in the cumulative stack of every enclosing
|
||||
/// [`BoundExpr::VarReturn`] block — outer blocks first, each block appending its own
|
||||
/// declarations in order — not its position inside the innermost `vars` list. The evaluator
|
||||
/// pushes each block's values onto the same stack, so the index stays valid across nesting.
|
||||
Variable {
|
||||
index: usize,
|
||||
name: String,
|
||||
},
|
||||
/// A function-specific keyword argument (`DAY` in `DATEDIFF`, a type name in `DATATABLE`).
|
||||
Keyword(String),
|
||||
/// `VAR name = expr ... RETURN body`.
|
||||
VarReturn {
|
||||
vars: Vec<BoundVariable>,
|
||||
body: Box<BoundExpr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BoundVariable {
|
||||
pub name: String,
|
||||
pub expr: BoundExpr,
|
||||
}
|
||||
|
||||
/// A bound measure with its direct measure dependencies.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BoundMeasure {
|
||||
pub name: String,
|
||||
pub expr: BoundExpr,
|
||||
pub dependencies: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Binds expressions against one model.
|
||||
pub struct Binder<'a> {
|
||||
model: &'a DataModel,
|
||||
}
|
||||
|
||||
impl<'a> Binder<'a> {
|
||||
pub fn new(model: &'a DataModel) -> Self {
|
||||
Binder { model }
|
||||
}
|
||||
|
||||
pub fn model(&self) -> &'a DataModel {
|
||||
self.model
|
||||
}
|
||||
|
||||
/// Binds an expression with no variables in scope.
|
||||
pub fn bind_expression(&self, expr: &Expr) -> Result<BoundExpr, BindError> {
|
||||
self.bind_with_vars(expr, &mut Vec::new())
|
||||
}
|
||||
|
||||
/// Parses and binds a measure formula. The model's measures must have been prepared with
|
||||
/// [`DataModel::parse_formulas`].
|
||||
pub fn bind_measure(&self, name: &str) -> Result<BoundMeasure, BindError> {
|
||||
let index = self.model.measure_index(name).ok_or_else(|| BindError::new(format!("unknown measure `{name}`"), crate::Span::empty()))?;
|
||||
let measure = &self.model.measures[index];
|
||||
if measure.expr.is_none() {
|
||||
return Err(BindError::new(
|
||||
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
|
||||
crate::Span::empty(),
|
||||
));
|
||||
}
|
||||
let Some(formula) = measure.expr.as_ref() else {
|
||||
return Err(BindError::new(
|
||||
format!("measure `{}` has no parsed formula; call DataModel::parse_formulas", measure.name),
|
||||
crate::Span::empty(),
|
||||
));
|
||||
};
|
||||
let expr = self.bind_expression(formula)?;
|
||||
let mut dependencies = BTreeSet::new();
|
||||
collect_measure_names(self.model, &expr, &mut dependencies);
|
||||
Ok(BoundMeasure { name: measure.name.clone(), expr, dependencies })
|
||||
}
|
||||
|
||||
/// Builds the direct measure dependency graph and rejects cycles.
|
||||
pub fn dependency_graph(&self) -> Result<BTreeMap<String, BTreeSet<String>>, BindError> {
|
||||
let mut graph = BTreeMap::new();
|
||||
for measure in &self.model.measures {
|
||||
let bound = self.bind_measure(&measure.name)?;
|
||||
graph.insert(bound.name, bound.dependencies);
|
||||
}
|
||||
let mut state: BTreeMap<String, u8> = BTreeMap::new();
|
||||
for name in graph.keys() {
|
||||
self.visit(name, &graph, &mut state)?;
|
||||
}
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
fn visit(&self, name: &str, graph: &BTreeMap<String, BTreeSet<String>>, state: &mut BTreeMap<String, u8>) -> Result<(), BindError> {
|
||||
// Iterative: a measure chain comes from the model JSON, so its length must not grow the
|
||||
// call stack (a long chain would otherwise abort the process instead of returning an error).
|
||||
if state.get(name).copied() == Some(2) {
|
||||
return Ok(());
|
||||
}
|
||||
let empty = BTreeSet::new();
|
||||
state.insert(name.to_string(), 1);
|
||||
let mut stack: Vec<(&str, std::collections::btree_set::Iter<'_, String>)> = vec![(name, graph.get(name).unwrap_or(&empty).iter())];
|
||||
while let Some((current, dependencies)) = stack.last_mut() {
|
||||
match dependencies.next() {
|
||||
Some(dependency) => match state.get(dependency.as_str()).copied() {
|
||||
Some(2) => {}
|
||||
Some(1) => {
|
||||
return Err(BindError::new(format!("circular measure dependency involving `{dependency}`"), crate::Span::empty()));
|
||||
}
|
||||
_ => {
|
||||
state.insert(dependency.clone(), 1);
|
||||
stack.push((dependency.as_str(), graph.get(dependency).unwrap_or(&empty).iter()));
|
||||
}
|
||||
},
|
||||
None => {
|
||||
state.insert((*current).to_string(), 2);
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn bind_with_vars(&self, expr: &Expr, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
|
||||
match &expr.kind {
|
||||
ExprKind::Literal(literal) => Ok(BoundExpr::Literal(literal.clone())),
|
||||
ExprKind::Name(name) => self.bind_name(name, expr.span, vars),
|
||||
ExprKind::Call(call) => self.bind_call(call, expr.span, vars),
|
||||
ExprKind::Unary { op, expr: inner } => Ok(BoundExpr::Unary { op: *op, expr: Box::new(self.bind_with_vars(inner, vars)?) }),
|
||||
ExprKind::Binary { op, left, right } => Ok(BoundExpr::Binary {
|
||||
op: *op,
|
||||
left: Box::new(self.bind_with_vars(left, vars)?),
|
||||
right: Box::new(self.bind_with_vars(right, vars)?),
|
||||
}),
|
||||
ExprKind::Table(items) => {
|
||||
Ok(BoundExpr::TableConstructor(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?))
|
||||
}
|
||||
ExprKind::Tuple(items) => Ok(BoundExpr::Tuple(items.iter().map(|item| self.bind_with_vars(item, vars)).collect::<Result<_, _>>()?)),
|
||||
ExprKind::VarReturn { vars: declarations, body } => {
|
||||
let mut bound = Vec::with_capacity(declarations.len());
|
||||
let mut names = vars.clone();
|
||||
for declaration in declarations {
|
||||
let value = self.bind_with_vars(&declaration.expr, &mut names)?;
|
||||
names.push(declaration.name.text.clone());
|
||||
bound.push(BoundVariable { name: declaration.name.text.clone(), expr: value });
|
||||
}
|
||||
let body = self.bind_with_vars(body, &mut names)?;
|
||||
Ok(BoundExpr::VarReturn { vars: bound, body: Box::new(body) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_name(&self, name: &NameRef, span: crate::Span, vars: &[String]) -> Result<BoundExpr, BindError> {
|
||||
if let Some(table) = &name.table {
|
||||
let table_index = self.model.table_index(&table.text).ok_or_else(|| BindError::new(format!("unknown table `{}`", table.text), span))?;
|
||||
if let Some(column_index) = self.model.column_index(table_index, &name.name.text) {
|
||||
return Ok(BoundExpr::Column { table: table_index, column: column_index });
|
||||
}
|
||||
// `Sales[Total Sales]` names a measure homed on the qualifying table; DAX allows the
|
||||
// table qualifier on a measure reference and only rejects it for another table.
|
||||
if let Some(index) = self.model.measure_index(&name.name.text)
|
||||
&& let Some(home) = self.model.measures[index].table.as_deref()
|
||||
{
|
||||
if self.model.table_index(home) == Some(table_index) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
return Err(BindError::new(format!("measure `{}` belongs to table `{}`, not `{}`", name.name.text, home, table.text), span));
|
||||
}
|
||||
return Err(BindError::new(format!("unknown column `{}` in table `{}`", name.name.text, table.text), span));
|
||||
}
|
||||
|
||||
// A bracketed name is always a model object reference (`[Measure]`, `[Column]`), never a
|
||||
// variable: DAX requires bare identifiers for variables, so `VAR Total = 1 ... [Total]`
|
||||
// refers to the measure, not the variable.
|
||||
if name.name.style == crate::NameStyle::Bracketed {
|
||||
if let Some(index) = self.model.measure_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
// A bracketed name may be a row-context column; the evaluator resolves it.
|
||||
return Ok(BoundExpr::UnqualifiedColumn { name: name.name.text.clone() });
|
||||
}
|
||||
|
||||
if let Some(index) = vars.iter().rposition(|var| var.eq_ignore_ascii_case(&name.name.text)) {
|
||||
return Ok(BoundExpr::Variable { index, name: name.name.text.clone() });
|
||||
}
|
||||
|
||||
if let Some(index) = self.model.table_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Table(index));
|
||||
}
|
||||
if let Some(index) = self.model.measure_index(&name.name.text) {
|
||||
return Ok(BoundExpr::Measure(index));
|
||||
}
|
||||
Err(BindError::new(format!("unknown name `{}`", name.name.text), span))
|
||||
}
|
||||
|
||||
fn bind_call(&self, call: &Call, span: crate::Span, vars: &mut Vec<String>) -> Result<BoundExpr, BindError> {
|
||||
let Some(spec) = lookup(&call.name.text) else {
|
||||
return Err(BindError::new(format!("unknown DAX function `{}`", call.name.text), span));
|
||||
};
|
||||
if let Some(error) = validate_call(call).into_iter().next() {
|
||||
return Err(BindError::new(error.message, span));
|
||||
}
|
||||
let mut args = Vec::with_capacity(call.args.len());
|
||||
for (index, arg) in call.args.iter().enumerate() {
|
||||
// Documented enum parameters (intervals, ties, blanks, text type names) are written
|
||||
// as bare names. The parser cannot tell them from table/measure names, but the
|
||||
// catalog's parameter kind can: a Text position only accepts a literal or a keyword.
|
||||
let expected = spec.overload_for(call.args.len()).and_then(|overload| overload.params.get(index)).copied();
|
||||
let keyword = match spec.name {
|
||||
"DATATABLE" if index % 2 == 1 => keyword_name(arg),
|
||||
"CONVERT" if index == 1 => keyword_name(arg),
|
||||
// RANKX's Ties argument is documented as `Dense` but catalogued as a Scalar.
|
||||
"RANKX" if index == 4 => keyword_name(arg),
|
||||
// RANKX's Order argument is catalogued as a Scalar too, but it is `ASC`/`DESC`.
|
||||
"RANKX" if index == 3 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"DATEDIFF" if index == 2 => keyword_name(arg),
|
||||
// TOPN's `(expression, Order)` pairs: ASC/DESC sit at every odd index from 3.
|
||||
"TOPN" if index >= 3 && index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"CROSSFILTER" if index == 2 => {
|
||||
clause_keyword(arg, &["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"])
|
||||
}
|
||||
// RANK/ROWNUMBER's Reset argument is `NONE`, `LOWESTPARENT` or `HIGHESTPARENT`,
|
||||
// catalogued as `Any` so that a relation expression still binds there.
|
||||
"RANK" if index == 6 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
|
||||
// The documented bare ASC/DESC slots: RANKX and RANK.EQ take Order at index 3/2,
|
||||
// TOPNSKIP/CONCATENATEX at index 4 and SAMPLE at index 3.
|
||||
"RANK.EQ" if index == 2 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
// SAMPLE and TOPNSKIP repeat `(orderBy, Order)` pairs, so every order word sits at
|
||||
// an even offset from the first one: 3, 5, 7, ... for SAMPLE and 4, 6, 8, ... for
|
||||
// TOPNSKIP.
|
||||
"TOPNSKIP" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"SAMPLE" if index >= 3 && (index - 3) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
// CONCATENATEX takes `(orderBy, Order)` pairs from index 4 on, so every even
|
||||
// offset from 4 is an order word.
|
||||
"CONCATENATEX" if index >= 4 && (index - 4) % 2 == 0 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"ROWNUMBER" if index == 5 => clause_keyword(arg, &["NONE", "LOWESTPARENT", "HIGHESTPARENT"]),
|
||||
// Window/relation clauses take bare enum words: `ORDERBY(x, DESC)`,
|
||||
// `WINDOW(1, ABS, 1, ABS, ...)`, `INDEX(..., KEEP, PARTITIONBY(...))`, and the
|
||||
// LOOKUP associated-columns behaviour (`INFERRED`).
|
||||
"ORDERBY" if index % 2 == 1 => clause_keyword(arg, &["ASC", "DESC"]),
|
||||
"INDEX" | "OFFSET" if index >= 2 => clause_keyword(arg, WINDOW_KEYWORDS),
|
||||
// FromType/ToType are optional, so the blanks/reset slots move with the layout;
|
||||
// `window_table` identifies each slot by its value.
|
||||
"WINDOW" if index >= 1 => clause_keyword(arg, WINDOW_KEYWORDS),
|
||||
"LOOKUP" | "LOOKUPWITHTOTALS" if index % 2 == 1 && index + 1 == call.args.len() => {
|
||||
clause_keyword(arg, &["EXPLICIT", "INFERRED", "DEFAULT"])
|
||||
}
|
||||
// PATHITEM's optional Type is documented as `TEXT`/`INTEGER` but catalogued as
|
||||
// `Any` so that the numeric `0`/`1` spellings still bind.
|
||||
"PATHITEM" | "PATHITEMREVERSE" if index == 2 => clause_keyword(arg, &["TEXT", "INTEGER"]),
|
||||
_ if matches!(expected, Some(ParamKind::Text)) => keyword_name(arg),
|
||||
_ => visual_keyword_name(spec.name, index, arg),
|
||||
}
|
||||
// A name only wins where the position genuinely accepts one — a documented `Text`
|
||||
// argument such as `RANKX(..., Dense)` or a visual calculation's axis. A fixed enum
|
||||
// slot (`DATEDIFF`'s interval, `CONVERT`'s type, the order words) is not a name
|
||||
// position: a table called `Month` must not turn `DATEDIFF(a, b, MONTH)` into a table
|
||||
// reference, and a variable called `YEAR` must not either.
|
||||
.filter(|keyword| {
|
||||
// `DATATABLE`'s type words are types even though the catalog marks them `Text`,
|
||||
// so a table named `INTEGER` must not capture them either.
|
||||
let fixed_slot =
|
||||
spec.name == "DATATABLE" || (!matches!(expected, Some(ParamKind::Text)) && !is_visual_keyword(spec.name, index, keyword));
|
||||
if fixed_slot {
|
||||
return true;
|
||||
}
|
||||
let named = self.model.table_index(keyword).is_some() || self.model.measure_index(keyword).is_some();
|
||||
let variable = vars.iter().any(|var| var.eq_ignore_ascii_case(keyword));
|
||||
!named && !variable
|
||||
});
|
||||
if let Some(keyword) = keyword {
|
||||
args.push(BoundExpr::Keyword(keyword));
|
||||
} else {
|
||||
args.push(self.bind_with_vars(arg, vars)?);
|
||||
}
|
||||
}
|
||||
Ok(BoundExpr::Call { spec, args })
|
||||
}
|
||||
}
|
||||
|
||||
fn keyword_name(expr: &Expr) -> Option<String> {
|
||||
match &expr.kind {
|
||||
ExprKind::Name(name) if name.table.is_none() && name.name.style == crate::NameStyle::Bare => Some(name.name.text.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bare identifiers that visual-calculation functions accept where their syntax documents an
|
||||
/// axis, an ORDERBY flag, a blank-ordering enumeration or a reset clause. These words are not
|
||||
/// names in the model, so they must become [`BoundExpr::Keyword`] instead of failing resolution.
|
||||
fn visual_keyword_name(function: &str, index: usize, arg: &Expr) -> Option<String> {
|
||||
let word = keyword_name(arg)?;
|
||||
is_visual_keyword(function, index, &word).then_some(word)
|
||||
}
|
||||
|
||||
/// Whether `word` is a documented keyword at the 0-based `index` of a visual-calculation call.
|
||||
///
|
||||
/// The positions mirror the Microsoft syntax for each function, e.g. `FIRST ( <column>[, <axis>]
|
||||
/// [, <orderBy>][, <blanks>][, reset] )` and `RANGE ( <step>[, <includeCurrent>][, <axis>]
|
||||
/// [, <orderBy>][, <blanks>][, <reset>] )`. `COLLAPSE`/`EXPAND` also have navigation-only forms
|
||||
/// whose first argument is the axis (`COLLAPSE ( <axis>[, N] )`).
|
||||
fn is_visual_keyword(function: &str, index: usize, word: &str) -> bool {
|
||||
let axis = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "ROWS" | "COLUMNS");
|
||||
let order_by = |positions: &[usize]| positions.contains(&index) && word.eq_ignore_ascii_case("KEEP");
|
||||
let blanks = |positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "DEFAULT" | "FIRST" | "LAST");
|
||||
let reset =
|
||||
|positions: &[usize]| positions.contains(&index) && matches!(word.to_ascii_uppercase().as_str(), "NONE" | "LOWESTPARENT" | "HIGHESTPARENT");
|
||||
match function {
|
||||
"COLLAPSE" | "EXPAND" | "COLLAPSEALL" | "EXPANDALL" => axis(&[0, 1]),
|
||||
"FIRST" | "LAST" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
|
||||
"PREVIOUS" | "NEXT" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
|
||||
"MOVINGAVERAGE" => axis(&[3]) || order_by(&[4]) || blanks(&[5]) || reset(&[6]),
|
||||
"RUNNINGSUM" => axis(&[1]) || order_by(&[2]) || blanks(&[3]) || reset(&[4]),
|
||||
"RANGE" => axis(&[2]) || order_by(&[3]) || blanks(&[4]) || reset(&[5]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The enum words accepted by the window/relation clauses. Matching is case-insensitive, and an
|
||||
/// identifier outside this set is left to normal name binding so typos still report an error.
|
||||
const WINDOW_KEYWORDS: &[&str] = &["ASC", "DESC", "ABS", "REL", "DEFAULT", "FIRST", "LAST", "KEEP", "NONE", "LOWESTPARENT", "HIGHESTPARENT"];
|
||||
|
||||
fn clause_keyword(expr: &Expr, allowed: &[&str]) -> Option<String> {
|
||||
let word = keyword_name(expr)?;
|
||||
allowed.iter().any(|candidate| word.eq_ignore_ascii_case(candidate)).then_some(word)
|
||||
}
|
||||
|
||||
fn collect_measure_names(model: &DataModel, expr: &BoundExpr, out: &mut BTreeSet<String>) {
|
||||
match expr {
|
||||
BoundExpr::Measure(index) => {
|
||||
if let Some(measure) = model.measures.get(*index) {
|
||||
out.insert(measure.name.clone());
|
||||
}
|
||||
}
|
||||
BoundExpr::Call { args, .. } | BoundExpr::TableConstructor(args) | BoundExpr::Tuple(args) => {
|
||||
for arg in args {
|
||||
collect_measure_names(model, arg, out);
|
||||
}
|
||||
}
|
||||
BoundExpr::Unary { expr, .. } => collect_measure_names(model, expr, out),
|
||||
BoundExpr::Binary { left, right, .. } => {
|
||||
collect_measure_names(model, left, out);
|
||||
collect_measure_names(model, right, out);
|
||||
}
|
||||
BoundExpr::VarReturn { vars, body } => {
|
||||
for var in vars {
|
||||
collect_measure_names(model, &var.expr, out);
|
||||
}
|
||||
collect_measure_names(model, body, out);
|
||||
}
|
||||
BoundExpr::Literal(_)
|
||||
| BoundExpr::Column { .. }
|
||||
| BoundExpr::UnqualifiedColumn { .. }
|
||||
| BoundExpr::Table(_)
|
||||
| BoundExpr::Variable { .. }
|
||||
| BoundExpr::Keyword(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses and binds one measure formula against a model, without requiring a full model parse.
|
||||
pub fn bind_formula(model: &DataModel, formula: &str) -> Result<BoundExpr, BindError> {
|
||||
let expr = parse_expression(formula).map_err(|error| BindError::new(error.message, error.span))?;
|
||||
Binder::new(model).bind_expression(&expr)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
//! Aggregation functions.
|
||||
//!
|
||||
//! The core evaluator switch owns `SUM`, `AVERAGE`, `COUNT`, `COUNTA`, `COUNTBLANK`, `MIN`,
|
||||
//! `MAX`, `PRODUCT` and the `*X` iterators. This module covers the aggregations the core switch
|
||||
//! leaves out: the `*A` variants, whose text/Boolean coercions differ from their plain
|
||||
//! counterparts, and `DISTINCTCOUNTNOBLANK`.
|
||||
//!
|
||||
//! All four read a column under the current filter context and delegate the arithmetic to
|
||||
//! [`support::aggregate_values`]. `AVERAGEA` uses every row in the denominator and coerces
|
||||
//! BLANK to 0 (Microsoft's DAX example averages 1, 20, "n/a", BLANK, TRUE as 22/5), so only a
|
||||
//! column with no rows at all is BLANK; `DISTINCTCOUNTNOBLANK` drops BLANK before counting
|
||||
//! distinct values.
|
||||
#![allow(unused_imports)]
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Scalar aggregation functions owned by this module.
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
match name.to_ascii_uppercase().as_str() {
|
||||
"AVERAGEA" | "DISTINCTCOUNTNOBLANK" | "MAXA" | "MINA" => Some(aggregate_column(ev, name, args, ctx)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregations are scalar-only; none of these names is a table function, so table dispatch
|
||||
/// never handles one and always returns `None`.
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Evaluates the single column argument and aggregates it. The catalog gives every function in
|
||||
/// this module exactly one `Column` parameter, so a missing argument is a programming error the
|
||||
/// binder already rejected; report it as an ordinary evaluation error all the same.
|
||||
fn aggregate_column(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let column = args.first().ok_or_else(|| EvalError::new(format!("{name} needs a column")))?;
|
||||
let values = ev.column_values(column, ctx)?;
|
||||
super::support::aggregate_values(name, &values)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,71 @@
|
||||
//! Logical functions.
|
||||
//!
|
||||
//! This module owns the engine-only bitwise integer operations and `IF.EAGER`. `IF`, `AND`, `OR`,
|
||||
//! `NOT`, `COALESCE` and `IFERROR` live in the core evaluator because they need lazy argument
|
||||
//! evaluation; `IF.EAGER` is the documented opposite: it forces both branches to be evaluated
|
||||
//! before the condition selects one.
|
||||
|
||||
use super::support::{args as arg_values, eval_all};
|
||||
use super::*;
|
||||
|
||||
/// Scalar logical functions owned by this module: the bitwise integer operations and `IF.EAGER`.
|
||||
pub(crate) fn call(ev: &Evaluator<'_>, name: &str, args: &[BoundExpr], ctx: &mut Context) -> Option<Result<Scalar, EvalError>> {
|
||||
let name = name.to_ascii_uppercase();
|
||||
match name.as_str() {
|
||||
"BITAND" | "BITOR" | "BITXOR" => Some(bitwise(&name, ev, args, ctx)),
|
||||
"IF.EAGER" => Some(if_eager(ev, args, ctx)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Logical functions are scalar-only; none of these names is a table function, so this module
|
||||
/// never handles table dispatch and always returns `None`.
|
||||
pub(crate) fn call_table(_ev: &Evaluator<'_>, _name: &str, _args: &[BoundExpr], _ctx: &mut Context) -> Option<Result<TableValue, EvalError>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Evaluates `BITAND`, `BITOR` or `BITXOR` with both arguments forced, truncating each operand
|
||||
/// to a 64-bit integer before applying the operation. A native `Integer` stays exact: converting
|
||||
/// it through `f64` would lose bits above 2^53.
|
||||
fn bitwise(name: &str, ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values(name, &values);
|
||||
let left = bit_operand(a.arg(0)?, name, 0)?;
|
||||
let right = bit_operand(a.arg(1)?, name, 1)?;
|
||||
let result = match name {
|
||||
"BITAND" => left & right,
|
||||
"BITOR" => left | right,
|
||||
"BITXOR" => left ^ right,
|
||||
_ => return Err(EvalError::new(format!("{name} is not a bitwise function"))),
|
||||
};
|
||||
Ok(Scalar::Integer(result))
|
||||
}
|
||||
|
||||
/// Bit operations use the truncated two's-complement `i64` value; DAX documents a signed 64-bit
|
||||
/// result, so negative operands participate through their two's-complement representation.
|
||||
///
|
||||
/// A native `Integer` is used as-is so whole numbers above 2^53 keep every bit. Other numeric
|
||||
/// variants are converted to `f64` (already lossy above 2^53 for `Decimal`) and truncated.
|
||||
fn bit_operand(value: &Scalar, name: &str, index: usize) -> Result<i64, EvalError> {
|
||||
if let Scalar::Integer(integer) = value {
|
||||
return Ok(*integer);
|
||||
}
|
||||
let number = value.to_number().ok_or_else(|| EvalError::new(format!("{name} argument {} must be numeric", index + 1)))?;
|
||||
if !number.is_finite() || number.trunc() < -9_223_372_036_854_775_808.0 || number.trunc() >= 9_223_372_036_854_775_808.0 {
|
||||
return Err(EvalError::new(format!("{name} argument {} is outside the 64-bit integer range", index + 1)));
|
||||
}
|
||||
Ok(number.trunc() as i64)
|
||||
}
|
||||
|
||||
/// `IF.EAGER` evaluates the condition and both branch expressions before choosing a result, so an
|
||||
/// error in the branch that would not be selected still propagates.
|
||||
fn if_eager(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Scalar, EvalError> {
|
||||
let values = eval_all(ev, args, ctx)?;
|
||||
let a = arg_values("IF.EAGER", &values);
|
||||
let condition = a.boolean(0)?;
|
||||
let when_true = a.arg(1)?;
|
||||
if condition {
|
||||
return Ok(when_true.clone());
|
||||
}
|
||||
Ok(a.optional(2).cloned().unwrap_or(Scalar::Blank))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,765 @@
|
||||
//! Shared helpers for the category-specific function implementations.
|
||||
//!
|
||||
//! Each function family lives in its own module (`financial`, `statistical`, ...) and exposes a
|
||||
//! `call`/`call_table` dispatcher. Those dispatchers receive the unevaluated arguments and the
|
||||
//! evaluator's [`Context`](super::Context), so they can choose lazy or eager evaluation and can
|
||||
//! push row frames for iterators. This module holds the small, boring pieces they share: scalar
|
||||
//! argument coercion, Excel date serials, rounding and row-frame construction.
|
||||
#![allow(dead_code)] // helpers are consumed by the per-family modules as they land
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use super::*;
|
||||
use chrono::{Datelike, NaiveDate};
|
||||
|
||||
/// The evaluated arguments of a scalar function call.
|
||||
pub(crate) struct Args<'a> {
|
||||
pub(crate) name: &'a str,
|
||||
pub(crate) values: &'a [Scalar],
|
||||
}
|
||||
|
||||
impl<'a> Args<'a> {
|
||||
pub(crate) fn arg(&self, index: usize) -> Result<&'a Scalar, EvalError> {
|
||||
self.values.get(index).ok_or_else(|| EvalError::new(format!("{} is missing argument {}", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn optional(&self, index: usize) -> Option<&'a Scalar> {
|
||||
self.values.get(index)
|
||||
}
|
||||
|
||||
pub(crate) fn number(&self, index: usize) -> Result<f64, EvalError> {
|
||||
self.arg(index)?.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn int(&self, index: usize) -> Result<i64, EvalError> {
|
||||
Ok(self.number(index)? as i64)
|
||||
}
|
||||
|
||||
pub(crate) fn text(&self, index: usize) -> Result<String, EvalError> {
|
||||
Ok(self.arg(index)?.to_text())
|
||||
}
|
||||
|
||||
pub(crate) fn boolean(&self, index: usize) -> Result<bool, EvalError> {
|
||||
self.arg(index)?.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
|
||||
}
|
||||
|
||||
pub(crate) fn date(&self, index: usize) -> Result<f64, EvalError> {
|
||||
let value = self.number(index)?;
|
||||
if !value.is_finite() {
|
||||
return Err(EvalError::new(format!("{} argument {} must be a date", self.name, index + 1)));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(crate) fn optional_number(&self, index: usize, default: f64) -> Result<f64, EvalError> {
|
||||
match self.values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
value.to_number().ok_or_else(|| EvalError::new(format!("{} argument {} must be numeric", self.name, index + 1)))
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn optional_bool(&self, index: usize, default: bool) -> Result<bool, EvalError> {
|
||||
match self.values.get(index) {
|
||||
Some(value) if !value.is_blank() => {
|
||||
value.to_bool().ok_or_else(|| EvalError::new(format!("{} argument {} must be Boolean", self.name, index + 1)))
|
||||
}
|
||||
_ => Ok(default),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates every argument eagerly, left to right.
|
||||
pub(crate) fn eval_all(ev: &Evaluator<'_>, args: &[BoundExpr], ctx: &mut Context) -> Result<Vec<Scalar>, EvalError> {
|
||||
args.iter().map(|arg| ev.eval(arg, ctx)).collect()
|
||||
}
|
||||
|
||||
/// Evaluates one argument as a table.
|
||||
pub(crate) fn eval_table(ev: &Evaluator<'_>, expr: &BoundExpr, ctx: &mut Context) -> Result<TableValue, EvalError> {
|
||||
ev.eval_table(expr, ctx)
|
||||
}
|
||||
|
||||
/// Builds a row frame for one row of a table value, mapping columns back to the model by name
|
||||
/// when the table keeps its lineage.
|
||||
pub(crate) fn frame_for(ev: &Evaluator<'_>, table: &TableValue, row: &[Scalar]) -> RowFrame {
|
||||
let names: Vec<String> = table.columns.iter().map(|column| column.name.clone()).collect();
|
||||
let model_columns: Vec<Option<usize>> = match table.lineage {
|
||||
Some(lineage) => names.iter().map(|name| ev.model().column_index(lineage, name)).collect(),
|
||||
None => vec![None; names.len()],
|
||||
};
|
||||
RowFrame { lineage: table.lineage, names, values: row.to_vec(), model_columns }
|
||||
}
|
||||
|
||||
/// Builds a frame for a plain model table row whose values follow the model column order.
|
||||
pub(crate) fn model_row_frame(ev: &Evaluator<'_>, table: usize, values: Vec<Scalar>) -> RowFrame {
|
||||
let names: Vec<String> =
|
||||
ev.model().tables.get(table).map(|table| table.columns.iter().map(|column| column.name.clone()).collect()).unwrap_or_default();
|
||||
let model_columns: Vec<Option<usize>> = (0..names.len()).map(Some).collect();
|
||||
RowFrame { lineage: Some(table), names, values, model_columns }
|
||||
}
|
||||
|
||||
/// Builds a frame for a derived table row whose columns are given explicitly.
|
||||
pub(crate) fn derived_row_frame(lineage: Option<usize>, names: Vec<String>, values: Vec<Scalar>, model_columns: Vec<Option<usize>>) -> RowFrame {
|
||||
RowFrame { lineage, names, values, model_columns }
|
||||
}
|
||||
|
||||
/// Eagerly evaluated scalar argument access for functions that already hold `Vec<Scalar>`.
|
||||
pub(crate) fn args<'a>(name: &'a str, values: &'a [Scalar]) -> Args<'a> {
|
||||
Args { name, values }
|
||||
}
|
||||
|
||||
/// Orders two scalars for sorting: deterministic, transitive and total over every variant.
|
||||
///
|
||||
/// [`Scalar::compare`] follows DAX's `=`/`<` coercion rules and answers `None` for pairs DAX
|
||||
/// does not compare: text against a number, and anything against NaN. A sort cannot read `None`
|
||||
/// as equality, because text would then equal every number while the numbers still order among
|
||||
/// themselves — not a total order, which `sort_by` may panic on (Rust 1.81+).
|
||||
///
|
||||
/// This ordering ranks whole classes instead, so mixed columns sort predictably:
|
||||
///
|
||||
/// 1. numbers (`Integer`, `Currency`, `Decimal`, `DateTime`) by numeric value, through
|
||||
/// `f64::total_cmp`, so NaN has a fixed place (after every other number) and `-0.0` sorts
|
||||
/// before `0.0`;
|
||||
/// 2. text, case-insensitively (Unicode lowercase, matching [`Scalar::compare`]); strings equal
|
||||
/// under lowercasing tie-break on the raw strings, so `"A"` and `"a"` still have a fixed
|
||||
/// order;
|
||||
/// 3. Booleans, `FALSE` before `TRUE`.
|
||||
///
|
||||
/// BLANK is the caller's business. Callers with a blank placement policy (`FIRST`/`LAST` in
|
||||
/// `RANK`/`ROWNUMBER`, the blank-aware window ordering) place blanks before calling. A blank
|
||||
/// that does reach this function orders as the number zero, which is DAX's default comparison
|
||||
/// and keeps the order transitive.
|
||||
pub(crate) fn total_order(left: &Scalar, right: &Scalar) -> Ordering {
|
||||
fn class(value: &Scalar) -> u8 {
|
||||
match value {
|
||||
Scalar::String(_) => 1,
|
||||
Scalar::Boolean(_) => 2,
|
||||
Scalar::Blank | Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
// BLANK counts as zero, as in DAX's default comparison; every other number-class variant has
|
||||
// a numeric value, so the NaN fallback is unreachable but keeps the function total.
|
||||
fn number(value: &Scalar) -> f64 {
|
||||
value.to_number().unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
match class(left).cmp(&class(right)) {
|
||||
Ordering::Equal => match (left, right) {
|
||||
(Scalar::String(a), Scalar::String(b)) => a.to_lowercase().cmp(&b.to_lowercase()).then_with(|| a.cmp(b)),
|
||||
(Scalar::Boolean(a), Scalar::Boolean(b)) => a.cmp(b),
|
||||
_ => number(left).total_cmp(&number(right)),
|
||||
},
|
||||
ordering => ordering,
|
||||
}
|
||||
}
|
||||
|
||||
/// 400 Gregorian years, after which the calendar (and every month length) repeats.
|
||||
const GREGORIAN_CYCLE_DAYS: i64 = 146_097;
|
||||
/// chrono counts days from 0001-01-01; 1970-01-01 is the 719,163rd of them.
|
||||
const UNIX_EPOCH_CE_DAYS: i64 = 719_163;
|
||||
/// Excel/OLE serial 0 is 1899-12-30, which is 25,569 days before 1970-01-01.
|
||||
const UNIX_EPOCH_SERIAL: i64 = 25_569;
|
||||
/// The CE day of Excel/OLE serial 0 (1899-12-30): `UNIX_EPOCH_CE_DAYS - UNIX_EPOCH_SERIAL`.
|
||||
const EXCEL_EPOCH_CE_DAYS: i64 = 693_594;
|
||||
|
||||
/// Excel/OLE date serial for a calendar date and time. Dates before 1900-03-01 ignore the
|
||||
/// 1900 leap-year compatibility bug; DAX/Excel only differ there.
|
||||
pub(crate) fn date_serial(year: i64, month: i64, day: i64, hour: i64, minute: i64, second: i64) -> f64 {
|
||||
// Normalize out-of-range months the way Excel does (DATE(2024, 13, 1) is 2025-01-01). The day
|
||||
// counts on from the first of that month, so day 0 is the last day of the month before.
|
||||
let months = month - 1;
|
||||
let year = year.saturating_add(months.div_euclid(12));
|
||||
let month = u32::try_from(months.rem_euclid(12) + 1).unwrap_or(1);
|
||||
let days = month_start_ce_days(year, month) - i128::from(EXCEL_EPOCH_CE_DAYS) + i128::from(day) - 1;
|
||||
days as f64 + (hour as f64 * 3600.0 + minute as f64 * 60.0 + second as f64) / 86400.0
|
||||
}
|
||||
|
||||
/// Calendar date of an Excel/OLE date serial's whole days.
|
||||
pub(crate) fn date_parts(serial: f64) -> (i64, i64, i64) {
|
||||
let unix = (serial.floor() as i64).saturating_sub(UNIX_EPOCH_SERIAL);
|
||||
// The calendar repeats every 400 years (146,097 days), so chrono converts the day within its
|
||||
// cycle and the whole cycles go back into the year (AGENTS.md).
|
||||
let (cycles, rest) = (unix.div_euclid(GREGORIAN_CYCLE_DAYS), unix.rem_euclid(GREGORIAN_CYCLE_DAYS));
|
||||
match i32::try_from(rest + UNIX_EPOCH_CE_DAYS).ok().and_then(NaiveDate::from_num_days_from_ce_opt) {
|
||||
Some(date) => {
|
||||
let year = i128::from(date.year()) + i128::from(cycles) * 400;
|
||||
let year = i64::try_from(year).unwrap_or(if year < 0 { i64::MIN } else { i64::MAX });
|
||||
(year, i64::from(date.month()), i64::from(date.day()))
|
||||
}
|
||||
// Unreachable: `rest + 719_163` is always a valid CE day.
|
||||
None => (1970, 1, 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of days in a calendar month, `30` for a month outside 1–12 (the value the caller expects
|
||||
/// for a month the evaluator has already normalized).
|
||||
pub(crate) fn days_in_month(year: i64, month: i64) -> i64 {
|
||||
if !(1..=12).contains(&month) {
|
||||
return 30;
|
||||
}
|
||||
// The month's length repeats with the 400-year cycle, so the year within it answers and always
|
||||
// fits `NaiveDate`.
|
||||
let year = year.rem_euclid(400) as i32;
|
||||
let month = month as u32;
|
||||
let first = |year: i32, month: u32| NaiveDate::from_ymd_opt(year, month, 1);
|
||||
match (first(year, month), if month == 12 { first(year + 1, 1) } else { first(year, month + 1) }) {
|
||||
(Some(start), Some(next)) => (next - start).num_days(),
|
||||
// Unreachable: the year is in 0..=399 and the month is 1..=12.
|
||||
_ => 30,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a year is a Gregorian leap year, for every `i64` year.
|
||||
pub(crate) fn is_leap_year(year: i64) -> bool {
|
||||
// Leap years repeat every 400 years, so the year within its cycle decides and always fits
|
||||
// `NaiveDate`: 29 February exists exactly in a leap year.
|
||||
NaiveDate::from_ymd_opt(year.rem_euclid(400) as i32, 2, 29).is_some()
|
||||
}
|
||||
|
||||
/// Days since 0001-01-01 (chrono's `num_days_from_ce`) of the first day of a calendar month, for
|
||||
/// every `i64` year. Whole 400-year Gregorian cycles are added back as days.
|
||||
fn month_start_ce_days(year: i64, month: u32) -> i128 {
|
||||
let cycles = i128::from(year.div_euclid(400));
|
||||
let year = year.rem_euclid(400) as i32;
|
||||
match NaiveDate::from_ymd_opt(year, month, 1) {
|
||||
Some(first) => i128::from(first.num_days_from_ce()) + cycles * i128::from(GREGORIAN_CYCLE_DAYS),
|
||||
// Unreachable: the year within its cycle is in 0..=399 and the month is 1..=12.
|
||||
None => i128::from(NaiveDate::MIN.num_days_from_ce()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn date_weekday(serial: f64) -> i64 {
|
||||
let days = serial.floor() as i64;
|
||||
let weekday = days.rem_euclid(7);
|
||||
if weekday == 0 { 7 } else { weekday }
|
||||
}
|
||||
|
||||
/// The year and month `months` away from the month of `serial`, or `None` when the shift leaves
|
||||
/// the years Excel dates can represent.
|
||||
///
|
||||
/// The month total is computed in `i128`: `months` arrives from `number(..) as i64`, which saturates
|
||||
/// at `i64::MAX`, and `year * 12 + month - 1 + months` would wrap (or panic in debug builds) for
|
||||
/// such an argument.
|
||||
fn shift_month(serial: f64, months: i64) -> Option<(i64, i64)> {
|
||||
let (year, month, _) = date_parts(serial);
|
||||
let total = i128::from(year) * 12 + i128::from(month) - 1 + i128::from(months);
|
||||
let year = i64::try_from(total.div_euclid(12)).ok()?;
|
||||
if !(1..=9999).contains(&year) {
|
||||
return None;
|
||||
}
|
||||
Some((year, i64::try_from(total.rem_euclid(12)).ok()? + 1))
|
||||
}
|
||||
|
||||
pub(crate) fn eomonth(serial: f64, months: i64) -> f64 {
|
||||
match shift_month(serial, months) {
|
||||
Some((year, month)) => date_serial(year, month, days_in_month(year, month), 0, 0, 0),
|
||||
// A shift Excel cannot represent leaves the date where it was instead of wrapping.
|
||||
None => serial,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn edate(serial: f64, months: i64) -> f64 {
|
||||
let (_, _, day) = date_parts(serial);
|
||||
match shift_month(serial, months) {
|
||||
Some((year, month)) => date_serial(year, month, day.min(days_in_month(year, month)), 0, 0, 0),
|
||||
None => serial,
|
||||
}
|
||||
}
|
||||
|
||||
/// The local date as an Excel serial (TODAY).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn today_serial() -> f64 {
|
||||
now_serial().floor()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn today_serial() -> f64 {
|
||||
now_serial().floor()
|
||||
}
|
||||
|
||||
/// The browser clock as an Excel serial, the wasm arm of [`now_serial`]/[`utc_now_serial`].
|
||||
///
|
||||
/// The standard library's clock traps on wasm, so the epoch comes from `js_sys::Date`, the same
|
||||
/// source `crates/core/src/date.rs` uses. `Date::now()` is UTC milliseconds; for the local serial
|
||||
/// the browser's time-zone offset is subtracted (it counts minutes *west* of UTC), and only
|
||||
/// `TODAY`/`UTCTODAY` floor the result.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn wasm_now_serial(local: bool) -> f64 {
|
||||
const MILLISECONDS_PER_DAY: f64 = 86_400_000.0;
|
||||
let offset_minutes = if local { -js_sys::Date::new_0().get_timezone_offset() } else { 0.0 };
|
||||
25569.0 + js_sys::Date::now() / MILLISECONDS_PER_DAY + offset_minutes / 1_440.0
|
||||
}
|
||||
|
||||
/// The local date and time as an Excel serial (NOW).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn now_serial() -> f64 {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let now = chrono::Local::now();
|
||||
date_serial(
|
||||
i64::from(now.year()),
|
||||
i64::from(now.month()),
|
||||
i64::from(now.day()),
|
||||
i64::from(now.hour()),
|
||||
i64::from(now.minute()),
|
||||
i64::from(now.second()),
|
||||
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn now_serial() -> f64 {
|
||||
wasm_now_serial(true)
|
||||
}
|
||||
|
||||
/// The UTC date and time as an Excel serial (UTCNOW).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn utc_now_serial() -> f64 {
|
||||
use chrono::{Datelike, Timelike};
|
||||
let now = chrono::Utc::now();
|
||||
date_serial(
|
||||
i64::from(now.year()),
|
||||
i64::from(now.month()),
|
||||
i64::from(now.day()),
|
||||
i64::from(now.hour()),
|
||||
i64::from(now.minute()),
|
||||
i64::from(now.second()),
|
||||
) + f64::from(now.nanosecond()) / 86_400_000_000_000.0
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn utc_now_serial() -> f64 {
|
||||
wasm_now_serial(false)
|
||||
}
|
||||
|
||||
/// The UTC date at midnight as an Excel serial (UTCTODAY).
|
||||
pub(crate) fn utc_today_serial() -> f64 {
|
||||
utc_now_serial().floor()
|
||||
}
|
||||
|
||||
/// Rounds `value` to 15 significant digits, the precision Excel and DAX compute with.
|
||||
///
|
||||
/// `value * 10^digits` carries the binary representation error of its factors, and a directed
|
||||
/// rounding makes that error visible: `0.29 * 100` is `28.999999999999996`, so `ROUNDDOWN ( 0.29,
|
||||
/// 2 )` would truncate to `0.28` and `ROUNDUP ( 0.07, 2 )` would ceil `7.000000000000001` to
|
||||
/// `0.08`. Snap that noise away before rounding, exactly as `to_dax_text` does when it prints.
|
||||
fn excel_precision(value: f64) -> f64 {
|
||||
// An exact whole number under 2^53 has no binary noise to remove, and snapping it would drop
|
||||
// digits: `ROUND ( 1234567890123457, 0 )` must stay that number.
|
||||
if is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
format!("{value:.14e}").parse().unwrap_or(value)
|
||||
}
|
||||
|
||||
/// Whether `value` is a whole number held exactly in an `f64`.
|
||||
fn is_exact_whole(value: f64) -> bool {
|
||||
value.fract() == 0.0 && value.abs() < 2f64.powi(53)
|
||||
}
|
||||
|
||||
pub(crate) fn round_to(value: f64, digits: i32) -> f64 {
|
||||
// The scale factor overflows or underflows outside f64's exponent range: past +308 digits the
|
||||
// value cannot change, past -308 every digit is rounded away.
|
||||
if digits > 308 {
|
||||
return value;
|
||||
}
|
||||
if digits < -308 {
|
||||
return 0.0;
|
||||
}
|
||||
// An exact whole number is already rounded: scaling it past 2^53 would only make the snap
|
||||
// lose digits, so `ROUND ( 1234567890123457, 1 )` stays that number.
|
||||
if digits >= 0 && is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
let factor = 10f64.powi(digits);
|
||||
let scaled = excel_precision(value * factor);
|
||||
if !scaled.is_finite() {
|
||||
return value;
|
||||
}
|
||||
scaled.round() / factor
|
||||
}
|
||||
|
||||
/// ROUNDUP/ROUNDDOWN: `up` rounds away from zero, otherwise toward zero. Excel and DAX define
|
||||
/// both in terms of the sign, not the floor/ceiling, so `ROUNDDOWN ( -2.9, 0 )` is -2 and
|
||||
/// `ROUNDUP ( -2.1, 0 )` is -3.
|
||||
pub(crate) fn round_direction(value: f64, digits: i32, up: bool) -> f64 {
|
||||
// `10^digits` overflows or underflows outside f64's exponent range; the result is the value
|
||||
// itself when rounding cannot move any digit, and zero when every digit is rounded away.
|
||||
if digits > 308 {
|
||||
return value;
|
||||
}
|
||||
if digits < -308 {
|
||||
return if up && value != 0.0 { f64::INFINITY.copysign(value) } else { 0.0 };
|
||||
}
|
||||
if digits >= 0 && is_exact_whole(value) {
|
||||
return value;
|
||||
}
|
||||
let factor = 10f64.powi(digits);
|
||||
let scaled = excel_precision(value * factor);
|
||||
if !scaled.is_finite() {
|
||||
return value;
|
||||
}
|
||||
let rounded = if up { scaled.abs().ceil().copysign(scaled) } else { scaled.trunc() };
|
||||
rounded / factor
|
||||
}
|
||||
|
||||
/// The greatest common divisor of the two magnitudes, so `i64::MIN` is represented without
|
||||
/// overflowing the way `i64::abs` would.
|
||||
pub(crate) fn gcd(a: i64, b: i64) -> u64 {
|
||||
let (mut a, mut b) = (a.unsigned_abs(), b.unsigned_abs());
|
||||
while b != 0 {
|
||||
let t = a % b;
|
||||
a = b;
|
||||
b = t;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// The least common multiple, or `None` when it does not fit in an `i64` (Excel answers `#NUM!`).
|
||||
pub(crate) fn lcm(a: i64, b: i64) -> Option<i64> {
|
||||
if a == 0 || b == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
(a.unsigned_abs() / gcd(a, b)).checked_mul(b.unsigned_abs()).and_then(|value| i64::try_from(value).ok())
|
||||
}
|
||||
|
||||
/// Applies a scalar aggregation over already-evaluated values.
|
||||
pub(crate) fn aggregate_values(name: &str, values: &[Scalar]) -> Result<Scalar, EvalError> {
|
||||
// Plain aggregations take numeric values only: DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT
|
||||
// ignore logicals and text instead of coercing them. The `*A` variants below keep their own
|
||||
// coercion and read `values` directly.
|
||||
let numbers: Vec<f64> = values
|
||||
.iter()
|
||||
.filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
|
||||
.filter_map(Scalar::to_number)
|
||||
.collect();
|
||||
match name.to_ascii_uppercase().as_str() {
|
||||
"SUM" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum()) }),
|
||||
"AVERAGE" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().sum::<f64>() / numbers.len() as f64) }),
|
||||
"AVERAGEA" => {
|
||||
// Every row counts: text (numeric or not) counts as 0, TRUE/FALSE as 1/0, and a BLANK
|
||||
// cell as 0, so it stays in the denominator — Microsoft's example averages 1, 20,
|
||||
// "n/a", BLANK and TRUE as 22/5. A column with no rows at all is BLANK.
|
||||
if values.is_empty() {
|
||||
return Ok(Scalar::Blank);
|
||||
}
|
||||
let sum: f64 = values
|
||||
.iter()
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.sum();
|
||||
Ok(Scalar::Decimal(sum / values.len() as f64))
|
||||
}
|
||||
"PRODUCT" => Ok(if numbers.is_empty() { Scalar::Blank } else { Scalar::Decimal(numbers.iter().product()) }),
|
||||
"MIN" | "MAX" => {
|
||||
// The winner keeps its own type — a date column answers a DateTime and an integer
|
||||
// column an Integer — so this cannot read the `f64` projection the sum-like
|
||||
// aggregations use. Only numbers compete: text and logicals are not observations.
|
||||
let want = if name.eq_ignore_ascii_case("MIN") { Ordering::Less } else { Ordering::Greater };
|
||||
let mut best: Option<&Scalar> = None;
|
||||
for value in
|
||||
values.iter().filter(|value| matches!(value, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_)))
|
||||
{
|
||||
match best {
|
||||
None => best = Some(value),
|
||||
Some(current) if value.compare(current) == Some(want) => best = Some(value),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(best.cloned().unwrap_or(Scalar::Blank))
|
||||
}
|
||||
"MINA" => Ok(values
|
||||
.iter()
|
||||
.filter(|value| !value.is_blank())
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.reduce(f64::min)
|
||||
.map(Scalar::Decimal)
|
||||
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
|
||||
"MAXA" => Ok(values
|
||||
.iter()
|
||||
.filter(|value| !value.is_blank())
|
||||
.map(|value| match value {
|
||||
Scalar::String(_) => 0.0,
|
||||
Scalar::Boolean(value) => f64::from(u8::from(*value)),
|
||||
other => other.to_number().unwrap_or(0.0),
|
||||
})
|
||||
.reduce(f64::max)
|
||||
.map(Scalar::Decimal)
|
||||
.unwrap_or(if values.is_empty() { Scalar::Blank } else { Scalar::Decimal(0.0) })),
|
||||
"COUNT" => {
|
||||
let count = values.iter().filter(|v| !v.is_blank() && !matches!(v, Scalar::Boolean(_))).count();
|
||||
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
|
||||
}
|
||||
"COUNTA" => {
|
||||
let count = values.iter().filter(|v| !v.is_blank()).count();
|
||||
Ok(if count == 0 { Scalar::Blank } else { Scalar::Integer(count as i64) })
|
||||
}
|
||||
"COUNTBLANK" => Ok(Scalar::Integer(values.iter().filter(|v| v.is_blank() || v.to_text().is_empty()).count() as i64)),
|
||||
"DISTINCTCOUNT" | "APPROXIMATEDISTINCTCOUNT" => {
|
||||
let distinct: BTreeSet<ScalarKey> = values.iter().map(distinct_key).collect();
|
||||
Ok(if values.is_empty() { Scalar::Blank } else { Scalar::Integer(distinct.len() as i64) })
|
||||
}
|
||||
"DISTINCTCOUNTNOBLANK" => {
|
||||
let distinct: BTreeSet<ScalarKey> = values.iter().filter(|value| !value.is_blank()).map(distinct_key).collect();
|
||||
Ok(Scalar::Integer(distinct.len() as i64))
|
||||
}
|
||||
_ => Err(EvalError::not_implemented(name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coerces a scalar to a date serial, treating blanks as 0.
|
||||
pub(crate) fn date_value(value: &Scalar) -> Option<f64> {
|
||||
match value {
|
||||
Scalar::DateTime(serial) => Some(*serial),
|
||||
Scalar::String(text) => parse_date_text(text),
|
||||
Scalar::Blank => None,
|
||||
other => other.to_number(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the common textual date forms Excel accepts (`YYYY-MM-DD`, `MM/DD/YYYY`,
|
||||
/// `YYYY-MM-DDTHH:MM:SS`). Locale-specific `DD/MM/YYYY` is deliberately ambiguous and rejected.
|
||||
/// A component outside the calendar (month 13, 30 February) is rejected rather than rolled over.
|
||||
pub(crate) fn parse_date_text(text: &str) -> Option<f64> {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (date, time) = match text.split_once(['T', ' ']) {
|
||||
Some((date, time)) => (date, Some(time)),
|
||||
None => (text, None),
|
||||
};
|
||||
let parts: Vec<&str> = date.split(['-', '/']).collect();
|
||||
let (year, month, day) = match parts.as_slice() {
|
||||
[first, second, third] => {
|
||||
let first_value: i64 = first.parse().ok()?;
|
||||
let second_value: i64 = second.parse().ok()?;
|
||||
let third_value: i64 = third.parse().ok()?;
|
||||
// A four-digit leading part is `YYYY-MM-DD`; anything else is `MM/DD/YYYY`.
|
||||
let (year, month, day) =
|
||||
if first.len() >= 4 { (first_value, second_value, third_value) } else { (third_value, first_value, second_value) };
|
||||
let year = if year < 100 { year + if year < 30 { 2000 } else { 1900 } } else { year };
|
||||
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
|
||||
return None;
|
||||
}
|
||||
(year, month, day)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let (hour, minute, second) = match time.map(str::trim).filter(|time| !time.is_empty()) {
|
||||
None => (0, 0, 0),
|
||||
Some(time) => {
|
||||
// `datetime_text` prints a date as `M/D/YYYY H:MM:SS AM/PM`, so the form the crate
|
||||
// itself writes has to parse back. The suffix decides the half of the day and the
|
||||
// hour is then 1-12; without it the hour is 0-23.
|
||||
let (clock, meridiem) = match time.rsplit_once(' ') {
|
||||
Some((clock, suffix)) if suffix.eq_ignore_ascii_case("AM") || suffix.eq_ignore_ascii_case("PM") => {
|
||||
(clock.trim(), Some(suffix.eq_ignore_ascii_case("PM")))
|
||||
}
|
||||
_ => (time, None),
|
||||
};
|
||||
// A present time must parse and be in range: `25:00:00` is rejected rather than
|
||||
// rolled into the next day, like an impossible date.
|
||||
let parts: Vec<&str> = clock.split(':').collect();
|
||||
let hour: i64 = parts.first()?.trim().parse().ok()?;
|
||||
let minute: i64 = parts.get(1).unwrap_or(&"0").trim().parse().ok()?;
|
||||
let second: i64 = parts.get(2).unwrap_or(&"0").trim().parse().ok()?;
|
||||
let hour = match meridiem {
|
||||
// 12 AM is midnight and 12 PM is noon; the other PM hours move to the afternoon.
|
||||
Some(pm) if (1..=12).contains(&hour) => match (hour, pm) {
|
||||
(12, false) => 0,
|
||||
(12, true) => 12,
|
||||
(hour, true) => hour + 12,
|
||||
(hour, false) => hour,
|
||||
},
|
||||
Some(_) => return None,
|
||||
None => hour,
|
||||
};
|
||||
if !(0..24).contains(&hour) || !(0..60).contains(&minute) || !(0..60).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
(hour, minute, second)
|
||||
}
|
||||
};
|
||||
Some(date_serial(year, month, day, hour, minute, second))
|
||||
}
|
||||
|
||||
/// Current evaluation frame's innermost row frame, if any.
|
||||
pub(crate) fn current_frame(ctx: &Context) -> Option<&RowFrame> {
|
||||
ctx.rows.last()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Columns that are rolled up (blanked) in the `SUMMARIZE` row currently being evaluated.
|
||||
/// `None` outside a `SUMMARIZE` expression, so `ISSUBTOTAL` can tell "detail row" from "not in
|
||||
/// a `SUMMARIZE` at all". The state lives here, next to the evaluator's other row-context
|
||||
/// state, because the function that reads it (`ISSUBTOTAL`) and the one that writes it
|
||||
/// (`SUMMARIZE`) ship in different evaluator families.
|
||||
static SUBTOTAL_COLUMNS: RefCell<Option<Vec<(usize, usize)>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The rolled-up columns of the `SUMMARIZE` row being evaluated, or `None` outside `SUMMARIZE`.
|
||||
pub(crate) fn subtotal_columns() -> Option<Vec<(usize, usize)>> {
|
||||
SUBTOTAL_COLUMNS.with(|columns| columns.borrow().clone())
|
||||
}
|
||||
|
||||
/// Pushes the rolled-up columns for one `SUMMARIZE` row and restores the outer state on drop, so
|
||||
/// a nested `SUMMARIZE` and an error path both leave the context as they found it.
|
||||
pub(crate) struct SubtotalGuard(Option<Vec<(usize, usize)>>);
|
||||
|
||||
impl SubtotalGuard {
|
||||
pub(crate) fn push(columns: Vec<(usize, usize)>) -> Self {
|
||||
let previous = SUBTOTAL_COLUMNS.with(|current| current.borrow_mut().replace(columns));
|
||||
SubtotalGuard(previous)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SubtotalGuard {
|
||||
fn drop(&mut self) {
|
||||
let previous = self.0.take();
|
||||
SUBTOTAL_COLUMNS.with(|current| *current.borrow_mut() = previous);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serials_round_trip_through_chrono() {
|
||||
// Serial 0 is 1899-12-30 and 25,569 is 1970-01-01.
|
||||
assert_eq!(date_serial(1899, 12, 30, 0, 0, 0), 0.0);
|
||||
assert_eq!(date_serial(1970, 1, 1, 0, 0, 0), 25_569.0);
|
||||
assert_eq!(date_parts(0.0), (1899, 12, 30));
|
||||
assert_eq!(date_parts(25_569.0), (1970, 1, 1));
|
||||
// Leap days exist exactly in leap years.
|
||||
assert_eq!(date_serial(2024, 2, 29, 0, 0, 0), 45_351.0);
|
||||
assert_eq!(date_parts(45_351.0), (2024, 2, 29));
|
||||
assert_eq!(date_serial(2000, 2, 29, 0, 0, 0), date_serial(2000, 3, 1, 0, 0, 0) - 1.0);
|
||||
// A time of day is a fraction of the serial.
|
||||
assert_eq!(date_serial(1970, 1, 1, 12, 0, 0), 25_569.5);
|
||||
assert_eq!(date_parts(25_569.75), (1970, 1, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serial_helpers_extend_past_chronos_year_range() {
|
||||
// 400 Gregorian years are 146,097 days, so year 400,000 is 999 cycles after year 400.
|
||||
let cycles = 999.0 * 146_097.0;
|
||||
assert_eq!(date_serial(400_000, 1, 1, 0, 0, 0) - cycles, date_serial(400, 1, 1, 0, 0, 0));
|
||||
assert_eq!(date_parts(date_serial(400_000, 2, 29, 0, 0, 0)), (400_000, 2, 29));
|
||||
// The cycle repeats leap-year and month-length rules too.
|
||||
assert!(is_leap_year(400_000));
|
||||
assert!(!is_leap_year(300_100));
|
||||
assert_eq!(days_in_month(400_000, 2), 29);
|
||||
assert_eq!(days_in_month(300_100, 2), 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_months_and_days_roll_over_like_date() {
|
||||
// DATE(2024, 13, 1) is 2025-01-01 and day 0 is the last day of the previous month.
|
||||
assert_eq!(date_serial(2024, 13, 1, 0, 0, 0), date_serial(2025, 1, 1, 0, 0, 0));
|
||||
assert_eq!(date_serial(2024, 0, 1, 0, 0, 0), date_serial(2023, 12, 1, 0, 0, 0));
|
||||
assert_eq!(date_serial(2024, 3, 0, 0, 0, 0), date_serial(2024, 2, 29, 0, 0, 0));
|
||||
assert_eq!(days_in_month(2024, 2), 29);
|
||||
assert_eq!(days_in_month(2023, 2), 28);
|
||||
assert_eq!(days_in_month(1900, 2), 28);
|
||||
assert_eq!(days_in_month(2000, 2), 29);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_aggregations_ignore_text_logicals_and_blanks() {
|
||||
// DAX specifies that SUM/AVERAGE/MIN/MAX/PRODUCT use the numeric rows only: text (even
|
||||
// numeric text), logicals and BLANK are ignored, unlike the `*A` variants.
|
||||
let values = [
|
||||
Scalar::Integer(2),
|
||||
Scalar::String("3".into()),
|
||||
Scalar::Boolean(true),
|
||||
Scalar::Blank,
|
||||
Scalar::Decimal(0.5),
|
||||
Scalar::Currency(15_000),
|
||||
Scalar::DateTime(10.0),
|
||||
];
|
||||
assert_eq!(aggregate_values("SUM", &values).expect("SUM"), Scalar::Decimal(14.0));
|
||||
assert_eq!(aggregate_values("AVERAGE", &values).expect("AVERAGE"), Scalar::Decimal(3.5));
|
||||
// MIN/MAX return the winning value itself: its type survives, so the 10.0 date stays a
|
||||
// DateTime rather than becoming a decimal serial.
|
||||
assert_eq!(aggregate_values("MIN", &values).expect("MIN"), Scalar::Decimal(0.5));
|
||||
assert_eq!(aggregate_values("MAX", &values).expect("MAX"), Scalar::DateTime(10.0));
|
||||
assert_eq!(aggregate_values("PRODUCT", &values).expect("PRODUCT"), Scalar::Decimal(15.0));
|
||||
let integers = [Scalar::Integer(7), Scalar::Integer(3), Scalar::Blank];
|
||||
assert_eq!(aggregate_values("MIN", &integers).expect("MIN"), Scalar::Integer(3));
|
||||
assert_eq!(aggregate_values("MAX", &integers).expect("MAX"), Scalar::Integer(7));
|
||||
// A column holding only text, logicals and blanks has no numeric observations at all.
|
||||
let non_numeric = [Scalar::String("5".into()), Scalar::Boolean(false), Scalar::Blank];
|
||||
assert_eq!(aggregate_values("SUM", &non_numeric).expect("SUM"), Scalar::Blank);
|
||||
assert_eq!(aggregate_values("AVERAGE", &non_numeric).expect("AVERAGE"), Scalar::Blank);
|
||||
// The `*A` variants keep their own coercion: text counts as 0 and TRUE as 1.
|
||||
assert_eq!(aggregate_values("MINA", &non_numeric).expect("MINA"), Scalar::Decimal(0.0));
|
||||
assert_eq!(aggregate_values("COUNTA", &non_numeric).expect("COUNTA"), Scalar::Integer(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_text_parses_month_first_and_rejects_impossible_dates() {
|
||||
// `MM/DD/YYYY`: the leading part is the month, not the year.
|
||||
assert_eq!(parse_date_text("1/8/2009"), Some(39_821.0));
|
||||
assert_eq!(parse_date_text("1/8/09"), Some(39_821.0));
|
||||
// ISO order, and a trailing time is kept.
|
||||
assert_eq!(parse_date_text("2024-01-15"), Some(45_306.0));
|
||||
assert_eq!(parse_date_text("2024-01-15T06:00:00"), Some(45_306.25));
|
||||
// Out-of-range components are rejected instead of rolling over.
|
||||
assert_eq!(parse_date_text("2024-02-30"), None);
|
||||
assert_eq!(parse_date_text("13/1/2024"), None);
|
||||
assert_eq!(parse_date_text("2024-00-10"), None);
|
||||
assert_eq!(parse_date_text("2023-02-29"), None);
|
||||
assert_eq!(parse_date_text("1/8"), None);
|
||||
assert_eq!(parse_date_text(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn date_text_round_trips_the_ampm_form_the_crate_prints() {
|
||||
// `datetime_text` writes `M/D/YYYY H:MM:SS AM/PM`, so the same text has to parse back:
|
||||
// 12 AM is midnight and 12 PM is noon, and the other PM hours move to the afternoon.
|
||||
assert_eq!(parse_date_text("1/2/2024 12:00:00 AM"), Some(date_serial(2024, 1, 2, 0, 0, 0)));
|
||||
assert_eq!(parse_date_text("1/2/2024 12:00:00 PM"), Some(date_serial(2024, 1, 2, 12, 0, 0)));
|
||||
assert_eq!(parse_date_text("1/2/2024 1:30:15 PM"), Some(date_serial(2024, 1, 2, 13, 30, 15)));
|
||||
assert_eq!(parse_date_text("1/2/2024 1:30:15 AM"), Some(date_serial(2024, 1, 2, 1, 30, 15)));
|
||||
// A suffixed hour is 1-12, so 13 PM and 0 AM are impossible rather than 13:00 and 00:00.
|
||||
assert_eq!(parse_date_text("1/2/2024 13:00:00 PM"), None);
|
||||
assert_eq!(parse_date_text("1/2/2024 0:00:00 AM"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rounding_snaps_binary_noise_at_fifteen_digits() {
|
||||
// `value * 100` carries the binary error of the input, and a directed rounding exposes it.
|
||||
assert_eq!(round_to(1.005, 2), 1.01);
|
||||
assert_eq!(round_direction(0.29, 2, false), 0.29);
|
||||
assert_eq!(round_direction(0.07, 2, true), 0.07);
|
||||
// The ordinary cases still behave: sign-aware directed rounding and half away from zero.
|
||||
assert_eq!(round_direction(-2.9, 0, false), -2.0);
|
||||
assert_eq!(round_direction(-2.1, 0, true), -3.0);
|
||||
assert_eq!(round_to(2.5, 0), 3.0);
|
||||
assert_eq!(round_to(2.345, 2), 2.35);
|
||||
// An exact whole input is already the answer: scaling it past 2^53 must not snap digits.
|
||||
assert_eq!(round_to(1_234_567_890_123_457.0, 1), 1_234_567_890_123_457.0);
|
||||
assert_eq!(round_direction(1_234_567_890_123_457.0, 2, true), 1_234_567_890_123_457.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gcd_and_lcm_report_results_that_do_not_fit() {
|
||||
assert_eq!(gcd(12, 18), 6);
|
||||
// `i64::MIN` has no positive counterpart: the magnitudes are used instead of `abs`.
|
||||
assert_eq!(gcd(i64::MIN, 2), 2);
|
||||
assert_eq!(lcm(4, 6), Some(12));
|
||||
assert_eq!(lcm(0, 7), Some(0));
|
||||
// Coprime operands above 2^32 overflow the product, which Excel answers with `#NUM!`.
|
||||
assert_eq!(lcm(1 << 40, (1 << 40) + 1), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
//! Semantic catalog of the DAX functions.
|
||||
//!
|
||||
//! The catalog records the documented signature of every function in every
|
||||
//! <https://dax.guide/functions/> category — arity, parameter kinds, overloads, return type,
|
||||
//! iterator/volatile behaviour, syntax-sugar relationships, blank handling and host-compatibility
|
||||
//! flags. It is static metadata: the parser already accepts these calls, and [`crate::validate`]
|
||||
//! uses the records to reject statically impossible arguments.
|
||||
//!
|
||||
//! Documentation conflicts (for example whether `COUNTBLANK` returns 0 when rows exist but no
|
||||
//! cell is blank) are recorded as [`BlankPolicy::Unspecified`] instead of silently picking one
|
||||
//! source. See the crate README for the per-function notes.
|
||||
|
||||
/// The function family, matching dax.guide's category pages.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum FunctionCategory {
|
||||
Aggregation,
|
||||
DateAndTime,
|
||||
Filter,
|
||||
Financial,
|
||||
Information,
|
||||
Logical,
|
||||
MathAndTrig,
|
||||
Other,
|
||||
ParentChild,
|
||||
RelationshipManagement,
|
||||
Statistical,
|
||||
TableManipulation,
|
||||
Text,
|
||||
TimeIntelligence,
|
||||
VisualCalculations,
|
||||
}
|
||||
|
||||
impl FunctionCategory {
|
||||
pub const ALL: [FunctionCategory; 15] = [
|
||||
FunctionCategory::Aggregation,
|
||||
FunctionCategory::DateAndTime,
|
||||
FunctionCategory::Filter,
|
||||
FunctionCategory::Financial,
|
||||
FunctionCategory::Information,
|
||||
FunctionCategory::Logical,
|
||||
FunctionCategory::MathAndTrig,
|
||||
FunctionCategory::Other,
|
||||
FunctionCategory::ParentChild,
|
||||
FunctionCategory::RelationshipManagement,
|
||||
FunctionCategory::Statistical,
|
||||
FunctionCategory::TableManipulation,
|
||||
FunctionCategory::Text,
|
||||
FunctionCategory::TimeIntelligence,
|
||||
FunctionCategory::VisualCalculations,
|
||||
];
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
FunctionCategory::Aggregation => "Aggregation",
|
||||
FunctionCategory::DateAndTime => "Date and Time",
|
||||
FunctionCategory::Filter => "Filter",
|
||||
FunctionCategory::Financial => "Financial",
|
||||
FunctionCategory::Information => "Information",
|
||||
FunctionCategory::Logical => "Logical",
|
||||
FunctionCategory::MathAndTrig => "Math and Trig",
|
||||
FunctionCategory::Other => "Other",
|
||||
FunctionCategory::ParentChild => "Parent-child",
|
||||
FunctionCategory::RelationshipManagement => "Relationship management",
|
||||
FunctionCategory::Statistical => "Statistical",
|
||||
FunctionCategory::TableManipulation => "Table manipulation",
|
||||
FunctionCategory::Text => "Text",
|
||||
FunctionCategory::TimeIntelligence => "Time Intelligence",
|
||||
FunctionCategory::VisualCalculations => "Visual calculations",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What an argument position accepts.
|
||||
///
|
||||
/// Only [`ParamKind::Column`] and [`ParamKind::Table`] can be checked without a data model;
|
||||
/// the remaining kinds are recorded for documentation and future type checking.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ParamKind {
|
||||
/// A column reference such as `Sales[Amount]` or `[Amount]`.
|
||||
Column,
|
||||
/// A table expression such as `Sales`, `FILTER ( ... )` or `{ 1, 2 }`.
|
||||
Table,
|
||||
/// A scalar expression evaluated in the iterator's row context.
|
||||
Expression,
|
||||
/// A scalar expression evaluated in the caller's context.
|
||||
Scalar,
|
||||
/// A logical (Boolean) expression.
|
||||
Logical,
|
||||
/// Any expression.
|
||||
Any,
|
||||
/// A date/time value.
|
||||
Date,
|
||||
/// A text value.
|
||||
Text,
|
||||
/// A numeric value.
|
||||
Number,
|
||||
/// A Boolean value.
|
||||
Boolean,
|
||||
/// A function or lambda reference.
|
||||
Function,
|
||||
/// A table or column reference.
|
||||
Reference,
|
||||
/// A JSON value.
|
||||
Json,
|
||||
/// A value whose type is decided at run time.
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ParamKind {
|
||||
/// Human-readable description used in validation messages.
|
||||
pub const fn description(self) -> &'static str {
|
||||
match self {
|
||||
ParamKind::Column => "a column reference",
|
||||
ParamKind::Table => "a table expression",
|
||||
ParamKind::Expression => "an expression",
|
||||
ParamKind::Scalar => "a scalar expression",
|
||||
ParamKind::Logical => "a logical expression",
|
||||
ParamKind::Any => "any expression",
|
||||
ParamKind::Date => "a date/time expression",
|
||||
ParamKind::Text => "a text expression",
|
||||
ParamKind::Number => "a numeric expression",
|
||||
ParamKind::Boolean => "a Boolean expression",
|
||||
ParamKind::Function => "a function reference",
|
||||
ParamKind::Reference => "a table or column reference",
|
||||
ParamKind::Json => "a JSON value",
|
||||
ParamKind::Variant => "a value of any type",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The documented result type. `Numeric` covers decimal/currency/integer results whose exact
|
||||
/// type depends on the model, and `Any` covers functions whose result type follows the inputs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ReturnType {
|
||||
Integer,
|
||||
Numeric,
|
||||
Currency,
|
||||
Decimal,
|
||||
Any,
|
||||
Boolean,
|
||||
DateTime,
|
||||
String,
|
||||
Table,
|
||||
Blank,
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl ReturnType {
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
ReturnType::Integer => "Integer",
|
||||
ReturnType::Numeric => "Numeric",
|
||||
ReturnType::Currency => "Currency",
|
||||
ReturnType::Decimal => "Decimal",
|
||||
ReturnType::Any => "Any",
|
||||
ReturnType::Boolean => "Boolean",
|
||||
ReturnType::DateTime => "DateTime",
|
||||
ReturnType::String => "String",
|
||||
ReturnType::Table => "Table",
|
||||
ReturnType::Blank => "Blank",
|
||||
ReturnType::Variant => "Variant",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns when there is nothing to aggregate.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum BlankPolicy {
|
||||
/// BLANK when the input has no rows or no qualifying value.
|
||||
BlankWhenEmpty,
|
||||
/// 0 when rows exist but none match, as Microsoft Learn documents for some functions. The
|
||||
/// catalog does not currently use this variant: observed engine behaviour and dax.guide
|
||||
/// disagree with that rule for every function where it was considered.
|
||||
ZeroWhenRowsButNoMatch,
|
||||
/// Sources conflict or are silent; callers must not rely on either result.
|
||||
Unspecified,
|
||||
}
|
||||
|
||||
impl BlankPolicy {
|
||||
/// Human-readable description used by documentation and tests.
|
||||
pub const fn description(self) -> &'static str {
|
||||
match self {
|
||||
BlankPolicy::BlankWhenEmpty => "BLANK when empty",
|
||||
BlankPolicy::ZeroWhenRowsButNoMatch => "0 when rows exist but none match",
|
||||
BlankPolicy::Unspecified => "unspecified",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Behaviours that change how a host or optimiser treats the function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FunctionFlags {
|
||||
/// The function is an iterator: it evaluates a second argument once per row of a table.
|
||||
pub iterator: bool,
|
||||
/// The function may return a different value on every call (`NOW`, `RAND`, ...).
|
||||
pub volatile: bool,
|
||||
/// dax.guide marks the function as not recommended.
|
||||
pub not_recommended: bool,
|
||||
/// The function is available to Excel's embedded DAX engine.
|
||||
pub excel_compatible: bool,
|
||||
/// Microsoft Learn documents DirectQuery restrictions (calculated columns / RLS rules).
|
||||
pub direct_query_limited: bool,
|
||||
}
|
||||
|
||||
impl FunctionFlags {
|
||||
pub const fn new(iterator: bool, volatile: bool, not_recommended: bool, excel_compatible: bool, direct_query_limited: bool) -> Self {
|
||||
FunctionFlags { iterator, volatile, not_recommended, excel_compatible, direct_query_limited }
|
||||
}
|
||||
}
|
||||
|
||||
/// One argument in a descriptive signature, including whether it may be omitted.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Parameter {
|
||||
pub name: &'static str,
|
||||
pub kind: ParamKind,
|
||||
pub optional: bool,
|
||||
}
|
||||
|
||||
const fn required(name: &'static str, kind: ParamKind) -> Parameter {
|
||||
Parameter { name, kind, optional: false }
|
||||
}
|
||||
|
||||
const fn optional(name: &'static str, kind: ParamKind) -> Parameter {
|
||||
Parameter { name, kind, optional: true }
|
||||
}
|
||||
|
||||
/// One exact arity and its parameter kinds. Overloads enumerate every accepted arity, including
|
||||
/// zero-argument `COUNTROWS ()` and the optional `Variant` argument of `MAXX`/`MINX`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Overload {
|
||||
pub params: &'static [ParamKind],
|
||||
/// When true, the last parameter kind repeats for every additional argument.
|
||||
pub variadic: bool,
|
||||
}
|
||||
|
||||
impl Overload {
|
||||
pub const fn arity(self) -> usize {
|
||||
self.params.len()
|
||||
}
|
||||
|
||||
/// Whether this overload accepts exactly `arity` arguments.
|
||||
pub const fn matches(self, arity: usize) -> bool {
|
||||
if self.variadic { arity >= self.params.len() } else { arity == self.params.len() }
|
||||
}
|
||||
|
||||
/// The parameter kind at `index`; a variadic overload repeats its last kind.
|
||||
pub fn kind_at(self, index: usize) -> Option<ParamKind> {
|
||||
self.params.get(index).copied().or_else(|| if self.variadic { self.params.last().copied() } else { None })
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn overload(params: &'static [ParamKind]) -> Overload {
|
||||
Overload { params, variadic: false }
|
||||
}
|
||||
|
||||
pub const fn variadic(params: &'static [ParamKind]) -> Overload {
|
||||
Overload { params, variadic: true }
|
||||
}
|
||||
|
||||
/// A complete catalog record.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionSpec {
|
||||
pub name: &'static str,
|
||||
pub category: FunctionCategory,
|
||||
pub min_args: usize,
|
||||
pub max_args: usize,
|
||||
/// Descriptive signature. Optional markers live here; [`FunctionSpec::overloads`] enumerates
|
||||
/// the concrete arity/kind combinations.
|
||||
pub params: &'static [Parameter],
|
||||
pub overloads: &'static [Overload],
|
||||
pub return_type: ReturnType,
|
||||
pub flags: FunctionFlags,
|
||||
/// The function this one is syntax sugar for, when the semantics are identical.
|
||||
pub sugar_of: Option<&'static str>,
|
||||
pub blank_policy: BlankPolicy,
|
||||
pub description: &'static str,
|
||||
pub examples: &'static [&'static str],
|
||||
}
|
||||
|
||||
impl FunctionSpec {
|
||||
/// Whether the function evaluates an expression per row of a table.
|
||||
pub const fn is_iterator(&self) -> bool {
|
||||
self.flags.iterator
|
||||
}
|
||||
|
||||
/// The overload accepting exactly `arity` arguments, if any.
|
||||
pub fn overload_for(&self, arity: usize) -> Option<&Overload> {
|
||||
self.overloads.iter().find(|overload| overload.matches(arity))
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a catalog record with no syntax-sugar link and an unspecified blank policy. Most
|
||||
/// functions use this; aggregation records spell out the extra fields.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub const fn spec(
|
||||
name: &'static str,
|
||||
category: FunctionCategory,
|
||||
min_args: usize,
|
||||
max_args: usize,
|
||||
params: &'static [Parameter],
|
||||
overloads: &'static [Overload],
|
||||
return_type: ReturnType,
|
||||
flags: FunctionFlags,
|
||||
description: &'static str,
|
||||
examples: &'static [&'static str],
|
||||
) -> FunctionSpec {
|
||||
FunctionSpec {
|
||||
name,
|
||||
category,
|
||||
min_args,
|
||||
max_args,
|
||||
params,
|
||||
overloads,
|
||||
return_type,
|
||||
flags,
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description,
|
||||
examples,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn standard(iterator: bool) -> FunctionFlags {
|
||||
FunctionFlags::new(iterator, false, false, true, true)
|
||||
}
|
||||
|
||||
/// All aggregation functions, in the order listed by dax.guide.
|
||||
pub static AGGREGATION: [FunctionSpec; 22] = [
|
||||
FunctionSpec {
|
||||
name: "APPROXIMATEDISTINCTCOUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: FunctionFlags::new(false, false, false, false, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Approximates the number of distinct values in a column. DirectQuery models \
|
||||
push the aggregation to the source; Import models use HyperLogLog with a \
|
||||
small error rate. The argument must be a column reference.",
|
||||
examples: &["APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGE",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("AVERAGEX"),
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Arithmetic mean of a numeric column, ignoring blanks and including zero. \
|
||||
Syntax sugar for AVERAGEX. dax.guide returns BLANK when no value qualifies, \
|
||||
while Microsoft Learn documents 0 when rows exist; the catalog keeps the \
|
||||
conflict explicit.",
|
||||
examples: &["AVERAGE ( Sales[Amount] )", "AVERAGE ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGEA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: FunctionFlags::new(false, false, true, true, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Averages a column, counting TRUE as 1, FALSE as 0 and any text as 0. \
|
||||
Internally evaluated with AVERAGEX but not pure sugar because of those \
|
||||
coercions; dax.guide marks it not recommended. Sources disagree on the \
|
||||
empty/all-blank result.",
|
||||
examples: &["AVERAGEA ( Customer[LargeFamily] )", "AVERAGEA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "AVERAGEX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression once per row of the table and returns the mean of \
|
||||
the non-blank results, including zeros. The expression runs in row context, \
|
||||
so a measure reference triggers context transition.",
|
||||
examples: &["AVERAGEX ( Sales, Sales[Quantity] * Sales[Net Price] )", "AVERAGEX ( Customer, [Sales Amount] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("COUNTX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts non-blank numbers, dates and strings in a column; empty strings count \
|
||||
and booleans do not. Syntax sugar for COUNTX.",
|
||||
examples: &["COUNT ( Customer[Customer Name] )", "COUNT ( Sales[Text] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("COUNTAX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts non-blank values in a column, including booleans (as values, not as \
|
||||
1/0). Syntax sugar for COUNTAX.",
|
||||
examples: &["COUNTA ( Customer[Customer Name] )", "COUNTA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTAX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and counts non-blank results, including \
|
||||
booleans.",
|
||||
examples: &["COUNTAX ( Customer, Customer[LargeFamily] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTBLANK",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Counts blanks in a column of any type; the empty string counts as blank and \
|
||||
zero does not. dax.guide says the function never returns 0, while Microsoft \
|
||||
Learn documents 0 when rows exist but no value is blank.",
|
||||
examples: &["COUNTBLANK ( Customer[Customer Name] )", "COUNTBLANK ( Sales[Text] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTROWS",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 0,
|
||||
max_args: 1,
|
||||
params: &[optional("Table", ParamKind::Table)],
|
||||
overloads: &[overload(&[]), overload(&[ParamKind::Table])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts the rows of a table expression. With no argument it counts the home \
|
||||
table of the measure or calculated column. Excel's embedded engine accepts \
|
||||
the one-argument form only.",
|
||||
examples: &["COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )", "COUNTROWS ( )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "COUNTX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and counts non-blank results of type number, \
|
||||
date or string; booleans are not counted (use COUNTAX).",
|
||||
examples: &["COUNTX ( Customer, DIVIDE ( Customer[Total Children], Customer[Cars Owned] ) )", "COUNTX ( Sales, Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "DISTINCTCOUNT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Counts distinct values in a column of any type. BLANK is one distinct value; \
|
||||
totals are not additive. Equivalent to COUNTROWS ( DISTINCT ( table[column] ) ).",
|
||||
examples: &["DISTINCTCOUNT ( Store[Area Manager] )", "DISTINCTCOUNT ( Sales[Region] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "DISTINCTCOUNTNOBLANK",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Integer,
|
||||
flags: FunctionFlags::new(false, false, false, false, true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Counts distinct values in a column, excluding BLANK — DISTINCTCOUNT counts \
|
||||
BLANK, so this is not pure sugar for it. Not available to Excel's embedded \
|
||||
engine.",
|
||||
examples: &["DISTINCTCOUNTNOBLANK ( Store[Area Manager] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 2,
|
||||
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
|
||||
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "With one argument, the largest non-blank value of a column (the same result \
|
||||
MAXX gives over the column); text compares alphabetically and logical values are unsupported. With \
|
||||
two arguments, the larger scalar, where BLANK is significant per dax.guide \
|
||||
but treated as zero by Microsoft Learn.",
|
||||
examples: &["MAX ( Sales[Net Price] )", "MAX ( 10000, [Sales Amount] )", "MAX ( 3, 5 )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAXA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Largest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
|
||||
ignoring logical values. Internally MAXX. Sources disagree on the empty \
|
||||
result; text is not rankable.",
|
||||
examples: &["MAXA ( Customer[LargeFamily] )", "MAXA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MAXX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 3,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Evaluates the expression per row and returns the largest value, skipping \
|
||||
blanks and ignoring logical values. Mixed-type expressions consider numbers \
|
||||
only unless Variant is TRUE, which compares per ORDER BY DESC.",
|
||||
examples: &["MAXX ( Customer, 1 * Customer[LargeFamily] )", "MAXX ( Sales, Sales[Amount], TRUE )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MIN",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 2,
|
||||
params: &[required("ColumnNameOrScalar1", ParamKind::Any), optional("Scalar2", ParamKind::Scalar)],
|
||||
overloads: &[overload(&[ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Scalar])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "With one argument, the smallest non-blank value of a column (the same result \
|
||||
MINX gives over the column); text compares alphabetically and logical values are unsupported. With \
|
||||
two arguments, the smaller scalar, where BLANK is significant per dax.guide \
|
||||
but treated as zero by Microsoft Learn.",
|
||||
examples: &["MIN ( Sales[Net Price] )", "MIN ( 5000000, [Sales Amount] )", "MIN ( 3, 5 )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MINA",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(false),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Smallest value of a column, counting TRUE as 1 and FALSE as 0 instead of \
|
||||
ignoring logical values. Internally MINX. Sources disagree on the empty \
|
||||
result.",
|
||||
examples: &["MINA ( Customer[LargeFamily] )", "MINA ( Sales[Flag] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "MINX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 3,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), optional("Variant", ParamKind::Logical)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression]), overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Logical])],
|
||||
return_type: ReturnType::Any,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::Unspecified,
|
||||
description: "Evaluates the expression per row and returns the smallest value, skipping \
|
||||
blanks and ignoring logical values. Mixed-type expressions consider numbers \
|
||||
only unless Variant is TRUE, which compares per ORDER BY ASC.",
|
||||
examples: &["MINX ( Customer, 1 * Customer[NoCars] )", "MINX ( Sales, Sales[Amount], FALSE )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "PRODUCT",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Decimal,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("PRODUCTX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Multiplies the numbers in a column, ignoring blanks, logical values and text. \
|
||||
Syntax sugar for PRODUCTX.",
|
||||
examples: &["PRODUCT ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "PRODUCTX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Decimal,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression per row and multiplies the non-blank numeric \
|
||||
results; blanks, logical values and text are ignored, unlike the `*` \
|
||||
operator.",
|
||||
examples: &["PRODUCTX ( Rates, 1 + Rates[InflationRate] )", "PRODUCTX ( Sales, Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "SUM",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 1,
|
||||
max_args: 1,
|
||||
params: &[required("ColumnName", ParamKind::Column)],
|
||||
overloads: &[overload(&[ParamKind::Column])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(false),
|
||||
sugar_of: Some("SUMX"),
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Adds the numbers in a column, ignoring blanks, logical values and text. \
|
||||
Syntax sugar for SUMX. dax.guide says the result type follows the column, \
|
||||
while Microsoft Learn documents a decimal number.",
|
||||
examples: &["SUM ( Sales[Amount] )", "SUM ( Sales[Quantity] )"],
|
||||
},
|
||||
FunctionSpec {
|
||||
name: "SUMX",
|
||||
category: FunctionCategory::Aggregation,
|
||||
min_args: 2,
|
||||
max_args: 2,
|
||||
params: &[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
overloads: &[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
return_type: ReturnType::Numeric,
|
||||
flags: standard(true),
|
||||
sugar_of: None,
|
||||
blank_policy: BlankPolicy::BlankWhenEmpty,
|
||||
description: "Evaluates the expression once per row of the table and sums the numeric \
|
||||
results; blanks, logical values and text are ignored. The expression runs \
|
||||
in row context.",
|
||||
examples: &[
|
||||
"SUMX ( Sales, Sales[Quantity] * Sales[Net Price] )",
|
||||
"SUMX ( FILTER ( InternetSales, InternetSales[SalesTerritoryID] = 5 ), [Freight] )",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
pub mod date_time;
|
||||
pub mod filter;
|
||||
pub mod financial;
|
||||
pub mod information;
|
||||
pub mod logical;
|
||||
pub mod math_trig;
|
||||
pub mod other;
|
||||
pub mod parent_child;
|
||||
pub mod relationships;
|
||||
pub mod statistical;
|
||||
pub mod table_manipulation;
|
||||
pub mod text;
|
||||
pub mod time_intelligence;
|
||||
pub mod visual_calculations;
|
||||
|
||||
/// Every function from every category, in dax.guide category order.
|
||||
static CATALOG: std::sync::LazyLock<Vec<FunctionSpec>> = std::sync::LazyLock::new(|| {
|
||||
let mut all = Vec::with_capacity(600);
|
||||
all.extend_from_slice(&AGGREGATION);
|
||||
all.extend_from_slice(date_time::FUNCTIONS);
|
||||
all.extend_from_slice(filter::FUNCTIONS);
|
||||
all.extend_from_slice(financial::FUNCTIONS);
|
||||
all.extend_from_slice(information::FUNCTIONS);
|
||||
all.extend_from_slice(logical::FUNCTIONS);
|
||||
all.extend_from_slice(math_trig::FUNCTIONS);
|
||||
all.extend_from_slice(other::FUNCTIONS);
|
||||
all.extend_from_slice(parent_child::FUNCTIONS);
|
||||
all.extend_from_slice(relationships::FUNCTIONS);
|
||||
all.extend_from_slice(statistical::FUNCTIONS);
|
||||
all.extend_from_slice(table_manipulation::FUNCTIONS);
|
||||
all.extend_from_slice(text::FUNCTIONS);
|
||||
all.extend_from_slice(time_intelligence::FUNCTIONS);
|
||||
all.extend_from_slice(visual_calculations::FUNCTIONS);
|
||||
all
|
||||
});
|
||||
|
||||
/// Every catalogued function.
|
||||
pub fn catalog() -> &'static [FunctionSpec] {
|
||||
&CATALOG
|
||||
}
|
||||
|
||||
/// Looks a function up by name, ignoring ASCII case.
|
||||
pub fn lookup(name: &str) -> Option<&'static FunctionSpec> {
|
||||
CATALOG.iter().find(|spec| spec.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
//! Date and time functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
use FunctionCategory::DateAndTime;
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CALENDAR",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
standard(false),
|
||||
"CALENDAR ( <StartDate>, <EndDate> ) returns a single-column table named Date with every \
|
||||
day from StartDate to EndDate, both included. Dates are stored as numbers, so integer \
|
||||
bounds such as CALENDAR ( 1, 100 ) are accepted; a date table should cover whole years \
|
||||
for time-intelligence compatibility.",
|
||||
&["CALENDAR ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "CALENDAR ( DATE ( 2023, 7, 1 ), DATE ( 2024, 6, 30 ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALENDARAUTO",
|
||||
DateAndTime,
|
||||
0,
|
||||
1,
|
||||
&[optional("FiscalYearEndMonth", ParamKind::Number)],
|
||||
&[overload(&[]), overload(&[ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
standard(false),
|
||||
"CALENDARAUTO ( [<FiscalYearEndMonth>] ) scans the imported date columns and returns a \
|
||||
contiguous Date table covering whole fiscal years. FiscalYearEndMonth is 1-12 and \
|
||||
defaults to 12 (December); calculated tables and calculated columns are ignored, and \
|
||||
the model must contain at least one imported datetime column or the call fails.",
|
||||
&["CALENDARAUTO ()", "CALENDARAUTO ( 6 )"],
|
||||
),
|
||||
spec(
|
||||
"DATE",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Year", ParamKind::Number), required("Month", ParamKind::Number), required("Day", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"DATE ( <Year>, <Month>, <Day> ) builds a DateTime from numeric parts. Years 0-99 add \
|
||||
1900 (DATE ( 98, 1, 2 ) is 1998-01-02) while years below -1800 or above 9999 raise an \
|
||||
error; month and day overflow roll into neighbouring months and days (DATE ( 2024, 13, \
|
||||
1 ) is 2025-01-01).",
|
||||
&["DATE ( 2024, 1, 1 )", "DATE ( 2024, 13, 1 )", "DATE ( YEAR ( Sales[Order Date] ), 1, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"DATEDIFF",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Date1", ParamKind::Date), required("Date2", ParamKind::Date), required("Interval", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"DATEDIFF ( <Date1>, <Date2>, <Interval> ) counts the Interval boundaries crossed \
|
||||
between two dates, positively when Date2 is later and negatively otherwise. Interval is \
|
||||
an unquoted keyword: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or YEAR.",
|
||||
&["DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), DAY )", "DATEDIFF ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), MONTH )"],
|
||||
),
|
||||
spec(
|
||||
"DATEVALUE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("DateText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"DATEVALUE ( <DateText> ) converts a text date to a DateTime using the locale of the \
|
||||
model, so \"1/8/2009\" may mean January 8 or August 1. A missing year is taken from the \
|
||||
current year and any time portion is ignored.",
|
||||
&["DATEVALUE ( \"2024-01-01\" )", "DATEVALUE ( \"1/8/2009\" )"],
|
||||
),
|
||||
spec(
|
||||
"DAY",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"DAY ( <Date> ) returns the day of the month as an integer from 1 to 31. A text argument \
|
||||
is converted with the same rules as DATEVALUE, so the locale of the model decides how \
|
||||
the text is read.",
|
||||
&["DAY ( DATE ( 2024, 1, 15 ) )", "DAY ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"EDATE",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"EDATE ( <StartDate>, <Months> ) shifts a date by the given number of months, keeping the \
|
||||
day of the month and clamping to the end of shorter months (2024-01-31 plus one month \
|
||||
is 2024-02-29). Unlike EOMONTH it does not move to the end of the month.",
|
||||
&["EDATE ( DATE ( 2024, 1, 31 ), 1 )", "EDATE ( Sales[Order Date], -3 )"],
|
||||
),
|
||||
spec(
|
||||
"EOMONTH",
|
||||
DateAndTime,
|
||||
2,
|
||||
2,
|
||||
&[required("StartDate", ParamKind::Date), required("Months", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"EOMONTH ( <StartDate>, <Months> ) returns the last day of the month that is Months \
|
||||
before or after StartDate; 0 gives the end of the current month. There is no SOMONTH, so \
|
||||
the start of a month is EOMONTH ( <date>, -1 ) + 1.",
|
||||
&["EOMONTH ( DATE ( 2024, 1, 15 ), 0 )", "EOMONTH ( Sales[Order Date], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"HOUR",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"HOUR ( <Datetime> ) gives the hour as an integer from 0 to 23. A string that holds only \
|
||||
a time, such as \"16:48:00\", is accepted and parsed using the client computer's locale \
|
||||
and time settings.",
|
||||
&["HOUR ( TIME ( 16, 48, 23 ) )", "HOUR ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"MINUTE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"MINUTE ( <Datetime> ) gives the minute as an integer from 0 to 59. A string that holds \
|
||||
only a time, such as \"16:48:00\", is accepted and parsed using the client computer's \
|
||||
locale and time settings.",
|
||||
&["MINUTE ( TIME ( 16, 48, 23 ) )", "MINUTE ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"MONTH",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"MONTH ( <Date> ) gives 1 for January through 12 for December. Text arguments are read \
|
||||
with the same rules as DATEVALUE.",
|
||||
&["MONTH ( DATE ( 2024, 1, 15 ) )", "MONTH ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NETWORKDAYS",
|
||||
DateAndTime,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("start_date", ParamKind::Date),
|
||||
required("end_date", ParamKind::Date),
|
||||
optional("weekend", ParamKind::Number),
|
||||
optional("holidays", ParamKind::Table),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Date]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Table]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"NETWORKDAYS ( <start_date>, <end_date> [, <weekend>] [, <holidays>] ) counts whole \
|
||||
workdays between two dates, both included, skipping weekends and holidays. The weekend \
|
||||
code defaults to 1 (Saturday and Sunday), accepts 2-7 for other pairs and 11-17 for a \
|
||||
single day; holidays is a single-column table of dates. Not available in Excel's DAX \
|
||||
engine.",
|
||||
&[
|
||||
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ) )",
|
||||
"NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, { DATE ( 2024, 1, 15 ) } )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"NOW",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Date and time at the moment of evaluation. Volatile: it is evaluated once per query and \
|
||||
moves only when the model or the containing calculated column is refreshed, not \
|
||||
continuously.",
|
||||
&["NOW ()", "YEAR ( NOW () )"],
|
||||
),
|
||||
spec(
|
||||
"QUARTER",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"QUARTER ( <Date> ) gives the calendar quarter number, 1 for January-March through 4 for \
|
||||
October-December; fiscal periods are not followed. Text arguments are read with the \
|
||||
same rules as DATEVALUE.",
|
||||
&["QUARTER ( DATE ( 2024, 5, 15 ) )", "QUARTER ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"SECOND",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Datetime", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"SECOND ( <Datetime> ) gives the second as an integer from 0 to 59. A string that holds \
|
||||
only a time, such as \"16:48:23\", is accepted and parsed using the client computer's \
|
||||
locale and time settings.",
|
||||
&["SECOND ( TIME ( 16, 48, 23 ) )", "SECOND ( Sales[Order Time] )"],
|
||||
),
|
||||
spec(
|
||||
"TIME",
|
||||
DateAndTime,
|
||||
3,
|
||||
3,
|
||||
&[required("Hour", ParamKind::Number), required("Minute", ParamKind::Number), required("Second", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"TIME ( <Hour>, <Minute>, <Second> ) builds a time on the 1899-12-30 epoch. Overflowing \
|
||||
arguments wrap inside the same day instead of raising an error (TIME ( 10, 90, 0 ) is \
|
||||
11:30 and TIME ( 50, 0, 0 ) is 02:00), and each argument is limited to 32,767.",
|
||||
&["TIME ( 16, 48, 23 )", "TIME ( 10, 90, 0 )"],
|
||||
),
|
||||
spec(
|
||||
"TIMEVALUE",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("TimeText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::DateTime,
|
||||
standard(false),
|
||||
"TIMEVALUE ( <TimeText> ) converts a text time to a DateTime, ignoring any date portion \
|
||||
of the string. Parsing uses the client computer's locale, date and time settings, so the \
|
||||
same text can fail or mean a different time on another machine.",
|
||||
&["TIMEVALUE ( \"16:48:23\" )", "TIMEVALUE ( \"4:48:47 PM\" )"],
|
||||
),
|
||||
spec(
|
||||
"TODAY",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"TODAY () returns the current date at 12:00:00 AM. Volatile: it is evaluated once per \
|
||||
query and only changes when the model or the containing calculated column is refreshed, \
|
||||
not continuously.",
|
||||
&["TODAY ()", "TODAY () - Sales[Order Date]"],
|
||||
),
|
||||
spec(
|
||||
"UTCNOW",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"UTCNOW () gives the date and time at the moment of evaluation, expressed in Coordinated \
|
||||
Universal Time. Volatile: it is evaluated once per query. The Power BI Service always \
|
||||
runs on UTC and applies no daylight saving, so NOW and UTCNOW agree there.",
|
||||
&["UTCNOW ()", "NOW () - UTCNOW ()"],
|
||||
),
|
||||
spec(
|
||||
"UTCTODAY",
|
||||
DateAndTime,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::DateTime,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"UTCTODAY () returns the current date at 12:00:00 AM in Coordinated Universal Time. \
|
||||
Volatile: it is evaluated once per query and only changes when the model is refreshed.",
|
||||
&["UTCTODAY ()", "TODAY () - UTCTODAY ()"],
|
||||
),
|
||||
spec(
|
||||
"WEEKDAY",
|
||||
DateAndTime,
|
||||
1,
|
||||
2,
|
||||
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"WEEKDAY ( <Date> [, <ReturnType>] ) returns the day of the week. ReturnType 1 (default) \
|
||||
numbers Sunday 1 through Saturday 7, 2 numbers Monday 1 through Sunday 7, 3 numbers \
|
||||
Monday 0 through Sunday 6, and 11-17 start the week on Monday through Sunday. A text \
|
||||
argument is converted with the same rules as DATEVALUE.",
|
||||
&["WEEKDAY ( DATE ( 2024, 1, 1 ) )", "WEEKDAY ( Sales[Order Date], 2 )"],
|
||||
),
|
||||
spec(
|
||||
"WEEKNUM",
|
||||
DateAndTime,
|
||||
1,
|
||||
2,
|
||||
&[required("Date", ParamKind::Date), optional("ReturnType", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"WEEKNUM ( <Date> [, <ReturnType>] ) gives the week number within the year. The documented \
|
||||
codes are 1 (default), 2, 11-17 and 21: 1, 2 and 11-17 use system 1, where the week \
|
||||
containing January 1 is week 1 (each code picks the first day of the week: 1 Sunday, 2 \
|
||||
Monday, 11 Monday, 12 Tuesday, ... 17 Sunday), and 21 uses ISO 8601 system 2, where the \
|
||||
week containing the first Thursday is week 1. Codes 3-10 are not valid. Text arguments \
|
||||
are read with the same rules as DATEVALUE.",
|
||||
&["WEEKNUM ( DATE ( 2024, 1, 15 ) )", "WEEKNUM ( Sales[Order Date], 21 )"],
|
||||
),
|
||||
spec(
|
||||
"YEAR",
|
||||
DateAndTime,
|
||||
1,
|
||||
1,
|
||||
&[required("Date", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"YEAR ( <Date> ) gives the calendar year as a four-digit integer between 1900 and 9999. \
|
||||
Text arguments are read with the same rules as DATEVALUE.",
|
||||
&["YEAR ( DATE ( 2024, 1, 1 ) )", "YEAR ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"YEARFRAC",
|
||||
DateAndTime,
|
||||
2,
|
||||
3,
|
||||
&[required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date), optional("Basis", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"YEARFRAC ( <StartDate>, <EndDate> [, <Basis>] ) returns the fraction of a year between \
|
||||
two dates. Basis selects the day-count convention: 0 (default) US 30/360, 1 \
|
||||
actual/actual, 2 actual/360, 3 actual/365 and 4 European 30/360. Because of a known bug \
|
||||
in age calculations, dax.guide suggests INT arithmetic instead.",
|
||||
&["YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )", "YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), 1 )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,561 @@
|
||||
//! Filter functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! This category covers table expressions that inspect or remove filter context (`ALL`,
|
||||
//! `ALLSELECTED`, ...), the two functions that build a filter context (`CALCULATE`,
|
||||
//! `CALCULATETABLE`), and the window/apply clauses (`INDEX`, `OFFSET`, `WINDOW`, `ORDERBY`,
|
||||
//! `PARTITIONBY`, `MATCHBY`) that are only meaningful inside one of those table expressions.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Functions whose original implementation shipped in Excel's embedded engine. The argument
|
||||
/// order and semantics are shared with Excel 2016 and later.
|
||||
const EXCEL: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Engine features that Power BI uses internally for composite models and window functions.
|
||||
/// Excel's embedded engine rejects them, and the DirectQuery notes still apply.
|
||||
const INTERNAL: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// `FILTER` is an iterator: it evaluates its predicate once per row.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ALL",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Returns a table ignoring any filters on it, or every value of a column ignoring the \
|
||||
filters on that column. As a table expression it materialises all rows (or all distinct \
|
||||
values of one or more columns). Without arguments it works only inside \
|
||||
CALCULATE/CALCULATETABLE and clears the whole filter context.",
|
||||
&["ALL ( Sales )", "ALL ( Sales[Region] )", "ALL ( Sales, Sales[Region], Sales[Country] )", "ALL ( )"],
|
||||
),
|
||||
spec(
|
||||
"ALLCROSSFILTERED",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableName", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Removes, as a CALCULATE modifier only, every filter on a table and on the tables that \
|
||||
cross-filter it through weak or bidirectional relationships. Unlike ALL it never returns \
|
||||
a materialised table, so it cannot be used as a table expression.",
|
||||
&["ALLCROSSFILTERED ( Sales )", "ALLCROSSFILTERED ( 'Product' )"],
|
||||
),
|
||||
spec(
|
||||
"ALLEXCEPT",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("TableName", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Removes all filters from a table except those on the listed columns. As a CALCULATE \
|
||||
modifier it keeps only the named column filters; as a table expression it materialises \
|
||||
the unique combinations of the table's remaining columns.",
|
||||
&["ALLEXCEPT ( Sales, Sales[Region] )", "ALLEXCEPT ( 'Product', 'Product'[Color], 'Product'[Brand] )"],
|
||||
),
|
||||
spec(
|
||||
"ALLNOBLANKROW",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Like ALL, removes the filters on a table or on the listed columns, but always excludes \
|
||||
the blank row that the engine adds for an invalid relationship. Real blank values stored \
|
||||
in the columns are kept in the result.",
|
||||
&["ALLNOBLANKROW ( Customer )", "ALLNOBLANKROW ( Customer[Country], Customer[City] )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTED",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Restores the filters that came from outside the query while ignoring the filters applied \
|
||||
inside it, so the result reflects the outer shadow filter context. As a table expression \
|
||||
it needs at least one argument; without arguments it is only a CALCULATE modifier.",
|
||||
&["ALLSELECTED ( Sales )", "ALLSELECTED ( Sales[Region] )", "ALLSELECTED ( )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTEDAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Marks a table expression supplied to GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE so that it \
|
||||
starts hidden from the filter context and only becomes active when ALLSELECTED runs \
|
||||
inside CALCULATE. Used internally by Power BI composite models.",
|
||||
&["ALLSELECTEDAPPLY ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ALLSELECTEDREMOVE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("TableExpression", ParamKind::Table), optional("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, hides the listed columns of a table \
|
||||
expression from a later ALLSELECTED so they no longer participate in the restored filter \
|
||||
context. With no column argument every column of the expression is hidden.",
|
||||
&["ALLSELECTEDREMOVE ( VALUES ( Product[Color] ) )", "ALLSELECTEDREMOVE ( VALUES ( Product[Color] ), Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ALWAYSAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, forces a filter table to influence the \
|
||||
measures even if the current filter context is unchanged, for example when the table is \
|
||||
empty. Used internally by Power BI composite models.",
|
||||
&["ALWAYSAPPLY ( FILTER ( VALUES ( Product[Color] ), FALSE ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALCULATE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Expression), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression]), variadic(&[ParamKind::Expression, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Evaluates an expression in a filter context modified by its filter arguments: table \
|
||||
expressions replace the filters on their columns, boolean predicates are wrapped in \
|
||||
FILTER over ALL, and context transition turns any row context into an equivalent filter \
|
||||
context. Returns the scalar result of the expression.",
|
||||
&["CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )", "CALCULATE ( [Sales Amount], ALL ( Product ) )"],
|
||||
),
|
||||
spec(
|
||||
"CALCULATETABLE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
EXCEL,
|
||||
"Runs a table expression under the filter context built by its filter arguments, with \
|
||||
the same filter semantics and context transition as CALCULATE but returning a table \
|
||||
instead of a scalar.",
|
||||
&["CALCULATETABLE ( VALUES ( Product[Color] ), Product[Brand] = \"GridCraft\" )"],
|
||||
),
|
||||
spec(
|
||||
"DEPENDON",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("TableExpression", ParamKind::Table), required("ColumnName", ParamKind::Column), optional("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Anchors a table expression to outer columns: its first columns are matched, in order, \
|
||||
against the current values of the listed outer columns, acting as an inner join and \
|
||||
hiding the matched columns from the result. Used internally by Power BI composite \
|
||||
models.",
|
||||
&["DEPENDON ( Sales, Sales[OrderDate] )", "DEPENDON ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[OrderDate] )"],
|
||||
),
|
||||
spec(
|
||||
"FILTER",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("FilterExpression", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Logical])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the rows of a table for which the predicate is TRUE. The predicate runs in a row \
|
||||
context, so it can read the current row's columns; context transition applies when it \
|
||||
calls a measure, and BLANK evaluates as FALSE. Filter context is preserved, not replaced.",
|
||||
&["FILTER ( Sales, Sales[Amount] > 0 )", "FILTER ( ALL ( Sales ), Sales[Region] = \"East\" )"],
|
||||
),
|
||||
spec(
|
||||
"FILTERCLUSTER",
|
||||
FunctionCategory::Filter,
|
||||
4,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
required("Separator", ParamKind::Text),
|
||||
required("TableScan", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Internal helper for GROUPCROSSAPPLY and GROUPCROSSAPPLYTABLE that assembles the \
|
||||
correlated join over a set of groups: group-by columns, filter tables and table scans \
|
||||
are combined with autoexist semantics, and the literal separator only marks where the \
|
||||
table scans begin. Used internally by Power BI composite models.",
|
||||
&["FILTERCLUSTER ( Product[Category], ALL ( Product ), \"\", ALL ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPCROSSAPPLY",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Any),
|
||||
],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Aggregates by the group-by columns across cross-joined filter tables, with no implicit \
|
||||
autoexist. Each name/expression pair adds a column, and rows whose expressions are all \
|
||||
blank are dropped. Used internally by Power BI composite models.",
|
||||
&["GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ) )", "GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ), \"Sales\", [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPCROSSAPPLYTABLE",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("TableExpression", ParamKind::Table),
|
||||
],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Table]), variadic(&[ParamKind::Column, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Like GROUPCROSSAPPLY, but the trailing name/table-expression pairs add whole tables \
|
||||
evaluated under the filter tables' context instead of scalar expressions. Used \
|
||||
internally by Power BI composite models.",
|
||||
&["GROUPCROSSAPPLYTABLE ( 'Date'[Year], ALL ( 'Date' ), \"Colors\", VALUES ( 'Product'[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"INDEX",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
7,
|
||||
&[
|
||||
required("Position", ParamKind::Number),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns, as a one-row table, the row at an absolute position (1-based, negative counts \
|
||||
from the end) within each partition of the relation, sorted by the ORDERBY clause. An \
|
||||
out-of-range or zero position yields an empty table; the relation defaults to \
|
||||
ALLSELECTED over the ordering and partitioning columns.",
|
||||
&[
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ) )",
|
||||
"INDEX ( -1, ALLSELECTED ( Sales ) )",
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ), KEEP, PARTITIONBY ( Sales[Region] ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"KEEPFILTERS",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Filter modifier that makes its argument intersect the existing filter context instead of \
|
||||
replacing it, so a conflicting existing filter is kept. Applies to a CALCULATE or \
|
||||
CALCULATETABLE filter argument and also preserves the filter context during context \
|
||||
transition in an iterator.",
|
||||
&["KEEPFILTERS ( Product[Color] = \"Red\" )", "KEEPFILTERS ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUP",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnOrExpression", ParamKind::Any),
|
||||
required("Search_Column", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_Column", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
optional("AssociatedColumnsBehavior", ParamKind::Text),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Searches the cells identified by the search column/value pairs and returns a column value \
|
||||
or an expression evaluated over those cells; filters on columns not listed stay applied. \
|
||||
Only one cell may match, and the optional behaviour argument selects Explicit or \
|
||||
Inferred handling of associated columns.",
|
||||
&["LOOKUP ( [Sales Amount], 'Date'[Year], 2018 )", "LOOKUP ( [Sales Amount], 'Date'[Year], 2018, \"Inferred\" )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUPVALUE",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnName", ParamKind::Column),
|
||||
required("Search_ColumnName", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_ColumnName", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
optional("Alternate_Result", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Returns the result column value from the row where every search column/value pair \
|
||||
matches, ignoring the current filter context. With no match it returns BLANK or the \
|
||||
alternate result; identical values in several matching rows return that value, while \
|
||||
different values return the alternate result or an error.",
|
||||
&["LOOKUPVALUE ( Product[Color], Product[ProductKey], 1 )", "LOOKUPVALUE ( Product[Color], Product[ProductKey], 1, \"Unknown\" )"],
|
||||
),
|
||||
spec(
|
||||
"LOOKUPWITHTOTALS",
|
||||
FunctionCategory::Filter,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Result_ColumnOrExpression", ParamKind::Any),
|
||||
required("Search_Column", ParamKind::Column),
|
||||
required("Search_Value", ParamKind::Any),
|
||||
optional("Search_Column", ParamKind::Column),
|
||||
optional("Search_Value", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Searches the cells identified by the search column/value pairs, like LOOKUP, but resets \
|
||||
the non-specified columns to their grand total instead of keeping the current filters. \
|
||||
Equivalent to COLLAPSEALL around LOOKUP.",
|
||||
&["LOOKUPWITHTOTALS ( [Sales Amount], [Year], 2018 )"],
|
||||
),
|
||||
spec(
|
||||
"MATCHBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("MatchBy_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the columns that identify the current row for a window function such as INDEX, \
|
||||
OFFSET or WINDOW. It is a clause, not a value: it can only appear inside a window \
|
||||
function and does not change the filter context by itself.",
|
||||
&["MATCHBY ( Sales[OrderKey] )", "MATCHBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"NONFILTER",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, keeps a table expression out of the filter \
|
||||
context permanently, even when its columns carry lineage, as if they were extension \
|
||||
columns. Used internally by Power BI composite models.",
|
||||
&["NONFILTER ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"OFFSET",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
7,
|
||||
&[
|
||||
required("Delta", ParamKind::Number),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns the row that is a number of rows before or after the current row within each \
|
||||
partition of the relation, ordered by the ORDERBY clause. The result is a one-row table; \
|
||||
a delta moving outside the partition yields an empty table.",
|
||||
&["OFFSET ( -1, Sales, ORDERBY ( Sales[OrderDate] ) )", "OFFSET ( 1, Sales )"],
|
||||
),
|
||||
spec(
|
||||
"ORDERBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("OrderBy_Expression", ParamKind::Any), optional("OrderBy_Direction", ParamKind::Any)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the sort expressions and directions (ASC or DESC, optionally with BLANKS FIRST \
|
||||
or BLANKS LAST) used by a window function such as INDEX, OFFSET or WINDOW. It is a \
|
||||
clause rather than a value and cannot be evaluated on its own.",
|
||||
&["ORDERBY ( Sales[Amount], DESC )", "ORDERBY ( Sales[OrderDate], ASC )", "ORDERBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"PARTITIONBY",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("PartitionBy_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), variadic(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
INTERNAL,
|
||||
"Declares the model columns that partition the relation of a window function such as \
|
||||
INDEX, OFFSET or WINDOW. It is a clause rather than a value, and the columns must have a \
|
||||
valid data lineage.",
|
||||
&["PARTITIONBY ( Sales[Region] )", "PARTITIONBY ( )"],
|
||||
),
|
||||
spec(
|
||||
"REMOVEFILTERS",
|
||||
FunctionCategory::Filter,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("TableNameOrColumnName", ParamKind::Reference), optional("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[]), overload(&[ParamKind::Reference]), variadic(&[ParamKind::Reference, ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Alias for ALL with the same filter-removal semantics: it clears the filters on the named \
|
||||
table or columns, or every filter when called without arguments. It is only valid as a \
|
||||
CALCULATE or CALCULATETABLE modifier and never returns a table.",
|
||||
&["REMOVEFILTERS ( Sales )", "REMOVEFILTERS ( Sales[Region] )", "REMOVEFILTERS ( )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDVALUE",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), optional("AlternateResult", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EXCEL,
|
||||
"Returns the value of a column when the filter context leaves exactly one distinct value, \
|
||||
otherwise returns the alternate result (BLANK when omitted). Equivalent to \
|
||||
IF ( HASONEVALUE ( column ), VALUES ( column ), alternate ).",
|
||||
&["SELECTEDVALUE ( Product[Color] )", "SELECTEDVALUE ( Product[Color], \"Multiple colors\" )"],
|
||||
),
|
||||
spec(
|
||||
"SHADOWCLUSTER",
|
||||
FunctionCategory::Filter,
|
||||
1,
|
||||
1,
|
||||
&[required("TableExpression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"In GROUPCROSSAPPLY or GROUPCROSSAPPLYTABLE, marks a table expression as a shadow so that \
|
||||
it is only enabled inside an ALLSELECTED context. Used internally by Power BI composite \
|
||||
models.",
|
||||
&["SHADOWCLUSTER ( VALUES ( Product[Color] ) )"],
|
||||
),
|
||||
spec(
|
||||
"WINDOW",
|
||||
FunctionCategory::Filter,
|
||||
2,
|
||||
10,
|
||||
&[
|
||||
required("From", ParamKind::Number),
|
||||
optional("FromType", ParamKind::Any),
|
||||
required("To", ParamKind::Number),
|
||||
optional("ToType", ParamKind::Any),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Number,
|
||||
ParamKind::Any,
|
||||
ParamKind::Table,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
ParamKind::Any,
|
||||
]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
INTERNAL,
|
||||
"Returns the rows between a start and an end boundary within each partition of the \
|
||||
relation, ordered by the ORDERBY clause. REL boundaries count rows from the current row \
|
||||
while ABS boundaries are absolute positions in the partition; the result is a table.",
|
||||
&["WINDOW ( 1, ABS, 1, ABS, Sales, ORDERBY ( Sales[OrderDate] ) )", "WINDOW ( -1, REL, 1, REL, Sales )"],
|
||||
),
|
||||
];
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,993 @@
|
||||
//! Information functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The `INFO.*` records take no required arguments: dax.guide documents an optional, repeatable
|
||||
//! `RestrictionName` / `RestrictionValue` pair for every one of them, so their arity is open and
|
||||
//! the descriptive signature keeps both positions optional. The `INFO.VIEW.*` functions take no
|
||||
//! arguments at all.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// An `INFO.*` table function with the shared optional restriction-pair syntax.
|
||||
macro_rules! info {
|
||||
($name:literal, $description:literal) => {
|
||||
spec(
|
||||
$name,
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
|
||||
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
$description,
|
||||
&[concat!($name, " ()")],
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COLUMNSTATISTICS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns one row per column visible in the model, with the table name, column name, \
|
||||
minimum, maximum, cardinality and maximum string length. The statistics respect the \
|
||||
security roles of the connected user.",
|
||||
&["COLUMNSTATISTICS ()"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINS",
|
||||
FunctionCategory::Information,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("ColumnName", ParamKind::Column), required("Value", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when at least one row of the table has all the supplied column/value \
|
||||
pairs. Each pair is a column reference followed by the value to match, using strict \
|
||||
equality (BLANK does not match 0).",
|
||||
&["CONTAINS ( Product, Product[Color], \"Red\" )", "CONTAINS ( Sales, Sales[ProductKey], 1, Sales[Quantity], 2 )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSROW",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Value", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table has a row whose values equal every supplied value, in \
|
||||
column order. The IN operator executes this function; comparisons are strict, so \
|
||||
BLANK does not match 0.",
|
||||
// The first argument is the row to test against, so both examples pair a one-column table
|
||||
// (a constructor, or a table expression) with exactly one scalar value.
|
||||
&["CONTAINSROW ( { \"Red\", \"Blue\" }, \"Red\" )", "CONTAINSROW ( VALUES ( Sales[ProductKey] ), 1 )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSSTRING",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
2,
|
||||
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when WithinText contains FindText. The comparison is case-insensitive and \
|
||||
accent-sensitive; `?` and `*` are wildcards and `~?` / `~*` match them literally.",
|
||||
&["CONTAINSSTRING ( Product[Product Name], \"red\" )", "CONTAINSSTRING ( \"Hello\", \"ell\" )"],
|
||||
),
|
||||
spec(
|
||||
"CONTAINSSTRINGEXACT",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
2,
|
||||
&[required("WithinText", ParamKind::Text), required("FindText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when WithinText contains FindText using a case-sensitive and \
|
||||
accent-sensitive comparison. Wildcards are not interpreted.",
|
||||
&["CONTAINSSTRINGEXACT ( Product[Product Name], \"Red\" )", "CONTAINSSTRINGEXACT ( \"Hello\", \"Hell\" )"],
|
||||
),
|
||||
spec(
|
||||
"CUSTOMDATA",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, true, false),
|
||||
"Returns the CustomData connection-string property supplied by the client, or an empty \
|
||||
string when the connection did not define it. It does not inspect the data model or the \
|
||||
filter context. GridCraft has no client connection string in a workbook, so the \
|
||||
evaluator always answers the empty string.",
|
||||
&["CUSTOMDATA ()"],
|
||||
),
|
||||
spec(
|
||||
"EVALUATEANDLOG",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
3,
|
||||
&[required("Value", ParamKind::Any), optional("Label", ParamKind::Text), optional("MaxRows", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns the first argument unchanged and writes its value to the DAX Evaluation Log \
|
||||
trace event. The optional Label annotates the event; MaxRows caps the rows captured for \
|
||||
a table expression and defaults to 10.",
|
||||
&["EVALUATEANDLOG ( 1 )", "EVALUATEANDLOG ( [Sales Amount] )", "EVALUATEANDLOG ( Sales, \"Sales rows\", 5 )"],
|
||||
),
|
||||
spec(
|
||||
"HASONEFILTER",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the column has exactly one distinct value resulting from direct \
|
||||
filters on that column. Unlike HASONEVALUE it ignores filters propagated from related \
|
||||
tables.",
|
||||
&["HASONEFILTER ( Product[Color] )", "HASONEFILTER ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"HASONEVALUE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the filter context leaves exactly one distinct value in the column, \
|
||||
regardless of whether the filter is direct or propagated through a relationship.",
|
||||
&["HASONEVALUE ( Product[Category] )", "HASONEVALUE ( Sales[Quantity] )"],
|
||||
),
|
||||
info!(
|
||||
"INFO.ALTERNATEOFDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_ALTERNATE_OF_DEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ANNOTATIONS",
|
||||
"One row per annotation in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ATTRIBUTEHIERARCHIES",
|
||||
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHIES schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ATTRIBUTEHIERARCHYSTORAGES",
|
||||
"Exposes the TMSCHEMA_ATTRIBUTE_HIERARCHY_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCDEPENDENCY",
|
||||
"Reports which objects a DAX query depends on, so tools can inspect the dependency graph \
|
||||
without parsing formulas."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCULATIONGROUPS",
|
||||
"Exposes the TMSCHEMA_CALCULATIONGROUPS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALCULATIONITEMS",
|
||||
"Exposes the TMSCHEMA_CALCULATIONITEMS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARCOLUMNGROUPS",
|
||||
"Exposes the TMSCHEMA_CALENDAR_COLUMN_GROUPS schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARCOLUMNREFERENCES",
|
||||
"Exposes the TMSCHEMA_CALENDAR_COLUMN_REFERENCES schema rowset as a table; optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CALENDARS",
|
||||
"Exposes the TMSCHEMA_CALENDARS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CATALOGS",
|
||||
"Exposes the DBSCHEMA_CATALOGS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CHANGEDPROPERTIES",
|
||||
"Exposes the TMSCHEMA_CHANGED_PROPERTIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNPARTITIONSTORAGES",
|
||||
"Exposes the TMSCHEMA_COLUMN_PARTITION_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNPERMISSIONS",
|
||||
"One row per column permission in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNS",
|
||||
"One row per column in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.COLUMNSTORAGES",
|
||||
"One row per column storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.CSDLMETADATA",
|
||||
"Provides the model metadata serialized as CSDL XML text, so a tool can read the \
|
||||
conceptual schema without a client library."
|
||||
),
|
||||
info!(
|
||||
"INFO.CULTURES",
|
||||
"One row per culture in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DATACOVERAGEDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_DATACOVERAGEDEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DATASOURCES",
|
||||
"Exposes the TMSCHEMA_DATASOURCES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DELTATABLEMETADATASTORAGES",
|
||||
"Exposes the TMSCHEMA_DELTA_TABLE_METADATA_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DEPENDENCIES",
|
||||
"Returns the dependency records of a DAX query, describing what the query reads from the \
|
||||
model."
|
||||
),
|
||||
info!(
|
||||
"INFO.DETAILROWSDEFINITIONS",
|
||||
"One row per detail-rows definition in the model, with the columns of the matching \
|
||||
schema rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.DICTIONARYSTORAGES",
|
||||
"Exposes the TMSCHEMA_DICTIONARY_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXCLUDEDARTIFACTS",
|
||||
"Exposes the TMSCHEMA_EXCLUDED_ARTIFACTS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXPRESSIONS",
|
||||
"One row per expression in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.EXTENDEDPROPERTIES",
|
||||
"One row per extended property in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.FORMATSTRINGDEFINITIONS",
|
||||
"Exposes the TMSCHEMA_FORMAT_STRING_DEFINITIONS data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.FUNCTIONS",
|
||||
"Lists the DAX functions the engine makes available, one row per function. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.GENERALSEGMENTMAPSEGMENTMETADATASTORAGES",
|
||||
"Exposes the TMSCHEMA_GENERAL_SEGMENT_MAP_SEGMENT_METADATA_STORAGES data management view \
|
||||
as a table; the optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.GROUPBYCOLUMNS",
|
||||
"Exposes the TMSCHEMA_GROUP_BY_COLUMNS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.HIERARCHIES",
|
||||
"Exposes the TMSCHEMA_HIERARCHIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.HIERARCHYSTORAGES",
|
||||
"Exposes the TMSCHEMA_HIERARCHY_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.KPIS",
|
||||
"One row per KPI in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.LEVELS",
|
||||
"One row per level in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.LINGUISTICMETADATA",
|
||||
"Exposes the TMSCHEMA_LINGUISTIC_METADATA schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.MEASURES",
|
||||
"One row per measure in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.MODEL",
|
||||
"Exposes the TMSCHEMA_MODEL schema rowset as a table; optional restriction name/value \
|
||||
pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.OBJECTTRANSLATIONS",
|
||||
"One row per object translation in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARQUETFILESTORAGES",
|
||||
"Exposes the TMSCHEMA_PARQUET_FILE_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARTITIONS",
|
||||
"Exposes the TMSCHEMA_PARTITIONS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PARTITIONSTORAGES",
|
||||
"One row per partition storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVECOLUMNS",
|
||||
"One row per perspective column in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVEHIERARCHIES",
|
||||
"One row per perspective hierarchy in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVEMEASURES",
|
||||
"One row per perspective measure in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVES",
|
||||
"One row per perspective in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PERSPECTIVETABLES",
|
||||
"One row per perspective table in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.PROPERTIES",
|
||||
"Exposes the DISCOVER_PROPERTIES schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.QUERYGROUPS",
|
||||
"Exposes the TMSCHEMA_QUERY_GROUPS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.REFRESHPOLICIES",
|
||||
"Exposes the TMSCHEMA_REFRESH_POLICIES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATEDCOLUMNDETAILS",
|
||||
"Exposes the TMSCHEMA_RELATED_COLUMN_DETAILS data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPINDEXSTORAGES",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIP_INDEX_STORAGES data management view as a table; the \
|
||||
optional restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPS",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIPS schema rowset as a table; optional restriction \
|
||||
name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.RELATIONSHIPSTORAGES",
|
||||
"Exposes the TMSCHEMA_RELATIONSHIP_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ROLEMEMBERSHIPS",
|
||||
"One row per role membership in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.ROLES",
|
||||
"One row per role in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.SEGMENTMAPSTORAGES",
|
||||
"One row per segment map storage in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.SEGMENTSTORAGES",
|
||||
"Exposes the TMSCHEMA_SEGMENT_STORAGES data management view as a table; the optional \
|
||||
restriction name/value pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGEFILES",
|
||||
"One row per storage file in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGEFOLDERS",
|
||||
"One row per storage folder in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGETABLECOLUMNS",
|
||||
"Reports storage statistics for each column of the in-memory tables, so a tool can see \
|
||||
how the model is packed."
|
||||
),
|
||||
info!(
|
||||
"INFO.STORAGETABLECOLUMNSEGMENTS",
|
||||
"Describes the column segments that hold data for the in-memory tables, one row per \
|
||||
segment."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLEPERMISSIONS",
|
||||
"One row per table permission in the model, with the columns of the matching schema \
|
||||
rowset. Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLES",
|
||||
"One row per table in the model, with the columns of the matching schema rowset. Optional \
|
||||
restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.TABLESTORAGES",
|
||||
"One row per table storage in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.USERDEFINEDFUNCTIONS",
|
||||
"Exposes the TMSCHEMA_FUNCTIONS schema rowset as a table; optional restriction name/value \
|
||||
pairs filter its rows."
|
||||
),
|
||||
info!(
|
||||
"INFO.VARIATIONS",
|
||||
"One row per variation in the model, with the columns of the matching schema rowset. \
|
||||
Optional restriction name/value pairs filter the rows."
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.COLUMNS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every column in the model, decoded so a query can use it without joins to \
|
||||
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.COLUMNS ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.MEASURES",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every measure in the model, decoded so a query can use it without joins to \
|
||||
other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.MEASURES ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.RELATIONSHIPS",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every relationship in the model, decoded so a query can use it without joins \
|
||||
to other DMV rowsets. Unlike the plain INFO functions it is allowed in measures, \
|
||||
calculated columns and calculated tables.",
|
||||
&["INFO.VIEW.RELATIONSHIPS ()"],
|
||||
),
|
||||
spec(
|
||||
"INFO.VIEW.TABLES",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Table of every table in the model, decoded so a query can use it without joins to other \
|
||||
DMV rowsets. Unlike the plain INFO functions it is allowed in measures, calculated \
|
||||
columns and calculated tables.",
|
||||
&["INFO.VIEW.TABLES ()"],
|
||||
),
|
||||
spec(
|
||||
"ISAFTER",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the Value1/Value2 groups compare strictly after the corresponding \
|
||||
values in the ascending/descending order given by each optional Order flag. The \
|
||||
comparison uses the existing evaluation context; ISAFTER is not an iterator.",
|
||||
&["ISAFTER ( Sales[Year], 2008 )", "ISAFTER ( Sales[Year], 2008, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ISBLANK",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is BLANK. Zero and the empty string are not blank; the \
|
||||
predicate is equivalent to the strict comparison `value == BLANK ()`.",
|
||||
&["ISBLANK ( Sales[Amount] )", "ISBLANK ( BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"ISBOOLEAN",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a Boolean value. Alias of ISLOGICAL.",
|
||||
&["ISBOOLEAN ( TRUE )", "ISBOOLEAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISCROSSFILTERED",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table or column is cross-filtered, meaning a filter is applied to \
|
||||
that table, to one of its columns, or to a column of a related table.",
|
||||
&["ISCROSSFILTERED ( Product )", "ISCROSSFILTERED ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDATETIME",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value has the Date/time type.",
|
||||
&["ISDATETIME ( DATE ( 2008, 1, 1 ) )", "ISDATETIME ( Sales[Order Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDECIMAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISCURRENCY.",
|
||||
&["ISDECIMAL ( 1.5 )", "ISDECIMAL ( Sales[Net Price] )"],
|
||||
),
|
||||
spec(
|
||||
"ISDOUBLE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a floating-point decimal value.",
|
||||
&["ISDOUBLE ( 1.5 )", "ISDOUBLE ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISEMPTY",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the table expression has no rows in the current evaluation context, \
|
||||
including tables whose only row would be blank.",
|
||||
&["ISEMPTY ( Sales )", "ISEMPTY ( FILTER ( Sales, FALSE ) )"],
|
||||
),
|
||||
spec(
|
||||
"ISERROR",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when evaluating the value produces an error. It inspects the value, so the \
|
||||
error is caught rather than propagated.",
|
||||
&["ISERROR ( 1 / 0 )", "ISERROR ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISEVEN",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the number is even, FALSE when it is odd. Truncation applies to \
|
||||
non-integers, matching the mathematical sign of the truncated value.",
|
||||
&["ISEVEN ( 4 )", "ISEVEN ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISFILTERED",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE when the column carries direct filters in the current context; filters propagated \
|
||||
from a related table do not count, so use ISCROSSFILTERED for those.",
|
||||
&["ISFILTERED ( Product[Color] )", "ISFILTERED ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISINSCOPE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the column is the level currently in scope in a hierarchy of levels, \
|
||||
for example the group-by column of the current SUMMARIZECOLUMNS row.",
|
||||
&["ISINSCOPE ( Product[Category] )", "ISINSCOPE ( Product[Subcategory] )"],
|
||||
),
|
||||
spec(
|
||||
"ISINT64",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a 64-bit integer. This is the alias of ISINTEGER.",
|
||||
&["ISINT64 ( 1 )", "ISINT64 ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISLOGICAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for a logical value (TRUE or FALSE). Alias of ISBOOLEAN.",
|
||||
&["ISLOGICAL ( FALSE )", "ISLOGICAL ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNONTEXT",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is not text. A blank cell is not text, so ISNONTEXT also \
|
||||
returns TRUE for BLANK.",
|
||||
&["ISNONTEXT ( 1 )", "ISNONTEXT ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNUMBER",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a number. Text that looks numeric is not a number; use \
|
||||
VALUE to convert it first.",
|
||||
&["ISNUMBER ( 1 )", "ISNUMBER ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ISNUMERIC",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"TRUE for an integer or decimal number, including Currency and floating-point values.",
|
||||
&["ISNUMERIC ( 1.5 )", "ISNUMERIC ( Sales[Net Price] )"],
|
||||
),
|
||||
spec(
|
||||
"ISODD",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the number is odd, FALSE when it is even. Non-integer values are \
|
||||
truncated before the parity test.",
|
||||
&["ISODD ( 3 )", "ISODD ( Sales[Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISONORAFTER",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any), optional("Order", ParamKind::Logical)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the Value1/Value2 groups compare on or after the corresponding values \
|
||||
in the order given by each optional Order flag, emulating a START AT clause. It is not \
|
||||
an iterator.",
|
||||
&["ISONORAFTER ( Sales[Year], 2008 )", "ISONORAFTER ( Sales[Year], 2008, 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ISSELECTEDMEASURE",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Measure", ParamKind::Reference)],
|
||||
&[variadic(&[ParamKind::Reference])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns TRUE when the measure currently evaluated in a calculation item is one of the \
|
||||
listed measures. A query measure redefined in the DAX query is not recognised.",
|
||||
&["ISSELECTEDMEASURE ( [Sales Amount] )", "ISSELECTEDMEASURE ( [Sales Amount], [Sales Quantity] )"],
|
||||
),
|
||||
spec(
|
||||
"ISSTRING",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is a string. This is the alias of ISTEXT; a blank value is \
|
||||
not text.",
|
||||
&["ISSTRING ( \"text\" )", "ISSTRING ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"ISSUBTOTAL",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns TRUE when the current SUMMARIZE row is the subtotal for the column, FALSE for a \
|
||||
detail row. It only makes sense inside SUMMARIZE with ROLLUP; SUMMARIZECOLUMNS with \
|
||||
ROLLUPADDISSUBTOTAL supersedes it.",
|
||||
&["ISSUBTOTAL ( Product[Brand] )", "ISSUBTOTAL ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISTEXT",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns TRUE when the value is text. This is the alias of ISSTRING; a blank value is not \
|
||||
text.",
|
||||
&["ISTEXT ( \"text\" )", "ISTEXT ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"NAMEOF",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
3,
|
||||
&[required("Value", ParamKind::Reference), optional("Component", ParamKind::Text), optional("Escaped", ParamKind::Text)],
|
||||
&[
|
||||
overload(&[ParamKind::Reference]),
|
||||
overload(&[ParamKind::Reference, ParamKind::Text]),
|
||||
overload(&[ParamKind::Reference, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Text name of a table, column, measure or calendar. Component selects TABLE, COLUMN, \
|
||||
MEASURE, CALENDAR, FULL, SELF or PARENT; Escaped selects ESCAPED, UNESCAPED or \
|
||||
MINIMALLYESCAPED. Variables and dynamic expressions are not accepted.",
|
||||
&["NAMEOF ( Sales[Amount] )", "NAMEOF ( [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASURE",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns a reference to the measure currently evaluated in a calculation item. During \
|
||||
application each call is replaced by the selected measure, which also triggers context \
|
||||
transition.",
|
||||
&["SELECTEDMEASURE ()"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASUREFORMATSTRING",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Format string of the measure under evaluation in the current calculation item.",
|
||||
&["SELECTEDMEASUREFORMATSTRING ()"],
|
||||
),
|
||||
spec(
|
||||
"SELECTEDMEASURENAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Name of the measure under evaluation in the current calculation item, including one \
|
||||
redefined in the DAX query.",
|
||||
&["SELECTEDMEASURENAME ()"],
|
||||
),
|
||||
spec(
|
||||
"TABLEOF",
|
||||
FunctionCategory::Information,
|
||||
1,
|
||||
1,
|
||||
&[required("Reference", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Resolves a column, measure or calendar reference to the table that owns it.",
|
||||
&["TABLEOF ( Sales[Amount] )", "TABLEOF ( Product[Color] )"],
|
||||
),
|
||||
spec(
|
||||
"TEXTCONTAINS",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
3,
|
||||
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"TRUE when the column text matches SearchText under full-text query semantics. MatchMode \
|
||||
is TEXTMATCHING (the default), FUZZYMATCHING or PHRASEMATCHING.",
|
||||
&["TEXTCONTAINS ( Product[Product Name], \"red\" )", "TEXTCONTAINS ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
|
||||
),
|
||||
spec(
|
||||
"TEXTSIMILARITY",
|
||||
FunctionCategory::Information,
|
||||
2,
|
||||
3,
|
||||
&[required("WithinTextColumn", ParamKind::Column), required("SearchText", ParamKind::Text), optional("MatchMode", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Text]), overload(&[ParamKind::Column, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Decimal,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns the BM25 relevance score of the text in the column against the search text; a \
|
||||
higher score is a stronger match and 0 means no match. MatchMode is TEXTMATCHING (the \
|
||||
default), FUZZYMATCHING or PHRASEMATCHING. Scores are comparable only within the same \
|
||||
search context.",
|
||||
&["TEXTSIMILARITY ( Product[Product Name], \"red\" )", "TEXTSIMILARITY ( Product[Product Name], \"red\", \"FUZZYMATCHING\" )"],
|
||||
),
|
||||
spec(
|
||||
"USERCULTURE",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, true),
|
||||
"Returns the culture code of the current user, such as \"en-US\", derived from the \
|
||||
operating system or browser settings.",
|
||||
&["USERCULTURE ()"],
|
||||
),
|
||||
spec(
|
||||
"USERNAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, true, false),
|
||||
"The connection identity in domain\\user form, as supplied when the connection was \
|
||||
opened.",
|
||||
&["USERNAME ()"],
|
||||
),
|
||||
spec(
|
||||
"USEROBJECTID",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, false),
|
||||
"Returns the current user's object ID from Azure AD, or the security identifier (SID) when \
|
||||
the model runs on-premises.",
|
||||
&["USEROBJECTID ()"],
|
||||
),
|
||||
spec(
|
||||
"USERPRINCIPALNAME",
|
||||
FunctionCategory::Information,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::String,
|
||||
FunctionFlags::new(false, true, false, false, false),
|
||||
"Returns the user principal name of the current user, typically the email address in \
|
||||
user@domain form.",
|
||||
&["USERPRINCIPALNAME ()"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Logical functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category holds three kinds of functions:
|
||||
//!
|
||||
//! - Boolean combinators (`AND`, `OR`, `NOT`) and the constants `TRUE`/`FALSE`, all of which
|
||||
//! return a Boolean;
|
||||
//! - bitwise integer operations (`BITAND`, `BITOR`, `BITXOR`), which are engine-only: dax.guide
|
||||
//! does not list them for any Excel version;
|
||||
//! - scalar selectors (`IF`, `IF.EAGER`, `IFERROR`, `SWITCH`, `COALESCE`), which return a value
|
||||
//! whose type follows the selected branch and are therefore catalogued as
|
||||
//! [`ReturnType::Any`].
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with the usual DirectQuery restrictions.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Engine-only functions: no Excel version listed by dax.guide supports them.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// Functions dax.guide flags as not recommended (`IFERROR`) or that are documented as an
|
||||
/// optimisation-only escape hatch (`IF.EAGER`).
|
||||
const DISCOURAGED: FunctionFlags = FunctionFlags::new(false, false, true, true, true);
|
||||
|
||||
/// `IF.EAGER` is engine-only and discouraged except for specific optimisations.
|
||||
const EAGER: FunctionFlags = FunctionFlags::new(false, false, true, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"AND",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns TRUE when both logical arguments are TRUE, and FALSE otherwise. The function \
|
||||
accepts exactly two arguments; use the `&&` operator to combine three or more conditions \
|
||||
without nesting. Like the operator, it does not short-circuit when evaluated eagerly.",
|
||||
&["AND ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "AND ( TRUE, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"BITAND",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise AND of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITAND ( 5, 3 )", "BITAND ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"BITOR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise OR of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITOR ( 5, 3 )", "BITOR ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"BITXOR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
ENGINE_ONLY,
|
||||
"Returns the bitwise XOR of two integers. Both arguments are converted to integers; the \
|
||||
result is a signed 64-bit integer.",
|
||||
&["BITXOR ( 5, 3 )", "BITXOR ( 13, 25 )"],
|
||||
),
|
||||
spec(
|
||||
"COALESCE",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Value1", ParamKind::Any), required("Value2", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
ENGINE_ONLY,
|
||||
"The first argument whose value is not BLANK; when every argument is blank the result is \
|
||||
BLANK. At least two arguments are required, and later arguments are not evaluated once \
|
||||
a non-blank value is found. Unlike a chain of IF/ISBLANK checks, the result type follows \
|
||||
the first non-blank argument.",
|
||||
&[
|
||||
"COALESCE ( Sales[Discount], 0 )",
|
||||
"COALESCE ( Store[Area Manager], \"** Not Assigned **\" )",
|
||||
"COALESCE ( [Sales Amount], [Budget Amount], 0 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"FALSE",
|
||||
FunctionCategory::Logical,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the logical value FALSE. `FALSE` without parentheses is the same constant; FALSE \
|
||||
is converted to 0 when a numeric result is required.",
|
||||
&["FALSE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
|
||||
),
|
||||
spec(
|
||||
"IF",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
3,
|
||||
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
STANDARD,
|
||||
"Evaluates the logical test and returns `ResultIfTrue` when it is TRUE and \
|
||||
`ResultIfFalse` otherwise. When the third argument is omitted a FALSE test returns \
|
||||
BLANK. Only the selected branch is evaluated in the regular (strict) execution plan, and \
|
||||
the result type follows the selected branch or the common type of both branches.",
|
||||
&["IF ( Sales[Amount] > 0, 1, 0 )", "IF ( [Sales Amount] > 1000, \"Large\", \"Small\" )", "IF ( Sales[Quantity] > 0, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"IF.EAGER",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
3,
|
||||
&[required("LogicalTest", ParamKind::Logical), required("ResultIfTrue", ParamKind::Any), optional("ResultIfFalse", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Any]), overload(&[ParamKind::Logical, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
EAGER,
|
||||
"Same conditional semantics as IF, but forces an eager execution plan in which both \
|
||||
branch expressions are evaluated before the test chooses one. It exists only for query \
|
||||
optimisation and should be used only after measuring a clear advantage over IF; the \
|
||||
result type is Variant when the branches differ.",
|
||||
&["IF.EAGER ( Sales[Amount] > 0, 1, 0 )", "IF.EAGER ( [Sales Amount] > 1000, \"Large\", \"Small\" )"],
|
||||
),
|
||||
spec(
|
||||
"IFERROR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Value", ParamKind::Any), required("ValueIfError", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
DISCOURAGED,
|
||||
"Yields `ValueIfError` when the first argument raises an error, and otherwise repeats the \
|
||||
first argument's value; faster than the equivalent \
|
||||
`IF ( ISERROR ( Value ), ValueIfError, Value )`. Neither IFERROR nor ISERROR catches \
|
||||
every runtime error, because block-mode execution can bypass the check, so both are \
|
||||
discouraged.",
|
||||
&["IFERROR ( 1 / 0, 0 )", "IFERROR ( VALUE ( Sales[Text] ), BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"NOT",
|
||||
FunctionCategory::Logical,
|
||||
1,
|
||||
1,
|
||||
&[required("Logical", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the opposite Boolean value: TRUE for a FALSE argument and FALSE for a TRUE \
|
||||
argument. NOT is an operator exposed through function syntax.",
|
||||
&["NOT ( Sales[Amount] > 0 )", "NOT ( TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"OR",
|
||||
FunctionCategory::Logical,
|
||||
2,
|
||||
2,
|
||||
&[required("Logical1", ParamKind::Logical), required("Logical2", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Logical, ParamKind::Logical])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns TRUE when either logical argument is TRUE, and FALSE when both are FALSE. The \
|
||||
function accepts exactly two arguments; use the `||` operator to combine three or more \
|
||||
conditions without nesting.",
|
||||
&["OR ( Sales[Amount] > 0, Sales[Quantity] > 0 )", "OR ( TRUE, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"SWITCH",
|
||||
FunctionCategory::Logical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
required("Value", ParamKind::Any),
|
||||
required("Result", ParamKind::Any),
|
||||
optional("Else", ParamKind::Any),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
STANDARD,
|
||||
"Compares the expression with each value in turn and returns the result paired with the \
|
||||
first match; when nothing matches it returns the optional else argument, or BLANK when \
|
||||
that argument is omitted. Values and results come in pairs, so the call needs an odd \
|
||||
number of arguments when there is no else and an even number when there is one. All \
|
||||
results and the else value must have the same data type. Using TRUE as the expression \
|
||||
turns SWITCH into a cleaner alternative to cascading IF calls.",
|
||||
&[
|
||||
"SWITCH ( [X], 1, \"a\", 2, \"b\", \"other\" )",
|
||||
"SWITCH ( Sales[Region], \"North\", 1, \"South\", 2, 0 )",
|
||||
"SWITCH ( TRUE (), Sales[Amount] > 1000, \"Large\", Sales[Amount] > 100, \"Medium\", \"Small\" )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"TRUE",
|
||||
FunctionCategory::Logical,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Returns the logical value TRUE. `TRUE` without parentheses is the same constant; TRUE is \
|
||||
converted to 1 when a numeric result is required.",
|
||||
&["TRUE ()", "IF ( Sales[Amount] > 0, TRUE (), FALSE () )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,677 @@
|
||||
//! Math and trigonometry functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ABS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Absolute value of Number with the sign stripped and the numeric type kept (Currency, \
|
||||
Decimal or Integer). Infinite values are accepted and nothing is rounded.",
|
||||
&["ABS ( -1 )", "ABS ( [Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ACOS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arccosine of a number in radians, in the range 0 to pi. The argument is the \
|
||||
cosine of the angle and must be between -1 and 1; multiply the result by 180/PI() or \
|
||||
use DEGREES to obtain degrees. Results are approximate Decimal values.",
|
||||
&["ACOS ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOSH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the inverse hyperbolic cosine, in radians, of a number greater than or equal to \
|
||||
1. ACOSH(COSH(x)) equals x when x is in range; the result is an approximate Decimal \
|
||||
value.",
|
||||
&["ACOSH ( 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Principal arccotangent of a real number, in radians between 0 and pi, as an approximate \
|
||||
Decimal.",
|
||||
&["ACOT ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ACOTH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse hyperbolic cotangent of a number whose absolute value exceeds 1, as an \
|
||||
approximate Decimal.",
|
||||
&["ACOTH ( 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ASIN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arcsine of a number, in radians, between -pi/2 and pi/2. The argument is \
|
||||
the sine of the angle and must be between -1 and 1; multiply by 180/PI() or use DEGREES \
|
||||
for degrees. Results are approximate Decimal values.",
|
||||
&["ASIN ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ASINH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the inverse hyperbolic sine of any real number, in radians. ASINH(SINH(x)) \
|
||||
equals x; the result is an approximate Decimal value.",
|
||||
&["ASINH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"ATAN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the arctangent of a number, in radians, between -pi/2 and pi/2. Multiply by \
|
||||
180/PI() or use DEGREES for degrees; the result is an approximate Decimal value.",
|
||||
&["ATAN ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ATANH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse hyperbolic tangent of a value strictly between -1 and 1, as an approximate \
|
||||
Decimal. The endpoints -1 and 1, and anything outside that range, are errors.",
|
||||
&["ATANH ( 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"CEILING",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Moves Number up to the closest multiple of Significance. Unlike ISO.CEILING, a \
|
||||
negative significance makes CEILING round negative numbers toward negative infinity. \
|
||||
The result usually follows the type of Significance, but a Currency Number stays \
|
||||
Currency, a Boolean Significance yields Integer and a non-numeric Significance yields \
|
||||
Decimal.",
|
||||
&["CEILING ( 10.2, 1 )", "CEILING ( 10.7, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"CONVERT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Expression", ParamKind::Any), required("DataType", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Converts an expression to the requested data type. The type is an unquoted keyword: \
|
||||
BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 or STRING/TEXT. \
|
||||
Numeric conversions follow the target type's precision, so CURRENCY/DECIMAL rounds to \
|
||||
four decimal places while DOUBLE keeps approximately 15 significant digits.",
|
||||
&["CONVERT ( \"123\", INTEGER )", "CONVERT ( 12345, DATETIME )"],
|
||||
),
|
||||
spec(
|
||||
"COS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the cosine of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value.",
|
||||
&["COS ( PI () / 3 )"],
|
||||
),
|
||||
spec(
|
||||
"COSH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic cosine of a real argument, as an approximate Decimal; it grows quickly as \
|
||||
the argument rises.",
|
||||
&["COSH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"COT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the cotangent of an angle given in radians, computed as 1/TAN(angle). It is \
|
||||
undefined at multiples of pi; the result is an approximate Decimal value.",
|
||||
&["COT ( PI () / 4 )"],
|
||||
),
|
||||
spec(
|
||||
"COTH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic cotangent of a hyperbolic angle in radians, computed as 1/TANH(angle); \
|
||||
undefined at zero and returned as an approximate Decimal.",
|
||||
&["COTH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"CURRENCY",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Scalar)],
|
||||
&[overload(&[ParamKind::Scalar])],
|
||||
ReturnType::Currency,
|
||||
standard(false),
|
||||
"Converts a scalar expression to the Currency type, which stores four decimal places. \
|
||||
The fifth significant decimal is rounded up when it is 5 or larger; TRUE becomes 1 and \
|
||||
FALSE becomes 0, and numeric text is parsed. Currency values are fixed-point, so this \
|
||||
conversion is not a general-purpose numeric cast.",
|
||||
&["CURRENCY ( 10.5 )", "CURRENCY ( \"3.66666\" )"],
|
||||
),
|
||||
spec(
|
||||
"DEGREES",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Converts an angle from radians to degrees by multiplying by 180/pi. The result is an \
|
||||
approximate Decimal value; RADIANS performs the inverse conversion.",
|
||||
&["DEGREES ( PI () / 2 )"],
|
||||
),
|
||||
spec(
|
||||
"DIVIDE",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
3,
|
||||
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number), optional("AlternateResult", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Performs safe division and returns an alternate result when the denominator is zero, \
|
||||
avoiding the error or infinity produced by the / operator. The alternate result must be \
|
||||
a constant and defaults to BLANK; the quotient is an approximate Decimal value. DIVIDE \
|
||||
runs in the formula engine and is slower than native division when the denominator is \
|
||||
known to be non-zero.",
|
||||
&["DIVIDE ( 10, 2 )", "DIVIDE ( 10, 0, 0 )"],
|
||||
),
|
||||
spec(
|
||||
"EVEN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rounds a number away from zero to the nearest even integer. An even integer is returned \
|
||||
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
|
||||
&["EVEN ( 3.2 )", "EVEN ( -3.2 )"],
|
||||
),
|
||||
spec(
|
||||
"EXP",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns e raised to the given power, the inverse of LN. The result is an approximate \
|
||||
Decimal value with about 15 significant digits; for other bases use POWER or ^.",
|
||||
&["EXP ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"FACT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the factorial of a non-negative number in Decimal form. A non-integer argument \
|
||||
is truncated, and values above 170 overflow; the result is exact only through 21!. \
|
||||
Calculated columns and RLS rules cannot use FACT in DirectQuery mode.",
|
||||
&["FACT ( 5 )", "FACT ( 21 )"],
|
||||
),
|
||||
spec(
|
||||
"FLOOR",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number toward zero to the closest multiple of Significance; both must share a \
|
||||
sign. The result is always Decimal regardless of the argument types.",
|
||||
&["FLOOR ( 2.7, 1 )", "FLOOR ( -2.7, -1 )"],
|
||||
),
|
||||
spec(
|
||||
"GCD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Greatest common divisor of two integers. Non-integer arguments are truncated before the \
|
||||
calculation; the result is an exact Integer.",
|
||||
&["GCD ( 36, 48 )"],
|
||||
),
|
||||
spec(
|
||||
"INT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Rounds a number down toward negative infinity to an integer, so INT(-2.1) is -3. The \
|
||||
result is Integer for Integer or Decimal input and Currency for Currency input; unlike \
|
||||
TRUNC, the result type follows the argument and negative values move away from zero.",
|
||||
&["INT ( -2.9 )", "INT ( 2.9 )"],
|
||||
),
|
||||
spec(
|
||||
"ISO.CEILING",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("Significance", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Numeric,
|
||||
standard(false),
|
||||
"Moves Number up to the closest multiple of Significance using ISO rules. When \
|
||||
Significance is omitted it defaults to 1; negative numbers and negative significance \
|
||||
can round differently from CEILING. The result keeps the numeric type of Number, with \
|
||||
Decimal precision when required by the multiple.",
|
||||
&["ISO.CEILING ( 10.2 )", "ISO.CEILING ( 10.7, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"LCM",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number1", ParamKind::Number), required("Number2", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Least common multiple of two integers: the smallest positive value that both arguments \
|
||||
divide without a remainder. Non-integer arguments are truncated; the result is an exact \
|
||||
Integer.",
|
||||
&["LCM ( 4, 6 )"],
|
||||
),
|
||||
spec(
|
||||
"LN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the natural logarithm (base e) of a positive number. Zero and negative numbers \
|
||||
produce an error; the result is an approximate Decimal value and is the inverse of EXP.",
|
||||
&["LN ( 10 )"],
|
||||
),
|
||||
spec(
|
||||
"LOG",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("Base", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the logarithm of a positive number in the given base; omitting the base uses \
|
||||
10. The result is an approximate Decimal value, and LOG10 is the fixed base-10 \
|
||||
shortcut.",
|
||||
&["LOG ( 1000 )", "LOG ( 8, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"LOG10",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Base-10 logarithm of a positive number, as an approximate Decimal; the same value as \
|
||||
LOG(number, 10).",
|
||||
&["LOG10 ( 10000 )"],
|
||||
),
|
||||
spec(
|
||||
"MOD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Divisor", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
standard(false),
|
||||
"Returns the remainder after dividing Number by Divisor. The result follows the operand \
|
||||
type (Integer, Currency or Decimal) and its sign follows the divisor; a zero divisor \
|
||||
produces an error. QUOTIENT returns the corresponding integer portion.",
|
||||
&["MOD ( 7, 3 )", "MOD ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"MROUND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Multiple", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Rounds a number to the nearest multiple, rounding away from zero when the remainder is \
|
||||
at least half the multiple. Number and Multiple must have the same sign; for decimal \
|
||||
multiples the midpoint direction is undefined, so MROUND(6.05, 0.1) can differ from \
|
||||
MROUND(7.05, 0.1). The result is Decimal.",
|
||||
&["MROUND ( 7.3, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ODD",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rounds a number away from zero to the nearest odd integer. An odd integer is returned \
|
||||
unchanged, and non-numeric input raises an error. The result is an exact Integer.",
|
||||
&["ODD ( 2.1 )", "ODD ( -2.1 )"],
|
||||
),
|
||||
spec(
|
||||
"PI",
|
||||
FunctionCategory::MathAndTrig,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The constant pi (3.14159265358979) as an approximate Decimal, accurate to 15 digits. \
|
||||
Takes no arguments.",
|
||||
&["PI ()"],
|
||||
),
|
||||
spec(
|
||||
"POWER",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Power", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns Number raised to Power. It is equivalent to the ^ operator and produces an \
|
||||
approximate Decimal value; fractional powers of negative bases produce an error.",
|
||||
&["POWER ( 2, 10 )", "POWER ( 9, 0.5 )"],
|
||||
),
|
||||
spec(
|
||||
"QUOTIENT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Numerator", ParamKind::Number), required("Denominator", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Whole-number part of dividing Numerator by Denominator, with the fraction cut toward \
|
||||
zero. The result is an exact Integer and a zero denominator is an error; MOD gives the \
|
||||
remainder.",
|
||||
&["QUOTIENT ( 7, 2 )", "QUOTIENT ( -7, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"RADIANS",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Converts an angle from degrees to radians by multiplying by pi/180. The result is an \
|
||||
approximate Decimal value; DEGREES performs the inverse conversion.",
|
||||
&["RADIANS ( 180 )"],
|
||||
),
|
||||
spec(
|
||||
"RAND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Decimal,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Returns a random Decimal value in [0, 1), uniformly distributed. RAND is volatile: it \
|
||||
may return a different value on every evaluation and changes on recalculation, so it \
|
||||
cannot be used where a stable result is required.",
|
||||
&["RAND ()"],
|
||||
),
|
||||
spec(
|
||||
"RANDBETWEEN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Bottom", ParamKind::Number), required("Top", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, true, false, true, true),
|
||||
"Returns a random Integer between Bottom and Top inclusive. Both bounds are integers; \
|
||||
if Bottom is greater than Top the function raises an error. RANDBETWEEN is volatile, so \
|
||||
it recalculates to a different value and is unsuitable for stable results.",
|
||||
&["RANDBETWEEN ( 5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUND",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Rounds a number to the specified number of digits, using half away from zero. A positive \
|
||||
count rounds right of the decimal point, zero rounds to an integer and a negative count \
|
||||
rounds left of it. The result is a Decimal, so large integers can lose precision beyond \
|
||||
about 15 significant digits.",
|
||||
&["ROUND ( 3.14159, 2 )", "ROUND ( 1234, -2 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUNDDOWN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number toward zero to the requested digit. Positive counts work right of the \
|
||||
decimal point, zero rounds to an integer and negative counts work left of it; the \
|
||||
result is Decimal and differs from FLOOR for negative numbers.",
|
||||
&["ROUNDDOWN ( 2.71828, 3 )", "ROUNDDOWN ( -3.14159, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"ROUNDUP",
|
||||
FunctionCategory::MathAndTrig,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Moves Number away from zero to the requested digit, so 2.31 at one digit becomes 2.4. \
|
||||
Positive counts work right of the decimal point, zero rounds to an integer and negative \
|
||||
counts work left of it; the result is Decimal.",
|
||||
&["ROUNDUP ( 3.14159, 2 )", "ROUNDUP ( -3.14159, 2 )"],
|
||||
),
|
||||
spec(
|
||||
"SIGN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Returns the sign of a real number: 1 when positive, 0 when zero and -1 when negative. \
|
||||
The result is an exact Integer; infinite values are not supported.",
|
||||
&["SIGN ( -5 )", "SIGN ( 0 )"],
|
||||
),
|
||||
spec(
|
||||
"SIN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the sine of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value.",
|
||||
&["SIN ( PI () / 6 )"],
|
||||
),
|
||||
spec(
|
||||
"SINH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic sine of a real argument, as an approximate Decimal; ASINH is its inverse.",
|
||||
&["SINH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"SQRT",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Square root of a non-negative number, as an approximate Decimal; a negative argument is \
|
||||
an error. SQRTPI multiplies by pi before taking the root.",
|
||||
&["SQRT ( 16 )"],
|
||||
),
|
||||
spec(
|
||||
"SQRTPI",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Square root of Number multiplied by pi, as an approximate Decimal; negative input is an \
|
||||
error, and SQRTPI(n) equals SQRT(n * PI()).",
|
||||
&["SQRTPI ( 3 )"],
|
||||
),
|
||||
spec(
|
||||
"TAN",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Returns the tangent of an angle given in radians. Convert degrees with RADIANS or by \
|
||||
multiplying by PI()/180; the result is an approximate Decimal value and is undefined at \
|
||||
odd multiples of pi/2.",
|
||||
&["TAN ( PI () / 4 )"],
|
||||
),
|
||||
spec(
|
||||
"TANH",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Hyperbolic tangent of a real argument, computed as SINH(number)/COSH(number); the value \
|
||||
lies between -1 and 1.",
|
||||
&["TANH ( 1 )"],
|
||||
),
|
||||
spec(
|
||||
"TRUNC",
|
||||
FunctionCategory::MathAndTrig,
|
||||
1,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), optional("NumberOfDigits", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Truncates a number toward zero by removing its fractional part or the digits beyond the \
|
||||
requested precision. NumberOfDigits defaults to 0, positive counts keep decimal places \
|
||||
and negative counts truncate left of the decimal point. The result is always Decimal, \
|
||||
unlike INT, which rounds toward negative infinity and follows the input type.",
|
||||
&["TRUNC ( 3.14159 )", "TRUNC ( 3.14159, 2 )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Other functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category collects the bit-shift operators, the row-context helpers, the window ranking
|
||||
//! functions, the metadata table function and the remaining special functions that dax.guide
|
||||
//! lists under "Other". `INFO.STORAGETABLES` keeps the exact dotted spelling and shares the
|
||||
//! optional restriction-pair syntax of the other `INFO.*` functions.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"BITLSHIFT",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the first argument's integer left by ShiftAmount bits; a negative amount shifts \
|
||||
right. Two's-complement semantics, so the result can overflow or underflow.",
|
||||
&["BITLSHIFT ( 4, 2 )", "BITLSHIFT ( Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"BITRSHIFT",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("ShiftAmount", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the first argument's integer right by ShiftAmount bits; a negative amount shifts \
|
||||
left. Two's-complement semantics, so the result can overflow or underflow.",
|
||||
&["BITRSHIFT ( 8, 2 )", "BITRSHIFT ( Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"BLANK",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Blank,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the BLANK value. BLANK has no data type and is converted automatically when \
|
||||
compared with other values; use the `==` operator or ISBLANK to test for it.",
|
||||
&["BLANK ()"],
|
||||
),
|
||||
spec(
|
||||
"EARLIER",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), optional("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns the value of a column in an outer row context, `Number` evaluation passes back \
|
||||
(default 1). Fails when no outer row context exists. dax.guide marks it not recommended: \
|
||||
a variable captured before the inner row context is easier to read and maintain.",
|
||||
&["EARLIER ( Customer[Yearly Income] )", "EARLIER ( Customer[Yearly Income], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"EARLIEST",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, true, true, true),
|
||||
"Returns the value of a column in the outermost row context, equivalent to EARLIER with \
|
||||
the largest possible scan count. dax.guide marks it not recommended in favour of storing \
|
||||
the value in a variable.",
|
||||
&["EARLIEST ( Customer[Yearly Income] )"],
|
||||
),
|
||||
spec(
|
||||
"ERROR",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("ErrorText", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Variant,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Stops evaluation and raises a user-specified error with the supplied message. It can be \
|
||||
used anywhere a scalar is expected, but has no data type of its own, so wrap it in \
|
||||
CONVERT to give the surrounding expression a concrete type.",
|
||||
&["ERROR ( \"Missing inflation rate\" )"],
|
||||
),
|
||||
spec(
|
||||
"EXTERNALMEASURE",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
3,
|
||||
&[required("MeasureName", ParamKind::Text), optional("Type", ParamKind::Text), optional("Datasource", ParamKind::Text)],
|
||||
&[
|
||||
overload(&[ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Invokes a measure defined in a remote model. The optional type name \
|
||||
(BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64, STRING/TEXT, \
|
||||
VARIANT) declares the remote result type and the optional data source names the \
|
||||
external model. Power BI generates these calls for composite models.",
|
||||
&["EXTERNALMEASURE ( \"Remote Sales\", \"DOUBLE\", \"RemoteModel\" )"],
|
||||
),
|
||||
spec(
|
||||
"HASH",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Any])],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Fingerprints a variable number of input expressions with a hash and returns an integer. \
|
||||
The function appears in the engine metadata but is not documented by Microsoft, so its \
|
||||
exact hash algorithm and stability across versions are unspecified.",
|
||||
&["HASH ( Sales[Amount] )", "HASH ( Sales[OrderNumber], Sales[LineNumber] )"],
|
||||
),
|
||||
spec(
|
||||
"INFO.STORAGETABLES",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[optional("RestrictionName", ParamKind::Text), optional("RestrictionValue", ParamKind::Any)],
|
||||
&[overload(&[]), overload(&[ParamKind::Text]), variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns statistics about the in-memory storage tables of the model, with one row per \
|
||||
table and columns such as DATABASE_NAME, TABLE_ID, TABLE_PARTITIONS_COUNT and \
|
||||
ROWS_COUNT. It corresponds to the DISCOVER_STORAGE_TABLES dynamic management view, \
|
||||
accepts optional restriction name/value pairs, and, like every INFO function, cannot be \
|
||||
used in calculated tables or calculated columns.",
|
||||
&["INFO.STORAGETABLES ()", "INFO.STORAGETABLES ( \"DATABASE_NAME\", \"Sales\" )"],
|
||||
),
|
||||
spec(
|
||||
"ISATLEVEL",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"TRUE when the given column appears at the current level of the visual calculation data \
|
||||
grid. Use it to apply different formatting or logic per hierarchy level.",
|
||||
&["ISATLEVEL ( 'Date'[Year] )", "ISATLEVEL ( Product[Category] )"],
|
||||
),
|
||||
spec(
|
||||
"ISCURRENCY",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"TRUE for a fixed-precision decimal (Currency) value. Alias of ISDECIMAL.",
|
||||
&["ISCURRENCY ( Sales[Amount] )", "ISCURRENCY ( 1.5 )"],
|
||||
),
|
||||
spec(
|
||||
"ISINTEGER",
|
||||
FunctionCategory::Other,
|
||||
1,
|
||||
1,
|
||||
&[required("Value", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"TRUE for an integer Value. Alias of ISINT64.",
|
||||
&["ISINTEGER ( Sales[Quantity] )", "ISINTEGER ( 2.5 )"],
|
||||
),
|
||||
spec(
|
||||
"KEYWORDMATCH",
|
||||
FunctionCategory::Other,
|
||||
2,
|
||||
2,
|
||||
&[required("MatchExpression", ParamKind::Text), required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
FunctionFlags::new(false, false, false, true, false),
|
||||
"Returns TRUE when the match expression matches the supplied text. dax.guide lists it as \
|
||||
deprecated: it was never released and only appeared in some Excel versions.",
|
||||
&["KEYWORDMATCH ( \"bike\", \"Mountain Bike\" )"],
|
||||
),
|
||||
spec(
|
||||
"RANK",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
7,
|
||||
&[
|
||||
optional("Ties", ParamKind::Text),
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Text),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[]),
|
||||
overload(&[ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Text, ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the rank of the current row inside its partition, ordered by an ORDERBY clause. \
|
||||
The optional Ties argument selects DENSE or SKIP (SKIP is the default), Blanks controls \
|
||||
where blank ordering values sort, PARTITIONBY splits the table, MATCHBY identifies the \
|
||||
current row and Reset restarts the numbering. Relation defaults to ALLSELECTED of the \
|
||||
ordering and partitioning columns, and either Relation or ORDERBY must be supplied.",
|
||||
&["RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ) )", "RANK ( SKIP, Sales, ORDERBY ( Sales[Amount], DESC ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROWNUMBER",
|
||||
FunctionCategory::Other,
|
||||
0,
|
||||
6,
|
||||
&[
|
||||
optional("Relation", ParamKind::Table),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Text),
|
||||
optional("PartitionBy", ParamKind::Any),
|
||||
optional("MatchBy", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[]),
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Table, ParamKind::Any, ParamKind::Text, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the unique row number of the current row inside its partition, ordered by an \
|
||||
ORDERBY clause. Unlike RANK, ties receive different numbers. The optional Blanks, \
|
||||
PARTITIONBY, MATCHBY and Reset arguments behave as they do for RANK; either Relation or \
|
||||
ORDERBY must be supplied.",
|
||||
&["ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ) )", "ROWNUMBER ( Sales, ORDERBY ( Sales[OrderDate] ), LAST )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLECARTESIANPOINTSBYCOVER",
|
||||
FunctionCategory::Other,
|
||||
4,
|
||||
7,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("XAxis", ParamKind::Column),
|
||||
required("YAxis", ParamKind::Column),
|
||||
optional("Radius", ParamKind::Column),
|
||||
optional("MaxMinRatio", ParamKind::Number),
|
||||
optional("MaxBlankRatio", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column]),
|
||||
overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Column, ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[
|
||||
ParamKind::Number,
|
||||
ParamKind::Table,
|
||||
ParamKind::Column,
|
||||
ParamKind::Column,
|
||||
ParamKind::Column,
|
||||
ParamKind::Number,
|
||||
ParamKind::Number,
|
||||
]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, false),
|
||||
"Returns a sample of at most `Size` rows from a table, chosen by plotting each row as a \
|
||||
point on the X and Y coordinates and then dropping overlapping points. The optional \
|
||||
Radius column controls point size, MaxMinRatio limits the ratio between the largest and \
|
||||
smallest drawn points, and MaxBlankRatio limits the ratio between the largest point and \
|
||||
those with a blank radius. The function is used by the engine's scatter chart sampling \
|
||||
and is not documented by Microsoft.",
|
||||
&[
|
||||
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[Longitude], Sales[Latitude] )",
|
||||
"SAMPLECARTESIANPOINTSBYCOVER ( 1000, Sales, Sales[X], Sales[Y], Sales[Radius], 4, 0.1 )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Parent-child functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! These five functions flatten a parent-child hierarchy into a delimited path. The delimiter
|
||||
//! is always the vertical bar (`|`); `PATH` produces the string, `PATHLENGTH` counts its items,
|
||||
//! `PATHCONTAINS` searches it, and `PATHITEM`/`PATHITEMREVERSE` extract one item from the left
|
||||
//! or the right end.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard};
|
||||
|
||||
const FLAGS: FunctionFlags = standard(false);
|
||||
|
||||
/// dax.guide lists the parent-child functions in this order: PATH, PATHCONTAINS, PATHITEM,
|
||||
/// PATHITEMREVERSE and PATHLENGTH.
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"PATH",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
2,
|
||||
&[required("ID_ColumnName", ParamKind::Column), required("Parent_ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Column])],
|
||||
ReturnType::String,
|
||||
FLAGS,
|
||||
"Returns a text string containing the delimited list of IDs that starts at the top of a \
|
||||
parent-child hierarchy and ends with the current row, separating the identifiers with \
|
||||
the vertical bar. Both arguments must be column references, not expressions, and must \
|
||||
share a data type (integer or text); the parent value must exist in the ID column. A \
|
||||
blank parent returns just the ID, a blank ID returns BLANK, and an ID that contains a \
|
||||
vertical bar returns an error. Duplicate IDs with different parents return an error; \
|
||||
with the same parent the common parent is returned.",
|
||||
&["PATH ( Account[AccountKey], Account[ParentAccountKey] )", "PATH ( Employee[EmployeeKey], Employee[ParentEmployeeKey] )"],
|
||||
),
|
||||
spec(
|
||||
"PATHCONTAINS",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
2,
|
||||
&[required("Path", ParamKind::Text), required("Item", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Boolean,
|
||||
FLAGS,
|
||||
"Returns TRUE when the item appears as a whole segment of the delimited path, and FALSE \
|
||||
otherwise. The path is normally the result of PATH. An integer item is converted to \
|
||||
text before the comparison; when that conversion fails the function returns an error.",
|
||||
&["PATHCONTAINS ( Account[AccountPath], 2 )", "PATHCONTAINS ( Account[AccountPath], \"24\" )", "PATHCONTAINS ( \"1|24|2\", 2 )"],
|
||||
),
|
||||
spec(
|
||||
"PATHITEM",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
3,
|
||||
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FLAGS,
|
||||
"Returns the item at the given position in the delimited path, counting from the left \
|
||||
end where 1 is the top of the hierarchy. A position below 1 or beyond the number of \
|
||||
items returns BLANK. The optional Type selects the result: TEXT (or 0), the default, \
|
||||
returns a string, while INTEGER (or 1) converts the item to an integer. The result \
|
||||
type therefore follows the Type argument. An invalid Type enumeration raises an error.",
|
||||
&[
|
||||
"PATHITEM ( Account[AccountPath], 1 )",
|
||||
"PATHITEM ( Account[AccountPath], 2, INTEGER )",
|
||||
"PATHITEM ( Account[AccountPath], 3, TEXT )",
|
||||
"PATHITEM ( \"123|456|789|764\", 2 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"PATHITEMREVERSE",
|
||||
FunctionCategory::ParentChild,
|
||||
2,
|
||||
3,
|
||||
&[required("Path", ParamKind::Text), required("Position", ParamKind::Number), optional("Type", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number]), overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FLAGS,
|
||||
"Returns the item at the given position in the delimited path, counting backwards from \
|
||||
the last item, so position 1 is the current item and position 2 is its immediate \
|
||||
parent. A position below 1 or beyond the number of items returns BLANK. The optional \
|
||||
Type selects the result: TEXT (or 0), the default, returns a string, while INTEGER (or \
|
||||
1) converts the item to an integer, so the result type follows the Type argument. An \
|
||||
invalid Type enumeration raises an error.",
|
||||
&[
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 1 )",
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 2, INTEGER )",
|
||||
"PATHITEMREVERSE ( Account[AccountPath], 3, TEXT )",
|
||||
"PATHITEMREVERSE ( \"123|456|789|764\", 2 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"PATHLENGTH",
|
||||
FunctionCategory::ParentChild,
|
||||
1,
|
||||
1,
|
||||
&[required("Path", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
FLAGS,
|
||||
"Counts the items in a delimited path, the current item included, so a root node's path \
|
||||
has length 1. The path is normally the result of PATH, but any text with vertical-bar \
|
||||
separators (including a literal such as \"123|456|789|764\") is accepted.",
|
||||
&["PATHLENGTH ( Account[AccountPath] )", "PATHLENGTH ( \"123|456|789|764\" )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Relationship management functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The four functions mirror <https://dax.guide/functions/relationships-management/> in index
|
||||
//! order. `CROSSFILTER` and `USERELATIONSHIP` are filter modifiers: they return no value and
|
||||
//! only alter filter propagation while the filter context that contains them is evaluated.
|
||||
//! `RELATED` and `RELATEDTABLE` traverse an existing relationship from a row context.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, overload, required, spec, standard};
|
||||
|
||||
/// Signature of `CROSSFILTER`, which names both endpoint columns and a direction.
|
||||
const CROSSFILTER_PARAMS: &[Parameter] =
|
||||
&[required("LeftColumnName", ParamKind::Column), required("RightColumnName", ParamKind::Column), required("CrossFilterType", ParamKind::Any)];
|
||||
|
||||
const CROSSFILTER_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])];
|
||||
|
||||
const USERELATIONSHIP_PARAMS: &[Parameter] = &[required("ColumnName1", ParamKind::Column), required("ColumnName2", ParamKind::Column)];
|
||||
|
||||
const USERELATIONSHIP_OVERLOADS: &[Overload] = &[overload(&[ParamKind::Column, ParamKind::Column])];
|
||||
|
||||
/// Flags shared by the relationship management functions: none of them is an iterator or
|
||||
/// volatile, dax.guide recommends all of them, and every one is usable in Excel and restricted
|
||||
/// by DirectQuery exactly like the rest of the catalog.
|
||||
const RELATIONSHIP_FLAGS: FunctionFlags = standard(false);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CROSSFILTER",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
3,
|
||||
3,
|
||||
CROSSFILTER_PARAMS,
|
||||
CROSSFILTER_OVERLOADS,
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Overrides the cross-filter direction of an existing relationship for the duration of \
|
||||
the filter context it modifies. The two column arguments identify the relationship \
|
||||
endpoints; the third argument is one of the words NONE, ONE, ONEWAY, BOTH, TWOWAY, \
|
||||
ONEWAY_LEFTFILTERSRIGHT or ONEWAY_RIGHTFILTERSLEFT (the last two flow from the first \
|
||||
column argument's table to the second's, or back). It changes filter propagation between \
|
||||
the two tables, never which relationship is active — activating an inactive relationship \
|
||||
is USERELATIONSHIP's job — so it is used as a filter modifier inside CALCULATE and \
|
||||
similar functions and returns no value.",
|
||||
&[
|
||||
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], BOTH ) )",
|
||||
"CALCULATE ( COUNTROWS ( Customer ), CROSSFILTER ( Sales[ProductKey], 'Product'[ProductKey], NONE ) )",
|
||||
"CALCULATE ( [Sales Amount], CROSSFILTER ( Sales[CustomerKey], Customer[CustomerKey], TWOWAY ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RELATED",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Returns the value of a column on the one side of a many-to-one relationship, following \
|
||||
one or more regular relationships from the current row. It requires a row context and \
|
||||
an active regular relationship, so it is used in calculated columns and inside table \
|
||||
iterators; a limited relationship cannot be traversed. The result is BLANK when no \
|
||||
related row exists and the column value can be of any type.",
|
||||
&[
|
||||
"SUMX ( Sales, Sales[Quantity] * RELATED ( 'Product'[List Price] ) )",
|
||||
"RELATED ( 'Product'[Category] )",
|
||||
"RELATED ( Customer[CountryRegion] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RELATEDTABLE",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
1,
|
||||
1,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Returns the rows of a table on the many side of a relationship, filtered to the rows \
|
||||
related to the current row. It performs a context transition from the row context to a \
|
||||
filter context before evaluating the table, making it a shortcut for CALCULATETABLE \
|
||||
with no additional filters; unlike CALCULATETABLE it accepts only a table reference, \
|
||||
not an arbitrary table expression.",
|
||||
&["AVERAGEX ( Customer, COUNTROWS ( RELATEDTABLE ( Sales ) ) )", "RELATEDTABLE ( Sales )", "COUNTROWS ( RELATEDTABLE ( OrderLines ) )"],
|
||||
),
|
||||
spec(
|
||||
"USERELATIONSHIP",
|
||||
FunctionCategory::RelationshipManagement,
|
||||
2,
|
||||
2,
|
||||
USERELATIONSHIP_PARAMS,
|
||||
USERELATIONSHIP_OVERLOADS,
|
||||
ReturnType::Any,
|
||||
RELATIONSHIP_FLAGS,
|
||||
"Activates an existing relationship for the duration of the filter context it modifies, \
|
||||
so its filters propagate even when the relationship is inactive in the model. The two \
|
||||
column arguments are the relationship endpoints; the innermost USERELATIONSHIP wins in \
|
||||
nested CALCULATE expressions. It selects which relationship propagates filters, not \
|
||||
their cross-filter direction, and returns no value.",
|
||||
&[
|
||||
"CALCULATE ( [Sales Amount], USERELATIONSHIP ( Sales[Delivery Date], 'Date'[Date] ) )",
|
||||
"CALCULATE ( COUNTROWS ( Sales ), USERELATIONSHIP ( Sales[Order Date], 'Date'[Date] ) )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,584 @@
|
||||
//! Statistical functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples. The order matches
|
||||
//! <https://dax.guide/functions/statistical/>.
|
||||
//!
|
||||
//! `LINEST`, `LINESTX` and `SAMPLE` have open-ended signatures: their repeated column/expression
|
||||
//! groups (and the trailing `Const`/`Order` argument) are modelled with a variadic overload and
|
||||
//! [`usize::MAX`] as the upper arity bound. All other functions have a closed arity range.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, standard, variadic};
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"BETA.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
4,
|
||||
6,
|
||||
&[
|
||||
required("X", ParamKind::Number),
|
||||
required("Alpha", ParamKind::Number),
|
||||
required("Beta", ParamKind::Number),
|
||||
required("Cumulative", ParamKind::Logical),
|
||||
optional("A", ParamKind::Number),
|
||||
optional("B", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical, ParamKind::Number, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Beta distribution on the interval [A, B]. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function. Omitting A and B uses the standard beta distribution on [0, 1]; Alpha and Beta must be positive, X must lie within [A, B], and a BLANK bound is an error rather than an omitted argument.",
|
||||
&["BETA.DIST ( 0.5, 3.51, 4.02, TRUE, 0, 1 )", "BETA.DIST ( 0.5, 3.51, 4.02, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"BETA.INV",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
5,
|
||||
&[
|
||||
required("Probability", ParamKind::Number),
|
||||
required("Alpha", ParamKind::Number),
|
||||
required("Beta", ParamKind::Number),
|
||||
optional("A", ParamKind::Number),
|
||||
optional("B", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the beta cumulative distribution function: returns the x for which BETA.DIST ( x, Alpha, Beta, TRUE ) equals Probability. Probability must be strictly between 0 and 1, Alpha and Beta must be positive, A must be less than B, and the result lies between A and B; A and B default to 0 and 1.",
|
||||
&["BETA.INV ( 0.5, 3.51, 4.02 )", "BETA.INV ( 0.75, 3.51, 4.02, 0, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Chi-squared distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the left-tailed cumulative distribution, FALSE the probability density. Negative X is an error and a non-integer Deg_freedom is truncated.",
|
||||
&["CHISQ.DIST ( 2.5, 10, TRUE )", "CHISQ.DIST ( 2.5, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.DIST.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Probability in the right tail of the chi-squared distribution with Deg_freedom degrees of freedom, used to compare observed and expected values in a chi-squared test. A non-integer Deg_freedom is truncated.",
|
||||
&["CHISQ.DIST.RT ( 2.5, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.INV",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the left-tailed chi-squared cumulative distribution: returns x such that CHISQ.DIST ( x, Deg_freedom, TRUE ) equals Probability. Probability must be at least 0 and less than 1; a non-integer Deg_freedom is rounded.",
|
||||
&["CHISQ.INV ( 0.95, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"CHISQ.INV.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Inverse of the right-tailed chi-squared probability: returns x such that CHISQ.DIST.RT ( x, Deg_freedom ) equals Probability. Probability must be greater than 0 and at most 1; a non-integer Deg_freedom is rounded and the iterative search reports an error if it does not converge.",
|
||||
&["CHISQ.INV.RT ( 0.05, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"COMBIN",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Number of unordered combinations of Number_chosen items drawn without repetition from Number items. Numeric arguments are truncated to integers, and Number must be at least Number_chosen.",
|
||||
&["COMBIN ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"COMBINA",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Number of combinations with repetition of Number_chosen items drawn from Number items. Non-integer arguments are truncated (the remarks document rounding), both must be non-negative, and Number must be at least Number_chosen.",
|
||||
&["COMBINA ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"CONFIDENCE.NORM",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Half-width around the sample mean for a normal-distribution confidence interval. Alpha \
|
||||
is the significance level (0.05 gives a 95% interval), Standard_dev is the known \
|
||||
population standard deviation and Size is the sample size.",
|
||||
&["CONFIDENCE.NORM ( 0.05, 2.5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"CONFIDENCE.T",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Alpha", ParamKind::Number), required("Standard_dev", ParamKind::Number), required("Size", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Half-width around the sample mean when the population standard deviation is unknown, \
|
||||
using Student's t with Size - 1 degrees of freedom. Alpha is the significance level and \
|
||||
Standard_dev is the sample standard deviation.",
|
||||
&["CONFIDENCE.T ( 0.05, 2.5, 50 )"],
|
||||
),
|
||||
spec(
|
||||
"EXPON.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Lambda", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Exponential distribution with rate Lambda. Cumulative TRUE returns the cumulative distribution, FALSE the probability density; X must be non-negative and Lambda must be positive. Commonly used to model the time between events.",
|
||||
&["EXPON.DIST ( 0.2, 10, TRUE )", "EXPON.DIST ( 0.2, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"GEOMEAN",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Geometric mean of the non-blank, positive values in a numeric column. Internally equivalent to GEOMEANX; blank and non-positive values do not contribute a valid term.",
|
||||
&["GEOMEAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"GEOMEANX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Evaluates the expression once per row of the table and returns the geometric mean of the non-blank, positive results. The expression runs in row context, so a measure reference triggers context transition.",
|
||||
&["GEOMEANX ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LINEST",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("ColumnY", ParamKind::Column), required("ColumnX", ParamKind::Column), optional("Const", ParamKind::Boolean)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Column]), variadic(&[ParamKind::Column, ParamKind::Column, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Least-squares straight-line fit of ColumnY against one or more ColumnX columns, returned as a one-row table with a slope per X column, the intercept, their standard errors, the coefficient of determination, the standard error, the F statistic, degrees of freedom and the regression/residual sums of squares. All column references must come from the same table; a trailing FALSE forces the intercept to 0.",
|
||||
&["LINEST ( Sales[Amount], Sales[Quantity] )", "LINEST ( Sales[Amount], Sales[Quantity], TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"LINESTX",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("ExpressionY", ParamKind::Expression),
|
||||
required("ExpressionX", ParamKind::Expression),
|
||||
optional("Const", ParamKind::Boolean),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Expression, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, false, true),
|
||||
"Evaluates the y and x expressions row by row and returns the same least-squares regression table as LINEST: one slope per x expression, intercept, standard errors, coefficient of determination, standard error, F statistic, degrees of freedom and regression/residual sums of squares. A trailing FALSE forces the intercept to 0.",
|
||||
&["LINESTX ( Sales, Sales[Amount], Sales[Quantity] )", "LINESTX ( Sales, Sales[Amount], Sales[Quantity], TRUE )"],
|
||||
),
|
||||
spec(
|
||||
"MEDIAN",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("Column", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"50th percentile (median) of the non-blank numeric values in a column. Logical values, dates and text are not supported. Returns BLANK when no row has a non-blank numeric value; internally equivalent to MEDIANX, which unlike MEDIAN does not ignore blank results.",
|
||||
&["MEDIAN ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"MEDIANX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Evaluates the expression once per row and returns the median of the results. Unlike MEDIAN, blank results returned by the expression are considered; the result is BLANK when no row returns a non-blank value. Integer results make the return type Variant (Integer without ties, Decimal with ties).",
|
||||
&["MEDIANX ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
4,
|
||||
4,
|
||||
&[
|
||||
required("X", ParamKind::Number),
|
||||
required("Mean", ParamKind::Number),
|
||||
required("Standard_dev", ParamKind::Number),
|
||||
required("Cumulative", ParamKind::Logical),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Normal distribution for the given Mean and Standard_dev. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function; Standard_dev must be positive.",
|
||||
&["NORM.DIST ( 45, 40, 2, TRUE )", "NORM.DIST ( 45, 40, 2, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.INV",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Probability", ParamKind::Number), required("Mean", ParamKind::Number), required("Standard_dev", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The x for which the normal cumulative probability equals Probability, given Mean and Standard_dev. Probability must lie in (0, 1) and Standard_dev must be positive.",
|
||||
&["NORM.INV ( 0.95, 40, 1.5 )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.S.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Z", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Standard normal distribution (mean 0, standard deviation 1). Cumulative TRUE returns the cumulative distribution function, FALSE the probability density function.",
|
||||
&["NORM.S.DIST ( 1.96, TRUE )", "NORM.S.DIST ( 1.96, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"NORM.S.INV",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("Probability", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"The x for which the standard normal cumulative probability equals Probability (mean 0, standard deviation 1). Probability must lie strictly between 0 and 1.",
|
||||
&["NORM.S.INV ( 0.975 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILE.EXC",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"Exclusive k-th percentile of the non-blank values in a column. K must lie in [1/(n+1), 1-1/(n+1)], where n is the number of valid values; K outside that interval is an error. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.EXC.",
|
||||
&["PERCENTILE.EXC ( Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILE.INC",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Column", ParamKind::Column), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(false),
|
||||
"Inclusive k-th percentile of the non-blank values in a column, where K lies in [0, 1]. Blanks in the column are ignored, unlike the blank results considered by PERCENTILEX.INC.",
|
||||
&["PERCENTILE.INC ( Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILEX.EXC",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Exclusive k-th percentile of the values returned by the expression, evaluated row by row. K must lie in [1/(n+1), 1-1/(n+1)]. Unlike PERCENTILE.EXC, blank values returned by the expression are considered.",
|
||||
&["PERCENTILEX.EXC ( Sales, Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERCENTILEX.INC",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression), required("K", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Number])],
|
||||
ReturnType::Variant,
|
||||
standard(true),
|
||||
"Inclusive k-th percentile of the values returned by the expression, evaluated row by row, where K lies in [0, 1]. Unlike PERCENTILE.INC, blank values returned by the expression are considered.",
|
||||
&["PERCENTILEX.INC ( Sales, Sales[Amount], 0.9 )"],
|
||||
),
|
||||
spec(
|
||||
"PERMUT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Number", ParamKind::Number), required("Number_chosen", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Number of ordered permutations of Number_chosen objects selected from Number objects, where order matters. Both arguments are truncated to integers; Number must be positive, Number_chosen non-negative and Number at least Number_chosen.",
|
||||
&["PERMUT ( 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"POISSON.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Mean", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Poisson distribution with the given Mean. Cumulative TRUE returns the probability of at most X events, FALSE the probability mass of exactly X events; a non-integer X is truncated and X must be non-negative.",
|
||||
&["POISSON.DIST ( 2, 5, TRUE )", "POISSON.DIST ( 2, 5, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"RANK.EQ",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
3,
|
||||
&[required("Value", ParamKind::Scalar), required("ColumnName", ParamKind::Column), optional("Order", ParamKind::Scalar)],
|
||||
&[overload(&[ParamKind::Scalar, ParamKind::Column]), overload(&[ParamKind::Scalar, ParamKind::Column, ParamKind::Scalar])],
|
||||
ReturnType::Integer,
|
||||
standard(false),
|
||||
"Rank of Value among the numbers in ColumnName, with ties sharing the top rank. Order 0/FALSE/DESC ranks descending (the default) and 1/TRUE/ASC ranks ascending. Equivalent to a RANKX call over SELECTCOLUMNS rather than pure syntax sugar.",
|
||||
&["RANK.EQ ( 42, Sales[Quantity] )", "RANK.EQ ( 42, Sales[Quantity], 1 )"],
|
||||
),
|
||||
spec(
|
||||
"RANKX",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
5,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("Expression", ParamKind::Expression),
|
||||
optional("Value", ParamKind::Scalar),
|
||||
optional("Order", ParamKind::Scalar),
|
||||
optional("Ties", ParamKind::Scalar),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Scalar, ParamKind::Scalar, ParamKind::Scalar]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
standard(true),
|
||||
"Rank of Value (or of Expression when Value is omitted) among the values Expression returns for every row of Table. Order defaults to descending and Ties defaults to Skip; Dense gives tied elements one shared rank without gaps. Expression runs in row context. Decimal inputs can rank unexpectedly because of floating-point storage, so ROUND or a Currency type is safer.",
|
||||
&["RANKX ( Sales, Sales[Amount] )", "RANKX ( Sales, Sales[Amount], 42, 0, Dense )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLE",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("OrderBy", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Scalar),
|
||||
],
|
||||
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
standard(true),
|
||||
"Deterministic sample of Size rows from Table, ordered by one or more OrderBy expressions with optional Order values. The result is fixed: it includes the first and final rows plus the rows spaced evenly between them; Size 0 or less returns an empty table. Group the input by the sort column to avoid duplicate rows.",
|
||||
&["SAMPLE ( 10, Sales, Sales[Amount] )", "SAMPLE ( 10, Sales, Sales[Amount], 0 )"],
|
||||
),
|
||||
spec(
|
||||
"STDEV.P",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Standard deviation of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.P; use STDEV.S for a sample.",
|
||||
&["STDEV.P ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEV.S",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Sample standard deviation of a numeric column, ignoring blanks, logical values and text. Internally equivalent to STDEVX.S; use STDEV.P for a complete population.",
|
||||
&["STDEV.S ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEVX.P",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Standard deviation of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["STDEVX.P ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"STDEVX.S",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Sample standard deviation computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["STDEVX.S ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST",
|
||||
FunctionCategory::Statistical,
|
||||
3,
|
||||
3,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number), required("Cumulative", ParamKind::Logical)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Logical])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Student's left-tailed t distribution with Deg_freedom degrees of freedom. Cumulative TRUE returns the cumulative distribution function, FALSE the probability density; Deg_freedom cannot be negative.",
|
||||
&["T.DIST ( 2, 10, TRUE )", "T.DIST ( 2, 10, FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST.2T",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Two-tailed Student's t distribution with Deg_freedom degrees of freedom. Neither argument can be negative.",
|
||||
&["T.DIST.2T ( 2, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.DIST.RT",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("X", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Right-tailed Student's t distribution with Deg_freedom degrees of freedom. Deg_freedom cannot be negative.",
|
||||
&["T.DIST.RT ( 2, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.INV",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Solves for the t value whose cumulative probability equals Probability, on the left tail of Student's t. Probability must lie between 0 and 1 and Deg_freedom cannot be negative.",
|
||||
&["T.INV ( 0.95, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"T.INV.2T",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Probability", ParamKind::Number), required("Deg_freedom", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Solves for the t value whose two-tailed probability equals Probability. Neither argument can be negative.",
|
||||
&["T.INV.2T ( 0.05, 10 )"],
|
||||
),
|
||||
spec(
|
||||
"VAR.P",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Variance of an entire population in a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.P; use VAR.S for a sample.",
|
||||
&["VAR.P ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VAR.S",
|
||||
FunctionCategory::Statistical,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Decimal,
|
||||
standard(false),
|
||||
"Sample variance of a numeric column, ignoring blanks, logical values and text. Internally equivalent to VARX.S; use VAR.P for a complete population.",
|
||||
&["VAR.S ( Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VARX.P",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Variance of an entire population, computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["VARX.P ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"VARX.S",
|
||||
FunctionCategory::Statistical,
|
||||
2,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Decimal,
|
||||
standard(true),
|
||||
"Sample variance computed from the expression evaluated once per row of the table. The expression runs in row context.",
|
||||
&["VARX.S ( Sales, Sales[Amount] )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,641 @@
|
||||
//! Table manipulation functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category holds four kinds of functions:
|
||||
//!
|
||||
//! - table constructors and projections (`DATATABLE`, `ROW`, `ADDCOLUMNS`, `SELECTCOLUMNS`,
|
||||
//! `SUMMARIZE`, `SUMMARIZECOLUMNS`, `GROUPBY`);
|
||||
//! - relational operations (`CROSSJOIN`, `UNION`, `EXCEPT`, `INTERSECT`, the natural joins and
|
||||
//! `SUBSTITUTEWITHINDEX`);
|
||||
//! - companion functions that are only valid as arguments of those operations (`CURRENTGROUP`,
|
||||
//! `IGNORE`, `NONVISUAL`, `NATURALJOINUSAGE`, `ROLLUP`, `ROLLUPGROUP`,
|
||||
//! `ROLLUPADDISSUBTOTAL`, `ROLLUPISSUBTOTAL`);
|
||||
//! - row selection and value helpers (`DISTINCT`, `VALUES`, `FILTERS`, `TOPN`, `TOPNSKIP`,
|
||||
//! `GENERATESERIES`, `DETAILROWS`, `TREATAS`, `SAMPLEAXISWITHLOCALMINMAX`,
|
||||
//! `TOPNPERLEVEL`).
|
||||
//!
|
||||
//! The companion functions are catalogued because the parser accepts them, but several do not
|
||||
//! return a value on their own: they are syntax markers inside `SUMMARIZE`,
|
||||
//! `SUMMARIZECOLUMNS` or `ADDMISSINGITEMS`, so their return type is [`ReturnType::Blank`].
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with the usual DirectQuery restrictions.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// Iterators evaluate an expression once per row of the first table argument.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
/// No Excel version listed by dax.guide supports the function.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
/// Power BI-only extension functions: engine extensions that DirectQuery cannot evaluate.
|
||||
const EXTENSION: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"ADDCOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Name", ParamKind::Text), required("Expression", ParamKind::Expression)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the input table with new columns added. Each expression is evaluated in the \
|
||||
row context of the table, so the expressions are repeatable in `Name, Expression` \
|
||||
pairs. The added columns keep the data lineage of a simple column reference for \
|
||||
NATURALINNERJOIN/NATURALLEFTOUTERJOIN but not for context transition.",
|
||||
&[
|
||||
"ADDCOLUMNS ( Sales, \"Margin\", Sales[Amount] - Sales[Cost] )",
|
||||
"ADDCOLUMNS ( Product, \"Brand\", Product[Brand], \"Price\", Product[List Price] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"ADDMISSINGITEMS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("ShowAll_ColumnName", ParamKind::Column),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Any),
|
||||
optional("FilterTable", ParamKind::Table),
|
||||
],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Adds back the rows of a SUMMARIZECOLUMNS result that were removed because every \
|
||||
measure was blank. The optional leading columns list which columns must show all \
|
||||
items; the table argument is the SUMMARIZECOLUMNS result, followed by optional \
|
||||
group-by columns (possibly ROLLUPGROUP/ROLLUPADDISSUBTOTAL calls) and filters. \
|
||||
ROLLUPISSUBTOTAL marks the subtotal columns.",
|
||||
&["ADDMISSINGITEMS ( Sales[Region], SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) ), Sales[Region] )"],
|
||||
),
|
||||
spec(
|
||||
"CROSSJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table)],
|
||||
&[variadic(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the Cartesian product of the table arguments. The result has the product of \
|
||||
the row counts and the sum of the column counts; column names must be different in \
|
||||
every argument or the function raises an error.",
|
||||
&["CROSSJOIN ( Product, Store )", "CROSSJOIN ( Product, Store, 'Date' )"],
|
||||
),
|
||||
spec(
|
||||
"CURRENTGROUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
0,
|
||||
0,
|
||||
&[],
|
||||
&[overload(&[])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the subset of rows of the GROUPBY input table that belong to the current \
|
||||
group. It takes no arguments and is only valid as the table argument of an \
|
||||
aggregation iterator inside GROUPBY, such as SUMX or COUNTX.",
|
||||
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"DATATABLE",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Name", ParamKind::Text), required("DataType", ParamKind::Text), required("Data", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a table whose columns and rows are declared inline. Column names and data type \
|
||||
names alternate, followed by a single table constructor with the data. Data type names \
|
||||
are BOOLEAN/LOGICAL, CURRENCY/DECIMAL, DATETIME, DOUBLE, INTEGER/INT64 and \
|
||||
STRING/TEXT; unlike the table constructor, DATATABLE requires literal values.",
|
||||
&[
|
||||
"DATATABLE ( \"Name\", STRING, { { \"Small\", 1 }, { \"Medium\", 2 } } )",
|
||||
"DATATABLE ( \"Name\", STRING, \"Ordinal\", INTEGER, { { \"Small\", 1 }, { \"Large\", 3 } } )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"DETAILROWS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Measure", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Reference])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the table produced by the DetailRows expression defined on a measure. When the \
|
||||
measure has no DetailRows expression, the entire table the measure belongs to is \
|
||||
returned. Context transition is not applied by the engine; wrap the call in \
|
||||
CALCULATETABLE inside a row context when transition is intended.",
|
||||
&["DETAILROWS ( [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"DISTINCT",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnNameOrTableExpr", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the distinct values of a column, or the distinct rows of a table expression. \
|
||||
Unlike VALUES, a column argument does not add the blank row generated by an invalid \
|
||||
relationship.",
|
||||
&["DISTINCT ( Sales[Region] )", "DISTINCT ( Sales )"],
|
||||
),
|
||||
spec(
|
||||
"EXCEPT",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the rows of the left table that do not appear in the right table. A row present \
|
||||
in both tables is removed together with its duplicates; columns are matched by position \
|
||||
with strict comparison and the result keeps the left table's column names and lineage.",
|
||||
&["EXCEPT ( Sales, SalesArchive )"],
|
||||
),
|
||||
spec(
|
||||
"FILTERS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("ColumnName", ParamKind::Column)],
|
||||
&[overload(&[ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the filter values applied directly to a column, as a single-column table. The \
|
||||
column argument must be a column reference; the result can include the blank row \
|
||||
generated by an invalid relationship.",
|
||||
&["FILTERS ( Store[Continent] )", "FILTERS ( 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATE",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Evaluates the second table expression for every row of the first table and returns the \
|
||||
union of those results with the corresponding first-table columns. Rows of the first \
|
||||
table whose second expression is empty are dropped, unlike GENERATEALL.",
|
||||
&["GENERATE ( Product, RELATEDTABLE ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATEALL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("Table1", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Evaluates the second table expression for every row of the first table and keeps the \
|
||||
first-table row even when that expression is empty, filling the second table's columns \
|
||||
with blanks. Column names must be different in both arguments.",
|
||||
&["GENERATEALL ( Product, RELATEDTABLE ( Sales ) )"],
|
||||
),
|
||||
spec(
|
||||
"GENERATESERIES",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
3,
|
||||
&[required("StartValue", ParamKind::Number), required("EndValue", ParamKind::Number), optional("IncrementValue", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Number]), overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a single-column table named Value holding an arithmetic series from StartValue \
|
||||
to EndValue. IncrementValue must be positive and defaults to 1; the series stops at the \
|
||||
last value less than or equal to EndValue, and EndValue below StartValue yields an \
|
||||
empty table.",
|
||||
&["GENERATESERIES ( 1, 10, 2 )", "GENERATESERIES ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )"],
|
||||
),
|
||||
spec(
|
||||
"GROUPBY",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Column),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Column]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Groups the input table by the given columns and adds expression columns evaluated per \
|
||||
group. Expressions added by GROUPBY must aggregate CURRENTGROUP() and cannot use \
|
||||
CALCULATE; use SUMMARIZE when the added columns aggregate base-table columns.",
|
||||
&["GROUPBY ( Sales, Sales[Region], \"Amount\", SUMX ( CURRENTGROUP (), Sales[Amount] ) )", "GROUPBY ( Customer, Customer[Country] )"],
|
||||
),
|
||||
spec(
|
||||
"IGNORE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Measure_Expression", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Marks a SUMMARIZECOLUMNS expression so that it is excluded when deciding whether a row \
|
||||
is blank. Rows are kept as long as another expression without IGNORE returns a value; \
|
||||
the function itself returns no value.",
|
||||
&["SUMMARIZECOLUMNS ( Sales[Region], IGNORE ( [Sales Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"INTERSECT",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns the rows of the left table that also appear in the right table, keeping \
|
||||
duplicates from the left table. Columns are matched by position without type coercion; \
|
||||
the operation is not commutative and the result keeps the left table's column names and \
|
||||
lineage.",
|
||||
&["INTERSECT ( Sales, SalesArchive )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALINNERJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Joins two tables on all columns they have in common (including columns of their \
|
||||
expanded tables) and returns the matching rows. Joined columns must have the same name, \
|
||||
data type and lineage; comparison is strict, with no type coercion.",
|
||||
&["NATURALINNERJOIN ( Sales, Product )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALJOINUSAGE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
ENGINE_ONLY,
|
||||
"Adds a table as a natural join to the filter context. It is only valid as a value \
|
||||
filter of SUMMARIZECOLUMNS and is used mostly in queries sent to composite models; \
|
||||
dax.guide lists no Excel support and Microsoft documentation is not available.",
|
||||
&["SUMMARIZECOLUMNS ( Sales[Region], NATURALJOINUSAGE ( Product ) )"],
|
||||
),
|
||||
spec(
|
||||
"NATURALLEFTOUTERJOIN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
2,
|
||||
&[required("LeftTable", ParamKind::Table), required("RightTable", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Joins two tables on all columns they have in common and returns every row of the left \
|
||||
table, with blanks where the right table has no match. Joined columns must share name, \
|
||||
data type and lineage, and comparison does not coerce types.",
|
||||
&["NATURALLEFTOUTERJOIN ( Sales, Product )"],
|
||||
),
|
||||
spec(
|
||||
"NONVISUAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("Expression", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Marks a SUMMARIZECOLUMNS value filter as non-visual: the filter still restricts the \
|
||||
grouping columns but does not affect measure values, so measures that use \
|
||||
ALLSELECTED can return the non-visual totals.",
|
||||
&["SUMMARIZECOLUMNS ( 'Date'[Calendar Year], NONVISUAL ( TREATAS ( { \"CY 2008\" }, 'Date'[Calendar Year] ) ), \"Amount\", [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("GroupBy_ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies the SUMMARIZE group-by columns that also produce subtotal rows. The \
|
||||
arguments must be qualified column names, not expressions, and are only valid inside \
|
||||
SUMMARIZE; the function itself returns no value.",
|
||||
&["SUMMARIZE ( Sales, ROLLUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPADDISSUBTOTAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GrandtotalFilter", ParamKind::Table),
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("Name", ParamKind::Text),
|
||||
optional("GroupLevelFilter", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies the SUMMARIZECOLUMNS group-by columns that produce subtotals and adds a \
|
||||
Boolean column per pair indicating whether the row is a subtotal. It accepts an \
|
||||
optional grand-total filter before the pairs and an optional per-level filter after \
|
||||
each pair; it is only valid inside SUMMARIZECOLUMNS and returns no value.",
|
||||
&["SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal Country\" ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPGROUP",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("GroupBy_ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Column])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Identifies a group of SUMMARIZE or SUMMARIZECOLUMNS columns that produce subtotals \
|
||||
together. Inside ROLLUP it suppresses the partial subtotals that ROLLUP would \
|
||||
otherwise add; the function itself returns no value.",
|
||||
&["SUMMARIZE ( Sales, ROLLUPGROUP ( Sales[Country], Sales[City] ), \"Amount\", SUM ( Sales[Amount] ) )"],
|
||||
),
|
||||
spec(
|
||||
"ROLLUPISSUBTOTAL",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GrandtotalFilter", ParamKind::Table),
|
||||
required("GroupBy_ColumnName", ParamKind::Column),
|
||||
required("IsSubtotal_ColumnName", ParamKind::Text),
|
||||
optional("GroupLevelFilter", ParamKind::Table),
|
||||
],
|
||||
&[variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Blank,
|
||||
STANDARD,
|
||||
"Pairs the subtotal columns created by ROLLUPADDISSUBTOTAL with their group-by columns \
|
||||
so that ADDMISSINGITEMS can add the missing subtotal rows. It is only valid inside \
|
||||
ADDMISSINGITEMS and returns no value.",
|
||||
&[
|
||||
"ADDMISSINGITEMS ( Sales[Country], SUMMARIZECOLUMNS ( ROLLUPADDISSUBTOTAL ( Sales[Country], \"IsSubtotal\" ), \"Amount\", SUM ( Sales[Amount] ) ), ROLLUPISSUBTOTAL ( Sales[Country], [IsSubtotal] ) )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"ROW",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Name", ParamKind::Text), required("Expression", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns a single-row table with the named columns. Arguments come in `Name, \
|
||||
Expression` pairs; column references used as expressions lose their data lineage rather \
|
||||
than keeping it.",
|
||||
&["ROW ( \"Product\", \"Bike\", \"Price\", 1500 )", "ROW ( \"Value\", 1 )"],
|
||||
),
|
||||
spec(
|
||||
"SAMPLEAXISWITHLOCALMINMAX",
|
||||
FunctionCategory::TableManipulation,
|
||||
5,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Size", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("Axis", ParamKind::Column),
|
||||
required("Measure", ParamKind::Expression),
|
||||
required("MinResolution", ParamKind::Number),
|
||||
optional("DynamicSeries", ParamKind::Column),
|
||||
optional("DynamicSeriesSelectionCriteria", ParamKind::Text),
|
||||
optional("DynamicSeriesSelectionOrder", ParamKind::Boolean),
|
||||
optional("MaxResolution", ParamKind::Number),
|
||||
optional("MaxDynamicSeries", ParamKind::Number),
|
||||
optional("MaxIterations", ParamKind::Number),
|
||||
],
|
||||
&[variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Column, ParamKind::Any, ParamKind::Number])],
|
||||
ReturnType::Table,
|
||||
ENGINE_ONLY,
|
||||
"Returns a subset of the input table obtained by binning the numeric or date axis into \
|
||||
equal-sized bins and preserving the local minimum and maximum of each measure per \
|
||||
series. Power BI uses it to reduce the points of line charts with a continuous axis; \
|
||||
dax.guide lists no Excel support and Microsoft documentation is not available.",
|
||||
&["SAMPLEAXISWITHLOCALMINMAX ( 100, Sales, Sales[Order Date], Sales[Amount], 10 )"],
|
||||
),
|
||||
spec(
|
||||
"SELECTCOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), optional("Name", ParamKind::Text), optional("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Table]), variadic(&[ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Projects the input to one column per `Name, Expression` pair, keeping the same row \
|
||||
count; each expression is evaluated in row context. Unlike ADDCOLUMNS it starts from an \
|
||||
empty table; the name may be omitted when the expression is a simple column reference, \
|
||||
and simple references keep their data lineage.",
|
||||
&[
|
||||
"SELECTCOLUMNS ( Sales, \"Amount\", Sales[Amount] )",
|
||||
"SELECTCOLUMNS ( Product, \"Brand\", Product[Brand], \"Category\", Product[Category] )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"SUBSTITUTEWITHINDEX",
|
||||
FunctionCategory::TableManipulation,
|
||||
4,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
required("Name", ParamKind::Text),
|
||||
required("SemiJoinIndexTable", ParamKind::Table),
|
||||
required("Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Text, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Semijoins two tables and replaces the common columns with a zero-based index column. \
|
||||
The index follows the row order obtained by sorting the second table with the supplied \
|
||||
order expressions; matching uses the same lineage rules as the natural joins and raises \
|
||||
an error when no column matches.",
|
||||
&["SUBSTITUTEWITHINDEX ( Sales, \"ProductIndex\", DISTINCT ( Sales[ProductKey] ), Sales[ProductKey] )"],
|
||||
),
|
||||
spec(
|
||||
"SUMMARIZE",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("GroupBy_ColumnName", ParamKind::Reference),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Reference]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Reference, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Groups the input table by the given columns and optionally adds computed columns. The \
|
||||
group-by arguments can be columns of the table or its related tables, or ROLLUP / \
|
||||
ROLLUPGROUP calls. Adding columns with SUMMARIZE is deprecated in favour of \
|
||||
SUMMARIZECOLUMNS or ADDCOLUMNS, and ROLLUP/ROLLUPGROUP columns lose their data lineage.",
|
||||
&["SUMMARIZE ( Sales, Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )", "SUMMARIZE ( Sales, 'Product'[Brand], 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"SUMMARIZECOLUMNS",
|
||||
FunctionCategory::TableManipulation,
|
||||
0,
|
||||
usize::MAX,
|
||||
&[
|
||||
optional("GroupBy_ColumnName", ParamKind::Any),
|
||||
optional("FilterTable", ParamKind::Table),
|
||||
optional("Name", ParamKind::Text),
|
||||
optional("Expression", ParamKind::Expression),
|
||||
],
|
||||
&[overload(&[]), variadic(&[ParamKind::Any])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Builds a summary table from group-by columns, filters applied only to the grouping, and \
|
||||
added expression columns. A row is included only when at least one expression returns a \
|
||||
non-blank value; filters accept KEEPFILTERS, REMOVEFILTERS and NONVISUAL, and group-by \
|
||||
arguments accept ROLLUPGROUP and ROLLUPADDISSUBTOTAL. Since June 2024 it can run inside \
|
||||
context transition, with the remaining limitations documented by Microsoft.",
|
||||
&[
|
||||
"SUMMARIZECOLUMNS ( Sales[Region], \"Amount\", SUM ( Sales[Amount] ) )",
|
||||
"SUMMARIZECOLUMNS ( 'Product'[Brand], 'Date'[Calendar Year], \"Amount\", [Sales Amount] )",
|
||||
"SUMMARIZECOLUMNS ( )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"TOPN",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("N_Value", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("OrderBy_Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Table]), variadic(&[ParamKind::Number, ParamKind::Table, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Returns the top N rows of a table according to the order-by expressions. Order is \
|
||||
0/FALSE/DESC or 1/TRUE/ASC and defaults to descending; ties at the N-th row are all \
|
||||
returned, and N_Value of zero or less yields an empty table. The result has no \
|
||||
guaranteed sort order.",
|
||||
&["TOPN ( 10, Sales, Sales[Amount], DESC )"],
|
||||
),
|
||||
spec(
|
||||
"TOPNPERLEVEL",
|
||||
FunctionCategory::TableManipulation,
|
||||
6,
|
||||
6,
|
||||
&[
|
||||
required("Rows", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
required("LevelsDefinition", ParamKind::Table),
|
||||
required("NodesExpanded", ParamKind::Table),
|
||||
required("LevelsBoundaries", ParamKind::Table),
|
||||
required("RestartIndicatorColumnName", ParamKind::Text),
|
||||
],
|
||||
&[overload(&[ParamKind::Number, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Table, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
EXTENSION,
|
||||
"Returns the rows to display for an expanded hierarchy, restricted to the selected nodes \
|
||||
and boundaries. It is an undocumented Power BI extension that is not part of the \
|
||||
Analysis Services engine and has no Excel or DirectQuery support.",
|
||||
&["TOPNPERLEVEL ( 10, Sales, Levels, Expanded, Boundaries, \"Restart\" )"],
|
||||
),
|
||||
spec(
|
||||
"TOPNSKIP",
|
||||
FunctionCategory::TableManipulation,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Rows", ParamKind::Number),
|
||||
required("Skip_Rows_Value", ParamKind::Number),
|
||||
required("Table", ParamKind::Table),
|
||||
optional("OrderBy_Expression", ParamKind::Expression),
|
||||
optional("Order", ParamKind::Number),
|
||||
optional("Ties", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Table]),
|
||||
variadic(&[ParamKind::Number, ParamKind::Number, ParamKind::Table, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
ITERATOR,
|
||||
"Retrieves Rows rows from a table after skipping Skip rows, ordered by the order-by \
|
||||
expressions. Ties can be handled as Skip (ranking skips tied elements) or Dense (all \
|
||||
tied elements count as one); the result has no guaranteed sort order. With a non-zero \
|
||||
skip the table has to reference physical columns that carry lineage, and context \
|
||||
transition cannot occur.",
|
||||
&["TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC )"],
|
||||
),
|
||||
spec(
|
||||
"TREATAS",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Expression", ParamKind::Table), required("ColumnName", ParamKind::Column)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Column])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Applies the data lineage of the output columns to the table returned by the first \
|
||||
argument, so that its values filter the model columns as if they came from those \
|
||||
columns. Only a table expression is accepted there; unused values are filtered out and \
|
||||
the result can be stored in a variable.",
|
||||
&["TREATAS ( { \"North America\" }, Sales[Region] )", "TREATAS ( { 2008, 2009 }, 'Date'[Calendar Year] )"],
|
||||
),
|
||||
spec(
|
||||
"UNION",
|
||||
FunctionCategory::TableManipulation,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Table2", ParamKind::Table)],
|
||||
&[variadic(&[ParamKind::Table, ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"Returns all rows of all table arguments, keeping duplicates. Columns are combined by \
|
||||
position and the result takes its column names from the first table; differing data \
|
||||
types are resolved with DAX coercion rules, and lineage is kept only where all input \
|
||||
columns share it.",
|
||||
&["UNION ( Sales, SalesArchive )", "UNION ( Sales, SalesArchive, SalesForecast )"],
|
||||
),
|
||||
spec(
|
||||
"VALUES",
|
||||
FunctionCategory::TableManipulation,
|
||||
1,
|
||||
1,
|
||||
&[required("TableNameOrColumnName", ParamKind::Reference)],
|
||||
&[overload(&[ParamKind::Column]), overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
STANDARD,
|
||||
"With a column, returns its unique values as a single-column table, including the blank \
|
||||
row produced by an invalid relationship. With a table name it returns every row of that \
|
||||
table with its columns unchanged, without removing duplicates. VALUES needs a model \
|
||||
table or column, so it cannot be applied to a variable.",
|
||||
&["VALUES ( Sales[Region] )", "VALUES ( Store )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Text functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! The category splits into three kinds of functions:
|
||||
//!
|
||||
//! - string construction (`COMBINEVALUES`, `CONCATENATE`, `CONCATENATEX`, `LEFT`, `MID`,
|
||||
//! `REPLACE`, `REPT`, `RIGHT`, `SUBSTITUTE`, `TRIM`), which return text and whose result
|
||||
//! length is measured in Unicode code points;
|
||||
//! - classification and conversion (`EXACT`, `FIND`, `LEN`, `LOWER`, `SEARCH`, `UNICHAR`,
|
||||
//! `UNICODE`, `UPPER`), which are case- or accent-sensitive to different degrees;
|
||||
//! - formatting and serialization (`FIXED`, `FORMAT`, `TOCSV`, `TOJSON`, `VALUE`), whose output
|
||||
//! or parsing depends on the model locale.
|
||||
|
||||
use super::{FunctionCategory, FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Available to every host, with no documented DirectQuery restriction.
|
||||
const STANDARD: FunctionFlags = FunctionFlags::new(false, false, false, true, false);
|
||||
|
||||
/// Functions that DirectQuery does not support in calculated columns.
|
||||
const DQ_RESTRICTED: FunctionFlags = FunctionFlags::new(false, false, false, true, true);
|
||||
|
||||
/// `CONCATENATEX` is an iterator and is also restricted in DirectQuery calculated columns.
|
||||
const ITERATOR: FunctionFlags = FunctionFlags::new(true, false, false, true, true);
|
||||
|
||||
/// Engine-only functions: no Excel version listed by dax.guide supports them.
|
||||
const ENGINE_ONLY: FunctionFlags = FunctionFlags::new(false, false, false, false, true);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COMBINEVALUES",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
usize::MAX,
|
||||
&[required("Delimiter", ParamKind::Text), required("Expression1", ParamKind::Any), required("Expression2", ParamKind::Any)],
|
||||
&[variadic(&[ParamKind::Text, ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Concatenates two or more scalar values with a delimiter and returns one text value. The \
|
||||
function is designed for calculated columns that stand in for multi-column relationships \
|
||||
in DirectQuery models: the engine can translate the call into an optimized join \
|
||||
predicate, assuming without validating that different input combinations produce \
|
||||
different output strings. Choose a delimiter that cannot occur ambiguously in the \
|
||||
values, and remember that the delimiter itself is not escaped.",
|
||||
&["COMBINEVALUES ( \" | \", Customer[Customer Name], Customer[Customer Code] )", "COMBINEVALUES ( \"-\", \"GridCraft\", \"2024\", \"Q1\" )"],
|
||||
),
|
||||
spec(
|
||||
"CONCATENATE",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Joins two text values into one text value without inserting a separator. The `&` operator \
|
||||
performs the same concatenation and accepts any number of operands, so CONCATENATE is \
|
||||
only convenient for two. Non-text arguments are converted to text using the model's \
|
||||
locale rather than the caller's culture.",
|
||||
&["CONCATENATE ( \"GridCraft\", \" 2024\" )", "CONCATENATE ( Customer[Customer Name], Customer[Customer Code] )"],
|
||||
),
|
||||
spec(
|
||||
"CONCATENATEX",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
usize::MAX,
|
||||
&[required("Table", ParamKind::Table), required("Expression", ParamKind::Expression)],
|
||||
&[
|
||||
overload(&[ParamKind::Table, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
|
||||
overload(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression, ParamKind::Logical]),
|
||||
variadic(&[ParamKind::Table, ParamKind::Expression, ParamKind::Text, ParamKind::Expression]),
|
||||
],
|
||||
ReturnType::String,
|
||||
ITERATOR,
|
||||
"Iterates a table, evaluates the expression for every row and concatenates the results \
|
||||
into a single text value using an optional delimiter. An order-by expression and an \
|
||||
optional order (0/FALSE/DESC or 1/TRUE/ASC, ascending by default) sort the values; \
|
||||
without them the row order is unspecified and does not reflect the source table's \
|
||||
physical order. Ordering follows the model collation, while the delimiter is inserted \
|
||||
verbatim.",
|
||||
&[
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \" )",
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount] )",
|
||||
"CONCATENATEX ( Sales, Sales[Product], \", \", Sales[Amount], TRUE )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"EXACT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text1", ParamKind::Text), required("Text2", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::Boolean,
|
||||
STANDARD,
|
||||
"Compares two text values and returns TRUE when they are exactly the same, including \
|
||||
case. The ordinary `=` comparison is case-insensitive, so EXACT is the way to force a \
|
||||
case-sensitive and accent-sensitive test. BLANK and an empty string compare equal here.",
|
||||
&["EXACT ( \"GridCraft\", \"gridcraft\" )", "EXACT ( Sales[Code], \"A-100\" )"],
|
||||
),
|
||||
spec(
|
||||
"FIND",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("FindText", ParamKind::Text),
|
||||
required("WithinText", ParamKind::Text),
|
||||
optional("StartPosition", ParamKind::Number),
|
||||
optional("NotFoundValue", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the 1-based position of FindText inside WithinText, beginning the search at \
|
||||
StartPosition (default 1). The comparison is case-sensitive and accent-sensitive, and \
|
||||
wildcards are not interpreted; use SEARCH for case-insensitive or wildcard matching. If \
|
||||
the text is absent the function returns NotFoundValue when it is supplied, otherwise it \
|
||||
raises an error.",
|
||||
&["FIND ( \"Red\", \"GridCraft Cell S100 Red\" )", "FIND ( \"Red\", \"GridCraft Cell S100 Red\", 1, BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"FIXED",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
3,
|
||||
&[required("Number", ParamKind::Number), optional("Decimals", ParamKind::Number), optional("NoCommas", ParamKind::Boolean)],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Number, ParamKind::Boolean]),
|
||||
],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Rounds a number to the requested number of decimals and returns it as text, grouping the \
|
||||
integer part with commas unless NoCommas is TRUE. Decimals defaults to 2, and a negative \
|
||||
value rounds to the left of the decimal separator. The decimal and grouping separators \
|
||||
come from the model locale, not from the caller's culture.",
|
||||
&["FIXED ( 384518.16, 2, FALSE )", "FIXED ( 4392768.29, 0, TRUE )", "FIXED ( 6741548.73, -2 )"],
|
||||
),
|
||||
spec(
|
||||
"FORMAT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
3,
|
||||
&[required("Value", ParamKind::Any), required("Format", ParamKind::Text), optional("LocaleName", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Any, ParamKind::Text]), overload(&[ParamKind::Any, ParamKind::Text, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Formats a value as text using a Visual Basic (OLE Automation) format string or one of \
|
||||
the predefined numeric and date/time format names; unknown strings are treated as a \
|
||||
custom format or literal. The result is always text, and BLANK produces an empty string. \
|
||||
Month and weekday names and separators follow the model locale, which the optional \
|
||||
LocaleName overrides where the host supports that argument.",
|
||||
&["FORMAT ( 0.742, \"Percent\" )", "FORMAT ( DATE ( 2019, 3, 28 ), \"yyyy-mm-dd\" )", "FORMAT ( 1234.567, \"$#,0.00\", \"en-US\" )"],
|
||||
),
|
||||
spec(
|
||||
"LEFT",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the first NumberOfCharacters characters of a text value; the count defaults to 1. \
|
||||
It is intended for fixed-position extraction. Characters are counted as Unicode code \
|
||||
points, and no case or locale conversion is applied to the result.",
|
||||
&["LEFT ( \"DAX is so cool!\", 3 )", "LEFT ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"LEN",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Character count of a text value, spaces included. Characters are Unicode code points, \
|
||||
so a character outside the Basic Multilingual Plane counts as one.",
|
||||
&["LEN ( \"DAX is so cool!\" )", "LEN ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"LOWER",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Converts every letter in a text value to lowercase and returns the result. Case mapping \
|
||||
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
|
||||
dotted and dotless I, while digits and symbols are left unchanged.",
|
||||
&["LOWER ( \"DAX is SO cool!\" )", "LOWER ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"MID",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
3,
|
||||
&[required("Text", ParamKind::Text), required("StartPosition", ParamKind::Number), required("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns NumberOfCharacters characters from a text value starting at the 1-based \
|
||||
StartPosition. If the requested length extends past the end of the text only the \
|
||||
remaining characters are returned. Positions and lengths are counted in Unicode code \
|
||||
points, and no case conversion is applied.",
|
||||
&["MID ( \"DAX is so cool!\", 11, 4 )", "MID ( \"123-45-6789\", 8, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"REPLACE",
|
||||
FunctionCategory::Text,
|
||||
4,
|
||||
4,
|
||||
&[
|
||||
required("OldText", ParamKind::Text),
|
||||
required("StartPosition", ParamKind::Number),
|
||||
required("NumberOfCharacters", ParamKind::Number),
|
||||
required("NewText", ParamKind::Text),
|
||||
],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number, ParamKind::Number, ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
DQ_RESTRICTED,
|
||||
"Replaces a fixed run of characters: NumberOfCharacters characters starting at the \
|
||||
1-based StartPosition are replaced by NewText, whose length need not match the removed \
|
||||
text. Because the position is explicit there is no searching, so case and locale do not \
|
||||
affect the match; positions are counted in Unicode code points.",
|
||||
&["REPLACE ( \"DAX is so cool!\", 11, 4, \"fantastic\" )", "REPLACE ( \"123-45-6789\", 1, 3, \"XXX\" )"],
|
||||
),
|
||||
spec(
|
||||
"REPT",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), required("NumberOfTimes", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Repeats a text value NumberOfTimes times and returns the concatenation. A count of zero \
|
||||
returns an empty string, a fractional count is truncated to an integer, and the \
|
||||
result may not exceed 32,767 characters or the function raises an error. The text is \
|
||||
repeated verbatim, without case or locale conversion.",
|
||||
&["REPT ( \"?\", 3 )", "REPT ( \"0\", 5 )"],
|
||||
),
|
||||
spec(
|
||||
"RIGHT",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Text", ParamKind::Text), optional("NumberOfCharacters", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Text]), overload(&[ParamKind::Text, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the last NumberOfCharacters characters of a text value; the count defaults to 1. \
|
||||
It is intended for fixed-position extraction from the end of the text. Counting is by \
|
||||
Unicode code point, and no case conversion is applied.",
|
||||
&["RIGHT ( \"DAX is so cool!\", 5 )", "RIGHT ( Customer[Customer Code], 4 )"],
|
||||
),
|
||||
spec(
|
||||
"SEARCH",
|
||||
FunctionCategory::Text,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("FindText", ParamKind::Text),
|
||||
required("WithinText", ParamKind::Text),
|
||||
optional("StartPosition", ParamKind::Number),
|
||||
optional("NotFoundValue", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Number, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the 1-based position of FindText inside WithinText, starting at StartPosition \
|
||||
(default 1). Unlike FIND the comparison ignores case but remains accent-sensitive, and \
|
||||
the search text treats `?` and `*` as wildcards with `~` as the escape character. If the \
|
||||
text is absent the function returns NotFoundValue when supplied, otherwise it raises an \
|
||||
error.",
|
||||
&["SEARCH ( \"red\", \"GridCraft Cell S100 Red\" )", "SEARCH ( \"cell*s100\", \"GridCraft Cell S100 Blue\", 1, BLANK () )"],
|
||||
),
|
||||
spec(
|
||||
"SUBSTITUTE",
|
||||
FunctionCategory::Text,
|
||||
3,
|
||||
4,
|
||||
&[
|
||||
required("Text", ParamKind::Text),
|
||||
required("OldText", ParamKind::Text),
|
||||
required("NewText", ParamKind::Text),
|
||||
optional("InstanceNumber", ParamKind::Number),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Text, ParamKind::Text, ParamKind::Text, ParamKind::Number]),
|
||||
],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Replaces occurrences of OldText with NewText in a text value. With no InstanceNumber \
|
||||
every occurrence is replaced; otherwise only that occurrence is. Matching is \
|
||||
case-sensitive and accent-sensitive, so a difference in case leaves the text untouched, \
|
||||
and the search text is a literal substring rather than a pattern.",
|
||||
&["SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"Cell\", \"Tablet\" )", "SUBSTITUTE ( \"GridCraft Cell S100 Red\", \"S\", \"X\", 1 )"],
|
||||
),
|
||||
spec(
|
||||
"TOCSV",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
4,
|
||||
&[
|
||||
required("Table", ParamKind::Table),
|
||||
optional("MaxRows", ParamKind::Number),
|
||||
optional("Delimiter", ParamKind::Text),
|
||||
optional("IncludeHeaders", ParamKind::Boolean),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Table]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Table, ParamKind::Number, ParamKind::Text, ParamKind::Boolean]),
|
||||
],
|
||||
ReturnType::String,
|
||||
ENGINE_ONLY,
|
||||
"Serializes a table's records as comma-separated text. MaxRows limits how many rows are \
|
||||
converted (default 10, negative for all), Delimiter is a non-empty constant field \
|
||||
separator (default a comma), and IncludeHeaders controls the header row (default TRUE). \
|
||||
Row order is unspecified and line endings are fixed; quotation marks are doubled, and a \
|
||||
value containing a quote or the delimiter is enclosed in quotes. Not available in Excel, \
|
||||
and not supported in DirectQuery calculated columns.",
|
||||
&["TOCSV ( Customer )", "TOCSV ( Customer, 3, \",\", FALSE )"],
|
||||
),
|
||||
spec(
|
||||
"TOJSON",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
2,
|
||||
&[required("Table", ParamKind::Table), optional("MaxRows", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Table]), overload(&[ParamKind::Table, ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
ENGINE_ONLY,
|
||||
"Serializes a table's records as a JSON document with header, rowCount and data members. \
|
||||
MaxRows limits how many rows are converted (default 10, negative for all), while values \
|
||||
keep their native types inside the JSON text. Row order is unspecified. Not available in \
|
||||
Excel, and not supported in DirectQuery calculated columns.",
|
||||
&["TOJSON ( Customer )", "TOJSON ( Customer, 3 )"],
|
||||
),
|
||||
spec(
|
||||
"TRIM",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Removes leading and trailing spaces and collapses runs of spaces between words to a \
|
||||
single space. Only the 7-bit ASCII space (character 32) is removed: the non-breaking \
|
||||
space (character 160), tabs and other whitespace survive, which matters for text copied \
|
||||
from web pages.",
|
||||
&["TRIM ( \" DAX is awesome !!! \" )", "TRIM ( Customer[Customer Name] )"],
|
||||
),
|
||||
spec(
|
||||
"UNICHAR",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Number", ParamKind::Number)],
|
||||
&[overload(&[ParamKind::Number])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Returns the Unicode character for a numeric code point. A supplementary character is \
|
||||
one code point value. Code point 0 and values outside the allowable Unicode range \
|
||||
raise an error.",
|
||||
&["UNICHAR ( 9473 )", "UNICHAR ( 65 )"],
|
||||
),
|
||||
spec(
|
||||
"UNICODE",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Integer,
|
||||
STANDARD,
|
||||
"Returns the numeric Unicode value of the first character of a text value; an empty \
|
||||
string raises an error. The engine counts Unicode code points, so a character outside \
|
||||
the Basic Multilingual Plane is returned as one value. Use UNICHAR for the inverse \
|
||||
conversion.",
|
||||
&["UNICODE ( \"A\" )", "UNICODE ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"UPPER",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::String,
|
||||
STANDARD,
|
||||
"Converts every letter in a text value to uppercase and returns the result. Case mapping \
|
||||
follows Unicode rules and is locale-sensitive for some scripts, such as the Turkish \
|
||||
dotted and dotless I, while digits and symbols are left unchanged.",
|
||||
&["UPPER ( \"dax is so cool!\" )", "UPPER ( Customer[CountryRegion] )"],
|
||||
),
|
||||
spec(
|
||||
"VALUE",
|
||||
FunctionCategory::Text,
|
||||
1,
|
||||
1,
|
||||
&[required("Text", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Text])],
|
||||
ReturnType::Decimal,
|
||||
STANDARD,
|
||||
"Converts text that represents a number, date or time into its numeric value. Parsing \
|
||||
accepts the constant, number and date/time formats the engine recognizes and follows the \
|
||||
model locale for separators and date order; text that cannot be parsed raises an error. \
|
||||
Because the engine also coerces text implicitly, VALUE mainly makes the conversion \
|
||||
explicit, and it should be protected with IF when the column may contain invalid text.",
|
||||
&["VALUE ( \"123.45678\" )", "VALUE ( \"2020-10-23\" )", "VALUE ( Sales[TextAmount] )"],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,716 @@
|
||||
//! Time intelligence functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! Every function in this category assumes a well-formed date table: a contiguous range of
|
||||
//! dates, one unique date/date-time column marked as the date table, and a relationship to the
|
||||
//! fact table based on that column (or the table explicitly marked as a date table). The
|
||||
//! optional `YearEndDate` arguments control fiscal years; the week-based functions and the
|
||||
//! calendar-only arguments introduced with model calendars require a calendar reference rather
|
||||
//! than a date column and are not available to Excel's embedded engine.
|
||||
|
||||
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec};
|
||||
use crate::functions::FunctionCategory;
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"CLOSINGBALANCEMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current month, after applying the \
|
||||
optional filter. It opens a month-to-date window only at its closing date, so a filter \
|
||||
on the date table is replaced by ENDOFMONTH; the date table must be contiguous and \
|
||||
marked as a date table for the relationship to be treated as a calendar.",
|
||||
&["CLOSINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current quarter, after applying the \
|
||||
optional filter. The quarter is derived from the marked date table, so missing dates or \
|
||||
a relationship not based on the date column invalidate the closing balance.",
|
||||
&["CLOSINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression at the last date of the current week of a model calendar, \
|
||||
after applying the optional filter. Week boundaries come from the calendar definition, \
|
||||
so a plain date column is not accepted and the calendar must define week categories.",
|
||||
&["CLOSINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"CLOSINGBALANCEYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression at the last date of the current year, after applying the \
|
||||
optional filter. Pass YearEndDate to make the closing date follow a fiscal year; the \
|
||||
date table must contain every day of that fiscal year and stay marked as a date table.",
|
||||
&["CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "CLOSINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"DATEADD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
5,
|
||||
&[
|
||||
required("Dates", ParamKind::Date),
|
||||
required("NumberOfIntervals", ParamKind::Number),
|
||||
required("Interval", ParamKind::Text),
|
||||
optional("Extension", ParamKind::Text),
|
||||
optional("Truncation", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Shifts the dates visible in the filter context by NumberOfIntervals units of Interval \
|
||||
(DAY, MONTH, QUARTER or YEAR) and returns the dates that exist in the date column. \
|
||||
Extension and Truncation are available only for a model calendar; for a date column \
|
||||
DATEADD accepts exactly three arguments. With a calendar, YEAR follows the calendar's \
|
||||
year definition, which may be a fiscal year.",
|
||||
&["DATEADD ( 'Date'[Date], -1, YEAR )", "DATEADD ( Gregorian, 1, MONTH )", "DATEADD ( Gregorian, 1, MONTH, EXTENDING, ANCHORED )"],
|
||||
),
|
||||
spec(
|
||||
"DATESBETWEEN",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
3,
|
||||
&[required("Dates", ParamKind::Date), required("StartDate", ParamKind::Date), required("EndDate", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates between two inclusive boundaries that exist in the date column. A \
|
||||
BLANK StartDate begins at MIN ( Dates ), a BLANK EndDate ends at MAX ( Dates ), and a \
|
||||
StartDate after EndDate returns an empty table. The result keeps the lineage of the \
|
||||
marked date table, so the date table must be contiguous for windows to be meaningful.",
|
||||
&["DATESBETWEEN ( 'Date'[Date], DATE ( 2008, 8, 1 ), DATE ( 2008, 8, 31 ) )"],
|
||||
),
|
||||
spec(
|
||||
"DATESINPERIOD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
4,
|
||||
5,
|
||||
&[
|
||||
required("Dates", ParamKind::Date),
|
||||
required("StartDate", ParamKind::Date),
|
||||
required("NumberOfIntervals", ParamKind::Number),
|
||||
required("Interval", ParamKind::Text),
|
||||
optional("EndBehavior", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text]),
|
||||
overload(&[ParamKind::Date, ParamKind::Date, ParamKind::Number, ParamKind::Text, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates from StartDate over NumberOfIntervals units of Interval (DAY, WEEK, \
|
||||
MONTH, QUARTER or YEAR); a negative count looks backwards. BLANK StartDate uses the \
|
||||
minimum date in the column. EndBehavior (PRECISE or ENDALIGNED) is available only with \
|
||||
a model calendar; consider WINDOW when the interval arithmetic is not needed.",
|
||||
&[
|
||||
"DATESINPERIOD ( 'Date'[Date], MAX ( 'Date'[Date] ), -12, MONTH )",
|
||||
"DATESINPERIOD ( Gregorian, DATE ( 2008, 2, 29 ), -1, MONTH, ENDALIGNED )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"DATESMTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Month-to-date window: from the first day of the month up to whatever latest date the \
|
||||
filter context exposes, restricted to dates present in the column. This is syntax sugar \
|
||||
for DATESBETWEEN over the current month and requires a marked, contiguous date table.",
|
||||
&["DATESMTD ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"DATESQTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Quarter-to-date window: from the first day of the current quarter up to whatever latest \
|
||||
date the filter context exposes. Quarter boundaries come from the marked date table, so \
|
||||
an incomplete or unmarked date table breaks the window.",
|
||||
&["DATESQTD ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"DATESWTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the week-to-date window of a model calendar: dates from the first day of the \
|
||||
current week through the last visible date. Week numbering and the first day of the week \
|
||||
come from the calendar definition, not from the date column, and the function is not \
|
||||
available to Excel's DAX engine.",
|
||||
&["DATESWTD ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"DATESYTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Year-to-date window: from the start of the year up to whatever latest date the filter \
|
||||
context exposes, keeping only dates present in the column. YearEndDate selects a fiscal \
|
||||
year end (for example \"6/30\"); the date table must cover whole fiscal years and be \
|
||||
marked as a date table for the window to be correct.",
|
||||
&["DATESYTD ( 'Date'[Date] )", "DATESYTD ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the month visible in the filter context as a single-row table: \
|
||||
the latest date of that month that exists in the date column of the marked date table. Use it as a CALCULATE \
|
||||
modifier for semi-additive measures.",
|
||||
&["ENDOFMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the quarter visible in the filter context as a single-row table, \
|
||||
restricted to dates present in the date column. Quarter boundaries follow the marked \
|
||||
date table; a non-contiguous table can omit the quarter-end date.",
|
||||
&["ENDOFQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the last date of the week visible in the filter context for a model calendar. \
|
||||
The week definition, including the first day of the week, comes from the calendar, so a \
|
||||
date column is not accepted and Excel's DAX engine does not support the function.",
|
||||
&["ENDOFWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"ENDOFYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date of the year visible in the filter context as a single-row table. \
|
||||
YearEndDate selects a fiscal year end; without it the window is December 31. The date \
|
||||
table must be marked and must contain the resulting date.",
|
||||
&["ENDOFYEAR ( 'Date'[Date] )", "ENDOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTDATE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date visible in the filter context, as a single-row table, restricted \
|
||||
to dates that exist in the date column. Blanks are considered, unlike FIRSTNONBLANK; \
|
||||
the column's table needs the date table marking so that time intelligence windows \
|
||||
behave correctly.",
|
||||
&["FIRSTDATE ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTNONBLANK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Iterates the column in its sort order and returns the first value for which the \
|
||||
expression is not blank, as a single-column, single-row table. The column need not be a \
|
||||
date, but over a marked date table it defines the start of the time window; the iterator \
|
||||
can cause performance and memory issues on large models, so prefer an optimized pattern.",
|
||||
&["FIRSTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"FIRSTNONBLANKVALUE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Returns the expression evaluated at the start of the visible time window: the first \
|
||||
value of the column whose expression is not blank, without returning a table. It is the \
|
||||
scalar counterpart of FIRSTNONBLANK and is commonly used for semi-additive measures over \
|
||||
a marked date table; the evaluation is an iterator, so large models pay per-row cost.",
|
||||
&["FIRSTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTDATE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the last date visible in the filter context, as a single-row table, restricted \
|
||||
to dates that exist in the date column. It is the anchor of many YTD windows; a missing \
|
||||
or unmarked date table makes the result follow partial selections instead of the calendar.",
|
||||
&["LASTDATE ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTNONBLANK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Iterates the column in its sort order and returns the last value for which the \
|
||||
expression is not blank, as a single-column, single-row table. The column need not be a \
|
||||
date, but over a marked date table it defines the end of the time window; the iterator \
|
||||
can be expensive, so dax.guide recommends optimized semi-additive patterns.",
|
||||
&["LASTNONBLANK ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"LASTNONBLANKVALUE",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
2,
|
||||
&[required("ColumnName", ParamKind::Column), required("Expression", ParamKind::Expression)],
|
||||
&[overload(&[ParamKind::Column, ParamKind::Expression])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(true, false, false, true, true),
|
||||
"Returns the expression evaluated at the end of the visible time window: the last value \
|
||||
of the column whose expression is not blank, without returning a table. It is the scalar \
|
||||
counterpart of LASTNONBLANK and a typical semi-additive pattern over a marked date \
|
||||
table; the per-row iteration is costly on large models.",
|
||||
&["LASTNONBLANKVALUE ( 'Date'[Date], [Sales Amount] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTDAY",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the day after the last date visible in the filter context, as a single-row table \
|
||||
restricted to dates present in the date column. Because the date table must be \
|
||||
contiguous, a missing next day yields an empty table.",
|
||||
&["NEXTDAY ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the month after the last date visible in the filter context. The \
|
||||
month boundaries come from the marked date table, so gaps in the calendar produce \
|
||||
incomplete results and a bad relationship makes the window follow the wrong selection.",
|
||||
&["NEXTMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the quarter after the last date visible in the filter context. The \
|
||||
quarter is derived from the marked date table; the result keeps the date column lineage \
|
||||
and excludes dates absent from the calendar.",
|
||||
&["NEXTQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns all dates of the week after the last date visible in the filter context, using \
|
||||
the week definition of a model calendar. A plain date column cannot supply week \
|
||||
boundaries, and Excel's embedded DAX engine does not expose the calendar-based function.",
|
||||
&["NEXTWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"NEXTYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the year after the last date visible in the filter context. \
|
||||
YearEndDate shifts the year to a fiscal calendar; the date table must contain the whole \
|
||||
following year, be contiguous and be marked as a date table.",
|
||||
&["NEXTYEAR ( 'Date'[Date] )", "NEXTYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding month, after applying the \
|
||||
optional filter. The opening balance uses the marked date table's month boundaries, so \
|
||||
the relationship and date coverage must be valid or the window slides on partial data.",
|
||||
&["OPENINGBALANCEMONTH ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding quarter, after applying the \
|
||||
optional filter. Quarter boundaries come from the marked date table; an unmarked table \
|
||||
or a relationship not based on the date column changes the opening period.",
|
||||
&["OPENINGBALANCEQUARTER ( [Sales Amount], 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression on the final date of the preceding week of a model calendar, \
|
||||
after applying the optional filter. The calendar defines the week, so a date column is \
|
||||
not accepted and the function is unavailable to Excel's DAX engine.",
|
||||
&["OPENINGBALANCEWEEK ( [Sales Amount], Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"OPENINGBALANCEYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression on the final date of the preceding year, after applying the \
|
||||
optional filter. YearEndDate aligns the opening balance with a fiscal year; the date \
|
||||
table must cover entire fiscal years and be marked as a date table.",
|
||||
&["OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date] )", "OPENINGBALANCEYEAR ( [Sales Amount], 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"PARALLELPERIOD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
3,
|
||||
3,
|
||||
&[required("Dates", ParamKind::Date), required("NumberOfIntervals", ParamKind::Number), required("Interval", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date, ParamKind::Number, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Moves the visible first and last dates by NumberOfIntervals units of MONTH, QUARTER or \
|
||||
YEAR, then returns the contiguous dates between the moved boundaries, expanding partial \
|
||||
periods to complete ones. Only dates in the marked date column appear, so a \
|
||||
discontinuous calendar leaves gaps.",
|
||||
&["PARALLELPERIOD ( 'Date'[Date], -1, YEAR )", "PARALLELPERIOD ( 'Date'[Date], 0, MONTH )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSDAY",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the day before the first date visible in the filter context, as a single-row \
|
||||
table restricted to dates present in the date column. The marked date table must be \
|
||||
contiguous; otherwise the previous day may not exist in the model.",
|
||||
&["PREVIOUSDAY ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the month before the first date visible in the filter context. Month \
|
||||
boundaries come from the marked date table; gaps in the calendar or an incorrect \
|
||||
relationship make the previous month incomplete.",
|
||||
&["PREVIOUSMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the quarter before the first date visible in the filter context. The \
|
||||
quarter is derived from the marked date table, so the table must contain every day of \
|
||||
the previous quarter for the window to be complete.",
|
||||
&["PREVIOUSQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns all dates of the week before the first date visible in the filter context, using \
|
||||
a model calendar's week definition. Week boundaries are calendar metadata, so a date \
|
||||
column is not accepted and Excel's DAX engine cannot call the function.",
|
||||
&["PREVIOUSWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUSYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns all dates of the year before the first date visible in the filter context, \
|
||||
optionally aligned to a fiscal year end. The marked date table must include the whole \
|
||||
previous year, including leap days, for the window to be complete.",
|
||||
&["PREVIOUSYEAR ( 'Date'[Date] )", "PREVIOUSYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"SAMEPERIODLASTYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the dates of the same period one year earlier, preserving the number of days \
|
||||
rather than the month boundaries. It is syntax sugar for DATEADD ( Dates, -1, YEAR ) and \
|
||||
relies on a marked, contiguous date table; a fiscal year requires adapting the offset \
|
||||
or the calendar definition.",
|
||||
&["SAMEPERIODLASTYEAR ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFMONTH",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the month visible in the filter context, as a single-row table \
|
||||
restricted to dates in the date column. The marked date table must contain the month's \
|
||||
first day for the result to be non-empty.",
|
||||
&["STARTOFMONTH ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFQUARTER",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Dates", ParamKind::Date)],
|
||||
&[overload(&[ParamKind::Date])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the quarter visible in the filter context, as a single-row \
|
||||
table restricted to dates in the date column. Quarter boundaries follow the marked date \
|
||||
table, so an incomplete calendar can omit the first day.",
|
||||
&["STARTOFQUARTER ( 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFWEEK",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
1,
|
||||
&[required("Calendar", ParamKind::Table)],
|
||||
&[overload(&[ParamKind::Table])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Returns the first date of the week visible in the filter context for a model calendar. \
|
||||
The calendar defines the first day of the week, so a date column is not accepted and the \
|
||||
function is not available to Excel's embedded DAX engine.",
|
||||
&["STARTOFWEEK ( Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"STARTOFYEAR",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
1,
|
||||
2,
|
||||
&[required("Dates", ParamKind::Date), optional("YearEndDate", ParamKind::Text)],
|
||||
&[overload(&[ParamKind::Date]), overload(&[ParamKind::Date, ParamKind::Text])],
|
||||
ReturnType::Table,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Returns the first date of the year visible in the filter context as a single-row table. \
|
||||
YearEndDate shifts the start to a fiscal year; the date table must be marked and include \
|
||||
every day from the fiscal-year start through year end.",
|
||||
&["STARTOFYEAR ( 'Date'[Date] )", "STARTOFYEAR ( 'Date'[Date], \"6/30/2008\" )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALMTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the month-to-date window, from the first day of the month \
|
||||
through the last visible date, after applying the optional filter. It is syntax sugar \
|
||||
for CALCULATE with DATESMTD and depends on a marked, contiguous date table.",
|
||||
&["TOTALMTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALQTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Dates", ParamKind::Date), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Date]), overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the quarter-to-date window, from the first day of the \
|
||||
quarter through the last visible date, after applying the optional filter. It is syntax \
|
||||
sugar for CALCULATE with DATESQTD and requires the date table to be marked.",
|
||||
&["TOTALQTD ( SUM ( Sales[Amount] ), 'Date'[Date] )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALWTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
3,
|
||||
&[required("Expression", ParamKind::Expression), required("Calendar", ParamKind::Table), optional("Filter", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Expression, ParamKind::Table]), overload(&[ParamKind::Expression, ParamKind::Table, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, false, true),
|
||||
"Evaluates the expression over the week-to-date window defined by a model calendar, from \
|
||||
the first day of the week through the last visible date, after applying the optional \
|
||||
filter. Week boundaries come from the calendar, and Excel's DAX engine does not support \
|
||||
the function.",
|
||||
&["TOTALWTD ( SUM ( Sales[Amount] ), Gregorian )"],
|
||||
),
|
||||
spec(
|
||||
"TOTALYTD",
|
||||
FunctionCategory::TimeIntelligence,
|
||||
2,
|
||||
4,
|
||||
&[
|
||||
required("Expression", ParamKind::Expression),
|
||||
required("Dates", ParamKind::Date),
|
||||
optional("Filter", ParamKind::Any),
|
||||
optional("YearEndDate", ParamKind::Text),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Expression, ParamKind::Date]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any]),
|
||||
overload(&[ParamKind::Expression, ParamKind::Date, ParamKind::Any, ParamKind::Text]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
FunctionFlags::new(false, false, false, true, true),
|
||||
"Evaluates the expression over the year-to-date window, from the first day of the year \
|
||||
through the last visible date, after applying the optional filter. It is syntax sugar \
|
||||
for CALCULATE with DATESYTD; YearEndDate selects a fiscal year and the date table must \
|
||||
be marked and cover whole fiscal years.",
|
||||
&[
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date] )",
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], Sales[Region] = \"US\" )",
|
||||
"TOTALYTD ( SUM ( Sales[Amount] ), 'Date'[Date], ALL ( Sales ), \"6/30/2008\" )",
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Visual calculation functions.
|
||||
//!
|
||||
//! Every record follows the shared catalog shape in `super`: exact name, arity, parameter
|
||||
//! kinds, overloads, return type, flags, description and parseable examples.
|
||||
//!
|
||||
//! All functions in this category are Power BI visual calculation functions: they can only be
|
||||
//! used in the visual calculation editor and are rejected in measures, calculated columns and
|
||||
//! calculated tables. The `axis` parameter is defined by the VISUAL SHAPE query syntax emitted
|
||||
//! by the visual calculation feature, so `ROWS` and `COLUMNS` appear in examples as bare names.
|
||||
|
||||
use super::{FunctionFlags, FunctionSpec, ParamKind, ReturnType, optional, overload, required, spec, variadic};
|
||||
|
||||
/// Power BI visual calculations are not available to Excel's embedded engine, and the
|
||||
/// DirectQuery restrictions listed for measures and calculated columns do not apply because
|
||||
/// the functions cannot be used there.
|
||||
const VISUAL: FunctionFlags = FunctionFlags::new(false, false, false, false, false);
|
||||
|
||||
pub static FUNCTIONS: &[FunctionSpec] = &[
|
||||
spec(
|
||||
"COLLAPSE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("Column", ParamKind::Column),
|
||||
optional("N", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Retrieves a context with the detail levels above the current one removed, or returns its \
|
||||
first argument evaluated in that coarser context. Navigation-only calls (an axis or a \
|
||||
list of columns) can be used inside CALCULATE. Available only in Power BI visual \
|
||||
calculations; `N` defaults to one level.",
|
||||
&[
|
||||
"COLLAPSE ( [Sales Amount], ROWS )",
|
||||
"COLLAPSE ( [Sales Amount], ROWS, 2 )",
|
||||
"COLLAPSE ( [Sales Amount], [Month] )",
|
||||
"COLLAPSE ( ROWS, 1 )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"COLLAPSEALL",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
2,
|
||||
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Removes every detail level along an axis, returning the expression evaluated at the \
|
||||
highest level of that axis. The inverse of EXPANDALL. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["COLLAPSEALL ( [Sales Amount], ROWS )", "COLLAPSEALL ( ROWS )", "COLLAPSEALL ( [Sales Amount], COLUMNS )"],
|
||||
),
|
||||
spec(
|
||||
"EXPAND",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
usize::MAX,
|
||||
&[
|
||||
required("Expression", ParamKind::Any),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("Column", ParamKind::Column),
|
||||
optional("N", ParamKind::Number),
|
||||
],
|
||||
&[overload(&[ParamKind::Any]), variadic(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Retrieves a context with additional detail levels compared to the current one, or \
|
||||
returns its first argument evaluated in that finer context. Navigation-only calls (an \
|
||||
axis or a list of columns) can be used inside CALCULATE. Available only in Power BI \
|
||||
visual calculations; `N` defaults to one level.",
|
||||
&["EXPAND ( [Sales Amount], ROWS )", "EXPAND ( [Sales Amount], ROWS, 2 )", "EXPAND ( [Sales Amount], [Month] )"],
|
||||
),
|
||||
spec(
|
||||
"EXPANDALL",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
2,
|
||||
&[optional("Expression", ParamKind::Any), required("Axis", ParamKind::Any)],
|
||||
&[overload(&[ParamKind::Any]), overload(&[ParamKind::Any, ParamKind::Any])],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Adds every detail level along an axis, returning the expression evaluated at the lowest \
|
||||
level of that axis. The inverse of COLLAPSEALL. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["EXPANDALL ( [Sales Amount], ROWS )", "EXPANDALL ( ROWS )", "EXPANDALL ( [Sales Amount], COLUMNS )"],
|
||||
),
|
||||
spec(
|
||||
"FIRST",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column in the first row of an axis or partition. OrderBy columns \
|
||||
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
|
||||
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["FIRST ( [Sales Amount] )", "FIRST ( [Sales Amount], ROWS )", "FIRST ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
spec(
|
||||
"LAST",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column in the last row of an axis or partition. OrderBy columns \
|
||||
define the sort order; Blanks accepts DEFAULT, FIRST or LAST and Reset accepts NONE, \
|
||||
LOWESTPARENT, HIGHESTPARENT or a level number. Available only in Power BI visual \
|
||||
calculations.",
|
||||
&["LAST ( [Sales Amount] )", "LAST ( [Sales Amount], ROWS )", "LAST ( [Sales Amount], ROWS, [Month], FIRST, LOWESTPARENT )"],
|
||||
),
|
||||
spec(
|
||||
"MOVINGAVERAGE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
2,
|
||||
7,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
required("WindowSize", ParamKind::Number),
|
||||
optional("IncludeCurrent", ParamKind::Boolean),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Numeric,
|
||||
VISUAL,
|
||||
"Calculates the average of the values in a sliding window of WindowSize rows along an \
|
||||
axis. IncludeCurrent defaults to TRUE; when FALSE the window holds the previous \
|
||||
WindowSize rows. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
|
||||
BI visual calculations.",
|
||||
&[
|
||||
"MOVINGAVERAGE ( [Sales Amount], 6 )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 3, FALSE )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 6, TRUE, ROWS )",
|
||||
"MOVINGAVERAGE ( [Sales Amount], 12, TRUE, ROWS, [Month], DEFAULT, NONE )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"NEXT",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Steps", ParamKind::Number),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column the given number of rows after the current row on an axis. \
|
||||
Steps defaults to 1 and must be at least 1. OrderBy, Blanks and Reset behave as in \
|
||||
FIRST. Available only in Power BI visual calculations.",
|
||||
&["NEXT ( [Sales Amount] )", "NEXT ( [Sales Amount], 1, ROWS )", "NEXT ( [Sales Amount], 2, ROWS, [Month], LAST, HIGHESTPARENT )"],
|
||||
),
|
||||
spec(
|
||||
"PREVIOUS",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Steps", ParamKind::Number),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Number, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Any,
|
||||
VISUAL,
|
||||
"Returns the value of a column the given number of rows before the current row on an \
|
||||
axis. Steps defaults to 1 and is negated internally, so it must be at least 1. OrderBy, \
|
||||
Blanks and Reset behave as in FIRST. Available only in Power BI visual calculations.",
|
||||
&[
|
||||
"PREVIOUS ( [Sales Amount] )",
|
||||
"PREVIOUS ( [Sales Amount], 1, ROWS )",
|
||||
"PREVIOUS ( [Sales Amount], 2, ROWS, [Month], DEFAULT, LOWESTPARENT )",
|
||||
],
|
||||
),
|
||||
spec(
|
||||
"RANGE",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
6,
|
||||
&[
|
||||
required("Step", ParamKind::Number),
|
||||
optional("IncludeCurrent", ParamKind::Boolean),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Number]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Number, ParamKind::Boolean, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Table,
|
||||
VISUAL,
|
||||
"Returns the interval of rows within an axis that starts Step rows before (negative Step) \
|
||||
or after (non-negative Step) the current row, optionally including the current row. The \
|
||||
result is normally passed to CALCULATE. Available only in Power BI visual calculations.",
|
||||
&["RANGE ( 6 )", "RANGE ( -5, TRUE, ROWS )", "RANGE ( 12, FALSE, ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
spec(
|
||||
"RUNNINGSUM",
|
||||
super::FunctionCategory::VisualCalculations,
|
||||
1,
|
||||
5,
|
||||
&[
|
||||
required("Column", ParamKind::Column),
|
||||
optional("Axis", ParamKind::Any),
|
||||
optional("OrderBy", ParamKind::Any),
|
||||
optional("Blanks", ParamKind::Any),
|
||||
optional("Reset", ParamKind::Any),
|
||||
],
|
||||
&[
|
||||
overload(&[ParamKind::Column]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
overload(&[ParamKind::Column, ParamKind::Any, ParamKind::Any, ParamKind::Any, ParamKind::Any]),
|
||||
],
|
||||
ReturnType::Numeric,
|
||||
VISUAL,
|
||||
"Calculates the cumulative sum of a column from the start of the axis or partition up to \
|
||||
the current row. OrderBy, Blanks and Reset behave as in FIRST. Available only in Power \
|
||||
BI visual calculations.",
|
||||
&["RUNNINGSUM ( [Sales Amount] )", "RUNNINGSUM ( [Sales Amount], ROWS )", "RUNNINGSUM ( [Sales Amount], ROWS, [Month], DEFAULT, NONE )"],
|
||||
),
|
||||
];
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,553 @@
|
||||
//! Tokenizer for DAX expressions.
|
||||
//!
|
||||
//! Spans are byte offsets into the source. Keywords are recognised case-insensitively; the
|
||||
//! parser keeps the source spelling of identifiers and function names. `TRUE`/`FALSE` stay
|
||||
//! identifiers here so the parser can tell the boolean literal from a call such as `TRUE()`.
|
||||
//!
|
||||
//! Numeric tokens are typed: digit-only text becomes [`TokenKind::Integer`] when it fits `i64`,
|
||||
//! while a decimal point or exponent becomes [`TokenKind::Decimal`]. `dt"..."` text is
|
||||
//! validated here and emitted as [`TokenKind::DateTime`]. Overflow and malformed date/time
|
||||
//! literals are [`LexError`] values carrying the literal's span.
|
||||
//!
|
||||
//! Statement punctuation is lexed here too: `:` ([`TokenKind::Colon`]) separates a function
|
||||
//! parameter's name from its annotation, `@name` becomes [`TokenKind::AtName`] for `START AT`
|
||||
//! parameters, and `;` ([`TokenKind::Semicolon`]) is the optional trailing query terminator.
|
||||
//! Statement keywords such as `DEFINE` and `MEASURE` stay plain [`TokenKind::Ident`] tokens and
|
||||
//! are matched case-insensitively by the parser, so they remain available as identifier text
|
||||
//! wherever the grammar does not reserve them.
|
||||
|
||||
use chrono::NaiveDate;
|
||||
|
||||
use crate::ast::{DateTimeLiteral, Span};
|
||||
|
||||
/// Longest expression accepted by [`crate::parse_expression`], in bytes. Mirrors DAX's
|
||||
/// expression limit and bounds the size of the tree a long operator chain can build.
|
||||
pub const MAX_INPUT_LEN: usize = 8_192;
|
||||
|
||||
/// Longest query accepted by [`crate::parse_query`], in bytes. A query has no documented length
|
||||
/// limit comparable to the expression bound, so it gets a larger, independent ceiling that still
|
||||
/// bounds memory for `DEFINE` blocks and repeated `EVALUATE` statements.
|
||||
pub const MAX_QUERY_LEN: usize = 1_048_576;
|
||||
|
||||
/// A lexical token.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TokenKind {
|
||||
/// A digit-only literal that fits in `i64`, e.g. `42`.
|
||||
Integer(i64),
|
||||
/// A literal with a decimal point or exponent, e.g. `3.14`, `.5`, `1e3`.
|
||||
Decimal(f64),
|
||||
/// A validated `dt"..."` date/time literal.
|
||||
DateTime(DateTimeLiteral),
|
||||
String(String),
|
||||
/// A bare identifier, function name or table name (`Sales`, `STDEV.P`, `TRUE`).
|
||||
Ident(String),
|
||||
/// A single-quoted table name, with `''` escapes resolved.
|
||||
QuotedIdent(String),
|
||||
/// A bracketed column name, with `]]` escapes resolved.
|
||||
BracketIdent(String),
|
||||
/// The `NOT` operator (case-insensitive).
|
||||
Not,
|
||||
/// The `IN` operator (case-insensitive).
|
||||
In,
|
||||
/// The `EVALUATE` statement keyword (case-insensitive).
|
||||
Evaluate,
|
||||
Plus,
|
||||
Minus,
|
||||
Star,
|
||||
Slash,
|
||||
Caret,
|
||||
Amp,
|
||||
Eq,
|
||||
StrictEq,
|
||||
NotEq,
|
||||
Lt,
|
||||
Gt,
|
||||
Le,
|
||||
Ge,
|
||||
AndAnd,
|
||||
OrOr,
|
||||
/// `=>`, used by `DEFINE FUNCTION` definitions.
|
||||
Arrow,
|
||||
/// `:` between a function parameter name and its type annotation.
|
||||
Colon,
|
||||
/// `@name`, an XMLA statement parameter reference in `START AT`.
|
||||
AtName(String),
|
||||
/// `;`, accepted only as an optional trailing statement terminator.
|
||||
Semicolon,
|
||||
LParen,
|
||||
RParen,
|
||||
LBrace,
|
||||
RBrace,
|
||||
Comma,
|
||||
Eof,
|
||||
}
|
||||
|
||||
/// A token and its byte span.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Token {
|
||||
pub kind: TokenKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct LexError {
|
||||
pub message: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl LexError {
|
||||
fn new(message: impl Into<String>, span: Span) -> Self {
|
||||
LexError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
/// Tokenizes `src` and appends an [`TokenKind::Eof`] token at `src.len()`.
|
||||
///
|
||||
/// Whitespace is insignificant and comments (`//`, `--` to end of line, and `/* ... */`) are
|
||||
/// skipped. A block comment does not nest.
|
||||
#[allow(clippy::cognitive_complexity)]
|
||||
// A hand-written scanner: one loop with a case per token kind.
|
||||
pub fn tokenize(src: &str) -> Result<Vec<Token>, LexError> {
|
||||
let chars: Vec<(usize, char)> = src.char_indices().collect();
|
||||
let n = chars.len();
|
||||
let ch = |i: usize| chars.get(i).map(|(_, c)| *c);
|
||||
let pos = |i: usize| chars.get(i).map(|(p, _)| *p).unwrap_or(src.len());
|
||||
let mut out: Vec<Token> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
|
||||
while i < n {
|
||||
let start = pos(i);
|
||||
let Some(c) = ch(i) else { break };
|
||||
match c {
|
||||
c if c.is_whitespace() => {
|
||||
i += 1;
|
||||
}
|
||||
'/' if ch(i + 1) == Some('/') => {
|
||||
i += 2;
|
||||
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'-' if ch(i + 1) == Some('-') => {
|
||||
i += 2;
|
||||
while ch(i).is_some_and(|c| c != '\n' && c != '\r') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'/' if ch(i + 1) == Some('*') => {
|
||||
let mut j = i + 2;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => {
|
||||
return Err(LexError::new("unterminated block comment", Span::new(start, src.len())));
|
||||
}
|
||||
Some('*') if ch(j + 1) == Some('/') => {
|
||||
j += 2;
|
||||
break;
|
||||
}
|
||||
Some(_) => j += 1,
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
'"' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated string literal", Span::new(start, src.len()))),
|
||||
Some('"') if ch(j + 1) == Some('"') => {
|
||||
text.push('"');
|
||||
j += 2;
|
||||
}
|
||||
Some('"') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(Token { kind: TokenKind::String(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'\'' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated quoted identifier", Span::new(start, src.len()))),
|
||||
Some('\'') if ch(j + 1) == Some('\'') => {
|
||||
text.push('\'');
|
||||
j += 2;
|
||||
}
|
||||
Some('\'') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("empty quoted identifier", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::QuotedIdent(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'[' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
loop {
|
||||
match ch(j) {
|
||||
None => return Err(LexError::new("unterminated bracketed identifier", Span::new(start, src.len()))),
|
||||
Some(']') if ch(j + 1) == Some(']') => {
|
||||
text.push(']');
|
||||
j += 2;
|
||||
}
|
||||
Some(']') => {
|
||||
j += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
text.push(c);
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("empty bracketed identifier", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::BracketIdent(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'0'..='9' | '.' if c != '.' || ch(i + 1).is_some_and(|d| d.is_ascii_digit()) => {
|
||||
let mut j = i;
|
||||
let mut text = String::new();
|
||||
// A digit-only literal is an Integer; a decimal point or exponent makes it a
|
||||
// Decimal. The sign is always a unary operator, never part of the token.
|
||||
let mut is_decimal = c == '.';
|
||||
if c == '.' {
|
||||
text.push_str("0.");
|
||||
j += 1;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
} else {
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if ch(j) == Some('.') {
|
||||
is_decimal = true;
|
||||
text.push('.');
|
||||
j += 1;
|
||||
let fraction = j;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j == fraction {
|
||||
// `1.` / `1.e3`: keep the literal parseable.
|
||||
text.push('0');
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(ch(j), Some('e' | 'E')) {
|
||||
is_decimal = true;
|
||||
text.push('e');
|
||||
j += 1;
|
||||
if matches!(ch(j), Some('+' | '-')) {
|
||||
if let Some(sign) = ch(j) {
|
||||
text.push(sign);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
let digits = j;
|
||||
while ch(j).is_some_and(|d| d.is_ascii_digit()) {
|
||||
if let Some(d) = ch(j) {
|
||||
text.push(d);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if j == digits {
|
||||
return Err(LexError::new("numeric literal has no exponent digits", Span::new(start, pos(j))));
|
||||
}
|
||||
}
|
||||
if ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
return Err(LexError::new("invalid numeric literal", Span::new(start, pos(j + 1))));
|
||||
}
|
||||
let span = Span::new(start, pos(j));
|
||||
let kind = if is_decimal {
|
||||
let value = text.parse::<f64>().map_err(|_| LexError::new("invalid numeric literal", span))?;
|
||||
if !value.is_finite() {
|
||||
return Err(LexError::new("decimal literal is out of range", span));
|
||||
}
|
||||
TokenKind::Decimal(value)
|
||||
} else {
|
||||
let value =
|
||||
text.parse::<i64>().map_err(|_| LexError::new("integer literal is out of range for a 64-bit signed integer", span))?;
|
||||
TokenKind::Integer(value)
|
||||
};
|
||||
out.push(Token { kind, span });
|
||||
i = j;
|
||||
}
|
||||
c if c.is_alphabetic() || c == '_' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i;
|
||||
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
if let Some(c) = ch(j) {
|
||||
text.push(c);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
// `dt` immediately followed by a double-quoted string is a date/time literal.
|
||||
// Whitespace between the prefix and the quote is not allowed, so `dt "..."` is
|
||||
// two tokens and fails to parse. The prefix is case-insensitive like other DAX
|
||||
// keywords; the printer canonicalises it to lowercase `dt`.
|
||||
if text.eq_ignore_ascii_case("dt") && ch(j) == Some('"') {
|
||||
let mut content = String::new();
|
||||
let mut k = j + 1;
|
||||
loop {
|
||||
match ch(k) {
|
||||
None => {
|
||||
return Err(LexError::new("unterminated date/time literal", Span::new(start, src.len())));
|
||||
}
|
||||
Some('"') => {
|
||||
k += 1;
|
||||
break;
|
||||
}
|
||||
Some(c) => {
|
||||
content.push(c);
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let span = Span::new(start, pos(k));
|
||||
let value = parse_datetime_literal(&content).map_err(|message| LexError::new(message, span))?;
|
||||
out.push(Token { kind: TokenKind::DateTime(value), span });
|
||||
i = k;
|
||||
continue;
|
||||
}
|
||||
let kind = if text.eq_ignore_ascii_case("NOT") {
|
||||
TokenKind::Not
|
||||
} else if text.eq_ignore_ascii_case("IN") {
|
||||
TokenKind::In
|
||||
} else if text.eq_ignore_ascii_case("EVALUATE") {
|
||||
TokenKind::Evaluate
|
||||
} else {
|
||||
TokenKind::Ident(text)
|
||||
};
|
||||
out.push(Token { kind, span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
'+' => {
|
||||
out.push(Token { kind: TokenKind::Plus, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'-' => {
|
||||
out.push(Token { kind: TokenKind::Minus, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'*' => {
|
||||
out.push(Token { kind: TokenKind::Star, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'/' => {
|
||||
out.push(Token { kind: TokenKind::Slash, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'^' => {
|
||||
out.push(Token { kind: TokenKind::Caret, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'&' if ch(i + 1) == Some('&') => {
|
||||
out.push(Token { kind: TokenKind::AndAnd, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'&' => {
|
||||
out.push(Token { kind: TokenKind::Amp, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'|' if ch(i + 1) == Some('|') => {
|
||||
out.push(Token { kind: TokenKind::OrOr, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'|' => return Err(LexError::new("unexpected `|`; the DAX logical OR operator is `||`", Span::new(start, pos(i + 1)))),
|
||||
'=' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::StrictEq, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'=' if ch(i + 1) == Some('>') => {
|
||||
out.push(Token { kind: TokenKind::Arrow, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'=' => {
|
||||
out.push(Token { kind: TokenKind::Eq, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'<' if ch(i + 1) == Some('>') => {
|
||||
out.push(Token { kind: TokenKind::NotEq, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'<' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::Le, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'<' => {
|
||||
out.push(Token { kind: TokenKind::Lt, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'>' if ch(i + 1) == Some('=') => {
|
||||
out.push(Token { kind: TokenKind::Ge, span: Span::new(start, pos(i + 2)) });
|
||||
i += 2;
|
||||
}
|
||||
'>' => {
|
||||
out.push(Token { kind: TokenKind::Gt, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'(' => {
|
||||
out.push(Token { kind: TokenKind::LParen, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
')' => {
|
||||
out.push(Token { kind: TokenKind::RParen, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'{' => {
|
||||
out.push(Token { kind: TokenKind::LBrace, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'}' => {
|
||||
out.push(Token { kind: TokenKind::RBrace, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
',' => {
|
||||
out.push(Token { kind: TokenKind::Comma, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
':' => {
|
||||
out.push(Token { kind: TokenKind::Colon, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
';' => {
|
||||
out.push(Token { kind: TokenKind::Semicolon, span: Span::new(start, pos(i + 1)) });
|
||||
i += 1;
|
||||
}
|
||||
'@' => {
|
||||
let mut text = String::new();
|
||||
let mut j = i + 1;
|
||||
while ch(j).is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | '.')) {
|
||||
if let Some(c) = ch(j) {
|
||||
text.push(c);
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Err(LexError::new("expected a parameter name after `@`", Span::new(start, pos(j))));
|
||||
}
|
||||
out.push(Token { kind: TokenKind::AtName(text), span: Span::new(start, pos(j)) });
|
||||
i = j;
|
||||
}
|
||||
other => {
|
||||
return Err(LexError::new(format!("unexpected character `{other}`"), Span::new(start, pos(i + 1))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out.push(Token { kind: TokenKind::Eof, span: Span::new(src.len(), src.len()) });
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Validates the content of a `dt"..."` literal and splits it into components.
|
||||
///
|
||||
/// Accepted forms are `YYYY-MM-DD`, `YYYY-MM-DDThh:mm:ss` and `YYYY-MM-DD hh:mm:ss`. Date and
|
||||
/// time components may be unpadded (`dt"2015-1-9T2:3:0"`), matching Microsoft's documented
|
||||
/// example. Timezone offsets, fractional seconds, time-only values and invalid calendar dates
|
||||
/// are rejected with a lexer error. The `dt` prefix itself is matched by the caller.
|
||||
fn parse_datetime_literal(text: &str) -> Result<DateTimeLiteral, String> {
|
||||
let (date, time) = if let Some((date, time)) = text.split_once('T') {
|
||||
(date, Some(time))
|
||||
} else if let Some((date, time)) = text.split_once(' ') {
|
||||
(date, Some(time))
|
||||
} else {
|
||||
(text, None)
|
||||
};
|
||||
|
||||
let (year, month, day) = parse_date(date)?;
|
||||
let (hour, minute, second) = match time {
|
||||
Some(time) => parse_time(time)?,
|
||||
None => (0, 0, 0),
|
||||
};
|
||||
Ok(DateTimeLiteral { year, month, day, hour, minute, second, has_time: time.is_some() })
|
||||
}
|
||||
|
||||
fn parse_date(text: &str) -> Result<(u32, u32, u32), String> {
|
||||
let mut parts = text.split('-');
|
||||
let year_text = parts.next().unwrap_or_default();
|
||||
let month_text = parts.next().unwrap_or_default();
|
||||
let day_text = parts.next().unwrap_or_default();
|
||||
if parts.next().is_some() || year_text.is_empty() || month_text.is_empty() || day_text.is_empty() {
|
||||
return Err("invalid date/time literal: the date must be YYYY-MM-DD".into());
|
||||
}
|
||||
if year_text.len() != 4 || month_text.len() > 2 || day_text.len() > 2 {
|
||||
return Err("invalid date/time literal: the date must be YYYY-MM-DD (unpadded month and day are allowed)".into());
|
||||
}
|
||||
let year = parse_component(year_text, "year")?;
|
||||
let month = parse_component(month_text, "month")?;
|
||||
let day = parse_component(day_text, "day")?;
|
||||
if year == 0 || year > 9999 {
|
||||
return Err("invalid date/time literal: the year must be between 0001 and 9999".into());
|
||||
}
|
||||
if !(1..=12).contains(&month) {
|
||||
return Err("invalid date/time literal: the month must be between 1 and 12".into());
|
||||
}
|
||||
// A date exists exactly when chrono can build it: that rejects day 0, 31 April and 29 February
|
||||
// of a common year without hand-written month lengths or leap-year math (AGENTS.md).
|
||||
if NaiveDate::from_ymd_opt(year as i32, month, day).is_none() {
|
||||
return Err("invalid date/time literal: the date is not a valid calendar date".into());
|
||||
}
|
||||
Ok((year, month, day))
|
||||
}
|
||||
|
||||
fn parse_time(text: &str) -> Result<(u32, u32, u32), String> {
|
||||
let mut parts = text.split(':');
|
||||
let hour_text = parts.next().unwrap_or_default();
|
||||
let minute_text = parts.next().unwrap_or_default();
|
||||
let second_text = parts.next().unwrap_or_default();
|
||||
if parts.next().is_some() || hour_text.is_empty() || minute_text.is_empty() || second_text.is_empty() {
|
||||
return Err("invalid date/time literal: the time must be hh:mm:ss".into());
|
||||
}
|
||||
if hour_text.len() > 2 || minute_text.len() > 2 || second_text.len() > 2 {
|
||||
return Err("invalid date/time literal: the time must be hh:mm:ss without fractional seconds".into());
|
||||
}
|
||||
let hour = parse_component(hour_text, "hour")?;
|
||||
let minute = parse_component(minute_text, "minute")?;
|
||||
let second = parse_component(second_text, "second")?;
|
||||
if hour > 23 || minute > 59 || second > 59 {
|
||||
return Err("invalid date/time literal: the time is out of range".into());
|
||||
}
|
||||
Ok((hour, minute, second))
|
||||
}
|
||||
|
||||
/// Parses one date/time component. Rejects signs, whitespace, fractional parts and everything
|
||||
/// else that is not an ASCII digit, so timezone offsets (`Z`, `+02:00`) and fractional seconds
|
||||
/// cannot slip through.
|
||||
fn parse_component(text: &str, unit: &str) -> Result<u32, String> {
|
||||
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(format!("invalid date/time literal: the {unit} must be digits"));
|
||||
}
|
||||
text.parse::<u32>().map_err(|_| format!("invalid date/time literal: the {unit} is out of range"))
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The DAX language: tokenizer, syntax tree, Pratt parser, canonical printer and static types.
|
||||
//!
|
||||
//! This crate covers the DAX expression grammar, the function catalog for every dax.guide category
|
||||
//! with static call validation, the static type surface (literal classification, inference and the documented
|
||||
//! operator result tables) and the DAX query statements: `DEFINE` (`MEASURE`, `COLUMN`, `TABLE`,
|
||||
//! `VAR`, `FUNCTION`, `MPARAMETER`), `EVALUATE`, `ORDER BY`, `START AT`, expression-level
|
||||
//! `VAR ... RETURN`, and `WITH VISUAL SHAPE` (`AXIS`, `GROUP`, `TOTAL`, `DENSIFY`). It also
|
||||
//! includes a model evaluator, a columnar model store and a PivotTable renderer. The evaluator materializes the model once into the columnar store and
|
||||
//! answers filtering, aggregates, `VALUES`/`DISTINCT`, relationship joins and pivot grouping from
|
||||
//! it; models that cannot be stored losslessly (ragged rows, promoted column types) and functions
|
||||
//! that need a row context still read the row-based `DataModel`.
|
||||
//!
|
||||
//! ```
|
||||
//! use gridcraft_dax::{parse_expression, print_expression};
|
||||
//!
|
||||
//! let expr = parse_expression("1 + 2 * 3")?;
|
||||
//! assert_eq!(print_expression(&expr), "1 + 2 * 3");
|
||||
//! # Ok::<(), gridcraft_dax::ParseError>(())
|
||||
//! ```
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
pub mod binder;
|
||||
pub mod eval;
|
||||
pub mod functions;
|
||||
pub mod integrity;
|
||||
pub mod lexer;
|
||||
pub mod model;
|
||||
pub mod parser;
|
||||
pub mod pivot;
|
||||
pub mod pivot_table;
|
||||
pub mod printer;
|
||||
pub mod references;
|
||||
pub mod storage;
|
||||
pub mod types;
|
||||
pub mod validate;
|
||||
pub mod value;
|
||||
|
||||
pub use ast::{
|
||||
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, DateTimeLiteral, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef,
|
||||
FunctionParam, Literal, MParameterDef, MeasureDef, Name, NameRef, NameStyle, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query,
|
||||
SortDirection, Span, StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
|
||||
};
|
||||
pub use binder::{BindError, Binder, BoundExpr, BoundMeasure, BoundVariable, bind_formula};
|
||||
pub use eval::{Evaluator, FilterContext, StorageStats};
|
||||
pub use functions::{BlankPolicy, FunctionCategory, FunctionFlags, FunctionSpec, Overload, ParamKind, Parameter, ReturnType, catalog, lookup};
|
||||
pub use integrity::{
|
||||
Cardinality, IntegrityCheck, IntegrityFinding, IntegrityReport, MAX_REPORTED_CYCLES, MAX_REPORTED_KEYS, MAX_REPORTED_ROWS, RelationshipCheck,
|
||||
Severity, validate_model,
|
||||
};
|
||||
pub use lexer::{LexError, MAX_INPUT_LEN, MAX_QUERY_LEN, Token, TokenKind, tokenize};
|
||||
pub use model::{DataModel, Measure, ModelColumn, ModelError, ModelTable, Relationship, parse_measure};
|
||||
pub use parser::{MAX_DEPTH, ParseError, parse_expression, parse_query};
|
||||
pub use pivot::{PivotError, PivotField, pivot, pivot_cross, pivot_fields};
|
||||
pub use printer::{print_expression, print_query};
|
||||
pub use references::{column_ref, implicit_measure_formula, table_ref};
|
||||
pub use storage::{ColumnFootprint, MIN_ENCODING_SAVING, PackedCodes, SCAN_BATCH_ROWS, StorageFootprint, TableFootprint, ValueRef};
|
||||
pub use validate::{ValidationError, ValidationErrorKind, validate_call, validate_expression};
|
||||
pub use value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,371 @@
|
||||
//! Tabular data-model metadata: tables, columns, relationships and measures.
|
||||
//!
|
||||
//! This is the binder/evaluator's model view. It deliberately does not implement XLSX storage:
|
||||
//! callers load the metadata from JSON or from a workbook adapter and parse the measure formulas
|
||||
//! with [`DataModel::parse_formulas`]. Rows are not part of this layer; the evaluator supplies
|
||||
//! table values.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::value::Scalar;
|
||||
use crate::{Expr, ParseError, parse_expression};
|
||||
|
||||
/// A table in the model. Column order is preserved because `RELATEDTABLE`, `ROW` and table
|
||||
/// constructors expose it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ModelTable {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub columns: Vec<ModelColumn>,
|
||||
/// Optional inline rows. Workbook adapters can fill these; the metadata-only binder ignores
|
||||
/// them. Each row has one scalar per column, in column order.
|
||||
#[serde(default)]
|
||||
pub rows: Vec<Vec<Scalar>>,
|
||||
}
|
||||
|
||||
/// A model column. `data_type` is the model's declared type name (`Int64`, `Double`, `String`,
|
||||
/// `DateTime`, `Boolean`, `Decimal`, ...); it is metadata, not a parsed [`crate::types::DataType`],
|
||||
/// because model type names and DAX expression types are not the same vocabulary.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ModelColumn {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub data_type: Option<String>,
|
||||
}
|
||||
|
||||
/// Model metadata the binder does not need: hidden columns, the marked date column and each
|
||||
/// column's default summarization. It travels inside the same model JSON document, on the table
|
||||
/// and column objects (`"date_column"`, `"hidden"`, `"summarize_by"`), so a model stays one file;
|
||||
/// the engine reads and validates it at the model boundary (`dataModel.load`) and reports it from
|
||||
/// `dataModel.status`.
|
||||
///
|
||||
/// The type doubles as the loader: unknown document keys (`rows`, `data_type`, `relationships`,
|
||||
/// `measures`, ...) are ignored, so a document written before these fields existed loads with
|
||||
/// every field at its default.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ModelMetadata {
|
||||
pub tables: Vec<TableMetadata>,
|
||||
}
|
||||
|
||||
/// One table's metadata slice of a model document.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TableMetadata {
|
||||
pub name: String,
|
||||
/// The column marked as this table's date column, in the model's spelling.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub date_column: Option<String>,
|
||||
pub columns: Vec<ColumnMetadata>,
|
||||
}
|
||||
|
||||
/// One column's metadata slice of a model document.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ColumnMetadata {
|
||||
pub name: String,
|
||||
/// Hidden from the Data View and the field list (`dataModel.setColumnHidden`). Model
|
||||
/// metadata, as in Excel; the window's "Show Hidden" toggle is only a view setting.
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub hidden: bool,
|
||||
/// Excel's "Summarize By" (`Sum`, `Average`, `Count`, `Min`, `Max`, `None`), canonicalized.
|
||||
/// Absent falls back to the type default: numbers sum, everything else counts.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub summarize_by: Option<String>,
|
||||
}
|
||||
|
||||
/// The canonical spelling of a `Summarize By` name, or `None` when it is not one. Names match
|
||||
/// case-insensitively and ignore spaces, hyphens and underscores, so `"do not summarize"`,
|
||||
/// `"DoNotSummarize"` and `"none"` all mean `None`.
|
||||
pub fn summarize_by_name(name: &str) -> Option<&'static str> {
|
||||
let key: String = name.chars().filter(|c| !matches!(c, ' ' | '-' | '_')).collect::<String>().to_ascii_lowercase();
|
||||
match key.as_str() {
|
||||
"sum" => Some("Sum"),
|
||||
"average" | "avg" => Some("Average"),
|
||||
"count" => Some("Count"),
|
||||
"min" | "minimum" => Some("Min"),
|
||||
"max" | "maximum" => Some("Max"),
|
||||
"none" | "donotsummarize" => Some("None"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a serde field should be left out of the serialized JSON (its default).
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
impl ModelMetadata {
|
||||
/// Parses and validates the metadata of a model JSON document.
|
||||
///
|
||||
/// The type itself is the loader: unknown document keys (`rows`, `data_type`,
|
||||
/// `relationships`, `measures`, ...) are ignored, so a document written before the metadata
|
||||
/// fields existed yields every table and column with default metadata.
|
||||
pub fn from_model_json(text: &str) -> Result<ModelMetadata, ModelError> {
|
||||
let mut metadata: ModelMetadata = serde_json::from_str(text).map_err(|error| ModelError::new(format!("invalid model JSON: {error}")))?;
|
||||
metadata.validate()?;
|
||||
Ok(metadata)
|
||||
}
|
||||
|
||||
/// Canonicalizes the names and rejects unknown summarizations and a date column that is not
|
||||
/// one of its table's columns. Duplicate table/column names are the [`DataModel`]'s check;
|
||||
/// they are rejected here too so a document cannot produce an ambiguous lookup.
|
||||
pub fn validate(&mut self) -> Result<(), ModelError> {
|
||||
let mut tables = BTreeMap::new();
|
||||
for table in &mut self.tables {
|
||||
if tables.insert(table.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
|
||||
}
|
||||
let mut columns = BTreeMap::new();
|
||||
for column in &mut table.columns {
|
||||
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
|
||||
}
|
||||
if let Some(name) = column.summarize_by.clone() {
|
||||
let Some(canonical) = summarize_by_name(&name) else {
|
||||
return Err(ModelError::new(format!("column `{}` has unknown summarization `{name}`", column.name)));
|
||||
};
|
||||
column.summarize_by = Some(canonical.to_string());
|
||||
}
|
||||
}
|
||||
if let Some(date) = table.date_column.clone() {
|
||||
let Some(column) = table.columns.iter().find(|column| column.name.eq_ignore_ascii_case(&date)) else {
|
||||
return Err(ModelError::new(format!("table `{}` marks unknown column `{date}` as its date column", table.name)));
|
||||
};
|
||||
table.date_column = Some(column.name.clone());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A table's metadata, matching names case-insensitively.
|
||||
pub fn table(&self, name: &str) -> Option<&TableMetadata> {
|
||||
self.tables.iter().find(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// A table's metadata for editing.
|
||||
pub fn table_mut(&mut self, name: &str) -> Option<&mut TableMetadata> {
|
||||
self.tables.iter_mut().find(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// A column's metadata, matching table and column names case-insensitively.
|
||||
pub fn column(&self, table: &str, column: &str) -> Option<&ColumnMetadata> {
|
||||
self.table(table)?.columns.iter().find(|entry| entry.name.eq_ignore_ascii_case(column))
|
||||
}
|
||||
|
||||
/// A column's metadata for editing.
|
||||
pub fn column_mut(&mut self, table: &str, column: &str) -> Option<&mut ColumnMetadata> {
|
||||
let table = self.table_mut(table)?;
|
||||
table.columns.iter_mut().find(|entry| entry.name.eq_ignore_ascii_case(column))
|
||||
}
|
||||
}
|
||||
|
||||
/// A single-column relationship between two model tables.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Relationship {
|
||||
pub from_table: String,
|
||||
pub from_column: String,
|
||||
pub to_table: String,
|
||||
pub to_column: String,
|
||||
/// `true` when the relationship filters in both directions.
|
||||
#[serde(default)]
|
||||
pub bidirectional: bool,
|
||||
/// Inactive relationships can be activated by `USERELATIONSHIP`.
|
||||
#[serde(default)]
|
||||
pub inactive: bool,
|
||||
}
|
||||
|
||||
/// A measure definition. The formula is DAX text; [`DataModel::parse_formulas`] parses it into
|
||||
/// [`Measure::expr`].
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Measure {
|
||||
pub name: String,
|
||||
pub formula: String,
|
||||
/// The home table, used by `COUNTROWS()` without an argument and for field-list placement.
|
||||
#[serde(default)]
|
||||
pub table: Option<String>,
|
||||
#[serde(default)]
|
||||
pub format: Option<String>,
|
||||
#[serde(skip)]
|
||||
pub expr: Option<Expr>,
|
||||
}
|
||||
|
||||
/// A model definition loaded from JSON or another workbook adapter.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DataModel {
|
||||
#[serde(default)]
|
||||
pub tables: Vec<ModelTable>,
|
||||
#[serde(default)]
|
||||
pub relationships: Vec<Relationship>,
|
||||
#[serde(default)]
|
||||
pub measures: Vec<Measure>,
|
||||
}
|
||||
|
||||
/// A metadata or formula error found while preparing a model for binding.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct ModelError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ModelError {
|
||||
fn new(message: impl Into<String>) -> Self {
|
||||
ModelError { message: message.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl DataModel {
|
||||
/// Parses every measure formula and validates table/column/relationship names.
|
||||
///
|
||||
/// Names are compared case-insensitively. Duplicate table names, duplicate column names
|
||||
/// within a table, and relationships naming missing tables/columns are rejected.
|
||||
pub fn parse_formulas(&mut self) -> Result<(), ModelError> {
|
||||
let mut tables: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for (index, table) in self.tables.iter().enumerate() {
|
||||
let key = table.name.to_ascii_lowercase();
|
||||
if tables.insert(key, index).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate model table `{}`", table.name)));
|
||||
}
|
||||
let mut columns = BTreeMap::new();
|
||||
for column in &table.columns {
|
||||
if columns.insert(column.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate column `{}` in table `{}`", column.name, table.name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for relationship in &self.relationships {
|
||||
self.require_column(&relationship.from_table, &relationship.from_column)?;
|
||||
self.require_column(&relationship.to_table, &relationship.to_column)?;
|
||||
}
|
||||
|
||||
let mut names = BTreeMap::new();
|
||||
for measure in &mut self.measures {
|
||||
// Measure names are compared case-insensitively everywhere else, so a duplicate would
|
||||
// silently hide the second formula.
|
||||
if names.insert(measure.name.to_ascii_lowercase(), ()).is_some() {
|
||||
return Err(ModelError::new(format!("duplicate measure `{}`", measure.name)));
|
||||
}
|
||||
let expr = parse_expression(&measure.formula).map_err(|error| ModelError::new(format!("measure `{}`: {error}", measure.name)))?;
|
||||
measure.expr = Some(expr);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The index of a table, ignoring case.
|
||||
pub fn table_index(&self, name: &str) -> Option<usize> {
|
||||
self.tables.iter().position(|table| table.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The index of a column within a table, ignoring case.
|
||||
pub fn column_index(&self, table: usize, name: &str) -> Option<usize> {
|
||||
self.tables.get(table)?.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The index of a measure, ignoring case.
|
||||
pub fn measure_index(&self, name: &str) -> Option<usize> {
|
||||
self.measures.iter().position(|measure| measure.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Tables that contain a column with this name.
|
||||
pub fn tables_with_column(&self, name: &str) -> Vec<usize> {
|
||||
self.tables
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, table)| table.columns.iter().any(|column| column.name.eq_ignore_ascii_case(name)))
|
||||
.map(|(index, _)| index)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn require_column(&self, table: &str, column: &str) -> Result<(), ModelError> {
|
||||
let Some(table_index) = self.table_index(table) else {
|
||||
return Err(ModelError::new(format!("relationship names missing table `{table}`")));
|
||||
};
|
||||
if self.column_index(table_index, column).is_none() {
|
||||
return Err(ModelError::new(format!("relationship names missing column `{column}` in table `{table}`")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of [`parse_expression`] for a measure, used by callers that want to surface the
|
||||
/// parse error separately from the model metadata.
|
||||
pub fn parse_measure(formula: &str) -> Result<Expr, ParseError> {
|
||||
parse_expression(formula)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The model JSON `docs/power-pivot.md` documents, written before the metadata fields existed.
|
||||
/// It must keep loading (the metadata parser ignores everything it does not own), and adding
|
||||
/// the fields must not change what the document means.
|
||||
const OLD_SCHEMA: &str = r#"{
|
||||
"tables": [{"name":"Sales","columns":[{"name":"Region","data_type":"String"},{"name":"Amount","data_type":"Double"}],
|
||||
"rows":[["East",10],["West",20]]}],
|
||||
"relationships": [],
|
||||
"measures": [{"name":"Total Sales","formula":"SUM(Sales[Amount])","table":"Sales"}]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn old_schema_json_loads_with_default_metadata() {
|
||||
let mut model: DataModel = serde_json::from_str(OLD_SCHEMA).expect("old model JSON loads");
|
||||
model.parse_formulas().expect("old model JSON validates");
|
||||
assert_eq!(model.tables[0].columns.len(), 2, "unknown metadata keys never disturb the model");
|
||||
|
||||
let metadata = ModelMetadata::from_model_json(OLD_SCHEMA).expect("old model JSON has valid metadata");
|
||||
let table = metadata.table("sales").expect("the table is in the metadata");
|
||||
assert_eq!(table.date_column, None);
|
||||
assert!(!metadata.column("Sales", "amount").expect("column metadata").hidden);
|
||||
assert_eq!(metadata.column("Sales", "Amount").and_then(|column| column.summarize_by.clone()), None);
|
||||
|
||||
let written = serde_json::to_value(&metadata).expect("metadata serializes");
|
||||
assert!(written["tables"][0].get("date_column").is_none(), "an unmarked table writes no date column: {written}");
|
||||
assert!(written["tables"][0]["columns"][0].get("hidden").is_none(), "a visible column writes no hidden flag: {written}");
|
||||
assert!(written["tables"][0]["columns"][0].get("summarize_by").is_none(), "an absent summarization stays absent: {written}");
|
||||
let reloaded = ModelMetadata::from_model_json(&written.to_string()).expect("the written metadata reloads");
|
||||
assert_eq!(reloaded, metadata);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_metadata_is_read_from_the_model_document() {
|
||||
let json = r#"{
|
||||
"tables": [{"name":"Calendar","date_column":"date",
|
||||
"columns":[{"name":"Date","data_type":"DateTime"},{"name":"Secret","hidden":true,"summarize_by":"do not summarize"}],
|
||||
"rows":[[45292,null]]}],
|
||||
"relationships": [],
|
||||
"measures": []
|
||||
}"#;
|
||||
let mut model: DataModel = serde_json::from_str(json).expect("JSON with metadata loads");
|
||||
model.parse_formulas().expect("the model validates");
|
||||
let metadata = ModelMetadata::from_model_json(json).expect("the metadata validates");
|
||||
let table = metadata.table("Calendar").expect("a table");
|
||||
assert_eq!(table.date_column.as_deref(), Some("Date"), "the stored name takes the column's spelling");
|
||||
let secret = metadata.column("calendar", "SECRET").expect("column metadata");
|
||||
assert!(secret.hidden);
|
||||
assert_eq!(secret.summarize_by.as_deref(), Some("None"), "the summarization is canonicalized");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_naming_missing_columns_or_aggregates_is_rejected() {
|
||||
let bad_date = r#"{"tables":[{"name":"T","columns":[{"name":"A"}],"rows":[],"date_column":"Missing"}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(bad_date).is_err(), "a date column that is not a column is rejected");
|
||||
|
||||
let bad_summary = r#"{"tables":[{"name":"T","columns":[{"name":"A","summarize_by":"median"}],"rows":[]}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(bad_summary).is_err(), "an unknown summarization is rejected");
|
||||
|
||||
let duplicate = r#"{"tables":[{"name":"T","columns":[{"name":"A"},{"name":"a"}]}]}"#;
|
||||
assert!(ModelMetadata::from_model_json(duplicate).is_err(), "ambiguous column names are rejected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarize_by_names_match_loosely() {
|
||||
assert_eq!(summarize_by_name("SUM"), Some("Sum"));
|
||||
assert_eq!(summarize_by_name("average"), Some("Average"));
|
||||
assert_eq!(summarize_by_name("Do Not Summarize"), Some("None"));
|
||||
assert_eq!(summarize_by_name("median"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,878 @@
|
||||
//! Pratt parser: tokens → [`Expr`] / [`Query`].
|
||||
//!
|
||||
//! Binding powers encode the operator table (tighter binds first): parentheses and function
|
||||
//! calls; `^`; unary `+`/`-`; `*`/`/`; binary `+`/`-`; `&`; comparisons, which include `IN`; `NOT`;
|
||||
//! `&&`; `||`. Every operator is left-associative, including `^`: Microsoft's operator reference
|
||||
//! orders equal-precedence operators from left to right, so `2^3^2` is `(2^3)^2`.
|
||||
|
||||
use crate::ast::{
|
||||
Axis, AxisGroup, AxisKind, AxisOrderItem, BinaryOp, Call, ColumnDef, Define, Definition, Evaluate, Expr, ExprKind, FunctionDef, FunctionParam,
|
||||
Literal, MParameterDef, MeasureDef, Name, NameRef, OrderItem, ParameterSubtype, ParameterType, PassingMode, Query, SortDirection, Span,
|
||||
StartValue, TableDef, UnaryOp, VarDecl, VarDef, VisualShape,
|
||||
};
|
||||
use crate::lexer::{LexError, Token, TokenKind, tokenize};
|
||||
|
||||
/// Deepest expression nesting accepted. Bounds parser recursion (and the tree that later
|
||||
/// evaluation walks) at 256 levels.
|
||||
pub const MAX_DEPTH: usize = 256;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message} at bytes {}..{}", span.start, span.end)]
|
||||
pub struct ParseError {
|
||||
pub message: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl ParseError {
|
||||
fn new(message: impl Into<String>, span: Span) -> Self {
|
||||
ParseError { message: message.into(), span }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LexError> for ParseError {
|
||||
fn from(e: LexError) -> Self {
|
||||
ParseError { message: e.message, span: e.span }
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a DAX expression. A single leading `=` (as typed in some editors) is accepted and
|
||||
/// ignored.
|
||||
pub fn parse_expression(src: &str) -> Result<Expr, ParseError> {
|
||||
if src.len() > crate::MAX_INPUT_LEN {
|
||||
return Err(ParseError::new(
|
||||
format!("input is too long ({} bytes, limit {})", src.len(), crate::MAX_INPUT_LEN),
|
||||
crate::Span::new(0, src.len()),
|
||||
));
|
||||
}
|
||||
let tokens = tokenize(src)?;
|
||||
let mut parser = Parser { tokens, i: 0, depth: 0 };
|
||||
if matches!(parser.peek(), TokenKind::Eq) {
|
||||
parser.next();
|
||||
}
|
||||
let expr = parser.expr(0)?;
|
||||
parser.expect_eof()?;
|
||||
ensure_depth(&expr)?;
|
||||
Ok(expr)
|
||||
}
|
||||
|
||||
/// Parses a DAX query: an optional `DEFINE` block followed by one or more `EVALUATE` statements.
|
||||
///
|
||||
/// For the simple form `EVALUATE <expression>` the result has `define: None` and a single
|
||||
/// evaluation with empty `order_by`/`start_at`. An optional trailing `;` is accepted; it is not
|
||||
/// part of the grammar, only a recovery extension.
|
||||
///
|
||||
/// Statement keywords (`DEFINE`, `MEASURE`, `COLUMN`, `TABLE`, `VAR`, `RETURN`, `FUNCTION`,
|
||||
/// `MPARAMETER`, `ORDER BY`, `START AT`, `WITH VISUAL SHAPE`, `AXIS`, `GROUP`, `TOTAL`,
|
||||
/// `DENSIFY`, `ASC`, `DESC`) are recognised case-insensitively at the positions where they are
|
||||
/// expected. Definition bounds and statement bounds therefore come from those keywords, never
|
||||
/// from newlines.
|
||||
pub fn parse_query(src: &str) -> Result<Query, ParseError> {
|
||||
if src.len() > crate::MAX_QUERY_LEN {
|
||||
return Err(ParseError::new(
|
||||
format!("query is too long ({} bytes, limit {})", src.len(), crate::MAX_QUERY_LEN),
|
||||
crate::Span::new(0, src.len()),
|
||||
));
|
||||
}
|
||||
let tokens = tokenize(src)?;
|
||||
let mut parser = Parser { tokens, i: 0, depth: 0 };
|
||||
let query = parser.query()?;
|
||||
validate_query_depth(&query)?;
|
||||
Ok(query)
|
||||
}
|
||||
|
||||
/// Rejects an AST deeper than [`MAX_DEPTH`] even when parser recursion stayed shallow (for
|
||||
/// example a function call wrapped around a grouped chain).
|
||||
fn ensure_depth(expr: &Expr) -> Result<(), ParseError> {
|
||||
let depth = expr.depth();
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(ParseError::new(format!("expression is nested too deeply (limit {MAX_DEPTH})"), expr.span));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies the AST-depth bound to every expression in a query, not only to the last parsed
|
||||
/// `EVALUATE` expression.
|
||||
fn validate_query_depth(query: &Query) -> Result<(), ParseError> {
|
||||
if let Some(define) = &query.define {
|
||||
for item in &define.items {
|
||||
match item {
|
||||
Definition::Measure(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Column(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Table(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Var(def) => ensure_depth(&def.expr)?,
|
||||
Definition::MParameter(def) => ensure_depth(&def.expr)?,
|
||||
Definition::Function(def) => {
|
||||
ensure_depth(&def.body)?;
|
||||
for param in &def.params {
|
||||
if let Some(default) = ¶m.default {
|
||||
ensure_depth(default)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for evaluate in &query.evaluates {
|
||||
ensure_depth(&evaluate.table)?;
|
||||
for item in &evaluate.order_by {
|
||||
ensure_depth(&item.expr)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn describe(kind: &TokenKind) -> String {
|
||||
match kind {
|
||||
TokenKind::Integer(n) => format!("integer literal `{n}`"),
|
||||
TokenKind::Decimal(n) => format!("decimal literal `{n}`"),
|
||||
TokenKind::DateTime(value) => format!("date/time literal `dt\"{value}\"`"),
|
||||
TokenKind::String(_) => "string literal".into(),
|
||||
TokenKind::Ident(s) => format!("`{s}`"),
|
||||
TokenKind::QuotedIdent(_) => "quoted identifier".into(),
|
||||
TokenKind::BracketIdent(_) => "bracketed identifier".into(),
|
||||
TokenKind::Not => "`NOT`".into(),
|
||||
TokenKind::In => "`IN`".into(),
|
||||
TokenKind::Evaluate => "`EVALUATE`".into(),
|
||||
TokenKind::Plus => "`+`".into(),
|
||||
TokenKind::Minus => "`-`".into(),
|
||||
TokenKind::Star => "`*`".into(),
|
||||
TokenKind::Slash => "`/`".into(),
|
||||
TokenKind::Caret => "`^`".into(),
|
||||
TokenKind::Amp => "`&`".into(),
|
||||
TokenKind::Eq => "`=`".into(),
|
||||
TokenKind::StrictEq => "`==`".into(),
|
||||
TokenKind::NotEq => "`<>`".into(),
|
||||
TokenKind::Lt => "`<`".into(),
|
||||
TokenKind::Gt => "`>`".into(),
|
||||
TokenKind::Le => "`<=`".into(),
|
||||
TokenKind::Ge => "`>=`".into(),
|
||||
TokenKind::AndAnd => "`&&`".into(),
|
||||
TokenKind::OrOr => "`||`".into(),
|
||||
TokenKind::Arrow => "`=>`".into(),
|
||||
TokenKind::Colon => "`:`".into(),
|
||||
TokenKind::AtName(name) => format!("parameter `@{name}`"),
|
||||
TokenKind::Semicolon => "`;`".into(),
|
||||
TokenKind::LParen => "`(`".into(),
|
||||
TokenKind::RParen => "`)`".into(),
|
||||
TokenKind::LBrace => "`{`".into(),
|
||||
TokenKind::RBrace => "`}`".into(),
|
||||
TokenKind::Comma => "`,`".into(),
|
||||
TokenKind::Eof => "end of input".into(),
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
i: usize,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn peek(&self) -> &TokenKind {
|
||||
self.tokens.get(self.i).map(|t| &t.kind).unwrap_or(&TokenKind::Eof)
|
||||
}
|
||||
|
||||
fn peek_span(&self) -> Span {
|
||||
self.tokens.get(self.i).map(|t| t.span).unwrap_or(Span::empty())
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Token {
|
||||
let token = self.tokens.get(self.i).cloned().unwrap_or(Token { kind: TokenKind::Eof, span: Span::empty() });
|
||||
if self.i < self.tokens.len() {
|
||||
self.i += 1;
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
fn error_here(&self, message: impl Into<String>) -> ParseError {
|
||||
ParseError::new(message, self.peek_span())
|
||||
}
|
||||
|
||||
fn expect(&mut self, kind: TokenKind, context: &str) -> Result<Token, ParseError> {
|
||||
if *self.peek() == kind {
|
||||
Ok(self.next())
|
||||
} else {
|
||||
Err(self.error_here(format!("expected {}, found {}; {context}", describe(&kind), describe(self.peek()))))
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_eof(&self) -> Result<(), ParseError> {
|
||||
match self.peek() {
|
||||
TokenKind::Eof => Ok(()),
|
||||
other => Err(self.error_here(format!("unexpected {} after expression", describe(other)))),
|
||||
}
|
||||
}
|
||||
|
||||
fn expect_query_eof(&self) -> Result<(), ParseError> {
|
||||
match self.peek() {
|
||||
TokenKind::Eof => Ok(()),
|
||||
other => Err(self.error_here(format!("unexpected {} after the query", describe(other)))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current token when it is a bare identifier, which is how statement keywords are
|
||||
/// lexed. Keywords are matched case-insensitively by their text.
|
||||
fn peek_word(&self) -> Option<&str> {
|
||||
match self.peek() {
|
||||
TokenKind::Ident(word) => Some(word),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn keyword_at(&self, word: &str) -> bool {
|
||||
self.peek_word().is_some_and(|text| text.eq_ignore_ascii_case(word))
|
||||
}
|
||||
|
||||
fn expect_keyword(&mut self, word: &str, context: &str) -> Result<Token, ParseError> {
|
||||
if self.keyword_at(word) {
|
||||
Ok(self.next())
|
||||
} else {
|
||||
Err(self.error_here(format!("expected `{word}`, found {}; {context}", describe(self.peek()))))
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------
|
||||
// Query statements
|
||||
// -------------------------------------------------------------------------------------
|
||||
|
||||
fn query(&mut self) -> Result<Query, ParseError> {
|
||||
let define = if self.keyword_at("DEFINE") { Some(self.define_block()?) } else { None };
|
||||
if !matches!(self.peek(), TokenKind::Evaluate) {
|
||||
return Err(self.error_here("a query needs at least one `EVALUATE` statement"));
|
||||
}
|
||||
let mut evaluates = Vec::new();
|
||||
while matches!(self.peek(), TokenKind::Evaluate) {
|
||||
evaluates.push(self.evaluate_statement()?);
|
||||
}
|
||||
// The documented grammar has no statement terminators. A trailing `;` is accepted as a
|
||||
// recovery extension only, never required.
|
||||
while matches!(self.peek(), TokenKind::Semicolon) {
|
||||
self.next();
|
||||
}
|
||||
self.expect_query_eof()?;
|
||||
Ok(Query { define, evaluates })
|
||||
}
|
||||
|
||||
fn define_block(&mut self) -> Result<Define, ParseError> {
|
||||
let keyword = self.next();
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let Some(word) = self.peek_word().map(str::to_owned) else {
|
||||
match self.peek() {
|
||||
TokenKind::Evaluate | TokenKind::Eof | TokenKind::Semicolon => break,
|
||||
other => {
|
||||
return Err(self.error_here(format!(
|
||||
"expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found {}",
|
||||
describe(other)
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
if word.eq_ignore_ascii_case("MEASURE") {
|
||||
self.next();
|
||||
items.push(Definition::Measure(self.measure_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("COLUMN") {
|
||||
self.next();
|
||||
items.push(Definition::Column(self.column_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("TABLE") {
|
||||
self.next();
|
||||
items.push(Definition::Table(self.table_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("VAR") {
|
||||
self.next();
|
||||
items.push(Definition::Var(self.var_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("FUNCTION") {
|
||||
self.next();
|
||||
items.push(Definition::Function(self.function_definition()?));
|
||||
} else if word.eq_ignore_ascii_case("MPARAMETER") {
|
||||
self.next();
|
||||
items.push(Definition::MParameter(self.mparameter_definition()?));
|
||||
} else {
|
||||
return Err(self.error_here(format!("expected a DEFINE entry (MEASURE, COLUMN, TABLE, VAR, FUNCTION or MPARAMETER), found `{word}`")));
|
||||
}
|
||||
}
|
||||
if items.is_empty() {
|
||||
return Err(ParseError::new("DEFINE needs at least one definition before `EVALUATE`", keyword.span));
|
||||
}
|
||||
Ok(Define { items })
|
||||
}
|
||||
|
||||
fn measure_definition(&mut self) -> Result<MeasureDef, ParseError> {
|
||||
let name = self.definition_name("measure")?;
|
||||
self.expect(TokenKind::Eq, "a MEASURE definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(MeasureDef { name, expr })
|
||||
}
|
||||
|
||||
fn column_definition(&mut self) -> Result<ColumnDef, ParseError> {
|
||||
let name = self.definition_name("column")?;
|
||||
self.expect(TokenKind::Eq, "a COLUMN definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(ColumnDef { name, expr })
|
||||
}
|
||||
|
||||
fn var_definition(&mut self) -> Result<VarDef, ParseError> {
|
||||
let name = self.variable_name()?;
|
||||
self.expect(TokenKind::Eq, "a query-scoped VAR needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(VarDef { name, expr })
|
||||
}
|
||||
|
||||
fn table_definition(&mut self) -> Result<TableDef, ParseError> {
|
||||
let name = self.table_name("table")?;
|
||||
self.expect(TokenKind::Eq, "a TABLE definition needs `=` before its table expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
let visual_shape = if self.keyword_at("WITH") { Some(self.visual_shape()?) } else { None };
|
||||
Ok(TableDef { name, expr, visual_shape })
|
||||
}
|
||||
|
||||
fn mparameter_definition(&mut self) -> Result<MParameterDef, ParseError> {
|
||||
let name = self.table_name("M parameter")?;
|
||||
self.expect(TokenKind::Eq, "an MPARAMETER definition needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
Ok(MParameterDef { name, expr })
|
||||
}
|
||||
|
||||
fn function_definition(&mut self) -> Result<FunctionDef, ParseError> {
|
||||
let name = self.table_name("function")?;
|
||||
self.expect(TokenKind::Eq, "a FUNCTION definition needs `=` before its parameter list")?;
|
||||
self.expect(TokenKind::LParen, "a FUNCTION definition needs a parenthesised parameter list")?;
|
||||
let mut params = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
self.next();
|
||||
} else {
|
||||
loop {
|
||||
params.push(self.function_param()?);
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Comma => {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
return Err(self.error_here("expected a parameter after `,`"));
|
||||
}
|
||||
}
|
||||
TokenKind::RParen => break,
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected `,` or `)` in the parameter list, found {}", describe(&other)), token.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.expect(TokenKind::Arrow, "a FUNCTION definition needs `=>` before its body")?;
|
||||
let body = self.expr(0)?;
|
||||
Ok(FunctionDef { name, params, body })
|
||||
}
|
||||
|
||||
fn function_param(&mut self) -> Result<FunctionParam, ParseError> {
|
||||
let token = self.next();
|
||||
let name = match &token.kind {
|
||||
TokenKind::Ident(text) => Name::bare(text.clone()),
|
||||
other => return Err(ParseError::new(format!("expected a parameter name, found {}", describe(other)), token.span)),
|
||||
};
|
||||
let mut ty = None;
|
||||
let mut subtype = None;
|
||||
let mut passing = None;
|
||||
if matches!(self.peek(), TokenKind::Colon) {
|
||||
let colon = self.next();
|
||||
let mut annotated = false;
|
||||
while let Some(word) = self.peek_word().map(str::to_owned) {
|
||||
if let Some(parsed) = ParameterType::from_keyword(&word) {
|
||||
if ty.is_some() {
|
||||
return Err(self.error_here(format!("duplicate parameter type `{}`", parsed.keyword())));
|
||||
}
|
||||
if subtype.is_some() || passing.is_some() {
|
||||
return Err(self.error_here("the parameter type must come before its subtype and passing mode"));
|
||||
}
|
||||
ty = Some(parsed);
|
||||
} else if let Some(parsed) = ParameterSubtype::from_keyword(&word) {
|
||||
if subtype.is_some() {
|
||||
return Err(self.error_here(format!("duplicate parameter subtype `{}`", parsed.keyword())));
|
||||
}
|
||||
if passing.is_some() {
|
||||
return Err(self.error_here("the parameter subtype must come before its passing mode"));
|
||||
}
|
||||
subtype = Some(parsed);
|
||||
} else if let Some(parsed) = PassingMode::from_keyword(&word) {
|
||||
if passing.is_some() {
|
||||
return Err(self.error_here("duplicate parameter passing mode"));
|
||||
}
|
||||
passing = Some(parsed);
|
||||
} else {
|
||||
return Err(self.error_here(format!("unknown function parameter type `{word}`")));
|
||||
}
|
||||
self.next();
|
||||
annotated = true;
|
||||
}
|
||||
if !annotated {
|
||||
return Err(ParseError::new("expected a parameter type, subtype or passing mode after `:`", colon.span));
|
||||
}
|
||||
if subtype.is_some() && ty.is_some_and(|ty| ty != ParameterType::Scalar) {
|
||||
return Err(self.error_here("only SCALAR parameters accept a subtype"));
|
||||
}
|
||||
}
|
||||
let default = if matches!(self.peek(), TokenKind::Eq) {
|
||||
self.next();
|
||||
Some(self.expr(0)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(FunctionParam { name, ty, subtype, passing, default })
|
||||
}
|
||||
|
||||
fn evaluate_statement(&mut self) -> Result<Evaluate, ParseError> {
|
||||
self.next(); // EVALUATE
|
||||
let table = self.expr(0)?;
|
||||
let order_by = if self.keyword_at("ORDER") {
|
||||
self.next();
|
||||
self.expect_keyword("BY", "ORDER must be followed by BY")?;
|
||||
self.order_items()?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let start_at = if self.keyword_at("START") {
|
||||
let span = self.peek_span();
|
||||
self.next();
|
||||
self.expect_keyword("AT", "START must be followed by AT")?;
|
||||
if order_by.is_empty() {
|
||||
return Err(ParseError::new("START AT requires a preceding ORDER BY clause", span));
|
||||
}
|
||||
let values = self.start_values()?;
|
||||
if values.len() > order_by.len() {
|
||||
return Err(ParseError::new(format!("START AT has {} value(s) but ORDER BY has {} item(s)", values.len(), order_by.len()), span));
|
||||
}
|
||||
values
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Ok(Evaluate { table, order_by, start_at })
|
||||
}
|
||||
|
||||
fn order_items(&mut self) -> Result<Vec<OrderItem>, ParseError> {
|
||||
let mut items = Vec::new();
|
||||
loop {
|
||||
let expr = self.expr(0)?;
|
||||
let direction = self.direction();
|
||||
items.push(OrderItem { expr, direction });
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
fn direction(&mut self) -> SortDirection {
|
||||
if self.keyword_at("ASC") {
|
||||
self.next();
|
||||
SortDirection::Asc
|
||||
} else if self.keyword_at("DESC") {
|
||||
self.next();
|
||||
SortDirection::Desc
|
||||
} else {
|
||||
SortDirection::Asc
|
||||
}
|
||||
}
|
||||
|
||||
fn start_values(&mut self) -> Result<Vec<StartValue>, ParseError> {
|
||||
let mut values = Vec::new();
|
||||
loop {
|
||||
values.push(self.start_value()?);
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
fn start_value(&mut self) -> Result<StartValue, ParseError> {
|
||||
let token = self.next();
|
||||
let negative = match &token.kind {
|
||||
TokenKind::Minus => Some(true),
|
||||
TokenKind::Plus => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(negative) = negative {
|
||||
let literal = self.next();
|
||||
return match literal.kind {
|
||||
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(if negative { -value } else { value }))),
|
||||
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(if negative { -value } else { value }))),
|
||||
other => Err(ParseError::new(format!("a signed START AT value must be a numeric literal, found {}", describe(&other)), literal.span)),
|
||||
};
|
||||
}
|
||||
match token.kind {
|
||||
TokenKind::Integer(value) => Ok(StartValue::Literal(Literal::Integer(value))),
|
||||
TokenKind::Decimal(value) => Ok(StartValue::Literal(Literal::Decimal(value))),
|
||||
TokenKind::DateTime(value) => Ok(StartValue::Literal(Literal::DateTime(value))),
|
||||
TokenKind::String(value) => Ok(StartValue::Literal(Literal::String(value))),
|
||||
TokenKind::AtName(name) => Ok(StartValue::Parameter(Name::bare(name))),
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("TRUE") => Ok(StartValue::Literal(Literal::Boolean(true))),
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("FALSE") => Ok(StartValue::Literal(Literal::Boolean(false))),
|
||||
other => Err(ParseError::new(format!("expected a literal or @parameter in START AT, found {}", describe(&other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn visual_shape(&mut self) -> Result<VisualShape, ParseError> {
|
||||
self.next(); // WITH
|
||||
self.expect_keyword("VISUAL", "WITH must be followed by VISUAL SHAPE")?;
|
||||
self.expect_keyword("SHAPE", "WITH VISUAL SHAPE is a single clause")?;
|
||||
let mut axes = Vec::new();
|
||||
while self.keyword_at("AXIS") {
|
||||
let span = self.peek_span();
|
||||
let axis = self.axis()?;
|
||||
if axes.iter().any(|existing: &Axis| existing.kind == axis.kind) {
|
||||
return Err(ParseError::new(format!("duplicate AXIS {} clause", axis.kind.keyword()), span));
|
||||
}
|
||||
axes.push(axis);
|
||||
}
|
||||
if axes.is_empty() {
|
||||
return Err(self.error_here("WITH VISUAL SHAPE needs at least one AXIS ROWS or AXIS COLUMNS clause"));
|
||||
}
|
||||
let densify = if self.keyword_at("DENSIFY") {
|
||||
self.next();
|
||||
let value = self.next();
|
||||
match value.kind {
|
||||
TokenKind::String(text) => Some(text),
|
||||
other => {
|
||||
return Err(ParseError::new(format!("DENSIFY needs a double-quoted column name, found {}", describe(&other)), value.span));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(VisualShape { axes, densify })
|
||||
}
|
||||
|
||||
fn axis(&mut self) -> Result<Axis, ParseError> {
|
||||
self.next(); // AXIS
|
||||
let kind_token = self.next();
|
||||
let kind = match &kind_token.kind {
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("ROWS") => AxisKind::Rows,
|
||||
TokenKind::Ident(word) if word.eq_ignore_ascii_case("COLUMNS") => AxisKind::Columns,
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected `ROWS` or `COLUMNS` after AXIS, found {}", describe(other)), kind_token.span));
|
||||
}
|
||||
};
|
||||
let mut groups = Vec::new();
|
||||
while self.keyword_at("GROUP") {
|
||||
self.next();
|
||||
let mut columns = vec![self.column_ref("GROUP")?];
|
||||
while matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
columns.push(self.column_ref("GROUP")?);
|
||||
}
|
||||
self.expect_keyword("TOTAL", "each GROUP needs a TOTAL column")?;
|
||||
let total = self.column_ref("TOTAL")?;
|
||||
groups.push(AxisGroup { columns, total });
|
||||
}
|
||||
if groups.is_empty() {
|
||||
return Err(self.error_here("AXIS needs at least one GROUP ... TOTAL level"));
|
||||
}
|
||||
self.expect_keyword("ORDER", "each AXIS needs an ORDER BY clause")?;
|
||||
self.expect_keyword("BY", "each AXIS needs an ORDER BY clause")?;
|
||||
let mut order_by = Vec::new();
|
||||
loop {
|
||||
let column = self.column_ref("ORDER BY")?;
|
||||
let direction = self.direction();
|
||||
order_by.push(AxisOrderItem { column, direction });
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Axis { kind, groups, order_by })
|
||||
}
|
||||
|
||||
/// A table name in a definition: a bare identifier or a single-quoted name.
|
||||
fn table_name(&mut self, what: &str) -> Result<Name, ParseError> {
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
|
||||
TokenKind::QuotedIdent(text) => Ok(Name::quoted(text.clone())),
|
||||
other => Err(ParseError::new(format!("expected a {what} name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<table>[<name>]`, the name of a MEASURE or COLUMN definition.
|
||||
fn definition_name(&mut self, kind: &str) -> Result<NameRef, ParseError> {
|
||||
let table = self.table_name(kind)?;
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
|
||||
other => Err(ParseError::new(format!("expected a bracketed {kind} name after the table name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable name: a plain identifier, never quoted or bracketed.
|
||||
fn variable_name(&mut self) -> Result<Name, ParseError> {
|
||||
let token = self.next();
|
||||
match &token.kind {
|
||||
TokenKind::Ident(text) => Ok(Name::bare(text.clone())),
|
||||
TokenKind::QuotedIdent(_) | TokenKind::BracketIdent(_) => {
|
||||
Err(ParseError::new("variable names cannot be quoted or bracketed", token.span))
|
||||
}
|
||||
other => Err(ParseError::new(format!("expected a variable name, found {}", describe(other)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A column reference: `[Column]`, `Table[Column]` or `'Table'[Column]`.
|
||||
fn column_ref(&mut self, context: &str) -> Result<NameRef, ParseError> {
|
||||
let token = self.next();
|
||||
let table = match &token.kind {
|
||||
TokenKind::BracketIdent(text) => return Ok(NameRef::unqualified(Name::bracketed(text.clone()))),
|
||||
TokenKind::Ident(text) => Name::bare(text.clone()),
|
||||
TokenKind::QuotedIdent(text) => Name::quoted(text.clone()),
|
||||
other => {
|
||||
return Err(ParseError::new(format!("expected a column reference in {context}, found {}", describe(other)), token.span));
|
||||
}
|
||||
};
|
||||
let column = self.next();
|
||||
match &column.kind {
|
||||
TokenKind::BracketIdent(text) => Ok(NameRef::qualified(table, Name::bracketed(text.clone()))),
|
||||
other => Err(ParseError::new(format!("expected a bracketed column name after the table name, found {}", describe(other)), column.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn enter(&mut self) -> Result<(), ParseError> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn leave(&mut self) {
|
||||
self.depth = self.depth.saturating_sub(1);
|
||||
}
|
||||
|
||||
fn binary_op(&self) -> Option<BinaryOp> {
|
||||
match self.peek() {
|
||||
TokenKind::Plus => Some(BinaryOp::Add),
|
||||
TokenKind::Minus => Some(BinaryOp::Sub),
|
||||
TokenKind::Star => Some(BinaryOp::Mul),
|
||||
TokenKind::Slash => Some(BinaryOp::Div),
|
||||
TokenKind::Caret => Some(BinaryOp::Pow),
|
||||
TokenKind::Amp => Some(BinaryOp::Concat),
|
||||
TokenKind::Eq => Some(BinaryOp::Eq),
|
||||
TokenKind::StrictEq => Some(BinaryOp::StrictEq),
|
||||
TokenKind::NotEq => Some(BinaryOp::Ne),
|
||||
TokenKind::Lt => Some(BinaryOp::Lt),
|
||||
TokenKind::Gt => Some(BinaryOp::Gt),
|
||||
TokenKind::Le => Some(BinaryOp::Le),
|
||||
TokenKind::Ge => Some(BinaryOp::Ge),
|
||||
TokenKind::AndAnd => Some(BinaryOp::And),
|
||||
TokenKind::OrOr => Some(BinaryOp::Or),
|
||||
TokenKind::In => Some(BinaryOp::In),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expr(&mut self, min_bp: u8) -> Result<Expr, ParseError> {
|
||||
self.enter()?;
|
||||
let mut lhs = self.prefix()?;
|
||||
let mut lhs_depth = lhs.depth();
|
||||
while let Some(op) = self.binary_op() {
|
||||
let bp = op.precedence();
|
||||
if bp < min_bp {
|
||||
break;
|
||||
}
|
||||
self.next();
|
||||
// Every binary operator is left-associative (DAX orders equal precedence left to right).
|
||||
let next_min = if op.is_right_associative() { bp } else { bp + 1 };
|
||||
let rhs = self.expr(next_min)?;
|
||||
// Grouped expressions return their inner tree without a parenthesis node, so the
|
||||
// depth must come from the AST itself, not from the parser's recursion frames.
|
||||
let depth = lhs_depth.max(rhs.depth());
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(self.error_here(format!("expression is nested too deeply (limit {MAX_DEPTH})")));
|
||||
}
|
||||
lhs_depth = depth + 1;
|
||||
let span = lhs.span.to(rhs.span);
|
||||
lhs = Expr::new(ExprKind::Binary { op, left: Box::new(lhs), right: Box::new(rhs) }, span);
|
||||
}
|
||||
self.leave();
|
||||
Ok(lhs)
|
||||
}
|
||||
|
||||
fn prefix(&mut self) -> Result<Expr, ParseError> {
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Integer(n) => Ok(Expr::literal(Literal::Integer(n), token.span)),
|
||||
TokenKind::Decimal(n) => Ok(Expr::literal(Literal::Decimal(n), token.span)),
|
||||
TokenKind::DateTime(value) => Ok(Expr::literal(Literal::DateTime(value), token.span)),
|
||||
TokenKind::String(s) => Ok(Expr::literal(Literal::String(s), token.span)),
|
||||
TokenKind::Ident(word) => {
|
||||
if word.eq_ignore_ascii_case("VAR") {
|
||||
return self.var_return(token.span);
|
||||
}
|
||||
if word.eq_ignore_ascii_case("RETURN") {
|
||||
return Err(ParseError::new("RETURN without a preceding VAR declaration", token.span));
|
||||
}
|
||||
self.prefix_ident(word, token.span)
|
||||
}
|
||||
TokenKind::QuotedIdent(word) => {
|
||||
let name = Name::quoted(word);
|
||||
if let TokenKind::BracketIdent(_) = self.peek() {
|
||||
self.qualified_name(name, token.span)
|
||||
} else {
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(name)), token.span))
|
||||
}
|
||||
}
|
||||
TokenKind::BracketIdent(word) => Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bracketed(word))), token.span)),
|
||||
TokenKind::Not => {
|
||||
let operand = self.expr(UnaryOp::Not.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Not, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::Plus => {
|
||||
let operand = self.expr(UnaryOp::Plus.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Plus, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::Minus => {
|
||||
let operand = self.expr(UnaryOp::Neg.precedence())?;
|
||||
let span = token.span.to(operand.span);
|
||||
Ok(Expr::new(ExprKind::Unary { op: UnaryOp::Neg, expr: Box::new(operand) }, span))
|
||||
}
|
||||
TokenKind::LParen => self.paren(token.span),
|
||||
TokenKind::LBrace => self.table(token.span),
|
||||
_ => Err(ParseError::new(format!("expected expression, found {}", describe(&token.kind)), token.span)),
|
||||
}
|
||||
}
|
||||
|
||||
fn prefix_ident(&mut self, word: String, span: Span) -> Result<Expr, ParseError> {
|
||||
if let TokenKind::BracketIdent(_) = self.peek() {
|
||||
return self.qualified_name(Name::bare(word), span);
|
||||
}
|
||||
if matches!(self.peek(), TokenKind::LParen) {
|
||||
return self.call(Name::bare(word), span);
|
||||
}
|
||||
if word.eq_ignore_ascii_case("TRUE") {
|
||||
return Ok(Expr::literal(Literal::Boolean(true), span));
|
||||
}
|
||||
if word.eq_ignore_ascii_case("FALSE") {
|
||||
return Ok(Expr::literal(Literal::Boolean(false), span));
|
||||
}
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::unqualified(Name::bare(word))), span))
|
||||
}
|
||||
|
||||
/// Parses `VAR <name> = <expr> ... RETURN <expr>`.
|
||||
///
|
||||
/// The declaration values and the `RETURN` body stop at the next statement or definition
|
||||
/// keyword because a bare identifier is never an infix operator, so no newline or terminator
|
||||
/// is needed. A nested `VAR ... RETURN ...` as a declaration value or body parses recursively.
|
||||
fn var_return(&mut self, start: Span) -> Result<Expr, ParseError> {
|
||||
let mut vars = Vec::new();
|
||||
// The leading `VAR` has already been consumed by `prefix`; each iteration parses one
|
||||
// declaration and continues only when another `VAR` follows the value expression.
|
||||
loop {
|
||||
let name = self.variable_name()?;
|
||||
self.expect(TokenKind::Eq, "a VAR declaration needs `=` before its expression")?;
|
||||
let expr = self.expr(0)?;
|
||||
vars.push(VarDecl { name, expr });
|
||||
if !self.keyword_at("VAR") {
|
||||
break;
|
||||
}
|
||||
self.next();
|
||||
}
|
||||
if !self.keyword_at("RETURN") {
|
||||
return Err(self.error_here("VAR declarations must be followed by RETURN <expression>"));
|
||||
}
|
||||
self.next();
|
||||
let body = self.expr(0)?;
|
||||
let span = start.to(body.span);
|
||||
Ok(Expr::new(ExprKind::VarReturn { vars, body: Box::new(body) }, span))
|
||||
}
|
||||
|
||||
/// Consumes a bracketed column that follows a table name.
|
||||
fn qualified_name(&mut self, table: Name, table_span: Span) -> Result<Expr, ParseError> {
|
||||
let column = self.next();
|
||||
let TokenKind::BracketIdent(text) = column.kind else {
|
||||
return Err(ParseError::new("expected bracketed column name", column.span));
|
||||
};
|
||||
let span = table_span.to(column.span);
|
||||
Ok(Expr::new(ExprKind::Name(NameRef::qualified(table, Name::bracketed(text))), span))
|
||||
}
|
||||
|
||||
fn call(&mut self, name: Name, name_span: Span) -> Result<Expr, ParseError> {
|
||||
self.expect(TokenKind::LParen, "function calls need `(` after the name")?;
|
||||
let mut args = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
let close = self.next();
|
||||
return Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close.span)));
|
||||
}
|
||||
let close_span = loop {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
return Err(self.error_here("expected an argument after `,`"));
|
||||
}
|
||||
args.push(self.expr(0)?);
|
||||
let token = self.next();
|
||||
match token.kind {
|
||||
TokenKind::Comma => {}
|
||||
TokenKind::RParen => break token.span,
|
||||
_ => {
|
||||
return Err(ParseError::new(
|
||||
format!("expected `,` or `)` in call to `{}`, found {}", name.text, describe(&token.kind)),
|
||||
token.span,
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(Expr::new(ExprKind::Call(Call { name, args }), name_span.to(close_span)))
|
||||
}
|
||||
|
||||
/// `( expr )` is grouping (parentheses are not AST nodes), `( a, b, ... )` is a row
|
||||
/// constructor.
|
||||
fn paren(&mut self, open: Span) -> Result<Expr, ParseError> {
|
||||
if matches!(self.peek(), TokenKind::RParen) {
|
||||
let close = self.next();
|
||||
return Err(ParseError::new("empty parentheses are not an expression", open.to(close.span)));
|
||||
}
|
||||
let first = self.expr(0)?;
|
||||
if matches!(self.peek(), TokenKind::Comma) {
|
||||
let mut items = vec![first];
|
||||
while matches!(self.peek(), TokenKind::Comma) {
|
||||
self.next();
|
||||
if matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
|
||||
return Err(self.error_here("expected an expression after `,` in a row constructor"));
|
||||
}
|
||||
items.push(self.expr(0)?);
|
||||
}
|
||||
let close = self.expect(TokenKind::RParen, "row constructors end with `)`")?;
|
||||
return Ok(Expr::new(ExprKind::Tuple(items), open.to(close.span)));
|
||||
}
|
||||
let close = self.expect(TokenKind::RParen, "parentheses end with `)`")?;
|
||||
Ok(Expr::new(first.kind, open.to(close.span)))
|
||||
}
|
||||
|
||||
fn table(&mut self, open: Span) -> Result<Expr, ParseError> {
|
||||
let mut items = Vec::new();
|
||||
if matches!(self.peek(), TokenKind::RBrace) {
|
||||
let close = self.next();
|
||||
return Ok(Expr::new(ExprKind::Table(items), open.to(close.span)));
|
||||
}
|
||||
loop {
|
||||
if matches!(self.peek(), TokenKind::RBrace | TokenKind::Eof) {
|
||||
return Err(self.error_here("expected a value in the table constructor"));
|
||||
}
|
||||
items.push(self.expr(0)?);
|
||||
match self.next().kind {
|
||||
TokenKind::Comma => {
|
||||
if matches!(self.peek(), TokenKind::RBrace) {
|
||||
return Err(self.error_here("expected a value after `,` in the table constructor"));
|
||||
}
|
||||
}
|
||||
TokenKind::RBrace => break,
|
||||
_ => {
|
||||
return Err(ParseError::new(
|
||||
"expected `,` or `}` in the table constructor",
|
||||
self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let close_span = self.tokens.get(self.i.saturating_sub(1)).map(|t| t.span).unwrap_or(open);
|
||||
Ok(Expr::new(ExprKind::Table(items), open.to(close_span)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Minimal pivot grouping over the in-memory model.
|
||||
//!
|
||||
//! A pivot groups a table by one or more column references and evaluates a measure once per
|
||||
//! group. This is the integration point a workbook/PivotTable adapter can call; the full
|
||||
//! PivotTable layout engine remains outside this crate.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::binder::{BindError, Binder, BoundExpr};
|
||||
use crate::eval::{Evaluator, FilterContext};
|
||||
use crate::model::DataModel;
|
||||
use crate::pivot_table::DEFAULT_MAX_CELLS;
|
||||
use crate::value::{EvalError, Scalar, ScalarKey, TableColumn, TableValue};
|
||||
use crate::{Expr, parse_expression};
|
||||
|
||||
/// One grouping field.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PivotField {
|
||||
pub table: usize,
|
||||
pub column: usize,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Evaluates a measure grouped by the supplied row fields (no column fields).
|
||||
pub fn pivot(model: &DataModel, measure: &str, row_fields: &[PivotField]) -> Result<TableValue, PivotError> {
|
||||
pivot_cross(model, measure, row_fields, &[])
|
||||
}
|
||||
|
||||
/// Evaluates a measure grouped by row fields and optional column fields.
|
||||
///
|
||||
/// The result has one column per row field followed by one measure column per distinct column
|
||||
/// group. With no column fields the result is the usual grouped table. Group order is ascending;
|
||||
/// BLANK is a group of its own. Missing combinations are BLANK.
|
||||
pub fn pivot_cross(model: &DataModel, measure: &str, row_fields: &[PivotField], column_fields: &[PivotField]) -> Result<TableValue, PivotError> {
|
||||
let evaluator = Evaluator::new(model)?;
|
||||
let table_index = model
|
||||
.measure_index(measure)
|
||||
.and_then(|index| model.measures.get(index))
|
||||
.and_then(|measure| measure.table.as_deref())
|
||||
.and_then(|table| model.table_index(table));
|
||||
let Some(table_index) = table_index else {
|
||||
return Err(PivotError::Eval(EvalError::new(format!(
|
||||
"measure `{measure}` has no home table; give the measure a home table, or set `PivotTable::source_table` and render through `PivotTable` instead of `pivot`/`pivot_cross`"
|
||||
))));
|
||||
};
|
||||
let source = model.tables.get(table_index).ok_or_else(|| PivotError::Eval(EvalError::new("missing table")))?;
|
||||
|
||||
let mut row_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
|
||||
let mut column_groups: BTreeMap<Vec<ScalarKey>, Vec<Scalar>> = BTreeMap::new();
|
||||
for row in &source.rows {
|
||||
let row_values = group_values(row, row_fields, table_index)?;
|
||||
row_groups.entry(row_values.iter().map(crate::value::distinct_key).collect()).or_insert(row_values);
|
||||
if !column_fields.is_empty() {
|
||||
let column_values = group_values(row, column_fields, table_index)?;
|
||||
column_groups.entry(column_values.iter().map(crate::value::distinct_key).collect()).or_insert(column_values);
|
||||
}
|
||||
}
|
||||
if column_fields.is_empty() {
|
||||
column_groups.insert(Vec::new(), Vec::new());
|
||||
}
|
||||
if row_groups.len().checked_mul(column_groups.len()).is_none_or(|cells| cells > DEFAULT_MAX_CELLS) {
|
||||
return Err(PivotError::Eval(EvalError::new(format!(
|
||||
"pivot would materialize {} rows x {} columns, over the limit of {} cells",
|
||||
row_groups.len(),
|
||||
column_groups.len(),
|
||||
DEFAULT_MAX_CELLS
|
||||
))));
|
||||
}
|
||||
|
||||
let mut columns = row_fields.iter().map(|field| TableColumn { name: field.name.clone() }).collect::<Vec<_>>();
|
||||
let column_headers: Vec<(Vec<ScalarKey>, Vec<Scalar>)> = column_groups.into_iter().collect();
|
||||
if column_fields.is_empty() {
|
||||
columns.push(TableColumn { name: measure.to_string() });
|
||||
} else {
|
||||
for (_, values) in &column_headers {
|
||||
// Headers show calendar text for dates and whole numbers without `.0`, as Excel does.
|
||||
columns.push(TableColumn { name: values.iter().map(|value| value.to_dax_text()).collect::<Vec<_>>().join(" | ") });
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows = Vec::with_capacity(row_groups.len());
|
||||
for (row_key, row_values) in row_groups {
|
||||
let mut out = row_values;
|
||||
for (column_key, _) in &column_headers {
|
||||
let mut filters = FilterContext::default();
|
||||
for (field, key) in row_fields.iter().zip(&row_key) {
|
||||
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
|
||||
}
|
||||
for (field, key) in column_fields.iter().zip(column_key) {
|
||||
crate::pivot_table::narrow_to_key(&mut filters, field.table, field.column, key);
|
||||
}
|
||||
out.push(evaluator.evaluate_measure(measure, filters)?);
|
||||
}
|
||||
rows.push(out);
|
||||
}
|
||||
Ok(TableValue::new(columns, rows))
|
||||
}
|
||||
|
||||
fn group_values(row: &[Scalar], fields: &[PivotField], table_index: usize) -> Result<Vec<Scalar>, PivotError> {
|
||||
let mut values = Vec::with_capacity(fields.len());
|
||||
for field in fields {
|
||||
if field.table != table_index {
|
||||
return Err(PivotError::Eval(EvalError::new("pivot fields must belong to the measure table")));
|
||||
}
|
||||
values.push(row.get(field.column).cloned().unwrap_or(Scalar::Blank));
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// Parses field references such as `Sales[Region]` against the model.
|
||||
pub fn pivot_fields(model: &DataModel, fields: &[String]) -> Result<Vec<PivotField>, PivotError> {
|
||||
let binder = Binder::new(model);
|
||||
let mut out = Vec::with_capacity(fields.len());
|
||||
for field in fields {
|
||||
let expr: Expr = parse_expression(field).map_err(|error| PivotError::Bind(BindError { message: error.message, span: error.span }))?;
|
||||
let bound = binder.bind_expression(&expr)?;
|
||||
let BoundExpr::Column { table, column } = bound else {
|
||||
return Err(PivotError::Bind(BindError { message: format!("pivot field `{field}` is not a column reference"), span: expr.span }));
|
||||
};
|
||||
let name =
|
||||
model.tables.get(table).and_then(|table| table.columns.get(column)).map(|column| column.name.clone()).unwrap_or_else(|| field.clone());
|
||||
out.push(PivotField { table, column, name });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PivotError {
|
||||
#[error(transparent)]
|
||||
Bind(#[from] BindError),
|
||||
#[error(transparent)]
|
||||
Eval(#[from] EvalError),
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,339 @@
|
||||
//! Canonical DAX printer: [`Expr`] / [`Query`] → text.
|
||||
//!
|
||||
//! Printing is iterative (an explicit work stack), so long operator chains — which parse into
|
||||
//! deep trees — cannot overflow the stack. Parentheses are emitted only where precedence or
|
||||
//! associativity requires them; re-parsing the result yields the same AST (spans ignored).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
use crate::ast::{
|
||||
Axis, Call, Definition, Evaluate, Expr, ExprKind, FunctionParam, Literal, Name, NameRef, NameStyle, Query, StartValue, UnaryOp, VisualShape,
|
||||
};
|
||||
|
||||
/// An expression-level `VAR ... RETURN ...` binds looser than every operator, so it needs
|
||||
/// parentheses whenever it is an operand rather than a whole expression.
|
||||
const VAR_RETURN_BP: u8 = 1;
|
||||
|
||||
/// Prints an expression in canonical form.
|
||||
pub fn print_expression(expr: &Expr) -> String {
|
||||
let mut out = String::new();
|
||||
write_expr(&mut out, expr, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// Prints a query in canonical form.
|
||||
///
|
||||
/// `DEFINE` entries are indented one level; `EVALUATE` is printed on one line for the simple
|
||||
/// `EVALUATE <expression>` form and followed by indented `ORDER BY`/`START AT` clauses when they
|
||||
/// exist. A visual shape prints its axes, groups, axis order and `DENSIFY` indented under the
|
||||
/// `TABLE` definition. Re-parsing the result yields the same [`Query`] (spans ignored).
|
||||
pub fn print_query(query: &Query) -> String {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
if let Some(define) = &query.define {
|
||||
lines.push("DEFINE".into());
|
||||
for item in &define.items {
|
||||
push_definition(&mut lines, item);
|
||||
}
|
||||
}
|
||||
for evaluate in &query.evaluates {
|
||||
push_evaluate(&mut lines, evaluate);
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn print_name(name: &Name) -> String {
|
||||
let mut out = String::new();
|
||||
write_name(&mut out, name);
|
||||
out
|
||||
}
|
||||
|
||||
fn print_name_ref(name: &NameRef) -> String {
|
||||
let mut out = String::new();
|
||||
write_name_ref(&mut out, name);
|
||||
out
|
||||
}
|
||||
|
||||
fn push_definition(lines: &mut Vec<String>, definition: &Definition) {
|
||||
match definition {
|
||||
Definition::Measure(def) => lines.push(format!(" MEASURE {} = {}", print_name_ref(&def.name), print_expression(&def.expr))),
|
||||
Definition::Column(def) => lines.push(format!(" COLUMN {} = {}", print_name_ref(&def.name), print_expression(&def.expr))),
|
||||
Definition::Var(def) => lines.push(format!(" VAR {} = {}", print_name(&def.name), print_expression(&def.expr))),
|
||||
Definition::MParameter(def) => {
|
||||
lines.push(format!(" MPARAMETER {} = {}", print_name(&def.name), print_expression(&def.expr)));
|
||||
}
|
||||
Definition::Function(def) => {
|
||||
let params: Vec<String> = def.params.iter().map(print_function_param).collect();
|
||||
lines.push(format!(" FUNCTION {} = ({}) => {}", print_name(&def.name), params.join(", "), print_expression(&def.body)));
|
||||
}
|
||||
Definition::Table(def) => {
|
||||
let mut head = format!(" TABLE {} = {}", print_name(&def.name), print_expression(&def.expr));
|
||||
match &def.visual_shape {
|
||||
None => lines.push(head),
|
||||
Some(shape) => {
|
||||
head.push_str(" WITH VISUAL SHAPE");
|
||||
lines.push(head);
|
||||
push_visual_shape(lines, shape);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_function_param(param: &FunctionParam) -> String {
|
||||
let mut out = print_name(¶m.name);
|
||||
let mut annotations: Vec<&'static str> = Vec::new();
|
||||
if let Some(ty) = param.ty {
|
||||
annotations.push(ty.keyword());
|
||||
}
|
||||
if let Some(subtype) = param.subtype {
|
||||
annotations.push(subtype.keyword());
|
||||
}
|
||||
if let Some(passing) = param.passing {
|
||||
annotations.push(passing.keyword());
|
||||
}
|
||||
if !annotations.is_empty() {
|
||||
out.push_str(" : ");
|
||||
out.push_str(&annotations.join(" "));
|
||||
}
|
||||
if let Some(default) = ¶m.default {
|
||||
out.push_str(" = ");
|
||||
out.push_str(&print_expression(default));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn push_visual_shape(lines: &mut Vec<String>, shape: &VisualShape) {
|
||||
for axis in &shape.axes {
|
||||
push_axis(lines, axis);
|
||||
}
|
||||
if let Some(densify) = &shape.densify {
|
||||
let mut line = String::from(" DENSIFY ");
|
||||
write_quoted(&mut line, densify, '"');
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_axis(lines: &mut Vec<String>, axis: &Axis) {
|
||||
lines.push(format!(" AXIS {}", axis.kind.keyword()));
|
||||
for group in &axis.groups {
|
||||
let columns: Vec<String> = group.columns.iter().map(print_name_ref).collect();
|
||||
lines.push(format!(" GROUP {} TOTAL {}", columns.join(", "), print_name_ref(&group.total)));
|
||||
}
|
||||
lines.push(" ORDER BY".into());
|
||||
for (index, item) in axis.order_by.iter().enumerate() {
|
||||
let mut line = format!(" {} {}", print_name_ref(&item.column), item.direction.keyword());
|
||||
if index + 1 < axis.order_by.len() {
|
||||
line.push(',');
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_evaluate(lines: &mut Vec<String>, evaluate: &Evaluate) {
|
||||
lines.push(format!("EVALUATE {}", print_expression(&evaluate.table)));
|
||||
if !evaluate.order_by.is_empty() {
|
||||
lines.push("ORDER BY".into());
|
||||
for (index, item) in evaluate.order_by.iter().enumerate() {
|
||||
let mut line = format!(" {} {}", print_expression(&item.expr), item.direction.keyword());
|
||||
if index + 1 < evaluate.order_by.len() {
|
||||
line.push(',');
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
if !evaluate.start_at.is_empty() {
|
||||
let mut line = String::from("START AT ");
|
||||
for (index, value) in evaluate.start_at.iter().enumerate() {
|
||||
if index > 0 {
|
||||
line.push_str(", ");
|
||||
}
|
||||
write_start_value(&mut line, value);
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_start_value(out: &mut String, value: &StartValue) {
|
||||
match value {
|
||||
StartValue::Literal(literal) => write_literal(out, literal),
|
||||
StartValue::Parameter(name) => {
|
||||
out.push('@');
|
||||
out.push_str(&name.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_quoted(out: &mut String, text: &str, quote: char) {
|
||||
out.push(quote);
|
||||
for c in text.chars() {
|
||||
if c == quote {
|
||||
out.push(quote);
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push(quote);
|
||||
}
|
||||
|
||||
fn write_bracketed(out: &mut String, text: &str) {
|
||||
out.push('[');
|
||||
for c in text.chars() {
|
||||
if c == ']' {
|
||||
out.push(']');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
|
||||
fn write_name(out: &mut String, name: &Name) {
|
||||
match name.style {
|
||||
NameStyle::Bare => out.push_str(&name.text),
|
||||
NameStyle::Quoted => write_quoted(out, &name.text, '\''),
|
||||
NameStyle::Bracketed => write_bracketed(out, &name.text),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_name_ref(out: &mut String, name: &NameRef) {
|
||||
if let Some(table) = &name.table {
|
||||
write_name(out, table);
|
||||
}
|
||||
write_name(out, &name.name);
|
||||
}
|
||||
|
||||
fn write_literal(out: &mut String, literal: &Literal) {
|
||||
match literal {
|
||||
Literal::Integer(n) => {
|
||||
let _ = write!(out, "{n}");
|
||||
}
|
||||
Literal::Decimal(n) => {
|
||||
// `Debug` keeps a decimal point (`1000.0`) or an exponent (`1e300`) for every finite
|
||||
// value, so the printed text re-lexes as a Decimal instead of an Integer.
|
||||
let _ = write!(out, "{n:?}");
|
||||
}
|
||||
Literal::DateTime(value) => {
|
||||
let _ = write!(out, "dt\"{value}\"");
|
||||
}
|
||||
Literal::String(s) => write_quoted(out, s, '"'),
|
||||
Literal::Boolean(true) => out.push_str("TRUE"),
|
||||
Literal::Boolean(false) => out.push_str("FALSE"),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_call_head(out: &mut String, call: &Call) {
|
||||
write_name(out, &call.name);
|
||||
out.push('(');
|
||||
}
|
||||
|
||||
/// One element of the printer's work stack. Expressions are expanded here rather than by
|
||||
/// recursion; text tasks cover operators and separators.
|
||||
enum Task<'a> {
|
||||
Expr(&'a Expr, u8),
|
||||
Text(&'static str),
|
||||
Name(&'a Name),
|
||||
}
|
||||
|
||||
fn write_expr(out: &mut String, root: &Expr, root_min_bp: u8) {
|
||||
let mut stack: Vec<Task<'_>> = vec![Task::Expr(root, root_min_bp)];
|
||||
|
||||
while let Some(task) = stack.pop() {
|
||||
match task {
|
||||
Task::Text(text) => out.push_str(text),
|
||||
Task::Name(name) => write_name(out, name),
|
||||
Task::Expr(expr, min_bp) => match &expr.kind {
|
||||
ExprKind::Literal(literal) => write_literal(out, literal),
|
||||
ExprKind::Name(name) => write_name_ref(out, name),
|
||||
ExprKind::Unary { op, expr } => {
|
||||
let bp = op.precedence();
|
||||
let parens = bp < min_bp;
|
||||
if parens {
|
||||
out.push('(');
|
||||
stack.push(Task::Text(")"));
|
||||
}
|
||||
stack.push(Task::Expr(expr, bp));
|
||||
if matches!(op, UnaryOp::Plus | UnaryOp::Neg) && matches!(expr.kind, ExprKind::Unary { op: UnaryOp::Plus | UnaryOp::Neg, .. }) {
|
||||
// `--` would start a line comment; separate repeated signs.
|
||||
stack.push(Task::Text(" "));
|
||||
}
|
||||
stack.push(Task::Text(match op {
|
||||
UnaryOp::Plus => "+",
|
||||
UnaryOp::Neg => "-",
|
||||
UnaryOp::Not => "NOT ",
|
||||
}));
|
||||
}
|
||||
ExprKind::Binary { op, left, right } => {
|
||||
let bp = op.precedence();
|
||||
let parens = bp < min_bp;
|
||||
if parens {
|
||||
out.push('(');
|
||||
stack.push(Task::Text(")"));
|
||||
}
|
||||
let (left_min, right_min) = if op.is_right_associative() { (bp + 1, bp) } else { (bp, bp + 1) };
|
||||
stack.push(Task::Expr(right, right_min));
|
||||
stack.push(Task::Text(" "));
|
||||
stack.push(Task::Text(op.symbol()));
|
||||
stack.push(Task::Text(" "));
|
||||
stack.push(Task::Expr(left, left_min));
|
||||
}
|
||||
ExprKind::Call(call) => {
|
||||
write_call_head(out, call);
|
||||
if call.args.is_empty() {
|
||||
out.push(')');
|
||||
} else {
|
||||
stack.push(Task::Text(")"));
|
||||
for (index, arg) in call.args.iter().enumerate().rev() {
|
||||
stack.push(Task::Expr(arg, 0));
|
||||
if index > 0 {
|
||||
stack.push(Task::Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::Table(items) => {
|
||||
out.push('{');
|
||||
if items.is_empty() {
|
||||
out.push('}');
|
||||
} else {
|
||||
out.push(' ');
|
||||
stack.push(Task::Text(" }"));
|
||||
for (index, item) in items.iter().enumerate().rev() {
|
||||
stack.push(Task::Expr(item, 0));
|
||||
if index > 0 {
|
||||
stack.push(Task::Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::Tuple(items) => {
|
||||
out.push('(');
|
||||
if items.is_empty() {
|
||||
out.push(')');
|
||||
} else {
|
||||
stack.push(Task::Text(")"));
|
||||
for (index, item) in items.iter().enumerate().rev() {
|
||||
stack.push(Task::Expr(item, 0));
|
||||
if index > 0 {
|
||||
stack.push(Task::Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
let parens = VAR_RETURN_BP < min_bp;
|
||||
if parens {
|
||||
out.push('(');
|
||||
stack.push(Task::Text(")"));
|
||||
}
|
||||
stack.push(Task::Expr(body, 0));
|
||||
stack.push(Task::Text("RETURN "));
|
||||
for var in vars.iter().rev() {
|
||||
stack.push(Task::Text(" "));
|
||||
stack.push(Task::Expr(&var.expr, 0));
|
||||
stack.push(Task::Text(" = "));
|
||||
stack.push(Task::Name(&var.name));
|
||||
stack.push(Task::Text("VAR "));
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//! Model references as DAX text, and the formulas of Excel's implicit measures.
|
||||
//!
|
||||
//! The model window lists every visible column with a summarization, and a model PivotTable
|
||||
//! summarizes a column the same way. Both spell the column the same way so the evaluator reads
|
||||
//! them identically: this module owns the one spelling.
|
||||
|
||||
/// Reserved words the lexer or parser turns into operators and statement keywords: a table with
|
||||
/// one of these names must be quoted, or `SUM(In[Amount])` would not parse.
|
||||
const RESERVED: [&str; 7] = ["NOT", "IN", "EVALUATE", "VAR", "RETURN", "TRUE", "FALSE"];
|
||||
|
||||
/// A DAX table reference for a model name, quoted when the name is not a plain identifier or is a
|
||||
/// reserved word.
|
||||
pub fn table_ref(name: &str) -> String {
|
||||
let plain = !name.is_empty()
|
||||
&& name.chars().next().is_some_and(|c| c.is_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
&& !RESERVED.iter().any(|word| word.eq_ignore_ascii_case(name));
|
||||
if plain { name.to_string() } else { format!("'{}'", name.replace('\'', "''")) }
|
||||
}
|
||||
|
||||
/// A DAX column reference for a model name; a `]` in the name is escaped as `]]`.
|
||||
pub fn column_ref(name: &str) -> String {
|
||||
format!("[{}]", name.replace(']', "]]"))
|
||||
}
|
||||
|
||||
/// The formula Excel's implicit measure over `table[column]` evaluates, or `None` when
|
||||
/// `aggregate` is not one of Excel's five summarizations.
|
||||
///
|
||||
/// `Count` is `COUNTA`, not `COUNT`: Excel counts the column's non-blank values whatever their
|
||||
/// type, and `COUNT` ignores booleans — a `TRUE`/`FALSE` column would answer BLANK — while
|
||||
/// `COUNTROWS` would count blanks too. `COUNTA` is the "non-blank values" rule the model window
|
||||
/// and a model PivotTable show under `Count of <column>`.
|
||||
pub fn implicit_measure_formula(aggregate: &str, table: &str, column: &str) -> Option<String> {
|
||||
let function = match aggregate.trim().to_ascii_lowercase().as_str() {
|
||||
"sum" => "SUM",
|
||||
"average" => "AVERAGE",
|
||||
"count" => "COUNTA",
|
||||
"min" => "MIN",
|
||||
"max" => "MAX",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!("{function}({}{})", table_ref(table), column_ref(column)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn references_quote_what_dax_needs_quoted() {
|
||||
assert_eq!(table_ref("Sales"), "Sales");
|
||||
assert_eq!(table_ref("Sales Data"), "'Sales Data'");
|
||||
assert_eq!(table_ref("O'Brien"), "'O''Brien'");
|
||||
assert_eq!(table_ref("In"), "'In'");
|
||||
assert_eq!(table_ref("VAR"), "'VAR'");
|
||||
// A bare `TRUE`/`FALSE` would parse as a Boolean literal, not as a table.
|
||||
assert_eq!(table_ref("TRUE"), "'TRUE'");
|
||||
assert_eq!(table_ref("False"), "'False'");
|
||||
assert_eq!(column_ref("Amount"), "[Amount]");
|
||||
assert_eq!(column_ref("a]b"), "[a]]b]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_measures_count_non_blank_values() {
|
||||
assert_eq!(implicit_measure_formula("Sum", "Sales", "Amount"), Some("SUM(Sales[Amount])".to_string()));
|
||||
// `Count` counts non-blank values of any type, so it maps to COUNTA: COUNT would ignore a
|
||||
// boolean column and answer BLANK.
|
||||
assert_eq!(implicit_measure_formula("count", "Sales Data", "Region"), Some("COUNTA('Sales Data'[Region])".to_string()));
|
||||
assert_eq!(implicit_measure_formula("Count", "Sales", "IsPriority"), Some("COUNTA(Sales[IsPriority])".to_string()));
|
||||
assert_eq!(implicit_measure_formula("Average", "Sales", "Amount"), Some("AVERAGE(Sales[Amount])".to_string()));
|
||||
assert_eq!(implicit_measure_formula("Min", "Sales", "Amount"), Some("MIN(Sales[Amount])".to_string()));
|
||||
assert_eq!(implicit_measure_formula("Max", "Sales", "Amount"), Some("MAX(Sales[Amount])".to_string()));
|
||||
assert_eq!(implicit_measure_formula("None", "Sales", "Amount"), None);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,477 @@
|
||||
use crate::ast::*;
|
||||
use crate::lexer::TokenKind;
|
||||
use crate::{MAX_DEPTH, MAX_INPUT_LEN, MAX_QUERY_LEN, parse_expression, parse_query, print_expression, print_query, tokenize};
|
||||
|
||||
fn expression(src: &str) -> Expr {
|
||||
match parse_expression(src) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("{src:?} did not parse: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses, prints, re-parses and asserts the AST is unchanged. Returns the canonical text.
|
||||
fn round_trip(src: &str) -> String {
|
||||
let parsed = expression(src);
|
||||
let printed = print_expression(&parsed);
|
||||
let reparsed = match parse_expression(&printed) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("canonical text {printed:?} did not parse: {error}"),
|
||||
};
|
||||
assert_eq!(parsed, reparsed, "round trip changed the AST for {src:?} via {printed:?}");
|
||||
printed
|
||||
}
|
||||
|
||||
fn binary(expr: &Expr) -> (&BinaryOp, &Expr, &Expr) {
|
||||
match &expr.kind {
|
||||
ExprKind::Binary { op, left, right } => (op, left, right),
|
||||
other => panic!("expected a binary expression, found {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_operator_spelling_and_canonical_text() {
|
||||
for (src, canonical) in [
|
||||
("1 + 2", "1 + 2"),
|
||||
("1 - 2", "1 - 2"),
|
||||
("1 * 2", "1 * 2"),
|
||||
("1 / 2", "1 / 2"),
|
||||
("1 ^ 2", "1 ^ 2"),
|
||||
("\"a\" & \"b\"", "\"a\" & \"b\""),
|
||||
("1 = 2", "1 = 2"),
|
||||
("1 == 2", "1 == 2"),
|
||||
("1 <> 2", "1 <> 2"),
|
||||
("1 < 2", "1 < 2"),
|
||||
("1 > 2", "1 > 2"),
|
||||
("1 <= 2", "1 <= 2"),
|
||||
("1 >= 2", "1 >= 2"),
|
||||
("TRUE && FALSE", "TRUE && FALSE"),
|
||||
("TRUE || FALSE", "TRUE || FALSE"),
|
||||
("NOT TRUE", "NOT TRUE"),
|
||||
("1 IN { 1 }", "1 IN { 1 }"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arithmetic_precedence_parentheses_and_associativity() {
|
||||
for (src, canonical) in [
|
||||
("1 + 2 * 3", "1 + 2 * 3"),
|
||||
("1 * 2 + 3", "1 * 2 + 3"),
|
||||
("1 + 2 / 3", "1 + 2 / 3"),
|
||||
("1 - 2 * 3", "1 - 2 * 3"),
|
||||
("1 / 2 - 3", "1 / 2 - 3"),
|
||||
("1 + 2 - 3", "1 + 2 - 3"),
|
||||
("1 - 2 + 3", "1 - 2 + 3"),
|
||||
("1 * 2 / 3", "1 * 2 / 3"),
|
||||
("1 / 2 * 3", "1 / 2 * 3"),
|
||||
("1 + 2 + 3", "1 + 2 + 3"),
|
||||
("1 - 2 - 3", "1 - 2 - 3"),
|
||||
("1 * 2 * 3", "1 * 2 * 3"),
|
||||
("1 / 2 / 3", "1 / 2 / 3"),
|
||||
("(1 + 2) * 3", "(1 + 2) * 3"),
|
||||
("1 * (2 + 3)", "1 * (2 + 3)"),
|
||||
("1 - (2 - 3)", "1 - (2 - 3)"),
|
||||
("((1))", "1"),
|
||||
("(1 + 2)", "1 + 2"),
|
||||
("2 ^ 3 * 4", "2 ^ 3 * 4"),
|
||||
("2 * 3 ^ 4", "2 * 3 ^ 4"),
|
||||
("2 ^ 3 + 4", "2 ^ 3 + 4"),
|
||||
("2 ^ 3 ^ 2", "2 ^ 3 ^ 2"),
|
||||
("(2 ^ 3) ^ 2", "2 ^ 3 ^ 2"),
|
||||
("2 ^ (3 ^ 2)", "2 ^ (3 ^ 2)"),
|
||||
("-2 ^ 2", "-2 ^ 2"),
|
||||
("(-2) ^ 2", "(-2) ^ 2"),
|
||||
("2 ^ -3", "2 ^ (-3)"),
|
||||
("2 ^ (-3)", "2 ^ (-3)"),
|
||||
("-(2 * 3)", "-(2 * 3)"),
|
||||
("-2 * 3", "-2 * 3"),
|
||||
("+1 - 2", "+1 - 2"),
|
||||
("1 + -2", "1 + -2"),
|
||||
("1 - -2", "1 - -2"),
|
||||
("- -2", "- -2"),
|
||||
("- +2", "- +2"),
|
||||
("+ -2", "+ -2"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("-2 ^ 2");
|
||||
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Neg, expr: inner }
|
||||
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::Pow, .. })));
|
||||
|
||||
let expr = expression("(-2) ^ 2");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Pow);
|
||||
assert!(matches!(&left.kind, ExprKind::Unary { op: UnaryOp::Neg, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_operators_associate_left() {
|
||||
let expr = expression("1 - 2 - 3");
|
||||
let (op, left, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Sub);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Sub, .. }));
|
||||
assert!(matches!(&right.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 3));
|
||||
|
||||
// DAX orders equal precedence left to right, so a `^` chain groups left: `(2^3)^2`.
|
||||
let expr = expression("2 ^ 3 ^ 2");
|
||||
let (op, left, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Pow);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Pow, .. }));
|
||||
assert!(matches!(&right.kind, ExprKind::Literal(Literal::Integer(n)) if *n == 2));
|
||||
|
||||
let expr = expression("1 / 2 / 3");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Div);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Div, .. }));
|
||||
|
||||
let expr = expression("1 - (2 - 3)");
|
||||
let (op, _, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Sub);
|
||||
assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::Sub, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comparison_and_concatenation_precedence() {
|
||||
for (src, canonical) in [
|
||||
("1 = 2", "1 = 2"),
|
||||
("1 == 2", "1 == 2"),
|
||||
("1 <> 2", "1 <> 2"),
|
||||
("1 < 2", "1 < 2"),
|
||||
("1 > 2", "1 > 2"),
|
||||
("1 <= 2", "1 <= 2"),
|
||||
("1 >= 2", "1 >= 2"),
|
||||
("1 = 2 == 3", "1 = 2 == 3"),
|
||||
("\"a\" & \"b\" = \"ab\"", "\"a\" & \"b\" = \"ab\""),
|
||||
("\"a\" & (\"b\" = \"c\")", "\"a\" & (\"b\" = \"c\")"),
|
||||
("\"a\" & \"b\" & \"c\"", "\"a\" & \"b\" & \"c\""),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("1 = 2");
|
||||
assert_eq!(*binary(&expr).0, BinaryOp::Eq);
|
||||
let expr = expression("1 == 2");
|
||||
assert_eq!(*binary(&expr).0, BinaryOp::StrictEq);
|
||||
let expr = expression("1 = 2 == 3");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::StrictEq);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Eq, .. }));
|
||||
|
||||
let expr = expression("\"a\" & \"b\" = \"ab\"");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Eq);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Concat, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_operators_and_not_precedence() {
|
||||
for (src, canonical) in [
|
||||
("NOT TRUE", "NOT TRUE"),
|
||||
("not false", "NOT FALSE"),
|
||||
("TRUE && FALSE", "TRUE && FALSE"),
|
||||
("TRUE || FALSE", "TRUE || FALSE"),
|
||||
("NOT TRUE || FALSE && TRUE", "NOT TRUE || FALSE && TRUE"),
|
||||
("TRUE && FALSE || TRUE", "TRUE && FALSE || TRUE"),
|
||||
("TRUE || FALSE && TRUE", "TRUE || FALSE && TRUE"),
|
||||
("NOT TRUE = FALSE", "NOT TRUE = FALSE"),
|
||||
("NOT (TRUE = FALSE)", "NOT TRUE = FALSE"),
|
||||
("NOT TRUE && FALSE", "NOT TRUE && FALSE"),
|
||||
("NOT (TRUE && FALSE)", "NOT (TRUE && FALSE)"),
|
||||
("NOT NOT TRUE", "NOT NOT TRUE"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("TRUE || FALSE && TRUE");
|
||||
let (op, left, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Or);
|
||||
assert!(matches!(&left.kind, ExprKind::Literal(Literal::Boolean(true))));
|
||||
assert!(matches!(&right.kind, ExprKind::Binary { op: BinaryOp::And, .. }));
|
||||
|
||||
let expr = expression("NOT TRUE && FALSE");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::And);
|
||||
assert!(matches!(&left.kind, ExprKind::Unary { op: UnaryOp::Not, .. }));
|
||||
|
||||
let expr = expression("NOT TRUE = FALSE");
|
||||
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Not, expr: inner }
|
||||
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::Eq, .. })));
|
||||
|
||||
let expr = expression("NOT (TRUE && FALSE)");
|
||||
assert!(matches!(&expr.kind, ExprKind::Unary { op: UnaryOp::Not, expr: inner }
|
||||
if matches!(&inner.kind, ExprKind::Binary { op: BinaryOp::And, .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_operator_with_lists_and_table_expressions() {
|
||||
for (src, canonical) in [
|
||||
("1 IN { 1 }", "1 IN { 1 }"),
|
||||
("1 IN {1, 2, 3}", "1 IN { 1, 2, 3 }"),
|
||||
("1 IN {}", "1 IN {}"),
|
||||
("'Sales'[Region] IN { \"East\", \"West\" }", "'Sales'[Region] IN { \"East\", \"West\" }"),
|
||||
("1 IN VALUES(T[Col])", "1 IN VALUES(T[Col])"),
|
||||
("1 IN (FILTER(T, T[X] > 0))", "1 IN FILTER(T, T[X] > 0)"),
|
||||
("1 IN { 1 } = TRUE", "1 IN { 1 } = TRUE"),
|
||||
("2 ^ 3 IN { 8 }", "2 ^ 3 IN { 8 }"),
|
||||
("1 + 2 IN { 3 }", "1 + 2 IN { 3 }"),
|
||||
("-1 IN { 1 }", "-1 IN { 1 }"),
|
||||
("NOT 1 IN { 1 }", "NOT 1 IN { 1 }"),
|
||||
("1 IN { 1 } IN { TRUE }", "1 IN { 1 } IN { TRUE }"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("1 IN { 1, 2 }");
|
||||
let (_, _, right) = binary(&expr);
|
||||
assert!(matches!(&right.kind, ExprKind::Table(items) if items.len() == 2));
|
||||
|
||||
let expr = expression("1 IN VALUES(T[Col])");
|
||||
let (_, _, right) = binary(&expr);
|
||||
assert!(matches!(&right.kind, ExprKind::Call(_)));
|
||||
|
||||
// `IN` sits in the comparison tier of Microsoft's operator table, so the arithmetic on its
|
||||
// left is grouped first and `IN` is the outermost operator.
|
||||
let expr = expression("2 ^ 3 IN { 8 }");
|
||||
let (op, left, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::In);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Pow, .. }));
|
||||
assert!(matches!(&right.kind, ExprKind::Table(_)));
|
||||
|
||||
let expr = expression("1 + 2 IN { 3 }");
|
||||
let (op, left, right) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::In);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Add, .. }));
|
||||
assert!(matches!(&right.kind, ExprKind::Table(_)));
|
||||
|
||||
// `IN` and `=` share the tier, so they group left to right.
|
||||
let expr = expression("1 IN { 1 } = TRUE");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::Eq);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::In, .. }));
|
||||
|
||||
let expr = expression("1 = 1 IN { TRUE }");
|
||||
let (op, left, _) = binary(&expr);
|
||||
assert_eq!(*op, BinaryOp::In);
|
||||
assert!(matches!(&left.kind, ExprKind::Binary { op: BinaryOp::Eq, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quoted_and_bracketed_identifiers_preserve_escapes() {
|
||||
for (src, canonical) in [
|
||||
("'My Table'[Sales Amount]", "'My Table'[Sales Amount]"),
|
||||
("'It''s'[A]]B]", "'It''s'[A]]B]"),
|
||||
("Sales[Amount]", "Sales[Amount]"),
|
||||
("[Measure]", "[Measure]"),
|
||||
("'Quoted Table'", "'Quoted Table'"),
|
||||
("SUM('Sales'[Amount])", "SUM('Sales'[Amount])"),
|
||||
("'Sales'[Amount] + 1", "'Sales'[Amount] + 1"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("'It''s'[A]]B]");
|
||||
match expr.kind {
|
||||
ExprKind::Name(name) => {
|
||||
let table = match &name.table {
|
||||
Some(table) => table,
|
||||
None => panic!("expected a table qualifier"),
|
||||
};
|
||||
assert_eq!(table.text, "It's");
|
||||
assert_eq!(table.style, NameStyle::Quoted);
|
||||
assert_eq!(name.name.text, "A]B");
|
||||
assert_eq!(name.name.style, NameStyle::Bracketed);
|
||||
}
|
||||
other => panic!("expected a name, found {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_numbers_booleans_and_calls() {
|
||||
for (src, canonical) in [
|
||||
("\"a\"\"b\"", "\"a\"\"b\""),
|
||||
("\"\"", "\"\""),
|
||||
("TRUE", "TRUE"),
|
||||
("true", "TRUE"),
|
||||
("False", "FALSE"),
|
||||
("1", "1"),
|
||||
("1.5", "1.5"),
|
||||
(".5", "0.5"),
|
||||
("1.", "1.0"),
|
||||
("1e3", "1000.0"),
|
||||
("1.5E-3", "0.0015"),
|
||||
("0.000001", "1e-6"),
|
||||
("0", "0"),
|
||||
("1000", "1000"),
|
||||
("SUM()", "SUM()"),
|
||||
("SUM(1, 2)", "SUM(1, 2)"),
|
||||
("SUM(1, MAX(2, 3))", "SUM(1, MAX(2, 3))"),
|
||||
("Sum(1, 2)", "Sum(1, 2)"),
|
||||
("STDEV.P(1, 2)", "STDEV.P(1, 2)"),
|
||||
("TRUE()", "TRUE()"),
|
||||
("true()", "true()"),
|
||||
("FALSE(1)", "FALSE(1)"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
match expression("\"a\"\"b\"").kind {
|
||||
ExprKind::Literal(Literal::String(text)) => assert_eq!(text, "a\"b"),
|
||||
other => panic!("expected a string literal, found {other:?}"),
|
||||
}
|
||||
assert!(matches!(expression("TRUE").kind, ExprKind::Literal(Literal::Boolean(true))));
|
||||
assert!(matches!(expression("FALSE").kind, ExprKind::Literal(Literal::Boolean(false))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_and_row_constructors() {
|
||||
for (src, canonical) in [
|
||||
("{}", "{}"),
|
||||
("{1}", "{ 1 }"),
|
||||
("{1, 2, 3}", "{ 1, 2, 3 }"),
|
||||
("{(1, 2), (3, 4)}", "{ (1, 2), (3, 4) }"),
|
||||
("{ (\"a\", TRUE), (\"b\", FALSE) }", "{ (\"a\", TRUE), (\"b\", FALSE) }"),
|
||||
("(1, 2)", "(1, 2)"),
|
||||
("(1, 2, 3)", "(1, 2, 3)"),
|
||||
("((1, 2))", "(1, 2)"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
let expr = expression("{ (1, \"a\"), (2, \"b\") }");
|
||||
match expr.kind {
|
||||
ExprKind::Table(rows) => {
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(rows.iter().all(|row| matches!(&row.kind, ExprKind::Tuple(items) if items.len() == 2)));
|
||||
}
|
||||
other => panic!("expected a table, found {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_skipped() {
|
||||
for (src, canonical) in [
|
||||
("1 + /* comment */ 2", "1 + 2"),
|
||||
("1 + // comment\n2", "1 + 2"),
|
||||
("1 + -- comment\n2", "1 + 2"),
|
||||
("/* lead */ 1 /* tail */", "1"),
|
||||
("1--2", "1"),
|
||||
("1 - -2", "1 - -2"),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_parsing_and_printing() {
|
||||
let query = parse_query("EVALUATE SUM('Sales'[Amount])").unwrap();
|
||||
assert!(query.define.is_none());
|
||||
assert_eq!(query.evaluates.len(), 1);
|
||||
assert_eq!(print_query(&query), "EVALUATE SUM('Sales'[Amount])");
|
||||
assert_eq!(parse_query(&print_query(&query)).unwrap(), query);
|
||||
|
||||
assert_eq!(print_query(&parse_query("evaluate 1 + 2 * 3").unwrap()), "EVALUATE 1 + 2 * 3");
|
||||
assert_eq!(print_query(&parse_query("/* c */ EVALUATE {1, 2}").unwrap()), "EVALUATE { 1, 2 }");
|
||||
|
||||
for bad in ["", "1 + 2", "EVALUATE", "EVALUATE 1 2", "EVALUATE 1 +"] {
|
||||
assert!(parse_query(bad).is_err(), "expected a query error for {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_equals_is_accepted_for_expressions() {
|
||||
assert_eq!(round_trip("= 1 + 2"), "1 + 2");
|
||||
assert!(parse_expression("=").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_input_reports_errors() {
|
||||
for bad in [
|
||||
"", " ", "(", "()", "(1,", "(1,)", "{1,", "{1, }", "1 +", "1 2", "1e", "1e+", "1.2.3", "123abc", "\"abc", "'abc", "[abc", "/* abc", "1 IN",
|
||||
"NOT", "1 == ", "1 & ", "=>", "1 => 2", "SUM(1,)", "SUM(1", "SUM(,1)", "1 ? 2", "=", "''", "1 | 2",
|
||||
] {
|
||||
assert!(parse_expression(bad).is_err(), "expected an error for {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_spans_point_at_the_problem() {
|
||||
let error = parse_expression("1 + )").unwrap_err();
|
||||
assert_eq!(error.span, Span::new(4, 5));
|
||||
assert!(error.to_string().contains("bytes 4..5"), "{error}");
|
||||
|
||||
let error = parse_expression("\"abc").unwrap_err();
|
||||
assert_eq!(error.span, Span::new(0, 4));
|
||||
|
||||
let error = parse_expression("1 + ").unwrap_err();
|
||||
assert_eq!(error.span, Span::new(4, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_and_input_length_are_bounded() {
|
||||
let deep = format!("{}1{}", "(".repeat(MAX_DEPTH + 4), ")".repeat(MAX_DEPTH + 4));
|
||||
let error = parse_expression(&deep).unwrap_err();
|
||||
assert!(error.message.contains("nested too deeply"), "{}", error.message);
|
||||
|
||||
let shallow = format!("{}1{}", "(".repeat(100), ")".repeat(100));
|
||||
assert_eq!(round_trip(&shallow), "1");
|
||||
|
||||
let long = "1".repeat(MAX_INPUT_LEN + 1);
|
||||
let error = parse_expression(&long).unwrap_err();
|
||||
assert!(error.message.contains("too long"), "{}", error.message);
|
||||
// Tokenizing itself is unbounded; only the expression/query entrypoints apply limits.
|
||||
assert!(tokenize(&" ".repeat(MAX_INPUT_LEN + 1)).is_ok());
|
||||
|
||||
let long_query = format!("EVALUATE ROW({})", vec!["\"A\", 1"; 1_200].join(", "));
|
||||
assert!(long_query.len() > MAX_INPUT_LEN && long_query.len() < MAX_QUERY_LEN);
|
||||
assert!(parse_query(&long_query).is_ok(), "queries may exceed the expression limit");
|
||||
let huge_query = " ".repeat(MAX_QUERY_LEN + 1);
|
||||
assert!(parse_query(&huge_query).unwrap_err().message.contains("query is too long"));
|
||||
|
||||
let chain = vec!["1"; 1_000].join(" + ");
|
||||
assert!(chain.len() < MAX_INPUT_LEN);
|
||||
assert!(parse_expression(&chain).is_err(), "a 1,000-term chain exceeds the nesting limit");
|
||||
let short = vec!["1"; 200].join(" + ");
|
||||
assert_eq!(round_trip(&short), short);
|
||||
// A flat list of sibling expressions must not accumulate the depth of their internal
|
||||
// binary folds.
|
||||
let args = (0..300).map(|i| format!("{i} + 1")).collect::<Vec<_>>().join(", ");
|
||||
let call = format!("ROW({args})");
|
||||
assert!(call.len() < MAX_INPUT_LEN);
|
||||
assert!(parse_expression(&call).is_ok());
|
||||
// Parentheses disappear from the AST, so a grouped chain keeps its depth; adding more
|
||||
// folds around it must still hit the limit.
|
||||
let inner = vec!["1"; 200].join(" + ");
|
||||
let outer = format!("({inner}) + {}", vec!["1"; 100].join(" + "));
|
||||
assert!(outer.len() < MAX_INPUT_LEN);
|
||||
assert!(parse_expression(&outer).is_err(), "a grouped 300-term chain exceeds the nesting limit");
|
||||
let ok_inner = vec!["1"; 100].join(" + ");
|
||||
let ok_outer = format!("({ok_inner}) + {}", vec!["1"; 100].join(" + "));
|
||||
assert!(parse_expression(&ok_outer).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spans_are_byte_offsets_and_ignored_by_ast_equality() {
|
||||
let expr = expression("1 + 23");
|
||||
assert_eq!(expr.span, Span::new(0, 6));
|
||||
let (_, left, right) = binary(&expr);
|
||||
assert_eq!(left.span, Span::new(0, 1));
|
||||
assert_eq!(right.span, Span::new(4, 6));
|
||||
|
||||
assert_eq!(expression("1 + 2"), expression(" 1 + 2 "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexer_tokens_keywords_and_arrow() {
|
||||
let tokens = tokenize("NOT true").unwrap();
|
||||
assert_eq!(tokens.first().map(|t| &t.kind), Some(&TokenKind::Not));
|
||||
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::Ident("true".into())));
|
||||
assert_eq!(tokens.get(2).map(|t| &t.kind), Some(&TokenKind::Eof));
|
||||
|
||||
let tokens = tokenize("x => y").unwrap();
|
||||
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::Arrow));
|
||||
|
||||
let tokens = tokenize("value in {1}").unwrap();
|
||||
assert_eq!(tokens.get(1).map(|t| &t.kind), Some(&TokenKind::In));
|
||||
}
|
||||
@@ -0,0 +1,741 @@
|
||||
//! DAX data types, literal classification, static inference and operator result tables.
|
||||
//!
|
||||
//! The eight scalar types are [`DataType`]'s variants, matching
|
||||
//! <https://dax.guide/datatypes/>: Binary, Boolean, Currency, DateTime, Decimal, Integer,
|
||||
//! String and Variant. [`PseudoType`] adds `BLANK` and `Table`, which Microsoft documents as DAX
|
||||
//! types but dax.guide does not list among the eight. They are inference results, not members of
|
||||
//! [`DataType`].
|
||||
//!
|
||||
//! # Parser-level versus evaluator-level
|
||||
//!
|
||||
//! This module is static. It classifies literals, infers types for expressions built from
|
||||
//! literals and operators, and reports clearly incompatible operands from the documented
|
||||
//! operator tables. It never evaluates an expression.
|
||||
//!
|
||||
//! The following belong to the evaluator and are deliberately absent:
|
||||
//!
|
||||
//! - text-to-number, text-to-date and text-to-Boolean parsing, and the conversion errors when
|
||||
//! text is not numeric (`"22" + 22` succeeds only when the text parses);
|
||||
//! - BLANK substitution, the BLANK truth tables, `0/BLANK` (NaN) and `5/BLANK` (Infinity);
|
||||
//! - Currency rounding/truncation and the fixed-point versus floating-point rules for `*` and
|
||||
//! `/`;
|
||||
//! - integer overflow at runtime (literal overflow is a lexer error);
|
||||
//! - IEEE-754 precision and equality (`0.1 + 0.2 = 0.3` can be false);
|
||||
//! - string collation, case folding and trailing-space trimming;
|
||||
//! - date normalization in `DATE`/`TIME`, date subtraction at runtime, and Variant dispatch.
|
||||
//!
|
||||
//! # Documented conflicts
|
||||
//!
|
||||
//! The published rules are not one consistent lattice; this module preserves the operator
|
||||
//! tables instead of "fixing" them:
|
||||
//!
|
||||
//! - `*` is documented as `Integer * DateTime -> Integer` and `Currency * DateTime ->
|
||||
//! Currency`, although no DateTime row exists in the source table. The table is reproduced
|
||||
//! cell for cell; a DateTime on the left of `*` is reported as a type error.
|
||||
//! - Subtraction of two DateTimes is documented as DateTime, while engines commonly produce a
|
||||
//! day count. The documented cell is used and the discrepancy is noted in [`TypeMetadata`].
|
||||
//! - Microsoft's comparison pages both say text is not compared with numbers (an error) and
|
||||
//! that a Boolean > String > numeric type rank makes such comparisons succeed. The operator
|
||||
//! reference's "error" rule is modelled: comparing String with a numeric type is a
|
||||
//! [`TypeError`]. String comparisons are case-insensitive and accent-sensitive at runtime.
|
||||
//! - Currency and Integer endpoint documentation disagree. The ranges recorded in
|
||||
//! [`TypeMetadata`] name the disagreement instead of picking a silent winner.
|
||||
//! - Excel's embedded engine rejects `==`; dax.guide documents it and this crate parses it.
|
||||
//! Strict equality is still modelled here: `==` does not coerce BLANK.
|
||||
//! - `dt"..."` literals are a Power BI/SSAS feature (August 2021 onwards) and are not supported
|
||||
//! by every engine version, despite being documented DAX syntax.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::ast::{BinaryOp, Call, Expr, ExprKind, Literal, UnaryOp};
|
||||
|
||||
/// The eight scalar DAX data types, in dax.guide's listing order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum DataType {
|
||||
Binary,
|
||||
Boolean,
|
||||
Currency,
|
||||
DateTime,
|
||||
Decimal,
|
||||
Integer,
|
||||
String,
|
||||
Variant,
|
||||
}
|
||||
|
||||
impl DataType {
|
||||
/// Every scalar type, in dax.guide's listing order.
|
||||
pub const ALL: [DataType; 8] = [
|
||||
DataType::Binary,
|
||||
DataType::Boolean,
|
||||
DataType::Currency,
|
||||
DataType::DateTime,
|
||||
DataType::Decimal,
|
||||
DataType::Integer,
|
||||
DataType::String,
|
||||
DataType::Variant,
|
||||
];
|
||||
|
||||
/// The type's canonical display name.
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
DataType::Binary => "Binary",
|
||||
DataType::Boolean => "Boolean",
|
||||
DataType::Currency => "Currency",
|
||||
DataType::DateTime => "DateTime",
|
||||
DataType::Decimal => "Decimal",
|
||||
DataType::Integer => "Integer",
|
||||
DataType::String => "String",
|
||||
DataType::Variant => "Variant",
|
||||
}
|
||||
}
|
||||
|
||||
/// Representation, literal availability, range, precision and notes.
|
||||
pub const fn metadata(self) -> TypeMetadata {
|
||||
match self {
|
||||
DataType::Binary => TypeMetadata {
|
||||
name: "Binary",
|
||||
representation: "opaque byte sequence; not usable as a DAX expression value",
|
||||
literal_syntax: None,
|
||||
range: "up to 67,108,864 bytes per value in SSAS tabular; unsupported in Power BI models",
|
||||
precision: "opaque bytes",
|
||||
notes: "A model-only type. No DAX operator or function produces or consumes Binary, so it is inert for tokenizing, parsing and typing.",
|
||||
},
|
||||
DataType::Boolean => TypeMetadata {
|
||||
name: "Boolean",
|
||||
representation: "TRUE or FALSE, nullable",
|
||||
literal_syntax: Some("TRUE | FALSE (case-insensitive); TRUE() and FALSE() are equivalent calls"),
|
||||
range: "TRUE, FALSE",
|
||||
precision: "exact",
|
||||
notes: "TRUE is 1 and FALSE is 0 when a numeric operator needs a number (TRUE + 1 = 2), but comparisons only pair Boolean with Boolean. BLANK is coerced to FALSE for =, not for ==.",
|
||||
},
|
||||
DataType::Currency => TypeMetadata {
|
||||
name: "Currency",
|
||||
representation: "64-bit signed integer scaled by 10,000 (fixed four decimal places)",
|
||||
literal_syntax: None,
|
||||
range: "about -922,337,203,685,477.5807 to 922,337,203,685,477.5807; Power BI, SSAS and Excel documentation disagree at the endpoints",
|
||||
precision: "four decimal places, 19 significant digits",
|
||||
notes: "No literal. Produced by Currency columns, CURRENCY() and CONVERT(..., CURRENCY) (where DECIMAL is an alias for Currency), plus aggregation over Currency columns. Addition and subtraction keep fixed-point rules; multiplication and division may yield a floating-point result.",
|
||||
},
|
||||
DataType::DateTime => TypeMetadata {
|
||||
name: "DateTime",
|
||||
representation: "double: whole days since 1899-12-30, fraction is the time of day",
|
||||
literal_syntax: Some("dt\"YYYY-MM-DD\", dt\"YYYY-MM-DDThh:mm:ss\" or dt\"YYYY-MM-DD hh:mm:ss\""),
|
||||
range: "serial 0 is 1899-12-30; maximum is 9999-12-31 00:00:00. Engine support before 1900-03-01 is documented as unreliable, and minimum-date documentation conflicts",
|
||||
precision: "Power BI stores time at 1/300 second (3.33 ms)",
|
||||
notes: "dt literals were introduced in Power BI Desktop (August 2021) and later in AS/Power Pivot, so not every engine version accepts them. Locale-sensitive text parsing uses DATEVALUE/TIMEVALUE and belongs to the evaluator. Two dates subtracted are documented as DateTime even though engines commonly return a day count.",
|
||||
},
|
||||
DataType::Decimal => TypeMetadata {
|
||||
name: "Decimal",
|
||||
representation: "IEEE-754 64-bit double (TOM Double / SQL Float)",
|
||||
literal_syntax: Some("digits with a decimal point or exponent: 3.14, .5, 1., 1e3; the sign is the unary operator"),
|
||||
range: "-1.79e308 to 1.79e308; NaN and Infinity can result from operations but have no literals",
|
||||
precision: "approximately 15-17 significant digits; values are approximate",
|
||||
notes: "Division always yields Decimal, including Integer/Integer. Equality is sensitive to binary representation, so compare with tolerance where appropriate. Integer or Currency arithmetic that promotes yields Decimal.",
|
||||
},
|
||||
DataType::Integer => TypeMetadata {
|
||||
name: "Integer",
|
||||
representation: "64-bit signed integer (Int64)",
|
||||
literal_syntax: Some("digit sequence such as 42; the sign is the unary operator"),
|
||||
range: "-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (i64). SSAS documents a narrower range because the endpoints are reserved as null sentinels",
|
||||
precision: "exact",
|
||||
notes: "There is no integer division: / always yields Decimal. Literal overflow is a lexer error; runtime overflow is an evaluator concern. The literal i64::MIN cannot be written, because the sign is a unary operator and its unsigned magnitude overflows.",
|
||||
},
|
||||
DataType::String => TypeMetadata {
|
||||
name: "String",
|
||||
representation: "UTF-16 Unicode text",
|
||||
literal_syntax: Some("\"text\" with doubled quotes, e.g. \"Say \"\"hi\"\"\""),
|
||||
range: "engine-dependent; about 32,000 characters in Power BI and larger in the Excel Data Model",
|
||||
precision: "Unicode characters; trailing spaces are trimmed by the engine, leading spaces are significant",
|
||||
notes: "The empty string \"\" is not BLANK. Comparison is case-insensitive and accent-sensitive in the engine. Text is not implicitly compared with numbers (the engine errors), but numeric text participates in arithmetic when it parses.",
|
||||
},
|
||||
DataType::Variant => TypeMetadata {
|
||||
name: "Variant",
|
||||
representation: "runtime-tagged scalar: Boolean, Integer, Currency, Decimal, DateTime, String or BLANK",
|
||||
literal_syntax: None,
|
||||
range: "the union of the scalar types",
|
||||
precision: "depends on the runtime type",
|
||||
notes: "Produced by expressions with mixed-type branches (IF, SWITCH, COALESCE) and some measures. Not a column type in a regular table, and Microsoft's syntax page states DAX does not support Variant; dax.guide and SSAS clarify that expression-level Variant exists. No literal and no operators of its own.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Integer, Currency and Decimal are the numeric types (Boolean coerces to 1/0 in numeric
|
||||
/// operators but is not itself numeric).
|
||||
pub const fn is_numeric(self) -> bool {
|
||||
matches!(self, DataType::Integer | DataType::Currency | DataType::Decimal)
|
||||
}
|
||||
|
||||
/// Whether a literal of this type can be written in DAX.
|
||||
pub const fn has_literal(self) -> bool {
|
||||
self.metadata().literal_syntax.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// `BLANK` and `Table` are DAX types in Microsoft's documentation but not members of
|
||||
/// dax.guide's eight-type list. They are inference results, never [`DataType`] values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PseudoType {
|
||||
Blank,
|
||||
Table,
|
||||
}
|
||||
|
||||
impl PseudoType {
|
||||
pub const ALL: [PseudoType; 2] = [PseudoType::Blank, PseudoType::Table];
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
PseudoType::Blank => "BLANK",
|
||||
PseudoType::Table => "Table",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn metadata(self) -> TypeMetadata {
|
||||
match self {
|
||||
PseudoType::Blank => TypeMetadata {
|
||||
name: "BLANK",
|
||||
representation: "the absence of a value; distinct from 0, \"\" and FALSE",
|
||||
literal_syntax: None,
|
||||
range: "not applicable",
|
||||
precision: "not applicable",
|
||||
notes: "There is no BLANK literal: BLANK() is a zero-argument function. Polymorphic: BLANK()+5 = 5, BLANK()*5 = BLANK, BLANK()=0 is TRUE. Do not silently treat BLANK as Integer; coercion depends on the operator and the other operand.",
|
||||
},
|
||||
PseudoType::Table => TypeMetadata {
|
||||
name: "Table",
|
||||
representation: "a set of rows and columns; non-scalar",
|
||||
literal_syntax: Some("table constructor { value, ... } or { (value, ...), ... }, plus table references"),
|
||||
range: "not applicable",
|
||||
precision: "not applicable",
|
||||
notes: "DAX has no row-value type: ROW(...) returns a one-row table. A single-column single-row table may be used as a scalar in an expression context; that is a type-checking special case, not a literal rule.",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of type documentation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TypeMetadata {
|
||||
/// Display name (`Integer`, `BLANK`, `Table`).
|
||||
pub name: &'static str,
|
||||
/// Internal or model representation.
|
||||
pub representation: &'static str,
|
||||
/// The literal syntax, or `None` when the type has no literal.
|
||||
pub literal_syntax: Option<&'static str>,
|
||||
/// Documented range, including conflicting endpoints where they exist.
|
||||
pub range: &'static str,
|
||||
/// Documented precision.
|
||||
pub precision: &'static str,
|
||||
/// Behaviour a static type checker cannot model.
|
||||
pub notes: &'static str,
|
||||
}
|
||||
|
||||
/// The result of static type inference.
|
||||
///
|
||||
/// [`InferredType::Unknown`] is not a DAX type: it means the expression's type depends on the
|
||||
/// model, a column, a measure or a function catalog. It is distinct from
|
||||
/// [`InferredType::Data(DataType::Variant)`], which is a real expression-level DAX type.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum InferredType {
|
||||
Data(DataType),
|
||||
Blank,
|
||||
Table,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl InferredType {
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
InferredType::Data(data_type) => data_type.name(),
|
||||
InferredType::Blank => "BLANK",
|
||||
InferredType::Table => "Table",
|
||||
InferredType::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn data(self) -> Option<DataType> {
|
||||
match self {
|
||||
InferredType::Data(data_type) => Some(data_type),
|
||||
InferredType::Blank | InferredType::Table | InferredType::Unknown => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DataType> for InferredType {
|
||||
fn from(value: DataType) -> Self {
|
||||
InferredType::Data(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PseudoType> for InferredType {
|
||||
fn from(value: PseudoType) -> Self {
|
||||
match value {
|
||||
PseudoType::Blank => InferredType::Blank,
|
||||
PseudoType::Table => InferredType::Table,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A static type error: operators applied to operands with no documented result type.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TypeError {
|
||||
/// The binary operator has no result for these operands, or was used with the wrong kind
|
||||
/// of API (for example `Eq` passed to [`arithmetic_type`]).
|
||||
IncompatibleOperands { op: BinaryOp, left: InferredType, right: InferredType },
|
||||
/// Unary `+`, `-` or `NOT` cannot be applied to this operand.
|
||||
IncompatibleUnaryOperand { op: UnaryOp, operand: InferredType },
|
||||
/// Two values have no documented common comparison type (used by
|
||||
/// [`comparison_coercion`], which takes no operator).
|
||||
IncompatibleTypes { left: InferredType, right: InferredType },
|
||||
}
|
||||
|
||||
impl fmt::Display for TypeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
TypeError::IncompatibleOperands { op, left, right } => {
|
||||
write!(f, "operator `{}` cannot combine {} and {}", op.symbol(), left.name(), right.name())
|
||||
}
|
||||
TypeError::IncompatibleUnaryOperand { op, operand } => {
|
||||
write!(f, "unary operator `{}` cannot be applied to {}", op.symbol(), operand.name())
|
||||
}
|
||||
TypeError::IncompatibleTypes { left, right } => {
|
||||
write!(f, "types {} and {} have no common comparison type", left.name(), right.name())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TypeError {}
|
||||
|
||||
/// Classifies a literal. Every literal form maps to one of the eight scalar types; BLANK has
|
||||
/// no literal form.
|
||||
pub const fn literal_type(literal: &Literal) -> DataType {
|
||||
match literal {
|
||||
Literal::Integer(_) => DataType::Integer,
|
||||
Literal::Decimal(_) => DataType::Decimal,
|
||||
Literal::DateTime(_) => DataType::DateTime,
|
||||
Literal::String(_) => DataType::String,
|
||||
Literal::Boolean(_) => DataType::Boolean,
|
||||
}
|
||||
}
|
||||
|
||||
/// A scalar operand's type: a table-valued call may still resolve to a single row/column at
|
||||
/// evaluation time (`LASTDATE('Date'[Date]) - 1`), so it is unknown here rather than a table.
|
||||
fn scalar_operand(expr: &Expr) -> Result<InferredType, TypeError> {
|
||||
let inferred = infer_type(expr)?;
|
||||
// A `VAR`/`RETURN` block is transparent for this check: its body is what the operator sees,
|
||||
// so `(VAR d = 1 RETURN LASTDATE('Date'[Date])) - 1` is the same table-valued operand as the
|
||||
// unwrapped call and must be rejected identically.
|
||||
let mut inner = expr;
|
||||
while let ExprKind::VarReturn { body, .. } = &inner.kind {
|
||||
inner = body;
|
||||
}
|
||||
Ok(if inferred == InferredType::Table && matches!(&inner.kind, ExprKind::Call(_)) { InferredType::Unknown } else { inferred })
|
||||
}
|
||||
|
||||
/// Infers the static type of an expression.
|
||||
///
|
||||
/// Name references are [`InferredType::Unknown`] (they need the model). Catalogued calls take
|
||||
/// their documented [`crate::functions::ReturnType`]; unknown functions and `Any`/`Numeric`
|
||||
/// return types stay unknown. Incompatible known operands produce a [`TypeError`].
|
||||
pub fn infer_type(expr: &Expr) -> Result<InferredType, TypeError> {
|
||||
match &expr.kind {
|
||||
ExprKind::Literal(literal) => Ok(InferredType::Data(literal_type(literal))),
|
||||
ExprKind::Name(_) => Ok(InferredType::Unknown),
|
||||
ExprKind::Call(call) => {
|
||||
// The call itself may be unknown without a signature catalog, but every argument
|
||||
// still has to type-check.
|
||||
for arg in &call.args {
|
||||
infer_type(arg)?;
|
||||
}
|
||||
Ok(call_type(call))
|
||||
}
|
||||
ExprKind::Unary { op, expr } => {
|
||||
let operand = scalar_operand(expr)?;
|
||||
unary_type(*op, operand)
|
||||
}
|
||||
ExprKind::Binary { op, left, right } => {
|
||||
// `(a, b) IN { (a, b), ... }` uses a row constructor on the left, not a table
|
||||
// expression. Validate its elements but let the operator comparison handle the
|
||||
// row value.
|
||||
let left = match (&left.kind, op) {
|
||||
(ExprKind::Tuple(items), BinaryOp::In) => {
|
||||
for item in items {
|
||||
infer_type(item)?;
|
||||
}
|
||||
InferredType::Unknown
|
||||
}
|
||||
_ if *op == BinaryOp::In => infer_type(left)?,
|
||||
_ => scalar_operand(left)?,
|
||||
};
|
||||
let right = if *op == BinaryOp::In { infer_type(right)? } else { scalar_operand(right)? };
|
||||
binary_type(*op, left, right)
|
||||
}
|
||||
ExprKind::Table(items) | ExprKind::Tuple(items) => {
|
||||
// Containers are tables, but their elements still have to type-check.
|
||||
for item in items {
|
||||
infer_type(item)?;
|
||||
}
|
||||
Ok(InferredType::Table)
|
||||
}
|
||||
// Variable references are names, so their values are unknown without an environment; the
|
||||
// block's type is the type of its `RETURN` expression. Every declaration still has to
|
||||
// type-check, even when the body does not use it.
|
||||
ExprKind::VarReturn { vars, body } => {
|
||||
for var in vars {
|
||||
infer_type(&var.expr)?;
|
||||
}
|
||||
infer_type(body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The documented return type of a catalogued function, mapped onto the static type model.
|
||||
///
|
||||
/// `Numeric` stays [`InferredType::Unknown`] because its concrete type (Integer, Currency or
|
||||
/// Decimal) follows the inputs; `Any`/unknown signatures stay unknown as well.
|
||||
fn call_type(call: &Call) -> InferredType {
|
||||
if call.args.is_empty() {
|
||||
if call.name.text.eq_ignore_ascii_case("TRUE") || call.name.text.eq_ignore_ascii_case("FALSE") {
|
||||
return InferredType::Data(DataType::Boolean);
|
||||
}
|
||||
if call.name.text.eq_ignore_ascii_case("BLANK") {
|
||||
return InferredType::Blank;
|
||||
}
|
||||
}
|
||||
let Some(spec) = crate::functions::lookup(&call.name.text) else {
|
||||
return InferredType::Unknown;
|
||||
};
|
||||
match spec.return_type {
|
||||
crate::functions::ReturnType::Integer => InferredType::Data(DataType::Integer),
|
||||
crate::functions::ReturnType::Decimal => InferredType::Data(DataType::Decimal),
|
||||
crate::functions::ReturnType::Numeric => InferredType::Unknown,
|
||||
crate::functions::ReturnType::Currency => InferredType::Data(DataType::Currency),
|
||||
crate::functions::ReturnType::Boolean => InferredType::Data(DataType::Boolean),
|
||||
crate::functions::ReturnType::DateTime => InferredType::Data(DataType::DateTime),
|
||||
crate::functions::ReturnType::String => InferredType::Data(DataType::String),
|
||||
crate::functions::ReturnType::Variant => InferredType::Data(DataType::Variant),
|
||||
crate::functions::ReturnType::Table => InferredType::Table,
|
||||
crate::functions::ReturnType::Blank => InferredType::Blank,
|
||||
crate::functions::ReturnType::Any => InferredType::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Infers the result type of a unary operator. `+` and `-` preserve the numeric type (DateTime
|
||||
/// keeps its serial type); `NOT` always yields Boolean. A BLANK operand stays polymorphic
|
||||
/// instead of becoming Integer.
|
||||
pub fn unary_type(op: UnaryOp, operand: InferredType) -> Result<InferredType, TypeError> {
|
||||
match op {
|
||||
UnaryOp::Not => match operand {
|
||||
InferredType::Table | InferredType::Data(DataType::Binary) => Err(TypeError::IncompatibleUnaryOperand { op, operand }),
|
||||
_ => Ok(InferredType::Data(DataType::Boolean)),
|
||||
},
|
||||
UnaryOp::Plus | UnaryOp::Neg => match operand {
|
||||
InferredType::Data(DataType::Integer) => Ok(InferredType::Data(DataType::Integer)),
|
||||
InferredType::Data(DataType::Currency) => Ok(InferredType::Data(DataType::Currency)),
|
||||
InferredType::Data(DataType::Decimal) => Ok(InferredType::Data(DataType::Decimal)),
|
||||
// TRUE/FALSE are 1/0 when a numeric operator needs a number.
|
||||
InferredType::Data(DataType::Boolean) => Ok(InferredType::Data(DataType::Integer)),
|
||||
InferredType::Data(DataType::Variant) => Ok(InferredType::Data(DataType::Variant)),
|
||||
// DAX documents unary `-` as preserving the operand type, and DateTime is a serial.
|
||||
InferredType::Data(DataType::DateTime) => Ok(InferredType::Data(DataType::DateTime)),
|
||||
// A text operand may parse as a number at runtime.
|
||||
InferredType::Data(DataType::String) | InferredType::Unknown => Ok(InferredType::Unknown),
|
||||
InferredType::Blank => Ok(InferredType::Blank),
|
||||
InferredType::Data(DataType::Binary) | InferredType::Table => Err(TypeError::IncompatibleUnaryOperand { op, operand }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Infers the result type of a binary operator using the documented DAX tables.
|
||||
pub fn binary_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
|
||||
match op {
|
||||
BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow => arithmetic_type(op, left, right),
|
||||
BinaryOp::Concat => {
|
||||
reject_non_scalar(op, left, right)?;
|
||||
Ok(InferredType::Data(DataType::String))
|
||||
}
|
||||
BinaryOp::And | BinaryOp::Or => {
|
||||
reject_non_scalar(op, left, right)?;
|
||||
Ok(InferredType::Data(DataType::Boolean))
|
||||
}
|
||||
BinaryOp::Eq | BinaryOp::StrictEq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => {
|
||||
comparison_type(op, left, right).map(InferredType::Data)
|
||||
}
|
||||
BinaryOp::In => in_type(op, left, right),
|
||||
}
|
||||
}
|
||||
|
||||
/// `IN` always yields Boolean. Its right operand is a table expression (`{ ... }`, a table
|
||||
/// reference or `VALUES(...)`), not a scalar.
|
||||
fn in_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
|
||||
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary)) {
|
||||
return Err(TypeError::IncompatibleOperands { op, left, right });
|
||||
}
|
||||
match right {
|
||||
InferredType::Table | InferredType::Unknown | InferredType::Data(DataType::Variant) => Ok(InferredType::Data(DataType::Boolean)),
|
||||
InferredType::Data(_) | InferredType::Blank => Err(TypeError::IncompatibleOperands { op, left, right }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Infers the result of `+`, `-`, `*`, `/` or `^`.
|
||||
///
|
||||
/// Unknown operands stay unknown. Text operands stay unknown because only the evaluator can
|
||||
/// decide whether the text parses as a number. Variant propagates. BLANK is polymorphic and
|
||||
/// follows the documented special cases instead of being treated as Integer.
|
||||
pub fn arithmetic_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
|
||||
if !matches!(op, BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div | BinaryOp::Pow) {
|
||||
return Err(TypeError::IncompatibleOperands { op, left, right });
|
||||
}
|
||||
reject_non_scalar(op, left, right)?;
|
||||
|
||||
if left == InferredType::Blank || right == InferredType::Blank {
|
||||
return blank_arithmetic(op, left, right);
|
||||
}
|
||||
if matches!(left, InferredType::Data(DataType::Variant)) || matches!(right, InferredType::Data(DataType::Variant)) {
|
||||
return Ok(InferredType::Data(DataType::Variant));
|
||||
}
|
||||
if left == InferredType::Unknown || right == InferredType::Unknown {
|
||||
return Ok(InferredType::Unknown);
|
||||
}
|
||||
if matches!(left, InferredType::Data(DataType::String)) || matches!(right, InferredType::Data(DataType::String)) {
|
||||
// `"22" + 22` succeeds only if the text parses; that is evaluator work.
|
||||
return Ok(InferredType::Unknown);
|
||||
}
|
||||
|
||||
let converted_left = coerce_boolean(left);
|
||||
let converted_right = coerce_boolean(right);
|
||||
let (Some(left_data), Some(right_data)) = (converted_left.data(), converted_right.data()) else {
|
||||
return Err(TypeError::IncompatibleOperands { op, left, right });
|
||||
};
|
||||
|
||||
let result = match op {
|
||||
BinaryOp::Add => numeric_cell(&ADDITION, left_data, right_data),
|
||||
BinaryOp::Sub => numeric_cell(&SUBTRACTION, left_data, right_data),
|
||||
BinaryOp::Mul => multiplication_cell(left_data, right_data),
|
||||
BinaryOp::Div => numeric_cell(&DIVISION, left_data, right_data),
|
||||
BinaryOp::Pow => match (left_data, right_data) {
|
||||
// `^` is not covered by the conversion tables; the engine computes a double.
|
||||
(DataType::DateTime, _) | (_, DataType::DateTime) => None,
|
||||
_ => Some(DataType::Decimal),
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
result.map(InferredType::Data).ok_or(TypeError::IncompatibleOperands { op, left, right })
|
||||
}
|
||||
|
||||
/// BLANK arithmetic follows the documented special cases:
|
||||
/// `BLANK()+5 = 5`, `BLANK()*5 = BLANK`, `5/BLANK() = Infinity` and
|
||||
/// `BLANK()/BLANK() = BLANK`. The runtime values are evaluator work; only the result types are
|
||||
/// recorded here.
|
||||
fn blank_arithmetic(op: BinaryOp, left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
|
||||
let left_blank = left == InferredType::Blank;
|
||||
let right_blank = right == InferredType::Blank;
|
||||
match op {
|
||||
BinaryOp::Add | BinaryOp::Sub => {
|
||||
if left_blank && right_blank {
|
||||
Ok(InferredType::Blank)
|
||||
} else {
|
||||
let other = if left_blank { right } else { left };
|
||||
Ok(neutral_arithmetic(other))
|
||||
}
|
||||
}
|
||||
// BLANK is absorbing in multiplication.
|
||||
BinaryOp::Mul => Ok(InferredType::Blank),
|
||||
BinaryOp::Div => {
|
||||
if left_blank {
|
||||
if right_blank {
|
||||
Ok(InferredType::Blank)
|
||||
} else if right == InferredType::Unknown {
|
||||
Ok(InferredType::Unknown)
|
||||
} else {
|
||||
Ok(InferredType::Blank)
|
||||
}
|
||||
} else if right_blank {
|
||||
if left == InferredType::Unknown {
|
||||
Ok(InferredType::Unknown)
|
||||
} else {
|
||||
// 5/BLANK() is Infinity and 0/BLANK() is NaN: both are Decimal.
|
||||
Ok(InferredType::Data(DataType::Decimal))
|
||||
}
|
||||
} else {
|
||||
Ok(InferredType::Unknown)
|
||||
}
|
||||
}
|
||||
// The evaluator coerces a BLANK operand to 0 and answers a number, so exponentiation is
|
||||
// Decimal rather than Blank.
|
||||
BinaryOp::Pow => Ok(InferredType::Data(DataType::Decimal)),
|
||||
_ => Err(TypeError::IncompatibleOperands { op, left, right }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of `BLANK + x` / `BLANK - x`: BLANK is neutral, so `x`'s numeric type survives.
|
||||
fn neutral_arithmetic(other: InferredType) -> InferredType {
|
||||
match other {
|
||||
InferredType::Data(DataType::Boolean) => InferredType::Data(DataType::Integer),
|
||||
InferredType::Data(DataType::String) => InferredType::Unknown,
|
||||
InferredType::Data(DataType::Variant) => InferredType::Data(DataType::Variant),
|
||||
InferredType::Data(DataType::Binary) | InferredType::Table => InferredType::Unknown,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
const fn coerce_boolean(value: InferredType) -> InferredType {
|
||||
match value {
|
||||
InferredType::Data(DataType::Boolean) => InferredType::Data(DataType::Integer),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the common type for a non-strict comparison (`=`, `<>`, `<`, `>`, `<=`, `>=`).
|
||||
///
|
||||
/// BLANK is coerced to the other operand's type (`0`, `""` or `FALSE` according to that type):
|
||||
/// `BLANK() = 0` is TRUE. Text is never compared implicitly with a number or a Boolean; those
|
||||
/// combinations are a [`TypeError`]. `==` does not use this function, because strict equality
|
||||
/// does not coerce BLANK.
|
||||
pub fn comparison_coercion(left: InferredType, right: InferredType) -> Result<InferredType, TypeError> {
|
||||
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary))
|
||||
|| matches!(right, InferredType::Table | InferredType::Data(DataType::Binary))
|
||||
{
|
||||
return Err(TypeError::IncompatibleTypes { left, right });
|
||||
}
|
||||
if left == InferredType::Blank && right == InferredType::Blank {
|
||||
return Ok(InferredType::Blank);
|
||||
}
|
||||
if left == InferredType::Blank {
|
||||
return Ok(right);
|
||||
}
|
||||
if right == InferredType::Blank {
|
||||
return Ok(left);
|
||||
}
|
||||
match (left, right) {
|
||||
(InferredType::Unknown, _) | (_, InferredType::Unknown) => Ok(InferredType::Unknown),
|
||||
(InferredType::Data(DataType::Variant), _) | (_, InferredType::Data(DataType::Variant)) => Ok(InferredType::Data(DataType::Variant)),
|
||||
(InferredType::Data(DataType::Boolean), InferredType::Data(DataType::Boolean)) => Ok(InferredType::Data(DataType::Boolean)),
|
||||
(InferredType::Data(DataType::String), InferredType::Data(DataType::String)) => Ok(InferredType::Data(DataType::String)),
|
||||
(InferredType::Data(left_data), InferredType::Data(right_data)) => {
|
||||
numeric_cell(&COMPARISON, left_data, right_data).map(InferredType::Data).ok_or(TypeError::IncompatibleTypes { left, right })
|
||||
}
|
||||
(InferredType::Table, _) | (_, InferredType::Table) => Err(TypeError::IncompatibleTypes { left, right }),
|
||||
// BLANK returns above; this arm keeps the match exhaustive without a panic.
|
||||
(InferredType::Blank, _) | (_, InferredType::Blank) => Ok(InferredType::Blank),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks whether a comparison operator accepts the two operands.
|
||||
///
|
||||
/// Non-strict operators use [`comparison_coercion`]. `==` is strict: BLANK is never replaced
|
||||
/// with `0`, `""` or FALSE, though a BLANK operand is still comparable. Numeric/DateTime
|
||||
/// pairs keep the documented comparison matrix; String/Boolean pairs are same-type only.
|
||||
pub fn comparison_compatible(op: BinaryOp, left: InferredType, right: InferredType) -> Result<(), TypeError> {
|
||||
if !op.is_comparison() {
|
||||
return Err(TypeError::IncompatibleOperands { op, left, right });
|
||||
}
|
||||
if matches!(left, InferredType::Table | InferredType::Data(DataType::Binary))
|
||||
|| matches!(right, InferredType::Table | InferredType::Data(DataType::Binary))
|
||||
{
|
||||
return Err(TypeError::IncompatibleOperands { op, left, right });
|
||||
}
|
||||
if op == BinaryOp::StrictEq {
|
||||
if left == InferredType::Blank || right == InferredType::Blank {
|
||||
return Ok(());
|
||||
}
|
||||
let compatible = matches!(
|
||||
(left, right),
|
||||
(InferredType::Unknown, _)
|
||||
| (_, InferredType::Unknown)
|
||||
| (InferredType::Data(DataType::Variant), _)
|
||||
| (_, InferredType::Data(DataType::Variant))
|
||||
| (InferredType::Data(DataType::Boolean), InferredType::Data(DataType::Boolean))
|
||||
| (InferredType::Data(DataType::String), InferredType::Data(DataType::String))
|
||||
) || matches!(
|
||||
(left.data(), right.data()),
|
||||
(Some(left_data), Some(right_data))
|
||||
if numeric_index(left_data).is_some() && numeric_index(right_data).is_some()
|
||||
);
|
||||
return if compatible { Ok(()) } else { Err(TypeError::IncompatibleOperands { op, left, right }) };
|
||||
}
|
||||
comparison_coercion(left, right).map(|_| ()).map_err(|_| TypeError::IncompatibleOperands { op, left, right })
|
||||
}
|
||||
|
||||
/// The result of any comparison is Boolean. This also checks operand compatibility.
|
||||
pub fn comparison_type(op: BinaryOp, left: InferredType, right: InferredType) -> Result<DataType, TypeError> {
|
||||
comparison_compatible(op, left, right)?;
|
||||
Ok(DataType::Boolean)
|
||||
}
|
||||
|
||||
fn reject_non_scalar(op: BinaryOp, left: InferredType, right: InferredType) -> Result<(), TypeError> {
|
||||
match (left, right) {
|
||||
(InferredType::Table, _)
|
||||
| (_, InferredType::Table)
|
||||
| (InferredType::Data(DataType::Binary), _)
|
||||
| (_, InferredType::Data(DataType::Binary)) => Err(TypeError::IncompatibleOperands { op, left, right }),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
// Documented operator result tables (rows = left operand, columns = right operand) for
|
||||
// Integer, Currency, Decimal ("Real") and DateTime. They are transcribed cell for cell.
|
||||
|
||||
const NUMERIC_ORDER: [DataType; 4] = [DataType::Integer, DataType::Currency, DataType::Decimal, DataType::DateTime];
|
||||
|
||||
const ADDITION: [[DataType; 4]; 4] = [
|
||||
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::DateTime],
|
||||
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::DateTime],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::DateTime],
|
||||
[DataType::DateTime, DataType::DateTime, DataType::DateTime, DataType::DateTime],
|
||||
];
|
||||
|
||||
const SUBTRACTION: [[DataType; 4]; 4] = [
|
||||
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::DateTime, DataType::DateTime, DataType::DateTime, DataType::DateTime],
|
||||
];
|
||||
|
||||
const MULTIPLICATION: [[Option<DataType>; 4]; 4] = [
|
||||
[Some(DataType::Integer), Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Integer)],
|
||||
[Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Currency), Some(DataType::Currency)],
|
||||
[Some(DataType::Decimal), Some(DataType::Currency), Some(DataType::Decimal), Some(DataType::Decimal)],
|
||||
[None, None, None, None],
|
||||
];
|
||||
|
||||
const DIVISION: [[DataType; 4]; 4] = [
|
||||
[DataType::Decimal, DataType::Currency, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Currency, DataType::Decimal, DataType::Currency, DataType::Decimal],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
|
||||
];
|
||||
|
||||
const COMPARISON: [[DataType; 4]; 4] = [
|
||||
[DataType::Integer, DataType::Currency, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Currency, DataType::Currency, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::Decimal],
|
||||
[DataType::Decimal, DataType::Decimal, DataType::Decimal, DataType::DateTime],
|
||||
];
|
||||
|
||||
const fn numeric_index(data_type: DataType) -> Option<usize> {
|
||||
match data_type {
|
||||
DataType::Integer => Some(0),
|
||||
DataType::Currency => Some(1),
|
||||
DataType::Decimal => Some(2),
|
||||
DataType::DateTime => Some(3),
|
||||
DataType::Binary | DataType::Boolean | DataType::String | DataType::Variant => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn numeric_cell(matrix: &[[DataType; 4]; 4], left: DataType, right: DataType) -> Option<DataType> {
|
||||
let row = numeric_index(left)?;
|
||||
let column = numeric_index(right)?;
|
||||
matrix.get(row)?.get(column).copied()
|
||||
}
|
||||
|
||||
fn multiplication_cell(left: DataType, right: DataType) -> Option<DataType> {
|
||||
let row = numeric_index(left)?;
|
||||
let column = numeric_index(right)?;
|
||||
MULTIPLICATION.get(row)?.get(column).copied().flatten()
|
||||
}
|
||||
|
||||
/// The row/column order of the operator tables, exposed for tests and tooling that wants to
|
||||
/// verify a particular documented cell.
|
||||
pub const fn numeric_matrix_order() -> [DataType; 4] {
|
||||
NUMERIC_ORDER
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Static validation of catalogued function calls.
|
||||
//!
|
||||
//! The parser accepts any `NAME ( args )`; this module applies the catalog in
|
||||
//! [`crate::functions`] to reject what can be decided without a data model, for every catalog
|
||||
//! category:
|
||||
//!
|
||||
//! - argument counts against the documented arities (including `COUNTROWS ()` and the optional
|
||||
//! `Variant` of `MAXX`/`MINX`);
|
||||
//! - column-only parameters that are not a bracketed name reference (`SUM ( 1 )`);
|
||||
//! - table parameters that are certainly not a table: an obvious scalar literal or scalar operator
|
||||
//! expression (`COUNTROWS ( 1 )`) or a bracketed column reference (`COUNTROWS ( Sales[Amount] )`).
|
||||
//! Dynamic table expressions such as `FILTER ( ... )`, `DISTINCT ( ... )`, variables and table
|
||||
//! constructors are accepted.
|
||||
//!
|
||||
//! Unknown functions are ignored, so the validator can run over expressions that use the rest of
|
||||
//! the DAX language.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::ast::{Call, Expr, ExprKind, NameStyle, Span};
|
||||
use crate::functions::{FunctionSpec, Overload, ParamKind, lookup};
|
||||
|
||||
/// The category of a validation failure.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ValidationErrorKind {
|
||||
/// Wrong number of arguments for every documented overload.
|
||||
Arity,
|
||||
/// The argument at the reported span cannot satisfy the parameter kind.
|
||||
ArgumentKind,
|
||||
}
|
||||
|
||||
impl ValidationErrorKind {
|
||||
pub const fn description(self) -> &'static str {
|
||||
match self {
|
||||
ValidationErrorKind::Arity => "wrong number of arguments",
|
||||
ValidationErrorKind::ArgumentKind => "wrong argument kind",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One error found by [`validate_call`] or [`validate_expression`].
|
||||
///
|
||||
/// `function` is the catalog spelling, `span` is the offending argument for kind errors and the
|
||||
/// whole call for arity errors. [`validate_call`] has no span for the call itself, so arity
|
||||
/// errors it returns carry an empty span; [`validate_expression`] fills the expression span.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ValidationError {
|
||||
pub function: &'static str,
|
||||
pub kind: ValidationErrorKind,
|
||||
pub message: String,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl fmt::Display for ValidationError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} at bytes {}..{}", self.message, self.span.start, self.span.end)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ValidationError {}
|
||||
|
||||
/// Validates one call against the function catalog.
|
||||
///
|
||||
/// Returns every error the call contains, or an empty vector for a valid call and for a function
|
||||
/// that is not in the catalog. Because [`Call`] does not carry its own span, arity errors use
|
||||
/// [`Span::empty`]; use [`validate_expression`] when spans matter.
|
||||
pub fn validate_call(call: &Call) -> Vec<ValidationError> {
|
||||
validate_call_at(call, Span::empty())
|
||||
}
|
||||
|
||||
/// Walks the expression tree and reports every invalid call to a known aggregation function.
|
||||
///
|
||||
/// Unknown functions are ignored but their arguments are still visited, so a bad `SUM` nested in
|
||||
/// `CALCULATE (...)` is reported. Results are in depth-first source order.
|
||||
pub fn validate_expression(expr: &Expr) -> Vec<ValidationError> {
|
||||
let mut errors = Vec::new();
|
||||
expr.walk(&mut |node| {
|
||||
if let ExprKind::Call(call) = &node.kind {
|
||||
errors.extend(validate_call_at(call, node.span));
|
||||
}
|
||||
});
|
||||
errors
|
||||
}
|
||||
|
||||
fn validate_call_at(call: &Call, call_span: Span) -> Vec<ValidationError> {
|
||||
let Some(spec) = lookup(&call.name.text) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let arity = call.args.len();
|
||||
if arity < spec.min_args || arity > spec.max_args {
|
||||
return vec![arity_error(spec, arity, call_span)];
|
||||
}
|
||||
let matching: Vec<&Overload> = spec.overloads.iter().filter(|overload| overload.matches(arity)).collect();
|
||||
if matching.is_empty() {
|
||||
return vec![arity_error(spec, arity, call_span)];
|
||||
}
|
||||
let mut errors = Vec::new();
|
||||
for (index, argument) in call.args.iter().enumerate() {
|
||||
if matching.iter().any(|overload| overload_accepts(overload, index, argument)) {
|
||||
continue;
|
||||
}
|
||||
let expected = expected_kinds(&matching, index);
|
||||
errors.push(ValidationError {
|
||||
function: spec.name,
|
||||
kind: ValidationErrorKind::ArgumentKind,
|
||||
message: format!("{} argument {} must be {expected}, found {}", spec.name, index + 1, describe_argument(argument)),
|
||||
span: argument.span,
|
||||
});
|
||||
}
|
||||
errors
|
||||
}
|
||||
|
||||
fn arity_error(spec: &FunctionSpec, arity: usize, span: Span) -> ValidationError {
|
||||
let expected = if spec.min_args == spec.max_args { format!("{}", spec.min_args) } else { format!("{} to {}", spec.min_args, spec.max_args) };
|
||||
ValidationError {
|
||||
function: spec.name,
|
||||
kind: ValidationErrorKind::Arity,
|
||||
message: format!("{} expects {expected} argument(s), found {arity}", spec.name),
|
||||
span,
|
||||
}
|
||||
}
|
||||
|
||||
fn overload_accepts(overload: &Overload, index: usize, argument: &Expr) -> bool {
|
||||
match overload.kind_at(index) {
|
||||
Some(kind) => accepts(kind, argument),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_kinds(overloads: &[&Overload], index: usize) -> String {
|
||||
let mut expected: Vec<&'static str> = Vec::new();
|
||||
for overload in overloads {
|
||||
let Some(kind) = overload.kind_at(index) else {
|
||||
continue;
|
||||
};
|
||||
let description = kind.description();
|
||||
if !expected.contains(&description) {
|
||||
expected.push(description);
|
||||
}
|
||||
}
|
||||
expected.join(" or ")
|
||||
}
|
||||
|
||||
/// The only argument checks that are decidable without a model.
|
||||
fn accepts(kind: ParamKind, argument: &Expr) -> bool {
|
||||
match kind {
|
||||
ParamKind::Column => is_column_reference(argument),
|
||||
ParamKind::Table => !is_obvious_scalar(argument) && !is_column_reference(argument),
|
||||
ParamKind::Expression
|
||||
| ParamKind::Scalar
|
||||
| ParamKind::Logical
|
||||
| ParamKind::Any
|
||||
| ParamKind::Date
|
||||
| ParamKind::Text
|
||||
| ParamKind::Number
|
||||
| ParamKind::Boolean
|
||||
| ParamKind::Function
|
||||
| ParamKind::Reference
|
||||
| ParamKind::Json
|
||||
| ParamKind::Variant => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_column_reference(expr: &Expr) -> bool {
|
||||
matches!(
|
||||
&expr.kind,
|
||||
ExprKind::Name(name_ref) if name_ref.name.style == NameStyle::Bracketed
|
||||
)
|
||||
}
|
||||
|
||||
/// Literals and operator expressions are certainly scalars, never tables. Names, calls, table
|
||||
/// constructors and row constructors may be dynamic table expressions, so they are not rejected.
|
||||
fn is_obvious_scalar(expr: &Expr) -> bool {
|
||||
matches!(&expr.kind, ExprKind::Literal(_) | ExprKind::Unary { .. } | ExprKind::Binary { .. })
|
||||
}
|
||||
|
||||
fn describe_argument(expr: &Expr) -> &'static str {
|
||||
match &expr.kind {
|
||||
ExprKind::Literal(_) => "a literal",
|
||||
ExprKind::Name(_) => "a name reference",
|
||||
ExprKind::Call(_) => "a function call",
|
||||
ExprKind::Unary { .. } | ExprKind::Binary { .. } => "an operator expression",
|
||||
ExprKind::Table(_) => "a table constructor",
|
||||
ExprKind::Tuple(_) => "a row constructor",
|
||||
ExprKind::VarReturn { .. } => "a VAR/RETURN expression",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
//! Runtime values for the DAX evaluator.
|
||||
//!
|
||||
//! Scalar values cover the DAX scalar types; tables are column-oriented metadata plus rows of
|
||||
//! scalars. BLANK is a distinct value, never silently zero or the empty string.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A DAX scalar value.
|
||||
///
|
||||
/// `Currency` and `DateTime` are plain numbers in DAX, so an untagged numeric representation
|
||||
/// would read them back as `Integer`/`Decimal`. They serialize as tagged JSON objects instead:
|
||||
/// `{"$currency": 1234}` (scaled by 10,000) and `{"$dateTime": 45292.5}`. Every other variant
|
||||
/// keeps its natural JSON form, so existing model files and command output stay unchanged.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Scalar {
|
||||
/// BLANK. It serializes as `null` and is the first untagged match.
|
||||
Blank,
|
||||
Boolean(bool),
|
||||
Integer(i64),
|
||||
/// Currency is an integer scaled by 10,000.
|
||||
#[serde(with = "currency_serde")]
|
||||
Currency(i64),
|
||||
/// A decimal. A finite value is a JSON number; `NaN`/`Infinity` become `{"$decimal": "NaN"}`
|
||||
/// so they survive a round trip (`serde_json` writes a non-finite float as `null`, which would
|
||||
/// read back as BLANK).
|
||||
#[serde(with = "decimal_serde")]
|
||||
Decimal(f64),
|
||||
/// DateTime is an OLE Automation serial: whole days since 1899-12-30 plus a time fraction.
|
||||
#[serde(with = "datetime_serde")]
|
||||
DateTime(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
mod currency_serde {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Tagged {
|
||||
#[serde(rename = "$currency")]
|
||||
value: i64,
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &i64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
Tagged { value: *value }.serialize(serializer)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
|
||||
Ok(Tagged::deserialize(deserializer)?.value)
|
||||
}
|
||||
}
|
||||
|
||||
mod decimals {
|
||||
/// The JSON text of a non-finite value, or `None` when it is finite.
|
||||
pub fn to_text(value: f64) -> Option<&'static str> {
|
||||
if value.is_nan() {
|
||||
Some("NaN")
|
||||
} else if value == f64::INFINITY {
|
||||
Some("Infinity")
|
||||
} else if value == f64::NEG_INFINITY {
|
||||
Some("-Infinity")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of a JSON text produced by [`to_text`].
|
||||
pub fn from_text(text: &str) -> Option<f64> {
|
||||
match text {
|
||||
"NaN" => Some(f64::NAN),
|
||||
"Infinity" => Some(f64::INFINITY),
|
||||
"-Infinity" => Some(f64::NEG_INFINITY),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod decimal_serde {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use super::decimals;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Json {
|
||||
Number(f64),
|
||||
Tagged {
|
||||
#[serde(rename = "$decimal")]
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match decimals::to_text(*value) {
|
||||
Some(text) => Json::Tagged { text: text.to_string() }.serialize(serializer),
|
||||
None => Json::Number(*value).serialize(serializer),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
|
||||
match Json::deserialize(deserializer)? {
|
||||
Json::Number(value) => Ok(value),
|
||||
Json::Tagged { text } => decimals::from_text(&text).ok_or_else(|| serde::de::Error::custom("unknown non-finite decimal")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod datetime_serde {
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use super::decimals;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Number {
|
||||
Finite(f64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Tagged {
|
||||
#[serde(rename = "$dateTime")]
|
||||
value: Number,
|
||||
}
|
||||
|
||||
pub fn serialize<S: Serializer>(value: &f64, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let value = match decimals::to_text(*value) {
|
||||
Some(text) => Number::Text(text.to_string()),
|
||||
None => Number::Finite(*value),
|
||||
};
|
||||
Tagged { value }.serialize(serializer)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f64, D::Error> {
|
||||
match Tagged::deserialize(deserializer)?.value {
|
||||
Number::Finite(value) => Ok(value),
|
||||
Number::Text(text) => decimals::from_text(&text).ok_or_else(|| serde::de::Error::custom("unknown non-finite serial")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Scalar {
|
||||
pub fn is_blank(&self) -> bool {
|
||||
matches!(self, Scalar::Blank)
|
||||
}
|
||||
|
||||
pub fn type_name(&self) -> &'static str {
|
||||
match self {
|
||||
Scalar::Blank => "BLANK",
|
||||
Scalar::Boolean(_) => "Boolean",
|
||||
Scalar::Integer(_) => "Integer",
|
||||
Scalar::Currency(_) => "Currency",
|
||||
Scalar::Decimal(_) => "Decimal",
|
||||
Scalar::DateTime(_) => "DateTime",
|
||||
Scalar::String(_) => "String",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the value is one of the four numeric variants, without coercing anything else.
|
||||
pub fn is_numeric(&self) -> bool {
|
||||
matches!(self, Scalar::Integer(_) | Scalar::Currency(_) | Scalar::Decimal(_) | Scalar::DateTime(_))
|
||||
}
|
||||
|
||||
/// DAX arithmetic coercion: BLANK is 0, booleans are 1/0, numeric text parses, dates are
|
||||
/// serials, and currency is divided by 10,000.
|
||||
pub fn to_number(&self) -> Option<f64> {
|
||||
match self {
|
||||
Scalar::Blank => Some(0.0),
|
||||
Scalar::Boolean(value) => Some(if *value { 1.0 } else { 0.0 }),
|
||||
Scalar::Integer(value) => Some(*value as f64),
|
||||
Scalar::Currency(value) => Some(*value as f64 / 10_000.0),
|
||||
Scalar::Decimal(value) | Scalar::DateTime(value) => Some(*value),
|
||||
// `f64::from_str` accepts "nan"/"inf"; DAX has no text form for those, so they are
|
||||
// not numbers here.
|
||||
Scalar::String(value) => value.trim().parse::<f64>().ok().filter(|number| number.is_finite()),
|
||||
}
|
||||
}
|
||||
|
||||
/// DAX's implicit text conversion, used by `&` and the text functions: a whole-valued number
|
||||
/// prints without a decimal point (`10`, not `10.0`) and a date prints as its calendar text.
|
||||
/// [`Scalar::to_text`] stays the storage/debug spelling other callers rely on.
|
||||
pub fn to_dax_text(&self) -> String {
|
||||
match self {
|
||||
Scalar::Decimal(value) if value.is_finite() && value.fract() == 0.0 => {
|
||||
// DAX switches to exponent form for very large whole numbers instead of printing
|
||||
// every digit.
|
||||
if value.abs() >= 1.0e15 {
|
||||
// Excel writes the exponent's sign: `1E+15`, not Rust's `1E15`.
|
||||
let text = format!("{value:E}");
|
||||
match text.split_once('E') {
|
||||
Some((mantissa, exponent)) if !exponent.starts_with('-') => format!("{mantissa}E+{exponent}"),
|
||||
_ => text,
|
||||
}
|
||||
} else {
|
||||
format!("{value:.0}")
|
||||
}
|
||||
}
|
||||
Scalar::Currency(value) => {
|
||||
// Integer arithmetic keeps every digit of the scaled range (about 19 significant
|
||||
// digits); an f64 round trip would lose the low ones.
|
||||
let sign = if *value < 0 { "-" } else { "" };
|
||||
let magnitude = value.unsigned_abs();
|
||||
let (whole, fraction) = (magnitude / 10_000, magnitude % 10_000);
|
||||
if fraction == 0 { format!("{sign}{whole}") } else { format!("{sign}{whole}.{}", format!("{fraction:04}").trim_end_matches('0')) }
|
||||
}
|
||||
Scalar::DateTime(serial) => datetime_text(*serial),
|
||||
// DAX prints at most 15 significant digits; Rust's shortest round-trip form can show
|
||||
// 17 (`0.30000000000000004`), so fractional decimals are rounded first.
|
||||
Scalar::Decimal(value) if value.is_finite() => {
|
||||
let rounded: f64 = format!("{value:.14e}").parse().unwrap_or(*value);
|
||||
rounded.to_string()
|
||||
}
|
||||
other => other.to_text(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_text(&self) -> String {
|
||||
match self {
|
||||
Scalar::Blank => String::new(),
|
||||
Scalar::Boolean(true) => "TRUE".into(),
|
||||
Scalar::Boolean(false) => "FALSE".into(),
|
||||
Scalar::Integer(value) => value.to_string(),
|
||||
Scalar::Currency(value) => format!("{:.4}", *value as f64 / 10_000.0),
|
||||
Scalar::Decimal(value) => {
|
||||
if value.fract() == 0.0 {
|
||||
format!("{value:.1}")
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
Scalar::DateTime(value) => value.to_string(),
|
||||
Scalar::String(value) => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_bool(&self) -> Option<bool> {
|
||||
match self {
|
||||
Scalar::Blank => Some(false),
|
||||
Scalar::Boolean(value) => Some(*value),
|
||||
Scalar::Integer(value) => Some(*value != 0),
|
||||
Scalar::Currency(value) => Some(*value != 0),
|
||||
Scalar::Decimal(value) => Some(*value != 0.0),
|
||||
Scalar::DateTime(value) => Some(*value != 0.0),
|
||||
Scalar::String(value) if value.eq_ignore_ascii_case("true") => Some(true),
|
||||
Scalar::String(value) if value.eq_ignore_ascii_case("false") => Some(false),
|
||||
Scalar::String(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Comparison with DAX's blank coercion for `=`/ordering and case-insensitive strings.
|
||||
///
|
||||
/// `None` means the types are not comparable: text against a number or a logical, and any
|
||||
/// pair with NaN. Text is never coerced to a number here — arithmetic coerces numeric text
|
||||
/// (`to_number`), comparison does not — so the caller decides what an incomparable pair means
|
||||
/// (the evaluator maps it to FALSE for `=`/ordering and to an error where DAX raises one).
|
||||
pub fn compare(&self, other: &Scalar) -> Option<Ordering> {
|
||||
match (self, other) {
|
||||
(Scalar::Blank, Scalar::Blank) => Some(Ordering::Equal),
|
||||
// BLANK converts to the empty string when compared with text, so `BLANK () = ""` is
|
||||
// TRUE and `BLANK () <> ""` is FALSE, symmetrically.
|
||||
(Scalar::Blank, Scalar::String(b)) => Some(String::new().cmp(&b.to_lowercase())),
|
||||
(Scalar::String(a), Scalar::Blank) => Some(a.to_lowercase().cmp(&String::new())),
|
||||
(Scalar::String(a), Scalar::String(b)) => Some(a.to_lowercase().cmp(&b.to_lowercase())),
|
||||
(Scalar::String(_), _) | (_, Scalar::String(_)) => None,
|
||||
(Scalar::Boolean(a), Scalar::Boolean(b)) => Some(a.cmp(b)),
|
||||
// Two keys of the same integer variant compare exactly: above 2^53 the `f64` route
|
||||
// would report distinct values as equal, and `IN`/`=` must not.
|
||||
(Scalar::Integer(a), Scalar::Integer(b)) => Some(a.cmp(b)),
|
||||
(Scalar::Currency(a), Scalar::Currency(b)) => Some(a.cmp(b)),
|
||||
_ => numeric_compare(self, other),
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity for relationship joins and member filters: BLANK equals only BLANK and text is
|
||||
/// case-sensitive, while the numeric variants compare by value — a key can be `Integer` on one
|
||||
/// side and `Decimal` or `Currency` on the other, and the two must still join.
|
||||
pub fn strict_eq(&self, other: &Scalar) -> bool {
|
||||
match (self, other) {
|
||||
(Scalar::Blank, Scalar::Blank) => true,
|
||||
(Scalar::String(a), Scalar::String(b)) => a == b,
|
||||
(a, b) if a.is_numeric() && b.is_numeric() => {
|
||||
// Two keys of the same variant compare exactly, however large they are.
|
||||
if std::mem::discriminant(a) == std::mem::discriminant(b) {
|
||||
return a == b;
|
||||
}
|
||||
match (exact_number(a), exact_number(b)) {
|
||||
(Some(x), Some(y)) => x == y,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => self == other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A comparable/hashable key used for filter context values, relationship joins and dictionary
|
||||
/// lookups.
|
||||
///
|
||||
/// Keys keep the exact spelling: they double as the reported key in integrity findings. Where DAX
|
||||
/// compares values for *distinctness* instead of identity — `DISTINCTCOUNT`, `VALUES`/`DISTINCT`
|
||||
/// — the text folds through [`distinct_key`], which is the model's case-insensitive collation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum ScalarKey {
|
||||
Blank,
|
||||
Boolean(bool),
|
||||
Integer(i64),
|
||||
Currency(i64),
|
||||
Decimal(u64),
|
||||
DateTime(u64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl From<&Scalar> for ScalarKey {
|
||||
fn from(value: &Scalar) -> Self {
|
||||
match value {
|
||||
Scalar::Blank => ScalarKey::Blank,
|
||||
Scalar::Boolean(value) => ScalarKey::Boolean(*value),
|
||||
Scalar::Integer(value) => ScalarKey::Integer(*value),
|
||||
Scalar::Currency(value) => ScalarKey::Currency(*value),
|
||||
Scalar::Decimal(value) => ScalarKey::Decimal(order_bits(*value)),
|
||||
Scalar::DateTime(value) => ScalarKey::DateTime(order_bits(*value)),
|
||||
Scalar::String(value) => ScalarKey::String(value.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares two numeric scalars.
|
||||
///
|
||||
/// An `Integer` against a `Decimal`/`DateTime` is compared through `i128` when the decimal is
|
||||
/// integral, so a value above 2^53 is not rounded into its neighbour; every other pair uses the
|
||||
/// `f64` coercion DAX applies.
|
||||
fn numeric_compare(left: &Scalar, right: &Scalar) -> Option<Ordering> {
|
||||
fn exact(value: &Scalar) -> Option<i128> {
|
||||
match value {
|
||||
Scalar::Integer(number) => Some(i128::from(*number)),
|
||||
Scalar::Decimal(number) | Scalar::DateTime(number) if number.fract() == 0.0 && number.abs() < 9.2e18 => Some(*number as i128),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let integer_involved = matches!(left, Scalar::Integer(_) | Scalar::Currency(_)) || matches!(right, Scalar::Integer(_) | Scalar::Currency(_));
|
||||
if integer_involved && let (Some(a), Some(b)) = (exact(left), exact(right)) {
|
||||
return Some(a.cmp(&b));
|
||||
}
|
||||
left.to_number()?.partial_cmp(&right.to_number()?)
|
||||
}
|
||||
|
||||
/// [`relationship_key_of`] for a value: the key a relationship index stores for it under the
|
||||
/// numeric rule.
|
||||
pub(crate) fn relationship_key_of_value(value: &Scalar) -> ScalarKey {
|
||||
relationship_key_of(&ScalarKey::from(value))
|
||||
}
|
||||
|
||||
/// [`relationship_key`] for a key that is already normalized-except-for-variant.
|
||||
pub(crate) fn relationship_key_of(key: &ScalarKey) -> ScalarKey {
|
||||
match key {
|
||||
ScalarKey::Integer(number) if number.unsigned_abs() <= (1 << 53) => ScalarKey::Decimal(order_bits(*number as f64)),
|
||||
ScalarKey::Currency(number) if number.unsigned_abs() <= (1 << 53) => {
|
||||
let major = *number as f64 / 10_000.0;
|
||||
// The division must land back on the stored amount. Past roughly 2^49 hundredths it
|
||||
// rounds, and two distinct currencies would then share one key.
|
||||
if (major * 10_000.0).round() as i64 == *number { ScalarKey::Decimal(order_bits(major)) } else { key.clone() }
|
||||
}
|
||||
// A NaN serial has no ordering and never joins, so it keeps its own variant instead of
|
||||
// folding onto a `Decimal` NaN with the same bits.
|
||||
ScalarKey::DateTime(serial) if !bits_order(*serial).is_nan() => ScalarKey::Decimal(*serial),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Intersects two key sets under [`folded_key`], keeping the left-hand representatives.
|
||||
///
|
||||
/// Two filters that allow `"East"` and `"east"` accept the same rows, so their intersection must
|
||||
/// not be empty; the same holds for `Integer(2)` and `Decimal(2.0)`.
|
||||
pub(crate) fn fold_intersect(left: &BTreeSet<ScalarKey>, right: &BTreeSet<ScalarKey>) -> BTreeSet<ScalarKey> {
|
||||
let right: BTreeSet<ScalarKey> = right.iter().map(folded_key).collect();
|
||||
left.iter().filter(|key| right.contains(&folded_key(key))).cloned().collect()
|
||||
}
|
||||
|
||||
/// Whether a key holds a NaN value, which never joins and is never a relationship key.
|
||||
pub(crate) fn is_nan_key(key: &ScalarKey) -> bool {
|
||||
match key {
|
||||
ScalarKey::Decimal(bits) | ScalarKey::DateTime(bits) => bits_order(*bits).is_nan(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same key with text folded to lower case: the rule filter keys and the values they are
|
||||
/// compared with share, so a filter set from `VALUES` matches every spelling of the value.
|
||||
pub(crate) fn folded_key(key: &ScalarKey) -> ScalarKey {
|
||||
match key {
|
||||
ScalarKey::String(text) => ScalarKey::String(text.to_lowercase()),
|
||||
// Numbers fold to one variant too, so a filter key built from `Integer(3)` matches a
|
||||
// column cell stored as `Decimal(3.0)` (a promoted column) and vice versa.
|
||||
other => relationship_key_of(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key a distinctness comparison uses: text folds to lower case, the model collation, so `"A"`
|
||||
/// and `"a"` are one value. Every other type keeps its exact key.
|
||||
///
|
||||
/// `DISTINCTCOUNT`, `DISTINCTCOUNTNOBLANK`, `VALUES`/`DISTINCT` and the storage dictionary all use
|
||||
/// this, so a faithful model and a row-scanned one count the same values.
|
||||
pub(crate) fn distinct_key(value: &Scalar) -> ScalarKey {
|
||||
// Text folds by case and numbers fold by value: a promoted column can hold `Integer(2)` and
|
||||
// `Decimal(2.0)` in the same cell family, and DAX counts that as one value. The relationship
|
||||
// rule keeps the conversions exact (and NaN distinct).
|
||||
folded_key(&ScalarKey::from(value))
|
||||
}
|
||||
|
||||
/// The numeric value of a variant that an `f64` holds exactly.
|
||||
///
|
||||
/// `Integer` and `Currency` are compared through their exact representation only up to 2^53:
|
||||
/// beyond it `9007199254740992` and `9007199254740993` share an `f64`, and a relationship must not
|
||||
/// treat two distinct keys as the same one.
|
||||
fn exact_number(value: &Scalar) -> Option<f64> {
|
||||
const LIMIT: i64 = 1 << 53;
|
||||
match value {
|
||||
Scalar::Integer(number) if number.unsigned_abs() <= LIMIT as u64 => Some(*number as f64),
|
||||
Scalar::Currency(number) if number.unsigned_abs() <= LIMIT as u64 => {
|
||||
let major = *number as f64 / 10_000.0;
|
||||
// The same round-trip rule the relationship key uses, so `strict_eq` and the join
|
||||
// indexes cannot disagree about an amount that does not survive the division.
|
||||
if (major * 10_000.0).round() as i64 == *number { Some(major) } else { None }
|
||||
}
|
||||
Scalar::Decimal(number) | Scalar::DateTime(number) => Some(*number),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps an `f64` to a `u64` whose unsigned order matches numeric order. `-0.0` and `0.0` map to
|
||||
/// the same key, so `Ord` on [`ScalarKey`] sorts pivot groups numerically.
|
||||
fn order_bits(value: f64) -> u64 {
|
||||
let value = if value == 0.0 { 0.0 } else { value };
|
||||
let bits = value.to_bits();
|
||||
if bits >> 63 == 1 { !bits } else { bits | (1 << 63) }
|
||||
}
|
||||
|
||||
/// Inverse of [`order_bits`].
|
||||
pub(crate) fn bits_order(bits: u64) -> f64 {
|
||||
let bits = if bits >> 63 == 1 { bits & !(1 << 63) } else { !bits };
|
||||
f64::from_bits(bits)
|
||||
}
|
||||
|
||||
impl ScalarKey {
|
||||
/// Rebuilds the scalar that produced this key.
|
||||
pub fn to_scalar(&self) -> Scalar {
|
||||
match self {
|
||||
ScalarKey::Blank => Scalar::Blank,
|
||||
ScalarKey::Boolean(value) => Scalar::Boolean(*value),
|
||||
ScalarKey::Integer(value) => Scalar::Integer(*value),
|
||||
ScalarKey::Currency(value) => Scalar::Currency(*value),
|
||||
ScalarKey::Decimal(value) => Scalar::Decimal(bits_order(*value)),
|
||||
ScalarKey::DateTime(value) => Scalar::DateTime(bits_order(*value)),
|
||||
ScalarKey::String(value) => Scalar::String(value.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `DateTime` serial as DAX prints it: `M/D/YYYY H:MM:SS AM/PM`.
|
||||
fn datetime_text(serial: f64) -> String {
|
||||
use chrono::Datelike;
|
||||
|
||||
// A non-finite serial is not a date: print the value itself instead of a fabricated one
|
||||
// (`NaN.floor() as i64` is 0, which would render as 1899-12-30 noon).
|
||||
if !serial.is_finite() {
|
||||
return serial.to_string();
|
||||
}
|
||||
let epoch = chrono::NaiveDate::from_ymd_opt(1899, 12, 30);
|
||||
let Some(epoch) = epoch else { return serial.to_string() };
|
||||
let mut seconds = ((serial - serial.floor()) * 86_400.0).round() as i64;
|
||||
let mut days = serial.floor() as i64;
|
||||
if seconds >= 86_400 {
|
||||
seconds -= 86_400;
|
||||
days = days.saturating_add(1);
|
||||
}
|
||||
let Some(date) = chrono::Duration::try_days(days).and_then(|offset| epoch.checked_add_signed(offset)) else {
|
||||
return serial.to_string();
|
||||
};
|
||||
let (hour, minute, second) = (seconds / 3600, (seconds / 60) % 60, seconds % 60);
|
||||
let hour12 = if hour % 12 == 0 { 12 } else { hour % 12 };
|
||||
let meridiem = if hour < 12 { "AM" } else { "PM" };
|
||||
format!("{}/{}/{} {}:{minute:02}:{second:02} {meridiem}", date.month(), date.day(), date.year(), hour12)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TableColumn {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// A materialized table value.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TableValue {
|
||||
pub columns: Vec<TableColumn>,
|
||||
pub rows: Vec<Vec<Scalar>>,
|
||||
/// The model table this value came from, when known. It lets row-context evaluation avoid
|
||||
/// guessing from column names.
|
||||
pub lineage: Option<usize>,
|
||||
}
|
||||
|
||||
impl TableValue {
|
||||
pub fn new(columns: Vec<TableColumn>, rows: Vec<Vec<Scalar>>) -> Self {
|
||||
TableValue { columns, rows, lineage: None }
|
||||
}
|
||||
|
||||
pub fn with_lineage(mut self, lineage: usize) -> Self {
|
||||
self.lineage = Some(lineage);
|
||||
self
|
||||
}
|
||||
|
||||
/// Keeps the existing lineage when the input had one.
|
||||
pub fn with_lineage_if(mut self, lineage: Option<usize>) -> Self {
|
||||
self.lineage = lineage;
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds a table from rows whose column names are given.
|
||||
pub fn from_rows(columns: Vec<TableColumn>, rows: Vec<Vec<Scalar>>, lineage: Option<usize>) -> Self {
|
||||
TableValue { columns, rows, lineage }
|
||||
}
|
||||
|
||||
pub fn column_index(&self, name: &str) -> Option<usize> {
|
||||
self.columns.iter().position(|column| column.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
pub fn column(&self, index: usize) -> Vec<Scalar> {
|
||||
self.rows.iter().filter_map(|row| row.get(index).cloned()).collect()
|
||||
}
|
||||
|
||||
pub fn distinct_rows(&self) -> Self {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut rows = Vec::new();
|
||||
for row in &self.rows {
|
||||
let key: Vec<ScalarKey> = row.iter().map(distinct_key).collect();
|
||||
if seen.insert(key) {
|
||||
rows.push(row.clone());
|
||||
}
|
||||
}
|
||||
TableValue { columns: self.columns.clone(), rows, lineage: self.lineage }
|
||||
}
|
||||
}
|
||||
|
||||
/// A runtime evaluation error.
|
||||
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct EvalError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl EvalError {
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
EvalError { message: message.into() }
|
||||
}
|
||||
|
||||
pub fn not_implemented(name: &str) -> Self {
|
||||
EvalError::new(format!("DAX function `{name}` is not implemented by this evaluator"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn distinct_keys_treat_one_number_as_one_value() {
|
||||
assert_eq!(distinct_key(&Scalar::Integer(2)), distinct_key(&Scalar::Decimal(2.0)));
|
||||
assert_eq!(distinct_key(&Scalar::Currency(20_000)), distinct_key(&Scalar::Decimal(2.0)));
|
||||
assert_eq!(distinct_key(&Scalar::String("A".into())), distinct_key(&Scalar::String("a".into())));
|
||||
assert_ne!(distinct_key(&Scalar::Integer(2)), distinct_key(&Scalar::Integer(3)));
|
||||
// A non-finite serial prints as itself, not as a fabricated calendar date.
|
||||
assert_eq!(Scalar::DateTime(f64::NAN).to_dax_text(), "NaN");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_values_survive_a_json_round_trip() {
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
for scalar in [Scalar::Decimal(value), Scalar::DateTime(value)] {
|
||||
let json = serde_json::to_value(&scalar).expect("serialize");
|
||||
let back: Scalar = serde_json::from_value(json.clone()).expect("deserialize");
|
||||
assert_eq!(format!("{back:?}"), format!("{scalar:?}"), "round trip through {json}");
|
||||
}
|
||||
}
|
||||
// A finite decimal keeps its natural JSON number, and text is still text.
|
||||
assert_eq!(serde_json::to_value(Scalar::Decimal(1.5)).expect("serialize"), serde_json::json!(1.5));
|
||||
let text: Scalar = serde_json::from_value(serde_json::json!("NaN")).expect("deserialize");
|
||||
assert_eq!(text, Scalar::String("NaN".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_keys_normalize_only_what_is_exact() {
|
||||
// Integer and currency amounts fold onto the decimal key a decimal column uses.
|
||||
assert_eq!(relationship_key_of(&ScalarKey::Integer(2)), relationship_key_of(&ScalarKey::Decimal(order_bits(2.0))));
|
||||
assert_eq!(relationship_key_of(&ScalarKey::Currency(20_000)), relationship_key_of(&ScalarKey::Decimal(order_bits(2.0))));
|
||||
// A currency amount whose major-unit division cannot round-trip keeps its own key.
|
||||
let huge = 5_500_000_000_000_001_i64;
|
||||
assert_ne!(
|
||||
relationship_key_of(&ScalarKey::Currency(huge)),
|
||||
relationship_key_of(&ScalarKey::Currency(huge + 1)),
|
||||
"two distinct currency keys must not collapse"
|
||||
);
|
||||
// A NaN serial never joins, so it keeps its variant instead of matching a decimal NaN.
|
||||
assert_ne!(
|
||||
relationship_key_of(&ScalarKey::from(&Scalar::DateTime(f64::NAN))),
|
||||
relationship_key_of(&ScalarKey::from(&Scalar::Decimal(f64::NAN))),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
//! Integration tests for the aggregation catalog and its static validation.
|
||||
|
||||
use gridcraft_dax::functions::{BlankPolicy, FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup};
|
||||
use gridcraft_dax::{Expr, ExprKind, ValidationError, ValidationErrorKind, parse_expression, validate_call, validate_expression};
|
||||
|
||||
fn aggregation_catalog() -> Vec<&'static FunctionSpec> {
|
||||
catalog().iter().filter(|spec| spec.category == FunctionCategory::Aggregation).collect()
|
||||
}
|
||||
|
||||
const FUNCTIONS: [(&str, usize, usize); 22] = [
|
||||
("APPROXIMATEDISTINCTCOUNT", 1, 1),
|
||||
("AVERAGE", 1, 1),
|
||||
("AVERAGEA", 1, 1),
|
||||
("AVERAGEX", 2, 2),
|
||||
("COUNT", 1, 1),
|
||||
("COUNTA", 1, 1),
|
||||
("COUNTAX", 2, 2),
|
||||
("COUNTBLANK", 1, 1),
|
||||
("COUNTROWS", 0, 1),
|
||||
("COUNTX", 2, 2),
|
||||
("DISTINCTCOUNT", 1, 1),
|
||||
("DISTINCTCOUNTNOBLANK", 1, 1),
|
||||
("MAX", 1, 2),
|
||||
("MAXA", 1, 1),
|
||||
("MAXX", 2, 3),
|
||||
("MIN", 1, 2),
|
||||
("MINA", 1, 1),
|
||||
("MINX", 2, 3),
|
||||
("PRODUCT", 1, 1),
|
||||
("PRODUCTX", 2, 2),
|
||||
("SUM", 1, 1),
|
||||
("SUMX", 2, 2),
|
||||
];
|
||||
|
||||
fn parse(src: &str) -> Expr {
|
||||
match parse_expression(src) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("{src:?} did not parse: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn spec(name: &str) -> &'static FunctionSpec {
|
||||
match lookup(name) {
|
||||
Some(spec) => spec,
|
||||
None => panic!("{name} is missing from the catalog"),
|
||||
}
|
||||
}
|
||||
|
||||
fn expression_errors(src: &str) -> Vec<ValidationError> {
|
||||
validate_expression(&parse(src))
|
||||
}
|
||||
|
||||
fn call_errors(src: &str) -> Vec<ValidationError> {
|
||||
let expr = parse(src);
|
||||
match &expr.kind {
|
||||
ExprKind::Call(call) => validate_call(call),
|
||||
other => panic!("{src:?} is not a call: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_valid(src: &str) {
|
||||
let errors = expression_errors(src);
|
||||
assert!(errors.is_empty(), "{src:?} should validate, got {errors:?}");
|
||||
}
|
||||
|
||||
fn assert_invalid_kind(src: &str, kind: ValidationErrorKind) -> Vec<ValidationError> {
|
||||
let errors = expression_errors(src);
|
||||
assert!(!errors.is_empty(), "{src:?} should be rejected");
|
||||
assert!(errors.iter().any(|error| error.kind == kind), "{src:?} should report {kind:?}, got {errors:?}");
|
||||
errors
|
||||
}
|
||||
|
||||
fn overload_kinds(spec: &FunctionSpec, arity: usize) -> Option<Vec<ParamKind>> {
|
||||
spec.overload_for(arity).map(|overload| overload.params.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_has_every_aggregation_function_exactly_once_with_documented_arity() {
|
||||
let specs = aggregation_catalog();
|
||||
assert_eq!(specs.len(), FUNCTIONS.len());
|
||||
|
||||
for (name, min_args, max_args) in FUNCTIONS {
|
||||
let matches: Vec<&FunctionSpec> = specs.iter().copied().filter(|spec| spec.name == name).collect();
|
||||
assert_eq!(matches.len(), 1, "{name} should appear exactly once");
|
||||
assert_eq!(matches[0].min_args, min_args, "{name} min arity");
|
||||
assert_eq!(matches[0].max_args, max_args, "{name} max arity");
|
||||
assert_eq!(matches[0].category, FunctionCategory::Aggregation);
|
||||
}
|
||||
|
||||
let catalogued: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.name).collect();
|
||||
let documented: std::collections::BTreeSet<&str> = FUNCTIONS.iter().map(|(name, _, _)| *name).collect();
|
||||
assert_eq!(catalogued, documented);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_is_case_insensitive() {
|
||||
for (name, _, _) in FUNCTIONS {
|
||||
assert_eq!(lookup(name).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_lowercase()).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_uppercase()).map(|spec| spec.name), Some(name));
|
||||
}
|
||||
assert_eq!(lookup("SuM").map(|spec| spec.name), Some("SUM"));
|
||||
assert!(lookup("SUMM").is_none());
|
||||
assert!(lookup("").is_none());
|
||||
assert!(lookup("SUM ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_record_has_consistent_signature_and_metadata() {
|
||||
for spec in aggregation_catalog() {
|
||||
assert!(!spec.description.is_empty(), "{} description", spec.name);
|
||||
assert!(!spec.examples.is_empty(), "{} examples", spec.name);
|
||||
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
|
||||
|
||||
let required = spec.params.iter().filter(|param| !param.optional).count();
|
||||
let optional = spec.params.iter().filter(|param| param.optional).count();
|
||||
assert_eq!(required, spec.min_args, "{} required params", spec.name);
|
||||
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
|
||||
|
||||
assert!(!spec.overloads.is_empty(), "{} overloads", spec.name);
|
||||
for arity in spec.min_args..=spec.max_args {
|
||||
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
|
||||
}
|
||||
let arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
|
||||
assert_eq!(arities.iter().min().copied(), Some(spec.min_args), "{} overload min", spec.name);
|
||||
assert_eq!(arities.iter().max().copied(), Some(spec.max_args), "{} overload max", spec.name);
|
||||
|
||||
if let Some(target) = spec.sugar_of {
|
||||
assert_ne!(target, spec.name, "{} is sugar of itself", spec.name);
|
||||
assert!(lookup(target).is_some(), "{} sugar target {target} is missing", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterator_and_sugar_metadata() {
|
||||
let iterators = ["AVERAGEX", "COUNTAX", "COUNTX", "MAXX", "MINX", "PRODUCTX", "SUMX"];
|
||||
for spec in aggregation_catalog() {
|
||||
assert_eq!(spec.flags.iterator, iterators.contains(&spec.name), "{} iterator flag", spec.name);
|
||||
assert_eq!(spec.is_iterator(), spec.flags.iterator, "{} is_iterator", spec.name);
|
||||
}
|
||||
|
||||
for (name, target) in [("AVERAGE", "AVERAGEX"), ("COUNT", "COUNTX"), ("COUNTA", "COUNTAX"), ("PRODUCT", "PRODUCTX"), ("SUM", "SUMX")] {
|
||||
assert_eq!(spec(name).sugar_of, Some(target), "{name} sugar");
|
||||
}
|
||||
|
||||
for name in [
|
||||
"APPROXIMATEDISTINCTCOUNT",
|
||||
"DISTINCTCOUNTNOBLANK",
|
||||
"MAX",
|
||||
"MIN",
|
||||
"AVERAGEA",
|
||||
"AVERAGEX",
|
||||
"COUNTAX",
|
||||
"COUNTBLANK",
|
||||
"COUNTROWS",
|
||||
"COUNTX",
|
||||
"DISTINCTCOUNT",
|
||||
"MAXA",
|
||||
"MAXX",
|
||||
"MINA",
|
||||
"MINX",
|
||||
"PRODUCTX",
|
||||
"SUMX",
|
||||
] {
|
||||
assert_eq!(spec(name).sugar_of, None, "{name} is not pure sugar");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_policy_metadata() {
|
||||
for (name, policy) in [
|
||||
("APPROXIMATEDISTINCTCOUNT", BlankPolicy::BlankWhenEmpty),
|
||||
("AVERAGE", BlankPolicy::Unspecified),
|
||||
("AVERAGEA", BlankPolicy::Unspecified),
|
||||
("AVERAGEX", BlankPolicy::BlankWhenEmpty),
|
||||
("COUNT", BlankPolicy::BlankWhenEmpty),
|
||||
("COUNTA", BlankPolicy::BlankWhenEmpty),
|
||||
("COUNTAX", BlankPolicy::BlankWhenEmpty),
|
||||
("COUNTBLANK", BlankPolicy::Unspecified),
|
||||
("COUNTROWS", BlankPolicy::BlankWhenEmpty),
|
||||
("COUNTX", BlankPolicy::BlankWhenEmpty),
|
||||
("DISTINCTCOUNT", BlankPolicy::BlankWhenEmpty),
|
||||
("DISTINCTCOUNTNOBLANK", BlankPolicy::Unspecified),
|
||||
("MAX", BlankPolicy::Unspecified),
|
||||
("MAXA", BlankPolicy::Unspecified),
|
||||
("MAXX", BlankPolicy::Unspecified),
|
||||
("MIN", BlankPolicy::Unspecified),
|
||||
("MINA", BlankPolicy::Unspecified),
|
||||
("MINX", BlankPolicy::Unspecified),
|
||||
("PRODUCT", BlankPolicy::BlankWhenEmpty),
|
||||
("PRODUCTX", BlankPolicy::BlankWhenEmpty),
|
||||
("SUM", BlankPolicy::BlankWhenEmpty),
|
||||
("SUMX", BlankPolicy::BlankWhenEmpty),
|
||||
] {
|
||||
assert_eq!(spec(name).blank_policy, policy, "{name} blank policy");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_type_metadata() {
|
||||
for (name, return_type) in [
|
||||
("APPROXIMATEDISTINCTCOUNT", ReturnType::Integer),
|
||||
("AVERAGE", ReturnType::Numeric),
|
||||
("AVERAGEA", ReturnType::Numeric),
|
||||
("AVERAGEX", ReturnType::Numeric),
|
||||
("COUNT", ReturnType::Integer),
|
||||
("COUNTA", ReturnType::Integer),
|
||||
("COUNTAX", ReturnType::Integer),
|
||||
("COUNTBLANK", ReturnType::Integer),
|
||||
("COUNTROWS", ReturnType::Integer),
|
||||
("COUNTX", ReturnType::Integer),
|
||||
("DISTINCTCOUNT", ReturnType::Integer),
|
||||
("DISTINCTCOUNTNOBLANK", ReturnType::Integer),
|
||||
("MAX", ReturnType::Any),
|
||||
("MAXA", ReturnType::Any),
|
||||
("MAXX", ReturnType::Any),
|
||||
("MIN", ReturnType::Any),
|
||||
("MINA", ReturnType::Any),
|
||||
("MINX", ReturnType::Any),
|
||||
("PRODUCT", ReturnType::Decimal),
|
||||
("PRODUCTX", ReturnType::Decimal),
|
||||
("SUM", ReturnType::Numeric),
|
||||
("SUMX", ReturnType::Numeric),
|
||||
] {
|
||||
assert_eq!(spec(name).return_type, return_type, "{name} return type");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compatibility_flags_are_honest() {
|
||||
assert!(!spec("APPROXIMATEDISTINCTCOUNT").flags.excel_compatible);
|
||||
assert!(!spec("DISTINCTCOUNTNOBLANK").flags.excel_compatible);
|
||||
assert!(spec("COUNTROWS").flags.excel_compatible);
|
||||
for spec in aggregation_catalog() {
|
||||
if spec.name != "APPROXIMATEDISTINCTCOUNT" && spec.name != "DISTINCTCOUNTNOBLANK" {
|
||||
assert!(spec.flags.excel_compatible, "{} should be Excel compatible", spec.name);
|
||||
}
|
||||
assert!(spec.flags.direct_query_limited, "{} DirectQuery note", spec.name);
|
||||
}
|
||||
|
||||
let not_recommended: Vec<&str> = aggregation_catalog().iter().filter(|spec| spec.flags.not_recommended).map(|spec| spec.name).collect();
|
||||
assert_eq!(not_recommended, ["AVERAGEA"]);
|
||||
|
||||
// COUNTROWS () is in the catalog even though Excel's embedded engine rejects that form.
|
||||
assert_valid("COUNTROWS ( )");
|
||||
assert_eq!(spec("COUNTROWS").min_args, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overloads_model_the_documented_signatures() {
|
||||
assert_eq!(overload_kinds(spec("MAX"), 1), Some(vec![ParamKind::Column]));
|
||||
assert_eq!(overload_kinds(spec("MAX"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar]));
|
||||
assert_eq!(overload_kinds(spec("MIN"), 1), Some(vec![ParamKind::Column]));
|
||||
assert_eq!(overload_kinds(spec("MIN"), 2), Some(vec![ParamKind::Scalar, ParamKind::Scalar]));
|
||||
assert_eq!(overload_kinds(spec("COUNTROWS"), 0), Some(Vec::new()));
|
||||
assert_eq!(overload_kinds(spec("COUNTROWS"), 1), Some(vec![ParamKind::Table]));
|
||||
assert_eq!(overload_kinds(spec("MAXX"), 2), Some(vec![ParamKind::Table, ParamKind::Expression]));
|
||||
assert_eq!(overload_kinds(spec("MAXX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical]));
|
||||
assert_eq!(overload_kinds(spec("MINX"), 3), Some(vec![ParamKind::Table, ParamKind::Expression, ParamKind::Logical]));
|
||||
|
||||
let maxx = spec("MAXX");
|
||||
assert_eq!(maxx.params.len(), 3);
|
||||
assert_eq!(maxx.params[2].name, "Variant");
|
||||
assert_eq!(maxx.params[2].kind, ParamKind::Logical);
|
||||
assert!(maxx.params[2].optional);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arity_boundaries_accept_and_reject_the_right_calls() {
|
||||
for src in [
|
||||
"SUM ( Sales[Amount] )",
|
||||
"COUNTROWS ( )",
|
||||
"COUNTROWS ( Sales )",
|
||||
"MAX ( 1, 2 )",
|
||||
"MAX ( Sales[Amount] )",
|
||||
"MIN ( 3, 5 )",
|
||||
"MAXX ( Sales, Sales[Amount] )",
|
||||
"MAXX ( Sales, Sales[Amount], TRUE )",
|
||||
"MINX ( Sales, Sales[Amount] )",
|
||||
"MINX ( Sales, Sales[Amount], FALSE )",
|
||||
"AVERAGEX ( Sales, Sales[Amount] )",
|
||||
"COUNTAX ( Sales, Sales[Flag] )",
|
||||
"COUNTX ( Sales, Sales[Quantity] )",
|
||||
"PRODUCTX ( Sales, Sales[Quantity] )",
|
||||
"SUMX ( Sales, Sales[Amount] )",
|
||||
"DISTINCTCOUNT ( Sales[Region] )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
|
||||
for src in [
|
||||
"SUM ( )",
|
||||
"SUM ( Sales[Amount], Sales[Amount] )",
|
||||
"COUNTROWS ( Sales, Sales )",
|
||||
"MAX ( )",
|
||||
"MAX ( 1, 2, 3 )",
|
||||
"MIN ( 1, 2, 3 )",
|
||||
"MAXX ( Sales )",
|
||||
"MAXX ( Sales, Sales[Amount], TRUE, FALSE )",
|
||||
"MINX ( Sales )",
|
||||
"MINX ( Sales, Sales[Amount], TRUE, FALSE )",
|
||||
"AVERAGEX ( Sales )",
|
||||
"AVERAGEX ( Sales, Sales[Amount], TRUE )",
|
||||
"COUNTAX ( Sales )",
|
||||
"COUNTX ( Sales )",
|
||||
"PRODUCTX ( Sales )",
|
||||
"SUMX ( Sales )",
|
||||
"DISTINCTCOUNT ( )",
|
||||
"COUNT ( )",
|
||||
] {
|
||||
let errors = assert_invalid_kind(src, ValidationErrorKind::Arity);
|
||||
assert_eq!(errors.len(), 1, "{src:?} should report exactly one arity error: {errors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_arity_boundary_is_enforced() {
|
||||
for spec in aggregation_catalog() {
|
||||
for arity in 0..=4usize {
|
||||
let arguments = vec!["1"; arity].join(", ");
|
||||
let src = format!("{} ( {arguments} )", spec.name);
|
||||
let errors = expression_errors(&src);
|
||||
let arity_errors: Vec<&ValidationError> = errors.iter().filter(|error| error.kind == ValidationErrorKind::Arity).collect();
|
||||
if arity < spec.min_args || arity > spec.max_args {
|
||||
assert_eq!(arity_errors.len(), 1, "{src:?} should report one arity error: {errors:?}");
|
||||
} else {
|
||||
assert!(arity_errors.is_empty(), "{src:?} has a documented overload and must not report an arity error: {errors:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_only_arguments_must_be_bracketed_references() {
|
||||
for src in [
|
||||
"SUM ( 1 )",
|
||||
"AVERAGE ( 1 + 1 )",
|
||||
"COUNT ( \"x\" )",
|
||||
"COUNTA ( TRUE )",
|
||||
"COUNTBLANK ( 1 )",
|
||||
"DISTINCTCOUNT ( 1 )",
|
||||
"DISTINCTCOUNTNOBLANK ( 1 )",
|
||||
"APPROXIMATEDISTINCTCOUNT ( 1 )",
|
||||
"PRODUCT ( 1 )",
|
||||
"MAXA ( 1 )",
|
||||
"MINA ( 1 )",
|
||||
"MAX ( 1 )",
|
||||
"MIN ( 1 )",
|
||||
"SUM ( -1 )",
|
||||
] {
|
||||
assert_invalid_kind(src, ValidationErrorKind::ArgumentKind);
|
||||
}
|
||||
|
||||
for src in [
|
||||
"SUM ( Sales[Amount] )",
|
||||
"SUM ( [Amount] )",
|
||||
"AVERAGE ( 'Sales'[Amount] )",
|
||||
"COUNT ( Sales[Text] )",
|
||||
"DISTINCTCOUNT ( Sales[Region] )",
|
||||
"APPROXIMATEDISTINCTCOUNT ( Sales[ProductKey] )",
|
||||
"PRODUCT ( Sales[Quantity] )",
|
||||
"MAX ( Sales[Amount] )",
|
||||
"MIN ( Sales[Amount] )",
|
||||
"MAXA ( Sales[Flag] )",
|
||||
"MINA ( Sales[Flag] )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
|
||||
let errors = assert_invalid_kind("SUM ( 1 )", ValidationErrorKind::ArgumentKind);
|
||||
let message = &errors[0].message;
|
||||
assert!(message.contains("SUM"), "{message}");
|
||||
assert!(message.contains("column reference"), "{message}");
|
||||
assert!(message.contains("literal"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_arguments_reject_obvious_scalars_but_accept_dynamic_tables() {
|
||||
for src in [
|
||||
"COUNTROWS ( 1 )",
|
||||
"COUNTROWS ( \"Sales\" )",
|
||||
"COUNTROWS ( -1 )",
|
||||
"COUNTROWS ( 1 + 1 )",
|
||||
"COUNTROWS ( Sales[Amount] )",
|
||||
"SUMX ( 1, Sales[Amount] )",
|
||||
"AVERAGEX ( 1 + 1, Sales[Amount] )",
|
||||
"MAXX ( TRUE, Sales[Amount] )",
|
||||
"MINX ( 2 * 2, Sales[Amount] )",
|
||||
"COUNTAX ( \"x\", Sales[Flag] )",
|
||||
"COUNTX ( FALSE, Sales[Quantity] )",
|
||||
] {
|
||||
assert_invalid_kind(src, ValidationErrorKind::ArgumentKind);
|
||||
}
|
||||
|
||||
for src in [
|
||||
"COUNTROWS ( Sales )",
|
||||
"COUNTROWS ( DISTINCT ( Sales[Region] ) )",
|
||||
"COUNTROWS ( VALUES ( Sales[Region] ) )",
|
||||
"COUNTROWS ( FILTER ( Sales, Sales[Amount] > 0 ) )",
|
||||
"COUNTROWS ( { 1, 2 } )",
|
||||
"SUMX ( FILTER ( Sales, Sales[Amount] > 0 ), Sales[Amount] )",
|
||||
"SUMX ( { 1, 2, 3 }, [Value] )",
|
||||
"AVERAGEX ( ALL ( Sales ), [Amount] )",
|
||||
"MAXX ( Sales, Sales[Amount] )",
|
||||
"MINX ( RELATEDTABLE ( ResellerSales ), [Sales Amount] )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_and_min_model_both_overloads() {
|
||||
assert_valid("MAX ( 1, 2 )");
|
||||
assert_valid("MAX ( 3, 5 )");
|
||||
assert_valid("MAX ( Sales[Amount] )");
|
||||
assert_valid("MAX ( 10000, [Sales Amount] )");
|
||||
assert_valid("MIN ( 3, 5 )");
|
||||
assert_valid("MIN ( Sales[Net Price] )");
|
||||
assert_valid("MIN ( 5000000, [Sales Amount] )");
|
||||
|
||||
// One argument is the column-only overload, not a scalar.
|
||||
assert_invalid_kind("MAX ( 1 )", ValidationErrorKind::ArgumentKind);
|
||||
assert_invalid_kind("MIN ( 1 )", ValidationErrorKind::ArgumentKind);
|
||||
|
||||
// Three arguments match no overload.
|
||||
assert_invalid_kind("MAX ( 1, 2, 3 )", ValidationErrorKind::Arity);
|
||||
assert_invalid_kind("MIN ( 1, 2, 3 )", ValidationErrorKind::Arity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn countrows_accepts_zero_or_one_table_argument() {
|
||||
for src in ["COUNTROWS ( )", "COUNTROWS ( Sales )", "COUNTROWS ( DISTINCT ( Sales[Region] ) )"] {
|
||||
assert_valid(src);
|
||||
}
|
||||
assert_invalid_kind("COUNTROWS ( Sales, Sales )", ValidationErrorKind::Arity);
|
||||
assert_invalid_kind("COUNTROWS ( 1 )", ValidationErrorKind::ArgumentKind);
|
||||
|
||||
let spec = spec("COUNTROWS");
|
||||
assert_eq!((spec.min_args, spec.max_args), (0, 1));
|
||||
assert_eq!(overload_kinds(spec, 0), Some(Vec::new()));
|
||||
assert_eq!(overload_kinds(spec, 1), Some(vec![ParamKind::Table]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maxx_and_minx_accept_the_optional_variant_argument() {
|
||||
for src in [
|
||||
"MAXX ( Sales, Sales[Amount] )",
|
||||
"MAXX ( Sales, Sales[Amount], TRUE )",
|
||||
"MAXX ( Customer, 1 * Customer[LargeFamily] )",
|
||||
"MINX ( Sales, Sales[Amount] )",
|
||||
"MINX ( Sales, Sales[Amount], FALSE )",
|
||||
"MINX ( Customer, 1 * Customer[NoCars] )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
assert_invalid_kind("MAXX ( Sales )", ValidationErrorKind::Arity);
|
||||
assert_invalid_kind("MAXX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity);
|
||||
assert_invalid_kind("MINX ( Sales )", ValidationErrorKind::Arity);
|
||||
assert_invalid_kind("MINX ( Sales, Sales[Amount], TRUE, FALSE )", ValidationErrorKind::Arity);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_catalog_example_parses_and_validates() {
|
||||
for spec in aggregation_catalog() {
|
||||
assert!(!spec.examples.is_empty(), "{} has no examples", spec.name);
|
||||
for example in spec.examples {
|
||||
let expr = parse(example);
|
||||
let errors = validate_expression(&expr);
|
||||
assert!(errors.is_empty(), "{} example {example:?} should validate, got {errors:?}", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_functions_are_ignored_but_nested_calls_are_checked() {
|
||||
assert!(expression_errors("FOO ( 1, 2, 3 )").is_empty());
|
||||
assert!(expression_errors("CALCULATE ( SUM ( Sales[Amount] ), Sales[Region] = \"East\" )").is_empty());
|
||||
assert!(call_errors("FOO ( 1, 2, 3 )").is_empty());
|
||||
|
||||
let errors = expression_errors("CALCULATE ( SUM ( 1 ) )");
|
||||
assert_eq!(errors.len(), 1, "{errors:?}");
|
||||
assert_eq!(errors[0].function, "SUM");
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_call_reports_arities_and_kinds() {
|
||||
let errors = call_errors("MAX ( 1, 2, 3 )");
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::Arity);
|
||||
// `Call` has no own span; the expression validator supplies it.
|
||||
assert!(errors[0].span.is_empty());
|
||||
|
||||
let errors = call_errors("SUM ( 1 )");
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
|
||||
assert!(!errors[0].span.is_empty());
|
||||
|
||||
assert!(call_errors("SUM ( Sales[Amount] )").is_empty());
|
||||
assert!(call_errors("COUNTROWS ( )").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_expression_reports_every_error_with_a_span() {
|
||||
let src = "SUM ( 1 ) + AVERAGE ( 2 ) + MAX ( 3 )";
|
||||
let errors = expression_errors(src);
|
||||
assert_eq!(errors.len(), 3, "{errors:?}");
|
||||
for error in &errors {
|
||||
assert!(!error.span.is_empty(), "{error:?}");
|
||||
assert!(error.span.end <= src.len(), "{error:?}");
|
||||
}
|
||||
let arguments: Vec<&str> = errors.iter().map(|error| &src[error.span.start..error.span.end]).collect();
|
||||
assert_eq!(arguments, ["1", "2", "3"]);
|
||||
|
||||
let src = "MAX ( 1, 2, 3 )";
|
||||
let errors = expression_errors(src);
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::Arity);
|
||||
assert_eq!(&src[errors[0].span.start..errors[0].span.end], src);
|
||||
|
||||
let src = "COUNTROWS ( 1 )";
|
||||
let errors = expression_errors(src);
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(&src[errors[0].span.start..errors[0].span.end], "1");
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Model metadata and name-binding tests.
|
||||
|
||||
use gridcraft_dax::binder::{BoundExpr, BoundVariable};
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::{Binder, parse_expression};
|
||||
|
||||
fn sample_model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![],
|
||||
},
|
||||
ModelTable { name: "Date".into(), columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], rows: vec![] },
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Region".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
Measure { name: "Total Sales".into(), formula: "SUM ( Sales[Amount] )".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure {
|
||||
name: "East Sales".into(),
|
||||
formula: "CALCULATE ( [Total Sales], Sales[Region] = \"East\" )".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
},
|
||||
Measure { name: "Cycle A".into(), formula: "[Cycle B]".into(), table: None, format: None, expr: None },
|
||||
Measure { name: "Cycle B".into(), formula: "[Cycle A]".into(), table: None, format: None, expr: None },
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn bind(model: &DataModel, formula: &str) -> BoundExpr {
|
||||
let expr = parse_expression(formula).expect("formula parses");
|
||||
Binder::new(model).bind_expression(&expr).expect("formula binds")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binds_qualified_columns_tables_and_measures() {
|
||||
let model = sample_model();
|
||||
match bind(&model, "SUM ( Sales[Amount] )") {
|
||||
BoundExpr::Call { spec, args } => {
|
||||
assert_eq!(spec.name, "SUM");
|
||||
match &args[0] {
|
||||
BoundExpr::Column { table, column } => {
|
||||
assert_eq!(model.tables[*table].name, "Sales");
|
||||
assert_eq!(model.tables[*table].columns[*column].name, "Amount");
|
||||
}
|
||||
other => panic!("expected column, got {other:?}"),
|
||||
}
|
||||
}
|
||||
other => panic!("expected call, got {other:?}"),
|
||||
}
|
||||
assert!(matches!(bind(&model, "Sales"), BoundExpr::Table(0)));
|
||||
assert!(matches!(bind(&model, "[Total Sales]"), BoundExpr::Measure(0)));
|
||||
// A measure reference may carry its home table as a qualifier.
|
||||
assert!(matches!(bind(&model, "Sales[Total Sales]"), BoundExpr::Measure(0)));
|
||||
assert!(matches!(bind(&model, "[Amount]"), BoundExpr::UnqualifiedColumn { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_unknown_names_and_bad_arities() {
|
||||
let model = sample_model();
|
||||
let error = |formula: &str| {
|
||||
let expr = parse_expression(formula).expect("parses");
|
||||
Binder::new(&model).bind_expression(&expr).expect_err("should fail")
|
||||
};
|
||||
assert!(error("Missing[Amount]").message.contains("unknown table"));
|
||||
assert!(error("Sales[Missing]").message.contains("unknown column"));
|
||||
// A measure qualifier has to name the measure's home table.
|
||||
assert!(error("Date[Total Sales]").message.contains("belongs to table `Sales`"));
|
||||
assert!(error("SUM ( )").message.contains("expects 1"));
|
||||
assert!(error("NOPE ( 1 )").message.contains("unknown DAX function"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binds_var_return_with_sequential_scopes() {
|
||||
let model = sample_model();
|
||||
let bound = bind(&model, "VAR x = 1 VAR y = x + 1 RETURN y");
|
||||
match bound {
|
||||
BoundExpr::VarReturn { vars, body } => {
|
||||
assert_eq!(vars.len(), 2);
|
||||
assert_eq!(vars[0].name, "x");
|
||||
assert_eq!(vars[1].name, "y");
|
||||
assert!(matches!(vars[0], BoundVariable { .. }));
|
||||
assert!(matches!(*body, BoundExpr::Variable { index: 1, .. }));
|
||||
}
|
||||
other => panic!("expected VAR block, got {other:?}"),
|
||||
}
|
||||
|
||||
// A variable shadows a table of the same name.
|
||||
assert!(matches!(
|
||||
bind(&model, "VAR Sales = 1 RETURN Sales"),
|
||||
BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_names_bind_measures_before_variables() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) }],
|
||||
rows: vec![],
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![Measure {
|
||||
name: "Total".into(),
|
||||
formula: "SUM ( Sales[Amount] )".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
|
||||
// `[Total]` is a bracketed model reference, so it binds to the measure even though a
|
||||
// variable of the same name is in scope.
|
||||
match bind(&model, "VAR Total = 1 RETURN [Total]") {
|
||||
BoundExpr::VarReturn { vars, body } => {
|
||||
assert_eq!(vars.len(), 1);
|
||||
assert_eq!(vars[0].name, "Total");
|
||||
assert!(matches!(*body, BoundExpr::Measure(0)), "expected measure, got {body:?}");
|
||||
}
|
||||
other => panic!("expected VAR block, got {other:?}"),
|
||||
}
|
||||
|
||||
// A bare name still resolves to the variable.
|
||||
assert!(matches!(
|
||||
bind(&model, "VAR Total = 1 RETURN Total"),
|
||||
BoundExpr::VarReturn { body, .. } if matches!(*body, BoundExpr::Variable { index: 0, .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pathitem_type_names_bind_as_keywords() {
|
||||
let model = sample_model();
|
||||
for (formula, function, expected) in
|
||||
[("PATHITEM ( \"1|2\", 1, TEXT )", "PATHITEM", "TEXT"), ("PATHITEMREVERSE ( \"1|2\", 1, INTEGER )", "PATHITEMREVERSE", "INTEGER")]
|
||||
{
|
||||
match bind(&model, formula) {
|
||||
BoundExpr::Call { spec, args } => {
|
||||
assert_eq!(spec.name, function);
|
||||
assert_eq!(args.len(), 3);
|
||||
assert!(matches!(&args[2], BoundExpr::Keyword(keyword) if keyword == expected), "expected `{expected}` keyword, got {:?}", args[2]);
|
||||
}
|
||||
other => panic!("expected call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_and_dependencies_are_bound() {
|
||||
let model = sample_model();
|
||||
let binder = Binder::new(&model);
|
||||
let total = binder.bind_measure("Total Sales").expect("measure binds");
|
||||
assert!(total.dependencies.is_empty());
|
||||
let east = binder.bind_measure("East Sales").expect("measure binds");
|
||||
assert_eq!(east.dependencies, ["Total Sales".to_string()].into_iter().collect());
|
||||
|
||||
let graph = binder.dependency_graph().expect_err("cycle is rejected");
|
||||
assert!(graph.message.contains("circular"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_validation_rejects_duplicates_and_missing_relationship_columns() {
|
||||
let mut model = sample_model();
|
||||
model.tables.push(ModelTable { name: "sales".into(), columns: vec![], rows: vec![] });
|
||||
assert!(model.parse_formulas().expect_err("duplicate table").message.contains("duplicate"));
|
||||
|
||||
let mut model = sample_model();
|
||||
model.relationships.push(Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Missing".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
});
|
||||
assert!(model.parse_formulas().expect_err("missing column").message.contains("missing column"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_json_deserializes_and_parses_measures() {
|
||||
let json = r#"{
|
||||
"tables": [{"name":"Sales","columns":[{"name":"Amount","data_type":"Double"}]}],
|
||||
"relationships": [],
|
||||
"measures": [{"name":"Total","formula":"SUM(Sales[Amount])","table":"Sales"}]
|
||||
}"#;
|
||||
let mut model: DataModel = serde_json::from_str(json).expect("json loads");
|
||||
model.parse_formulas().expect("model parses");
|
||||
assert!(model.measures[0].expr.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_keyword_arguments_bind_instead_of_resolving_as_names() {
|
||||
let model = sample_model();
|
||||
// CROSSFILTER's direction words are documented enum values, including the two directional
|
||||
// spellings; none of them may be resolved as a model name.
|
||||
for direction in ["NONE", "ONE", "ONEWAY", "BOTH", "TWOWAY", "ONEWAY_LEFTFILTERSRIGHT", "ONEWAY_RIGHTFILTERSLEFT"] {
|
||||
let formula = format!("CROSSFILTER ( Sales[Region], Date[Date], {direction} )");
|
||||
match bind(&model, &formula) {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(&args[2], BoundExpr::Keyword(word) if word.eq_ignore_ascii_case(direction)), "{direction}: {:?}", args[2]);
|
||||
}
|
||||
other => panic!("expected a call for {direction}, got {other:?}"),
|
||||
}
|
||||
}
|
||||
// RANK/ROWNUMBER's Reset argument takes the same three words at the documented position.
|
||||
for reset in ["NONE", "LOWESTPARENT", "HIGHESTPARENT"] {
|
||||
let rank =
|
||||
format!("RANK ( DENSE, Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )");
|
||||
assert!(matches!(bind(&model, &rank), BoundExpr::Call { .. }), "RANK should bind {reset}");
|
||||
let rownumber =
|
||||
format!("ROWNUMBER ( Sales, ORDERBY ( Sales[Amount] ), DEFAULT, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[Amount] ), {reset} )");
|
||||
assert!(matches!(bind(&model, &rownumber), BoundExpr::Call { .. }), "ROWNUMBER should bind {reset}");
|
||||
}
|
||||
// RANKX's Order argument is `ASC`/`DESC`, not a name.
|
||||
match bind(&model, "RANKX ( Sales, Sales[Amount], 42, DESC )") {
|
||||
BoundExpr::Call { args, .. } => assert!(matches!(args[3], BoundExpr::Keyword(ref word) if word == "DESC"), "{:?}", args[3]),
|
||||
other => panic!("expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interval_keyword_is_not_shadowed_by_a_variable() {
|
||||
let model = sample_model();
|
||||
// A variable in scope must not turn the documented interval argument into a name: `YEAR` here
|
||||
// is DATEDIFF's interval, and the binder keeps it a keyword.
|
||||
let bound = bind(&model, "VAR YEAR = 1 RETURN DATEDIFF ( Sales[Amount], Sales[Amount], YEAR )");
|
||||
let debug = format!("{bound:?}");
|
||||
assert!(debug.contains("Keyword(\"YEAR\")"), "{debug}");
|
||||
// A variable still wins where the parameter is documented as text: RANKX's Ties argument.
|
||||
let bound = bind(&model, "VAR DENSE = 1 RETURN RANKX ( Sales, Sales[Amount], 42, DENSE )");
|
||||
assert!(format!("{bound:?}").contains("Variable"), "{bound:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_order_keywords_bind_at_their_argument_positions() {
|
||||
let model = sample_model();
|
||||
// Each documented bare `ASC`/`DESC` slot binds as a keyword instead of failing as an unknown
|
||||
// name, and an undocumented word there is still a name (and therefore an unknown one).
|
||||
let calls = [
|
||||
("RANKX ( Sales, Sales[Amount], 42, DESC )", 3),
|
||||
("RANK.EQ ( 42, Sales[Amount], DESC )", 2),
|
||||
("TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC )", 4),
|
||||
("CONCATENATEX ( Sales, Sales[Amount], \", \", Sales[Amount], DESC )", 4),
|
||||
("SAMPLE ( 10, Sales, Sales[Amount], DESC )", 3),
|
||||
];
|
||||
for (src, position) in calls {
|
||||
match bind(&model, src) {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(&args[position], BoundExpr::Keyword(word) if word == "DESC"), "{src}: {:?}", args[position]);
|
||||
}
|
||||
other => panic!("{src}: expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
// Every repeated `(orderBy, Order)` pair binds, not just the first one.
|
||||
for (src, positions) in [
|
||||
("SAMPLE ( 10, Sales, Sales[Amount], DESC, Sales[Amount], ASC )", [3usize, 5usize]),
|
||||
("TOPNSKIP ( 10, 20, Sales, Sales[Amount], DESC, Sales[Amount], ASC )", [4usize, 6usize]),
|
||||
] {
|
||||
match bind(&model, src) {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(&args[positions[0]], BoundExpr::Keyword(word) if word == "DESC"), "{src}: {:?}", args[positions[0]]);
|
||||
assert!(matches!(&args[positions[1]], BoundExpr::Keyword(word) if word == "ASC"), "{src}: {:?}", args[positions[1]]);
|
||||
}
|
||||
other => panic!("{src}: expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
// An unknown word in a keyword slot is still unknown.
|
||||
let expr = parse_expression("SAMPLE ( 10, Sales, Sales[Amount], SIDEWAYS )").expect("parse");
|
||||
assert!(Binder::new(&model).bind_expression(&expr).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concatenate_x_binds_a_bare_order_word_in_every_pair() {
|
||||
let model = sample_model();
|
||||
// Every `(orderBy, Order)` pair takes a bare keyword: index 4 and index 6 here.
|
||||
let bound = bind(&model, "CONCATENATEX ( Sales, Sales[Region], \"|\", Sales[Region], DESC, Sales[Amount], ASC )");
|
||||
match bound {
|
||||
BoundExpr::Call { args, .. } => {
|
||||
assert!(matches!(&args[4], BoundExpr::Keyword(word) if word == "DESC"), "{:?}", args[4]);
|
||||
assert!(matches!(&args[6], BoundExpr::Keyword(word) if word == "ASC"), "{:?}", args[6]);
|
||||
}
|
||||
other => panic!("expected a call, got {other:?}"),
|
||||
}
|
||||
// A non-keyword in an order slot is still a name, and there is no such name here.
|
||||
let expr = parse_expression("CONCATENATEX ( Sales, Sales[Region], \"|\", Sales[Region], SIDEWAYS )").expect("parse");
|
||||
assert!(Binder::new(&model).bind_expression(&expr).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_datatable_type_word_is_never_a_table_name() {
|
||||
let mut model = sample_model();
|
||||
// A table called `INTEGER` must not capture DATATABLE's type word.
|
||||
model.tables.push(gridcraft_dax::model::ModelTable {
|
||||
name: "INTEGER".into(),
|
||||
columns: vec![gridcraft_dax::model::ModelColumn { name: "Id".into(), data_type: Some("Int64".into()) }],
|
||||
rows: Vec::new(),
|
||||
});
|
||||
match bind(&model, "DATATABLE ( \"Id\", INTEGER, { { 1 } } )") {
|
||||
BoundExpr::Call { args, .. } => assert!(matches!(&args[1], BoundExpr::Keyword(word) if word == "INTEGER"), "{:?}", args[1]),
|
||||
other => panic!("expected a call, got {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Cross-category invariants for the complete DAX function catalog.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, ReturnType, catalog, lookup};
|
||||
use gridcraft_dax::parse_expression;
|
||||
use gridcraft_dax::types::{DataType, InferredType, infer_type};
|
||||
|
||||
#[test]
|
||||
fn every_category_has_functions_and_names_are_unique() {
|
||||
for category in FunctionCategory::ALL {
|
||||
let count = catalog().iter().filter(|spec| spec.category == category).count();
|
||||
assert!(count > 0, "{} has no functions", category.name());
|
||||
}
|
||||
|
||||
let mut names = BTreeMap::new();
|
||||
for spec in catalog() {
|
||||
if let Some(previous) = names.insert(spec.name, spec.category) {
|
||||
panic!("{} appears in both {} and {}", spec.name, previous.name(), spec.category.name());
|
||||
}
|
||||
}
|
||||
assert_eq!(names.len(), catalog().len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_have_consistent_signatures_and_parseable_examples() {
|
||||
for spec in catalog() {
|
||||
assert!(!spec.name.is_empty(), "empty name");
|
||||
assert!(!spec.description.is_empty(), "{} has no description", spec.name);
|
||||
assert!(!spec.examples.is_empty(), "{} has no examples", spec.name);
|
||||
assert!(spec.min_args <= spec.max_args, "{} has min > max", spec.name);
|
||||
|
||||
let variadic = spec.overloads.iter().any(|overload| overload.variadic);
|
||||
if variadic {
|
||||
assert!(
|
||||
spec.overloads.iter().any(|overload| overload.matches(spec.min_args)),
|
||||
"{} has no variadic overload for min arity {}",
|
||||
spec.name,
|
||||
spec.min_args
|
||||
);
|
||||
assert!(
|
||||
spec.overloads.iter().any(|overload| overload.matches(spec.max_args)),
|
||||
"{} has no overload for max arity {}",
|
||||
spec.name,
|
||||
spec.max_args
|
||||
);
|
||||
} else {
|
||||
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
|
||||
let required = spec.params.iter().filter(|param| !param.optional).count();
|
||||
let optional = spec.params.iter().filter(|param| param.optional).count();
|
||||
assert_eq!(required, spec.min_args, "{} required params", spec.name);
|
||||
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
|
||||
for arity in spec.min_args..=spec.max_args {
|
||||
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
|
||||
}
|
||||
}
|
||||
|
||||
for example in spec.examples {
|
||||
assert!(parse_expression(example).is_ok(), "{} example does not parse: {example}", spec.name);
|
||||
}
|
||||
assert!(lookup(&spec.name.to_ascii_lowercase()).is_some(), "{} lookup", spec.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalogued_zero_argument_functions_expose_their_return_type() {
|
||||
for spec in catalog().iter().filter(|spec| spec.min_args == 0) {
|
||||
let source = format!("{}()", spec.name);
|
||||
let expr = parse_expression(&source).unwrap_or_else(|error| panic!("{source}: {error}"));
|
||||
let expected = match spec.return_type {
|
||||
ReturnType::Integer => InferredType::Data(DataType::Integer),
|
||||
ReturnType::Decimal => InferredType::Data(DataType::Decimal),
|
||||
ReturnType::Numeric => InferredType::Unknown,
|
||||
ReturnType::Currency => InferredType::Data(DataType::Currency),
|
||||
ReturnType::Boolean => InferredType::Data(DataType::Boolean),
|
||||
ReturnType::DateTime => InferredType::Data(DataType::DateTime),
|
||||
ReturnType::String => InferredType::Data(DataType::String),
|
||||
ReturnType::Variant => InferredType::Data(DataType::Variant),
|
||||
ReturnType::Table => InferredType::Table,
|
||||
ReturnType::Blank => InferredType::Blank,
|
||||
ReturnType::Any => InferredType::Unknown,
|
||||
};
|
||||
assert_eq!(infer_type(&expr), Ok(expected), "{} return type", spec.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Every catalogued DAX function must reach an evaluator path.
|
||||
//!
|
||||
//! The catalog is the source of truth for the 484 functions. These tests build a minimal call for
|
||||
//! each spec — at *every* documented arity, using each overload's parameter kinds — bind it
|
||||
//! against a small model and evaluate it. A structured "not implemented" error, or a bind
|
||||
//! failure, fails the test: both mean the function has no evaluator path.
|
||||
//!
|
||||
//! `catalog_counts_by_category` guards the documented catalog numbers; `catalog_names_are_unique`
|
||||
//! guards against a duplicate record hiding a missing function.
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, ParamKind, ReturnType, catalog};
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
/// Whether this build links every evaluator family.
|
||||
///
|
||||
/// The evaluator families ship in separate branches, and the crate documents that a function
|
||||
/// whose family is not linked reports "not implemented". Only a build that links all of them can
|
||||
/// assert that *no* catalogued function lacks an evaluator path, so the assertion below is armed
|
||||
/// again automatically as soon as the last family lands.
|
||||
fn all_families_linked() -> bool {
|
||||
gridcraft_dax::eval::linked_families().count() == gridcraft_dax::eval::ALL_FAMILIES.len()
|
||||
}
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Boolean(true), Scalar::DateTime(45292.0)],
|
||||
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Boolean(false), Scalar::DateTime(45293.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Boolean(true), Scalar::DateTime(45294.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::String("Bike".into()), Scalar::Decimal(100.0)], vec![Scalar::String("Helmet".into()), Scalar::Decimal(25.0)]],
|
||||
},
|
||||
],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
/// A syntactically valid argument for a catalog parameter kind.
|
||||
fn placeholder(kind: ParamKind) -> &'static str {
|
||||
match kind {
|
||||
ParamKind::Column => "Sales[Amount]",
|
||||
ParamKind::Table | ParamKind::Reference => "Sales",
|
||||
ParamKind::Expression => "Sales[Amount]",
|
||||
ParamKind::Logical | ParamKind::Boolean => "TRUE",
|
||||
ParamKind::Text => "\"text\"",
|
||||
ParamKind::Date => "DATE(2024,1,1)",
|
||||
ParamKind::Function => "SUM",
|
||||
ParamKind::Number | ParamKind::Scalar | ParamKind::Any | ParamKind::Variant | ParamKind::Json => "1",
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a minimal call with `arity` arguments taken from the matching overload (or the
|
||||
/// descriptive signature when no overload matches, which the shape test rejects).
|
||||
fn formula(name: &str, arity: usize) -> String {
|
||||
let spec = gridcraft_dax::functions::lookup(name).expect("catalogued");
|
||||
let kinds: Vec<ParamKind> = match spec.overload_for(arity) {
|
||||
Some(overload) => (0..arity).map(|index| overload.kind_at(index).unwrap_or(ParamKind::Any)).collect(),
|
||||
None => (0..arity).map(|index| spec.params.get(index).map(|param| param.kind).unwrap_or(ParamKind::Any)).collect(),
|
||||
};
|
||||
let args: Vec<&str> = kinds.iter().map(|kind| placeholder(*kind)).collect();
|
||||
format!("{name}({})", args.join(", "))
|
||||
}
|
||||
|
||||
/// Every arity the catalog documents for a function, including the variadic minimum.
|
||||
fn documented_arities(name: &str) -> Vec<usize> {
|
||||
let spec = gridcraft_dax::functions::lookup(name).expect("catalogued");
|
||||
let mut arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
|
||||
arities.push(spec.min_args);
|
||||
arities.sort_unstable();
|
||||
arities.dedup();
|
||||
arities
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_catalogued_function_has_an_evaluator_path() {
|
||||
let model = model();
|
||||
let binder = Binder::new(&model);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let mut failures = Vec::new();
|
||||
let mut checked = 0usize;
|
||||
|
||||
for spec in catalog() {
|
||||
for arity in documented_arities(spec.name) {
|
||||
checked += 1;
|
||||
let source = formula(spec.name, arity);
|
||||
let expr = match parse_expression(&source) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => {
|
||||
failures.push(format!("{}: parse error in `{source}`: {error}", spec.name));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let bound = match binder.bind_expression(&expr) {
|
||||
Ok(bound) => bound,
|
||||
Err(error) => {
|
||||
failures.push(format!("{}: bind error in `{source}`: {error}", spec.name));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = if spec.return_type == ReturnType::Table {
|
||||
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
|
||||
} else {
|
||||
evaluator.evaluate(&bound)
|
||||
};
|
||||
if let Err(error) = result
|
||||
&& error.message.contains("not implemented")
|
||||
&& all_families_linked()
|
||||
{
|
||||
failures.push(format!("{}: `{source}` -> {error}", spec.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(checked >= catalog().len(), "every function is checked at least once");
|
||||
assert!(failures.is_empty(), "{} calls have no evaluator path:\n{}", failures.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_counts_by_category() {
|
||||
// Guards the documentation numbers: 484 catalogued, split across the documented families.
|
||||
assert_eq!(catalog().len(), 484);
|
||||
for category in FunctionCategory::ALL {
|
||||
assert!(catalog().iter().any(|spec| spec.category == category), "{} has functions", category.name());
|
||||
}
|
||||
|
||||
// The exact split, so a function moving family (or a silently dropped record) fails here
|
||||
// instead of hiding behind the total.
|
||||
let expected: [(FunctionCategory, usize); 15] = [
|
||||
(FunctionCategory::Aggregation, 22),
|
||||
(FunctionCategory::DateAndTime, 24),
|
||||
(FunctionCategory::Filter, 29),
|
||||
(FunctionCategory::Financial, 51),
|
||||
(FunctionCategory::Information, 114),
|
||||
(FunctionCategory::Logical, 13),
|
||||
(FunctionCategory::MathAndTrig, 49),
|
||||
(FunctionCategory::Other, 16),
|
||||
(FunctionCategory::ParentChild, 5),
|
||||
(FunctionCategory::RelationshipManagement, 4),
|
||||
(FunctionCategory::Statistical, 43),
|
||||
(FunctionCategory::TableManipulation, 35),
|
||||
(FunctionCategory::Text, 23),
|
||||
(FunctionCategory::TimeIntelligence, 45),
|
||||
(FunctionCategory::VisualCalculations, 11),
|
||||
];
|
||||
let mut failures = Vec::new();
|
||||
for (category, count) in expected {
|
||||
let actual = catalog().iter().filter(|spec| spec.category == category).count();
|
||||
if actual != count {
|
||||
failures.push(format!("{}: {actual} catalogued, documented {count}", category.name()));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "catalog family counts drifted:\n{}", failures.join("\n"));
|
||||
assert_eq!(expected.iter().map(|(_, count)| count).sum::<usize>(), catalog().len(), "the family counts add up to the catalog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_names_are_unique() {
|
||||
let mut names: Vec<String> = catalog().iter().map(|spec| spec.name.to_ascii_uppercase()).collect();
|
||||
let total = names.len();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(total, names.len(), "the catalog has duplicate function names");
|
||||
for spec in catalog() {
|
||||
assert!(gridcraft_dax::functions::lookup(spec.name).is_some(), "{} is not reachable through lookup", spec.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
//! Data-type, literal and operator-table tests for `gridcraft-dax`.
|
||||
|
||||
use gridcraft_dax::ast::{DateTimeLiteral, Expr, ExprKind, Literal};
|
||||
use gridcraft_dax::types::{
|
||||
DataType, InferredType, PseudoType, TypeError, arithmetic_type, binary_type, comparison_coercion, comparison_compatible, comparison_type,
|
||||
infer_type, literal_type, numeric_matrix_order, unary_type,
|
||||
};
|
||||
use gridcraft_dax::{BinaryOp, Span, TokenKind, UnaryOp, parse_expression, print_expression, tokenize};
|
||||
|
||||
fn parse(src: &str) -> Expr {
|
||||
match parse_expression(src) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("{src:?} did not parse: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn literal(src: &str) -> Literal {
|
||||
match parse(src).kind {
|
||||
ExprKind::Literal(literal) => literal,
|
||||
other => panic!("{src:?} is not a literal: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses, prints, re-parses and asserts the AST is unchanged. Returns the canonical text.
|
||||
fn round_trip(src: &str) -> String {
|
||||
let parsed = parse(src);
|
||||
let printed = print_expression(&parsed);
|
||||
let reparsed = parse(&printed);
|
||||
assert_eq!(parsed, reparsed, "round trip changed the AST for {src:?} via {printed:?}");
|
||||
printed
|
||||
}
|
||||
|
||||
fn infer(src: &str) -> Result<InferredType, TypeError> {
|
||||
infer_type(&parse(src))
|
||||
}
|
||||
|
||||
fn data(data_type: DataType) -> InferredType {
|
||||
InferredType::Data(data_type)
|
||||
}
|
||||
|
||||
fn arithmetic(op: BinaryOp, left: DataType, right: DataType) -> Result<InferredType, TypeError> {
|
||||
arithmetic_type(op, data(left), data(right))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_scalar_types_and_metadata() {
|
||||
assert_eq!(DataType::ALL.map(DataType::name), ["Binary", "Boolean", "Currency", "DateTime", "Decimal", "Integer", "String", "Variant"]);
|
||||
|
||||
for data_type in DataType::ALL {
|
||||
let metadata = data_type.metadata();
|
||||
assert_eq!(metadata.name, data_type.name());
|
||||
assert!(!metadata.representation.is_empty(), "{} representation", data_type.name());
|
||||
assert!(!metadata.range.is_empty(), "{} range", data_type.name());
|
||||
assert!(!metadata.precision.is_empty(), "{} precision", data_type.name());
|
||||
assert!(!metadata.notes.is_empty(), "{} notes", data_type.name());
|
||||
assert_eq!(data_type.has_literal(), metadata.literal_syntax.is_some());
|
||||
assert!(!metadata.name.is_empty());
|
||||
}
|
||||
|
||||
assert_eq!(DataType::ALL.map(DataType::has_literal), [false, true, false, true, true, true, true, false], "literal availability per type");
|
||||
assert!(DataType::Binary.metadata().literal_syntax.is_none());
|
||||
assert!(DataType::Boolean.metadata().literal_syntax.is_some());
|
||||
assert!(DataType::Currency.metadata().literal_syntax.is_none());
|
||||
assert!(DataType::DateTime.metadata().literal_syntax.is_some());
|
||||
assert!(DataType::Decimal.metadata().literal_syntax.is_some());
|
||||
assert!(DataType::Integer.metadata().literal_syntax.is_some());
|
||||
assert!(DataType::String.metadata().literal_syntax.is_some());
|
||||
assert!(DataType::Variant.metadata().literal_syntax.is_none());
|
||||
|
||||
assert!(DataType::Integer.is_numeric());
|
||||
assert!(DataType::Currency.is_numeric());
|
||||
assert!(DataType::Decimal.is_numeric());
|
||||
assert!(!DataType::Boolean.is_numeric());
|
||||
assert!(!DataType::DateTime.is_numeric());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_and_table_are_pseudo_types_distinct_from_the_eight() {
|
||||
assert_eq!(PseudoType::ALL.map(PseudoType::name), ["BLANK", "Table"]);
|
||||
assert!(DataType::ALL.iter().all(|data_type| data_type.name() != "BLANK"));
|
||||
assert!(DataType::ALL.iter().all(|data_type| data_type.name() != "Table"));
|
||||
|
||||
let blank = PseudoType::Blank.metadata();
|
||||
assert_eq!(blank.name, "BLANK");
|
||||
assert!(blank.literal_syntax.is_none(), "BLANK has no literal");
|
||||
assert!(blank.notes.contains("BLANK()"), "BLANK is a function: {}", blank.notes);
|
||||
|
||||
let table = PseudoType::Table.metadata();
|
||||
assert_eq!(table.name, "Table");
|
||||
assert!(table.literal_syntax.is_some(), "table constructors exist");
|
||||
assert!(!table.representation.is_empty());
|
||||
|
||||
assert_eq!(InferredType::from(PseudoType::Blank), InferredType::Blank);
|
||||
assert_eq!(InferredType::from(PseudoType::Table), InferredType::Table);
|
||||
assert_eq!(InferredType::Blank.name(), "BLANK");
|
||||
assert_eq!(InferredType::Table.name(), "Table");
|
||||
assert_eq!(InferredType::Unknown.name(), "unknown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_classification() {
|
||||
for (src, data_type) in [
|
||||
("42", DataType::Integer),
|
||||
("-42", DataType::Integer),
|
||||
("3.14", DataType::Decimal),
|
||||
("1e3", DataType::Decimal),
|
||||
("dt\"2023-05-19\"", DataType::DateTime),
|
||||
("\"text\"", DataType::String),
|
||||
("TRUE", DataType::Boolean),
|
||||
] {
|
||||
// `-42` is a unary expression, so inspect its operand before classifying.
|
||||
let expr = parse(src);
|
||||
let node = match &expr.kind {
|
||||
ExprKind::Unary { expr, .. } => expr.as_ref(),
|
||||
_ => &expr,
|
||||
};
|
||||
match &node.kind {
|
||||
ExprKind::Literal(value) => assert_eq!(literal_type(value), data_type, "{src}"),
|
||||
other => panic!("{src:?} did not contain a literal: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::approx_constant)] // 3.14 is the documented Decimal example, not PI.
|
||||
fn integer_and_decimal_literals_are_distinct() {
|
||||
assert_eq!(literal("0"), Literal::Integer(0));
|
||||
assert_eq!(literal("42"), Literal::Integer(42));
|
||||
assert_eq!(literal("007"), Literal::Integer(7));
|
||||
assert_eq!(literal("9223372036854775807"), Literal::Integer(i64::MAX));
|
||||
|
||||
for (src, value, canonical) in [
|
||||
("3.14", 3.14, "3.14"),
|
||||
("1e3", 1000.0, "1000.0"),
|
||||
("1E3", 1000.0, "1000.0"),
|
||||
("1.5E-3", 0.0015, "0.0015"),
|
||||
(".5", 0.5, "0.5"),
|
||||
("1.", 1.0, "1.0"),
|
||||
("1.e3", 1000.0, "1000.0"),
|
||||
("0.000001", 0.000001, "1e-6"),
|
||||
] {
|
||||
assert_eq!(literal(src), Literal::Decimal(value), "{src}");
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
// The sign is always the unary operator, never part of the numeric token.
|
||||
match parse("-42").kind {
|
||||
ExprKind::Unary { op: UnaryOp::Neg, expr } => {
|
||||
assert_eq!(expr.kind, ExprKind::Literal(Literal::Integer(42)));
|
||||
}
|
||||
other => panic!("expected unary minus, found {other:?}"),
|
||||
}
|
||||
match parse("+42").kind {
|
||||
ExprKind::Unary { op: UnaryOp::Plus, expr } => {
|
||||
assert_eq!(expr.kind, ExprKind::Literal(Literal::Integer(42)));
|
||||
}
|
||||
other => panic!("expected unary plus, found {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_literal_overflow_is_a_structured_error() {
|
||||
for (src, needle) in [
|
||||
("9223372036854775808", "integer literal is out of range"),
|
||||
("99999999999999999999999999999999999999", "integer literal is out of range"),
|
||||
("1e400", "decimal literal is out of range"),
|
||||
] {
|
||||
let error = match parse_expression(src) {
|
||||
Ok(expr) => panic!("{src:?} unexpectedly parsed as {expr:?}"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.message.contains(needle), "{}: {}", src, error.message);
|
||||
assert_eq!(error.span, Span::new(0, src.len()), "{src}");
|
||||
assert!(error.to_string().contains(&error.span.start.to_string()));
|
||||
}
|
||||
|
||||
// Limitation: the sign is a unary operator, so the unsigned magnitude of i64::MIN cannot be
|
||||
// written as an Integer literal. The parser reports the overflow instead of wrapping.
|
||||
assert!(parse_expression("-9223372036854775808").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lexer_emits_typed_literal_tokens() {
|
||||
let tokens = match tokenize("1 2.5 dt\"2023-01-01\" \"x\" TRUE") {
|
||||
Ok(tokens) => tokens,
|
||||
Err(error) => panic!("tokenization failed: {error}"),
|
||||
};
|
||||
assert_eq!(tokens.first().map(|token| &token.kind), Some(&TokenKind::Integer(1)));
|
||||
assert_eq!(tokens.get(1).map(|token| &token.kind), Some(&TokenKind::Decimal(2.5)));
|
||||
assert!(matches!(
|
||||
tokens.get(2).map(|token| &token.kind),
|
||||
Some(TokenKind::DateTime(DateTimeLiteral { year: 2023, month: 1, day: 1, has_time: false, .. }))
|
||||
));
|
||||
assert_eq!(tokens.get(3).map(|token| &token.kind), Some(&TokenKind::String("x".into())));
|
||||
assert_eq!(tokens.get(4).map(|token| &token.kind), Some(&TokenKind::Ident("TRUE".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_literal_forms_are_accepted_and_canonicalised() {
|
||||
for (src, canonical) in [
|
||||
("dt\"2023-05-19\"", "dt\"2023-05-19\""),
|
||||
("dt\"2023-05-19T14:30:00\"", "dt\"2023-05-19T14:30:00\""),
|
||||
("dt\"2023-05-19 14:30:00\"", "dt\"2023-05-19T14:30:00\""),
|
||||
("dt\"2015-1-9T2:3:0\"", "dt\"2015-01-09T02:03:00\""),
|
||||
("dt\"2023-5-9\"", "dt\"2023-05-09\""),
|
||||
("dt\"2024-2-29\"", "dt\"2024-02-29\""),
|
||||
("DT\"2023-5-19\"", "dt\"2023-05-19\""),
|
||||
] {
|
||||
assert_eq!(round_trip(src), canonical, "{src}");
|
||||
}
|
||||
|
||||
match literal("dt\"2015-1-9T2:3:0\"") {
|
||||
Literal::DateTime(value) => {
|
||||
assert_eq!(value, DateTimeLiteral { year: 2015, month: 1, day: 9, hour: 2, minute: 3, second: 0, has_time: true })
|
||||
}
|
||||
other => panic!("expected a DateTime literal, found {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_literal_rejects_invalid_forms() {
|
||||
for src in [
|
||||
// Timezone offsets and fractional seconds are not part of the DAX literal forms.
|
||||
"dt\"2023-05-19T14:30:00Z\"",
|
||||
"dt\"2023-05-19T14:30:00+02:00\"",
|
||||
"dt\"2023-05-19T14:30:00.123\"",
|
||||
// Time-only and incomplete values.
|
||||
"dt\"14:30:00\"",
|
||||
"dt\"2023-05-19T14:30\"",
|
||||
"dt\"2023-05\"",
|
||||
"dt\"20230519\"",
|
||||
"dt\"23-05-19\"",
|
||||
"dt\"2023-05-19T\"",
|
||||
// Invalid calendar fields.
|
||||
"dt\"2023-02-29\"",
|
||||
"dt\"1900-02-29\"",
|
||||
"dt\"2023-13-01\"",
|
||||
"dt\"2023-00-01\"",
|
||||
"dt\"2023-04-31\"",
|
||||
"dt\"2023-01-00\"",
|
||||
"dt\"2023-01-32\"",
|
||||
"dt\"0000-01-01\"",
|
||||
"dt\"2023-05-19T24:00:00\"",
|
||||
"dt\"2023-05-19T14:60:00\"",
|
||||
"dt\"2023-05-19T14:30:60\"",
|
||||
// Wrong case separator; whitespace between prefix and quote.
|
||||
"dt\"2023-05-19t14:30:00\"",
|
||||
"dt \"2023-05-19\"",
|
||||
] {
|
||||
assert!(parse_expression(src).is_err(), "expected an error for {src:?}");
|
||||
}
|
||||
|
||||
// `dt` alone is an ordinary identifier, not a literal.
|
||||
assert!(matches!(parse("dt").kind, ExprKind::Name(_)));
|
||||
let error = match parse_expression("dt\"2023-02-29\"") {
|
||||
Ok(expr) => panic!("invalid calendar date parsed as {expr:?}"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.message.contains("date/time literal"), "{}", error.message);
|
||||
assert_eq!(error.span, Span::new(0, "dt\"2023-02-29\"".len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_printing_round_trips() {
|
||||
for src in [
|
||||
"0",
|
||||
"42",
|
||||
"3.14",
|
||||
"1e300",
|
||||
"1.2345678901234568e18",
|
||||
"dt\"2023-05-19\"",
|
||||
"dt\"2023-05-19T14:30:00\"",
|
||||
"\"a\"\"b\"",
|
||||
"\"\"",
|
||||
"TRUE",
|
||||
"FALSE",
|
||||
"TRUE()",
|
||||
"BLANK()",
|
||||
"1 + 2.5",
|
||||
"(1 + 2) * 3.0",
|
||||
"dt\"2023-05-19\" + 1",
|
||||
] {
|
||||
let printed = round_trip(src);
|
||||
if let ExprKind::Literal(Literal::Decimal(value)) = parse(&printed).kind {
|
||||
assert!(value.is_finite(), "{src} printed a non-finite Decimal");
|
||||
assert!(printed.contains('.') || printed.contains('e') || printed.contains('E'), "Decimal text must re-lex as a Decimal: {printed}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boolean_literals_are_distinct_from_boolean_calls() {
|
||||
assert_eq!(literal("TRUE"), Literal::Boolean(true));
|
||||
assert_eq!(literal("FALSE"), Literal::Boolean(false));
|
||||
|
||||
for (src, spelling) in [("TRUE()", "TRUE"), ("true()", "true"), ("FALSE()", "FALSE")] {
|
||||
match parse(src).kind {
|
||||
ExprKind::Call(call) => {
|
||||
assert!(call.args.is_empty());
|
||||
assert_eq!(call.name.text, spelling);
|
||||
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
|
||||
}
|
||||
other => panic!("{src:?} is not a call: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// `TRUE(1)` is still a call and is not a literal; the catalog return type is Boolean even
|
||||
// though arity validation rejects the call.
|
||||
assert!(matches!(parse("TRUE(1)").kind, ExprKind::Call(_)));
|
||||
assert_eq!(infer("TRUE(1)"), Ok(data(DataType::Boolean)));
|
||||
assert_eq!(infer("FALSE(1)"), Ok(data(DataType::Boolean)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_is_a_call_not_a_literal() {
|
||||
match parse("BLANK()").kind {
|
||||
ExprKind::Call(call) => {
|
||||
assert_eq!(call.name.text, "BLANK");
|
||||
assert!(call.args.is_empty());
|
||||
}
|
||||
other => panic!("BLANK() is a call: {other:?}"),
|
||||
}
|
||||
assert_eq!(infer("BLANK()"), Ok(InferredType::Blank));
|
||||
assert!(matches!(parse("BLANK").kind, ExprKind::Name(_)));
|
||||
assert_eq!(infer("BLANK"), Ok(InferredType::Unknown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_operator_inference() {
|
||||
for (src, expected) in [
|
||||
("1 + 2", data(DataType::Integer)),
|
||||
("1 - 2", data(DataType::Integer)),
|
||||
("1 * 2", data(DataType::Integer)),
|
||||
("1 / 2", data(DataType::Decimal)),
|
||||
("1.0 + 2", data(DataType::Decimal)),
|
||||
("1 + 2.0", data(DataType::Decimal)),
|
||||
("2 ^ 3", data(DataType::Decimal)),
|
||||
("1 & 2", data(DataType::String)),
|
||||
// Excel: 12&34 is "1234"; the observed result is evaluator output, the type is String.
|
||||
("12 & 34", data(DataType::String)),
|
||||
("1 = 2", data(DataType::Boolean)),
|
||||
// Excel: "Report" = "REPORT" is TRUE (case-insensitive collation is evaluator work).
|
||||
("\"Report\" = \"REPORT\"", data(DataType::Boolean)),
|
||||
("1 <> 2", data(DataType::Boolean)),
|
||||
("1 < 2", data(DataType::Boolean)),
|
||||
("1 > 2", data(DataType::Boolean)),
|
||||
("1 <= 2", data(DataType::Boolean)),
|
||||
("1 >= 2", data(DataType::Boolean)),
|
||||
("1 == 1", data(DataType::Boolean)),
|
||||
("TRUE && FALSE", data(DataType::Boolean)),
|
||||
("TRUE || FALSE", data(DataType::Boolean)),
|
||||
("NOT TRUE", data(DataType::Boolean)),
|
||||
("1 IN { 1 }", data(DataType::Boolean)),
|
||||
("(1, \"a\") IN { (1, \"a\") }", data(DataType::Boolean)),
|
||||
("TRUE() + 1", data(DataType::Integer)),
|
||||
("-1", data(DataType::Integer)),
|
||||
("+1", data(DataType::Integer)),
|
||||
("-1.5", data(DataType::Decimal)),
|
||||
("-TRUE()", data(DataType::Integer)),
|
||||
("dt\"2023-05-19\" + 1", data(DataType::DateTime)),
|
||||
("1 + dt\"2023-05-19\"", data(DataType::DateTime)),
|
||||
("dt\"2023-05-19\" - 1", data(DataType::DateTime)),
|
||||
("dt\"2023-05-19\" - dt\"2023-05-20\"", data(DataType::DateTime)),
|
||||
("SUM(1, 2)", InferredType::Unknown),
|
||||
("VALUES(T[Col])", InferredType::Table),
|
||||
] {
|
||||
assert_eq!(infer(src), Ok(expected), "{src}");
|
||||
}
|
||||
|
||||
for src in ["[Amount]", "\"22\" + 22", "[Amount] + 1", "[Amount] - 1"] {
|
||||
assert_eq!(infer(src), Ok(InferredType::Unknown), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_arithmetic_keeps_blank_polymorphic() {
|
||||
for (src, expected) in [
|
||||
("BLANK() + 5", data(DataType::Integer)),
|
||||
("5 + BLANK()", data(DataType::Integer)),
|
||||
("BLANK() + 2.5", data(DataType::Decimal)),
|
||||
("BLANK() + TRUE()", data(DataType::Integer)),
|
||||
("BLANK() + dt\"2023-05-19\"", data(DataType::DateTime)),
|
||||
("BLANK() + BLANK()", InferredType::Blank),
|
||||
("BLANK() - BLANK()", InferredType::Blank),
|
||||
("BLANK() * 5", InferredType::Blank),
|
||||
("5 * BLANK()", InferredType::Blank),
|
||||
("BLANK() * BLANK()", InferredType::Blank),
|
||||
("5 / BLANK()", data(DataType::Decimal)),
|
||||
("0 / BLANK()", data(DataType::Decimal)),
|
||||
("BLANK() / 5", InferredType::Blank),
|
||||
("BLANK() / BLANK()", InferredType::Blank),
|
||||
("-BLANK()", InferredType::Blank),
|
||||
] {
|
||||
assert_eq!(infer(src), Ok(expected), "{src}");
|
||||
}
|
||||
|
||||
assert_eq!(infer("BLANK() + [Amount]"), Ok(InferredType::Unknown));
|
||||
assert_eq!(infer("BLANK() * [Amount]"), Ok(InferredType::Blank));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_comparisons_and_coercions() {
|
||||
for src in ["TRUE() = 1", "1 = TRUE()", "\"1\" = 1", "1 = \"1\"", "\"1\" > 0", "TRUE() == 1", "\"1\" == 1"] {
|
||||
let error = match infer(src) {
|
||||
Ok(inferred) => panic!("{src:?} unexpectedly inferred {inferred:?}"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{src}: {error:?}");
|
||||
assert!(error.to_string().contains("cannot combine"), "{error}");
|
||||
}
|
||||
|
||||
// BLANK is coerced to 0, "" or FALSE for `=`, and comparisons still yield Boolean.
|
||||
for src in ["BLANK() = 0", "BLANK() <> 0", "BLANK() = \"\"", "BLANK() = FALSE()", "BLANK() = BLANK()"] {
|
||||
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
|
||||
}
|
||||
|
||||
// `==` is strict and does not coerce BLANK, but the comparison is still well-typed.
|
||||
for src in ["BLANK() == 0", "BLANK() == \"\"", "0 == BLANK()"] {
|
||||
assert_eq!(infer(src), Ok(data(DataType::Boolean)), "{src}");
|
||||
}
|
||||
|
||||
assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::Integer)), Ok(data(DataType::Integer)));
|
||||
assert_eq!(comparison_coercion(InferredType::Blank, data(DataType::String)), Ok(data(DataType::String)));
|
||||
assert_eq!(comparison_coercion(data(DataType::Boolean), InferredType::Blank), Ok(data(DataType::Boolean)));
|
||||
assert_eq!(comparison_coercion(InferredType::Blank, InferredType::Blank), Ok(InferredType::Blank));
|
||||
assert_eq!(comparison_coercion(data(DataType::Integer), data(DataType::Currency)), Ok(data(DataType::Currency)));
|
||||
assert_eq!(
|
||||
comparison_coercion(data(DataType::String), data(DataType::Integer)),
|
||||
Err(TypeError::IncompatibleTypes { left: data(DataType::String), right: data(DataType::Integer) })
|
||||
);
|
||||
assert_eq!(
|
||||
comparison_coercion(data(DataType::Boolean), data(DataType::Integer)),
|
||||
Err(TypeError::IncompatibleTypes { left: data(DataType::Boolean), right: data(DataType::Integer) })
|
||||
);
|
||||
assert_eq!(
|
||||
comparison_coercion(InferredType::Table, InferredType::Blank),
|
||||
Err(TypeError::IncompatibleTypes { left: InferredType::Table, right: InferredType::Blank })
|
||||
);
|
||||
|
||||
assert_eq!(comparison_compatible(BinaryOp::StrictEq, InferredType::Blank, data(DataType::Integer)), Ok(()));
|
||||
assert_eq!(
|
||||
comparison_compatible(BinaryOp::Eq, data(DataType::String), data(DataType::Integer)),
|
||||
Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: data(DataType::String), right: data(DataType::Integer) })
|
||||
);
|
||||
assert_eq!(
|
||||
comparison_compatible(BinaryOp::Eq, InferredType::Table, data(DataType::Integer)),
|
||||
Err(TypeError::IncompatibleOperands { op: BinaryOp::Eq, left: InferredType::Table, right: data(DataType::Integer) })
|
||||
);
|
||||
assert_eq!(comparison_type(BinaryOp::Eq, data(DataType::Integer), data(DataType::Decimal)), Ok(DataType::Boolean));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_arithmetic_result_matrices() {
|
||||
use DataType::{Currency, DateTime, Decimal, Integer};
|
||||
|
||||
assert_eq!(numeric_matrix_order(), [Integer, Currency, Decimal, DateTime], "matrix order is Integer, Currency, Real, DateTime");
|
||||
|
||||
for (op, left, right, expected) in [
|
||||
// Addition: DateTime wins; Currency promotes against Integer and Decimal.
|
||||
(BinaryOp::Add, Integer, Integer, Integer),
|
||||
(BinaryOp::Add, Integer, Currency, Currency),
|
||||
(BinaryOp::Add, Currency, Decimal, Decimal),
|
||||
(BinaryOp::Add, Integer, DateTime, DateTime),
|
||||
(BinaryOp::Add, DateTime, Integer, DateTime),
|
||||
(BinaryOp::Add, DateTime, DateTime, DateTime),
|
||||
// Subtraction: two dates are documented as DateTime.
|
||||
(BinaryOp::Sub, Integer, Integer, Integer),
|
||||
(BinaryOp::Sub, Integer, Currency, Currency),
|
||||
(BinaryOp::Sub, Integer, DateTime, Decimal),
|
||||
(BinaryOp::Sub, DateTime, Integer, DateTime),
|
||||
(BinaryOp::Sub, DateTime, DateTime, DateTime),
|
||||
// Multiplication reproduces the quirky published cells, including INT*DT -> INT.
|
||||
(BinaryOp::Mul, Integer, Integer, Integer),
|
||||
(BinaryOp::Mul, Integer, Currency, Currency),
|
||||
(BinaryOp::Mul, Currency, Currency, Decimal),
|
||||
(BinaryOp::Mul, Integer, DateTime, Integer),
|
||||
(BinaryOp::Mul, Currency, DateTime, Currency),
|
||||
(BinaryOp::Mul, Decimal, DateTime, Decimal),
|
||||
// Division is Decimal for Integer/Integer and keeps the published Currency cells.
|
||||
(BinaryOp::Div, Integer, Integer, Decimal),
|
||||
(BinaryOp::Div, Integer, Currency, Currency),
|
||||
(BinaryOp::Div, Currency, Currency, Decimal),
|
||||
(BinaryOp::Div, Currency, Integer, Currency),
|
||||
(BinaryOp::Div, DateTime, DateTime, Decimal),
|
||||
(BinaryOp::Div, DateTime, Currency, Decimal),
|
||||
] {
|
||||
assert_eq!(arithmetic(op, left, right), Ok(data(expected)), "{op:?} {left:?} {right:?}");
|
||||
}
|
||||
|
||||
// The multiplication table has no DateTime row; DateTime on the left is a type error.
|
||||
assert!(arithmetic(BinaryOp::Mul, DateTime, Integer).is_err());
|
||||
assert!(arithmetic(BinaryOp::Mul, DateTime, DateTime).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_comparison_matrix_and_date_comparisons() {
|
||||
use DataType::{Currency, DateTime, Decimal, Integer};
|
||||
|
||||
for (left, right, expected) in [
|
||||
(Integer, Integer, Integer),
|
||||
(Integer, Currency, Currency),
|
||||
(Currency, Currency, Currency),
|
||||
(Integer, Decimal, Decimal),
|
||||
(Integer, DateTime, Decimal),
|
||||
(Currency, DateTime, Decimal),
|
||||
(DateTime, DateTime, DateTime),
|
||||
] {
|
||||
assert_eq!(comparison_coercion(data(left), data(right)), Ok(data(expected)), "{left:?} vs {right:?}");
|
||||
}
|
||||
|
||||
for op in [BinaryOp::Eq, BinaryOp::Ne, BinaryOp::Lt, BinaryOp::Gt, BinaryOp::Le, BinaryOp::Ge, BinaryOp::StrictEq] {
|
||||
assert_eq!(comparison_type(op, data(DateTime), data(DateTime)), Ok(DataType::Boolean), "date vs date with {op:?}");
|
||||
assert_eq!(comparison_type(op, data(DateTime), data(Integer)), Ok(DataType::Boolean), "date vs number with {op:?}");
|
||||
}
|
||||
|
||||
assert_eq!(infer("dt\"2023-05-19\" = dt\"2023-05-20\""), Ok(data(DataType::Boolean)));
|
||||
assert_eq!(infer("dt\"2023-05-19\" < 1"), Ok(data(DataType::Boolean)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variant_and_binary_have_no_literals_or_operators() {
|
||||
assert!(DataType::Variant.metadata().literal_syntax.is_none());
|
||||
assert!(DataType::Binary.metadata().literal_syntax.is_none());
|
||||
assert!(matches!(parse("VARIANT").kind, ExprKind::Name(_)));
|
||||
// Container children still participate in inference.
|
||||
assert!(infer("{ 1 + { 2 } }").is_err());
|
||||
assert!(infer("(1 + { 2 })").is_err());
|
||||
assert!(infer("SUM(1 + { 2 })").is_err());
|
||||
assert!(infer("VAR x = 1 + { 2 } RETURN 1").is_err());
|
||||
// Catalogued functions expose their documented return type; unknown names stay unknown.
|
||||
assert_eq!(infer("SUM(Sales[Amount])"), Ok(InferredType::Unknown));
|
||||
assert_eq!(infer("NOT_A_DAX_FUNCTION(1)"), Ok(InferredType::Unknown));
|
||||
assert!(matches!(parse("BINARY").kind, ExprKind::Name(_)));
|
||||
assert_eq!(infer("VARIANT"), Ok(InferredType::Unknown));
|
||||
assert_eq!(infer("BINARY"), Ok(InferredType::Unknown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unary_and_binary_type_helpers_reject_non_scalars() {
|
||||
assert_eq!(unary_type(UnaryOp::Neg, data(DataType::Decimal)), Ok(data(DataType::Decimal)));
|
||||
assert_eq!(unary_type(UnaryOp::Neg, data(DataType::DateTime)), Ok(data(DataType::DateTime)));
|
||||
assert_eq!(unary_type(UnaryOp::Plus, data(DataType::Currency)), Ok(data(DataType::Currency)));
|
||||
assert!(unary_type(UnaryOp::Neg, InferredType::Table).is_err());
|
||||
assert!(unary_type(UnaryOp::Neg, data(DataType::Binary)).is_err());
|
||||
assert_eq!(
|
||||
unary_type(UnaryOp::Not, InferredType::Table),
|
||||
Err(TypeError::IncompatibleUnaryOperand { op: UnaryOp::Not, operand: InferredType::Table })
|
||||
);
|
||||
|
||||
assert_eq!(binary_type(BinaryOp::Concat, data(DataType::Integer), data(DataType::Boolean)), Ok(data(DataType::String)));
|
||||
assert_eq!(binary_type(BinaryOp::And, InferredType::Blank, data(DataType::Boolean)), Ok(data(DataType::Boolean)));
|
||||
assert!(binary_type(BinaryOp::Concat, InferredType::Table, data(DataType::Integer)).is_err());
|
||||
assert!(binary_type(BinaryOp::In, data(DataType::Integer), data(DataType::Integer)).is_err());
|
||||
assert_eq!(binary_type(BinaryOp::In, data(DataType::Integer), InferredType::Table), Ok(data(DataType::Boolean)));
|
||||
assert_eq!(binary_type(BinaryOp::Eq, data(DataType::Boolean), data(DataType::Boolean)), Ok(data(DataType::Boolean)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_calls_are_unknown_in_scalar_operand_positions() {
|
||||
// A table-valued call may resolve to one row/column at evaluation time, so scalar operators
|
||||
// accept it as unknown rather than rejecting a valid formula.
|
||||
for src in ["LASTDATE('Date'[Date]) - 1", "FIRSTDATE('Date'[Order Date]) < TODAY()", "-VALUES(Sales[Amount])"] {
|
||||
assert!(infer(src).is_ok(), "{src} should infer: {:?}", infer(src));
|
||||
}
|
||||
assert_eq!(infer("LASTDATE('Date'[Date]) - 1"), Ok(InferredType::Unknown));
|
||||
// `IN` keeps its operands typed: the left must not be a table.
|
||||
let error = infer("VALUES(Sales[Amount]) IN { 1 }").expect_err("a table on the left of IN");
|
||||
assert!(matches!(error, TypeError::IncompatibleOperands { .. }), "{error:?}");
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Evaluator tests for `AVERAGEA`, `MAXA`, `MINA` and `DISTINCTCOUNTNOBLANK`.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
|
||||
ModelColumn { name: "Note".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Empty".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::Boolean(true), Scalar::String("5".into()), Scalar::Blank],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(20), Scalar::Boolean(false), Scalar::String(String::new()), Scalar::Blank],
|
||||
vec![Scalar::String("East".into()), Scalar::Blank, Scalar::Boolean(true), Scalar::String("abc".into()), Scalar::Blank],
|
||||
vec![Scalar::Blank, Scalar::Integer(40), Scalar::Boolean(false), Scalar::String("7".into()), Scalar::Blank],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn eval(src: &str) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn value(src: &str) -> Scalar {
|
||||
match eval(src) {
|
||||
Ok(value) => value,
|
||||
Err(error) => panic!("{src} failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn averagea_counts_text_booleans_and_blanks() {
|
||||
// Every row counts, a BLANK cell as 0: 10 + 20 + 0 + 40 over four rows. This is the
|
||||
// documented DAX example (1, 20, "n/a", BLANK and TRUE average 22/5).
|
||||
assert_eq!(value("AVERAGEA(Sales[Amount])"), Scalar::Decimal(17.5));
|
||||
// TRUE = 1, FALSE = 0: (1 + 0 + 1 + 0) / 4.
|
||||
assert_eq!(value("AVERAGEA(Sales[Flag])"), Scalar::Decimal(0.5));
|
||||
// Any text counts as 0, numeric or not: "5", "", "abc" and "7" all contribute 0.
|
||||
assert_eq!(value("AVERAGEA(Sales[Note])"), Scalar::Decimal(0.0));
|
||||
// A column with rows but only BLANK cells averages 0, not BLANK.
|
||||
assert_eq!(value("AVERAGEA(Sales[Empty])"), Scalar::Decimal(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn averagea_respects_the_filter_context_and_is_blank_for_no_rows() {
|
||||
// East rows are 10 and BLANK: the BLANK row stays in the denominator.
|
||||
assert_eq!(value("CALCULATE(AVERAGEA(Sales[Amount]), Sales[Region] = \"East\")"), Scalar::Decimal(5.0));
|
||||
assert_eq!(value("CALCULATE(AVERAGEA(Sales[Amount]), Sales[Region] = \"Nowhere\")"), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maxa_and_mina_count_logical_values() {
|
||||
assert_eq!(value("MINA(Sales[Flag])"), Scalar::Decimal(0.0));
|
||||
assert_eq!(value("MAXA(Sales[Flag])"), Scalar::Decimal(1.0));
|
||||
// Text is not rankable, so every text value coerces to 0 before the comparison.
|
||||
assert_eq!(value("MINA(Sales[Note])"), Scalar::Decimal(0.0));
|
||||
assert_eq!(value("MAXA(Sales[Note])"), Scalar::Decimal(0.0));
|
||||
assert_eq!(value("MAXA(Sales[Amount])"), Scalar::Decimal(40.0));
|
||||
assert_eq!(value("MINA(Sales[Amount])"), Scalar::Decimal(10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maxa_and_mina_follow_the_filter_context() {
|
||||
assert_eq!(value("CALCULATE(MAXA(Sales[Amount]), Sales[Region] = \"East\")"), Scalar::Decimal(10.0));
|
||||
assert_eq!(value("CALCULATE(MINA(Sales[Amount]), Sales[Region] = \"West\")"), Scalar::Decimal(20.0));
|
||||
assert_eq!(value("CALCULATE(MAXA(Sales[Flag]), Sales[Region] = \"West\")"), Scalar::Decimal(0.0));
|
||||
assert_eq!(value("CALCULATE(MAXA(Sales[Amount]), Sales[Region] = \"Nowhere\")"), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinctcountnoblank_excludes_blank() {
|
||||
// East, West and one BLANK row -> two distinct non-blank values.
|
||||
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Region])"), Scalar::Integer(2));
|
||||
// The plain DISTINCTCOUNT counts BLANK as a value.
|
||||
assert_eq!(value("DISTINCTCOUNT(Sales[Region])"), Scalar::Integer(3));
|
||||
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Amount])"), Scalar::Integer(3));
|
||||
assert_eq!(value("DISTINCTCOUNTNOBLANK(Sales[Empty])"), Scalar::Integer(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinctcountnoblank_respects_the_filter_context() {
|
||||
// Both East rows carry the same region, so the flag filter leaves one distinct value.
|
||||
assert_eq!(value("CALCULATE(DISTINCTCOUNTNOBLANK(Sales[Region]), Sales[Flag] = TRUE)"), Scalar::Integer(1));
|
||||
assert_eq!(value("CALCULATE(DISTINCTCOUNTNOBLANK(Sales[Region]), Sales[Region] = \"Nowhere\")"), Scalar::Integer(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_a_variants_still_require_a_column() {
|
||||
assert!(eval("AVERAGEA(1)").is_err());
|
||||
assert!(eval("MAXA(\"text\")").is_err());
|
||||
assert!(eval("DISTINCTCOUNTNOBLANK()").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_and_min_with_two_scalars_return_the_larger_or_smaller_value() {
|
||||
// The catalog's two-scalar overload, `MAX ( 10000, [Sales Amount] )`.
|
||||
assert_eq!(value("MAX(3, 5)"), Scalar::Integer(5));
|
||||
assert_eq!(value("MIN(3, 5)"), Scalar::Integer(3));
|
||||
assert_eq!(value("MAX(10000, SUM(Sales[Amount]))"), Scalar::Integer(10000));
|
||||
assert_eq!(value("MIN(1, SUM(Sales[Amount]))"), Scalar::Integer(1));
|
||||
// Text compares case-insensitively, like every DAX comparison.
|
||||
assert_eq!(value("MAX(\"a\", \"B\")"), Scalar::String("B".into()));
|
||||
assert_eq!(value("MIN(\"a\", \"B\")"), Scalar::String("a".into()));
|
||||
// One argument still aggregates the column, not the first cell. The winner keeps its own
|
||||
// Scalar type, so an integer column answers an Integer (`aggregate_values` in the core).
|
||||
assert_eq!(value("MAX(Sales[Amount])"), Scalar::Integer(40));
|
||||
assert_eq!(value("MIN(Sales[Amount])"), Scalar::Integer(10));
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
//! Dispatch audit: every catalogued function, at every documented arity, must reach a real
|
||||
//! evaluator path — never the `not implemented` fallback and never an "unknown function" error.
|
||||
//!
|
||||
//! Three tests:
|
||||
//!
|
||||
//! 1. [`catalog_shape_is_consistent`] — the catalog itself is coherent: 484 unique names, every
|
||||
//! documented family populated, overload arities inside `min_args..=max_args`, sugar links
|
||||
//! resolving.
|
||||
//! 2. [`no_catalogued_function_reaches_a_stub`] — for every overload arity, the call parses,
|
||||
//! binds and evaluates, and the outcome is never the generic "not implemented" fallback.
|
||||
//! 3. [`context_functions_fail_with_a_context_error`] — the functions that legitimately need a
|
||||
//! visual, calculation-item, row or window context reject a bare model evaluation with a
|
||||
//! documented context error, never a stub and never a silently wrong value.
|
||||
//!
|
||||
//! `INFO.*` metadata functions are not in that list: they evaluate against the model catalogue
|
||||
//! itself (returning row counts), so the dispatch audit covers them like any other function.
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog};
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
/// Whether this build links every evaluator family.
|
||||
///
|
||||
/// The evaluator families ship in separate branches, and the crate documents that a function
|
||||
/// whose family is not linked reports "not implemented". The "no stub" assertions therefore only
|
||||
/// apply to a build that links all of them; they arm themselves again as soon as the last family
|
||||
/// lands, so the audit keeps its full strength on the assembled crate.
|
||||
fn all_families_linked() -> bool {
|
||||
gridcraft_dax::eval::linked_families().count() == gridcraft_dax::eval::ALL_FAMILIES.len()
|
||||
}
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
|
||||
ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Boolean(true), Scalar::DateTime(45292.0)],
|
||||
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Boolean(false), Scalar::DateTime(45293.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Boolean(true), Scalar::DateTime(45294.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::String("Bike".into()), Scalar::Decimal(100.0)], vec![Scalar::String("Helmet".into()), Scalar::Decimal(25.0)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(45292.0)], vec![Scalar::DateTime(45293.0)], vec![Scalar::DateTime(45294.0)]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Date".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
/// A syntactically valid argument for a catalog parameter kind.
|
||||
fn placeholder(kind: ParamKind) -> &'static str {
|
||||
match kind {
|
||||
ParamKind::Column => "Sales[Amount]",
|
||||
ParamKind::Table | ParamKind::Reference => "Sales",
|
||||
ParamKind::Expression => "Sales[Amount]",
|
||||
ParamKind::Logical | ParamKind::Boolean => "TRUE",
|
||||
ParamKind::Text => "\"text\"",
|
||||
ParamKind::Date => "DATE(2024,1,1)",
|
||||
ParamKind::Function => "SUM",
|
||||
ParamKind::Number | ParamKind::Scalar | ParamKind::Any | ParamKind::Variant | ParamKind::Json => "1",
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the call for one arity using that overload's parameter kinds.
|
||||
fn formula(spec: &FunctionSpec, arity: usize) -> String {
|
||||
let kinds: Vec<ParamKind> = match spec.overload_for(arity) {
|
||||
Some(overload) => (0..arity).map(|index| overload.kind_at(index).unwrap_or(ParamKind::Any)).collect(),
|
||||
None => (0..arity).map(|index| spec.params.get(index).map(|param| param.kind).unwrap_or(ParamKind::Any)).collect(),
|
||||
};
|
||||
let args: Vec<&str> = kinds.iter().map(|kind| placeholder(*kind)).collect();
|
||||
format!("{}({})", spec.name, args.join(", "))
|
||||
}
|
||||
|
||||
/// The exact text the evaluator uses when a function has no implementation. Two sites produce it
|
||||
/// (`eval.rs` fallback and the time-intelligence range dispatcher), so matching it catches both.
|
||||
const STUB_MARKER: &str = "is not implemented by this evaluator";
|
||||
|
||||
fn is_stub(message: &str) -> bool {
|
||||
let lower = message.to_ascii_lowercase();
|
||||
lower.contains(STUB_MARKER) || lower.contains("unknown function") || lower.contains("is not a function")
|
||||
}
|
||||
|
||||
/// Functions that legitimately cannot be evaluated against a bare model: they need a visual, a
|
||||
/// calculation item, a window/row context or a CALCULATE modifier. Each entry is the *substring the
|
||||
/// evaluator's context error must contain*.
|
||||
fn documented_context_requirements() -> Vec<(&'static str, &'static str)> {
|
||||
let mut list = vec![
|
||||
("ISSUBTOTAL", "SUMMARIZE row context"),
|
||||
("CURRENTGROUP", "GROUPBY"),
|
||||
("ROLLUP", "SUMMARIZE group-by"),
|
||||
("ROLLUPGROUP", "ROLLUP"),
|
||||
("ROLLUPADDISSUBTOTAL", "SUMMARIZECOLUMNS"),
|
||||
("ROLLUPISSUBTOTAL", "ADDMISSINGITEMS"),
|
||||
("SELECTEDMEASURE", "calculation item"),
|
||||
("SELECTEDMEASUREFORMATSTRING", "calculation item"),
|
||||
("SELECTEDMEASURENAME", "calculation item"),
|
||||
("EARLIER", "outer row context"),
|
||||
("EARLIEST", "outer row context"),
|
||||
("RANK", "needs a relation"),
|
||||
("ROWNUMBER", "needs a relation"),
|
||||
("OFFSET", "window function"),
|
||||
("WINDOW", "window function"),
|
||||
("ORDERBY", "window function"),
|
||||
("PARTITIONBY", "window function"),
|
||||
("MATCHBY", "window function"),
|
||||
("RELATED", "row context"),
|
||||
("RELATEDTABLE", "row context"),
|
||||
("CROSSFILTER", "CALCULATE"),
|
||||
("USERELATIONSHIP", "CALCULATE"),
|
||||
];
|
||||
// Visual calculations need a visual frame; they are the whole `VisualCalculations` family.
|
||||
for spec in catalog() {
|
||||
if spec.category == FunctionCategory::VisualCalculations && !list.iter().any(|(name, _)| *name == spec.name) {
|
||||
list.push((spec.name, "visual"));
|
||||
}
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_shape_is_consistent() {
|
||||
let specs = catalog();
|
||||
assert_eq!(specs.len(), 484, "catalogued function count");
|
||||
|
||||
let mut seen: Vec<&str> = specs.iter().map(|spec| spec.name).collect();
|
||||
seen.sort_unstable();
|
||||
let before = seen.len();
|
||||
seen.dedup();
|
||||
assert_eq!(before, seen.len(), "catalog has duplicate names");
|
||||
|
||||
for spec in specs {
|
||||
assert!(spec.min_args <= spec.max_args, "{}: min_args > max_args", spec.name);
|
||||
assert!(!spec.overloads.is_empty(), "{}: no overloads", spec.name);
|
||||
assert!(!spec.description.is_empty(), "{}: empty description", spec.name);
|
||||
for overload in spec.overloads {
|
||||
assert!(
|
||||
overload.arity() >= spec.min_args && overload.arity() <= spec.max_args,
|
||||
"{}: overload arity {} outside {}..={}",
|
||||
spec.name,
|
||||
overload.arity(),
|
||||
spec.min_args,
|
||||
spec.max_args
|
||||
);
|
||||
}
|
||||
if let Some(target) = spec.sugar_of {
|
||||
assert!(specs.iter().any(|other| other.name.eq_ignore_ascii_case(target)), "{}: sugar target `{target}` is not catalogued", spec.name);
|
||||
}
|
||||
}
|
||||
|
||||
let mut counts: Vec<(FunctionCategory, usize)> = FunctionCategory::ALL.iter().map(|category| (*category, 0)).collect();
|
||||
for spec in specs {
|
||||
if let Some(entry) = counts.iter_mut().find(|(category, _)| *category == spec.category) {
|
||||
entry.1 += 1;
|
||||
}
|
||||
}
|
||||
let summary: Vec<String> = counts.iter().map(|(category, count)| format!("{}={count}", category.name())).collect();
|
||||
println!("catalog: {} functions [{}]", specs.len(), summary.join(", "));
|
||||
for (category, count) in counts {
|
||||
assert!(count > 0, "{} has no functions", category.name());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_catalogued_function_reaches_a_stub() {
|
||||
let model = model();
|
||||
let binder = Binder::new(&model);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let mut checked = 0usize;
|
||||
let mut valued = 0usize;
|
||||
let mut blank = 0usize;
|
||||
let mut rejected = 0usize;
|
||||
let mut stubs = Vec::new();
|
||||
let mut bind_failures = Vec::new();
|
||||
let mut functions_with_a_value = 0usize;
|
||||
let mut without_value = Vec::new();
|
||||
|
||||
for spec in catalog() {
|
||||
let mut arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
|
||||
arities.push(spec.min_args);
|
||||
arities.sort_unstable();
|
||||
arities.dedup();
|
||||
|
||||
let mut any_value = false;
|
||||
let mut first_error = String::new();
|
||||
for arity in arities {
|
||||
checked += 1;
|
||||
let source = formula(spec, arity);
|
||||
let expr = match parse_expression(&source) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => {
|
||||
bind_failures.push(format!("{}: parse error in `{source}`: {error}", spec.name));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let bound = match binder.bind_expression(&expr) {
|
||||
Ok(bound) => bound,
|
||||
Err(error) => {
|
||||
bind_failures.push(format!("{}: bind error in `{source}`: {error}", spec.name));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = if spec.return_type == ReturnType::Table {
|
||||
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
|
||||
} else {
|
||||
evaluator.evaluate(&bound)
|
||||
};
|
||||
match result {
|
||||
Ok(Scalar::Blank) => {
|
||||
blank += 1;
|
||||
any_value = true;
|
||||
}
|
||||
Ok(_) => {
|
||||
valued += 1;
|
||||
any_value = true;
|
||||
}
|
||||
Err(error) => {
|
||||
if first_error.is_empty() {
|
||||
first_error = error.message.clone();
|
||||
}
|
||||
if is_stub(&error.message) && all_families_linked() {
|
||||
stubs.push(format!("{}: `{source}` -> {}", spec.name, error.message));
|
||||
} else {
|
||||
rejected += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if any_value {
|
||||
functions_with_a_value += 1;
|
||||
} else {
|
||||
without_value.push(format!("{}: {first_error}", spec.name));
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"dispatch audit: {checked} calls over {} functions — {valued} values, {blank} blanks, {rejected} argument/context rejections, {} stubs",
|
||||
catalog().len(),
|
||||
stubs.len()
|
||||
);
|
||||
println!("functions that produced at least one value: {functions_with_a_value}");
|
||||
for line in &without_value {
|
||||
println!("NO VALUE {line}");
|
||||
}
|
||||
assert!(bind_failures.is_empty(), "{} calls do not parse/bind:\n{}", bind_failures.len(), bind_failures.join("\n"));
|
||||
assert!(stubs.is_empty(), "{} calls reach no evaluator path:\n{}", stubs.len(), stubs.join("\n"));
|
||||
// Mass-regression guard: with deliberately generic placeholder arguments a majority of
|
||||
// functions still return a value (the rest reject the argument shape), so a collapse in this
|
||||
// number means dispatch broke, not that the placeholders changed. A partial build is exempt:
|
||||
// the families it does not link answer with the documented fallback.
|
||||
if all_families_linked() {
|
||||
assert!(
|
||||
functions_with_a_value * 100 >= catalog().len() * 70,
|
||||
"only {functions_with_a_value} of {} functions produced a value; dispatch may have regressed",
|
||||
catalog().len()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_functions_fail_with_a_context_error() {
|
||||
// The list below mixes core functions (`RELATED`, `CROSSFILTER`, `USERELATIONSHIP`) with
|
||||
// functions owned by evaluator families that ship in other branches, and an unlinked family
|
||||
// rejects the column argument before it can report its documented context error. The audit
|
||||
// therefore runs on a build that links every family and re-arms itself as soon as the last
|
||||
// one lands.
|
||||
if !all_families_linked() {
|
||||
return;
|
||||
}
|
||||
let model = model();
|
||||
let binder = Binder::new(&model);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let mut problems = Vec::new();
|
||||
|
||||
for (name, marker) in documented_context_requirements() {
|
||||
let spec = catalog().iter().find(|spec| spec.name.eq_ignore_ascii_case(name));
|
||||
let Some(spec) = spec else {
|
||||
problems.push(format!("{name}: documented as context-dependent but not catalogued"));
|
||||
continue;
|
||||
};
|
||||
let source = formula(spec, spec.min_args);
|
||||
let expr = match parse_expression(&source) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => {
|
||||
problems.push(format!("{name}: parse error in `{source}`: {error}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let bound = match binder.bind_expression(&expr) {
|
||||
Ok(bound) => bound,
|
||||
Err(error) => {
|
||||
problems.push(format!("{name}: bind error in `{source}`: {error}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = if spec.return_type == ReturnType::Table {
|
||||
evaluator.evaluate_table(&bound).map(|table| Scalar::Integer(table.rows.len() as i64))
|
||||
} else {
|
||||
evaluator.evaluate(&bound)
|
||||
};
|
||||
match result {
|
||||
Ok(value) => {
|
||||
// A value is acceptable only when it is BLANK: the function had nothing to work
|
||||
// with, which is a documented empty result, not a wrong answer.
|
||||
if !value.is_blank() {
|
||||
problems.push(format!("{name}: `{source}` returned {value:?} without a context"));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
if is_stub(&error.message) {
|
||||
problems.push(format!("{name}: `{source}` -> stub: {}", error.message));
|
||||
} else if !error.message.to_ascii_lowercase().contains(&marker.to_ascii_lowercase()) {
|
||||
problems.push(format!("{name}: `{source}` -> undocumented error `{}` (expected `{marker}`)", error.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(problems.is_empty(), "{} context functions do not report a documented context error:\n{}", problems.len(), problems.join("\n"));
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Semantic audit regressions.
|
||||
//!
|
||||
//! Each test pins a documented DAX result that the evaluator used to get wrong. The expected
|
||||
//! values come from the function contracts in `crates/dax/src/functions/` and from Microsoft's
|
||||
//! DAX reference; the regression names say which rule is being held.
|
||||
//!
|
||||
//! Covered: BLANK's empty-string comparison, `CALCULATE` filters written with `IN` and its
|
||||
//! removal modifiers, `IF`'s Boolean condition, and the BLANK/Boolean/error propagation rules the
|
||||
//! audit depends on. The per-function cases (`TRIM`, `MOD`, `ROUNDUP`/`ROUNDDOWN`, `DATEDIFF`,
|
||||
//! `TIME`, `WEEKDAY`) live with the evaluator families that implement them, under
|
||||
//! `tests/eval_*.rs`.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel { tables: Vec::new(), relationships: Vec::new(), measures: Vec::new() };
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
/// One table with a text column and a numeric column, enough for CALCULATE filter tests.
|
||||
fn sales_model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::String("West".into()), Scalar::Decimal(20.0)],
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(30.0)],
|
||||
vec![Scalar::String("North".into()), Scalar::Decimal(40.0)],
|
||||
vec![Scalar::String("South".into()), Scalar::Decimal(50.0)],
|
||||
],
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn eval_in_sales(source: &str) -> Scalar {
|
||||
let model = sales_model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(source).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
}
|
||||
|
||||
fn eval(source: &str) -> Scalar {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(source).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
}
|
||||
|
||||
fn error(source: &str) -> String {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(source).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect_err("evaluate must fail").message
|
||||
}
|
||||
|
||||
fn number(source: &str) -> f64 {
|
||||
eval(source).to_number().unwrap_or_else(|| panic!("{source} is not numeric: {:?}", eval(source)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_boolean_and_error_propagation() {
|
||||
// BLANK coerces to 0 in arithmetic and comparisons, but multiplying by BLANK stays BLANK.
|
||||
assert_eq!(number("BLANK() + 1"), 1.0);
|
||||
assert_eq!(eval("BLANK() * 5"), Scalar::Blank);
|
||||
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("BLANK() & \"x\""), Scalar::String("x".into()));
|
||||
assert_eq!(eval("ISBLANK(BLANK())"), Scalar::Boolean(true));
|
||||
// Booleans are 1/0 in arithmetic.
|
||||
assert_eq!(number("TRUE() + 1"), 2.0);
|
||||
// The model engine divides by zero without an error: BLANK for 0/0 and the numerator's sign
|
||||
// of infinity otherwise (Excel's worksheet gives #DIV/0!, DAX does not).
|
||||
assert_eq!(eval("ISERROR(1/0)"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("5 / 0"), Scalar::Decimal(f64::INFINITY));
|
||||
assert_eq!(eval("-5 / 0"), Scalar::Decimal(f64::NEG_INFINITY));
|
||||
assert_eq!(eval("0 / 0"), Scalar::Blank);
|
||||
assert_eq!(eval("BLANK() / BLANK()"), Scalar::Blank);
|
||||
assert_eq!(eval("5 / BLANK()"), Scalar::Decimal(f64::INFINITY));
|
||||
assert_eq!(eval("BLANK() + BLANK()"), Scalar::Blank);
|
||||
assert_eq!(eval("BLANK() - BLANK()"), Scalar::Blank);
|
||||
// Errors still stay errors unless a handler catches them.
|
||||
assert_eq!(eval("ISERROR(1)"), Scalar::Boolean(false));
|
||||
assert!(error("ERROR(\"boom\")").contains("boom"));
|
||||
assert_eq!(number("IFERROR(1/0, 42)"), f64::INFINITY);
|
||||
assert_eq!(eval("IFERROR(ERROR(\"boom\"), 42)"), Scalar::Integer(42));
|
||||
assert_eq!(eval("DIVIDE(1, 0)"), Scalar::Blank);
|
||||
assert_eq!(eval("DIVIDE(1, 0, 99)"), Scalar::Integer(99));
|
||||
assert_eq!(number("DIVIDE(1, 2)"), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_compares_as_empty_text_and_as_zero() {
|
||||
// Excel's DAX: BLANK converts to an empty string against text and to 0 against a number.
|
||||
// `BLANK () = ""` is TRUE in Excel (observed through the Power Pivot model connection).
|
||||
assert_eq!(eval("BLANK() = \"\""), Scalar::Boolean(true));
|
||||
assert_eq!(eval("\"\" = BLANK()"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() <> \"\""), Scalar::Boolean(false));
|
||||
assert_eq!(eval("BLANK() = \"x\""), Scalar::Boolean(false));
|
||||
assert_eq!(eval("\"x\" = BLANK()"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() = BLANK()"), Scalar::Boolean(true));
|
||||
// BLANK converts to FALSE against a logical value, so the comparison is TRUE. This case was
|
||||
// not covered by the Excel sample (BLANK has no worksheet equivalent); it follows the same
|
||||
// convert-to-the-other-operand rule as the two above.
|
||||
assert_eq!(eval("BLANK() = FALSE()"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_filter_accepts_an_in_list() {
|
||||
// East (10 + 30) plus West (20).
|
||||
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "West" })"#), Scalar::Decimal(60.0));
|
||||
// A list of one.
|
||||
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "North" })"#), Scalar::Decimal(40.0));
|
||||
// Duplicates in the list do not double-count rows.
|
||||
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "East", "East", "East" })"#), Scalar::Decimal(40.0));
|
||||
// A value that is not in the column filters everything out.
|
||||
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN { "Nowhere" })"#), Scalar::Blank);
|
||||
// IN over a single-column table expression.
|
||||
assert_eq!(
|
||||
eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Region] IN FILTER(VALUES(Sales[Region]), Sales[Region] <> "East"))"#),
|
||||
Scalar::Decimal(110.0)
|
||||
);
|
||||
// The filter form follows DAX equality too: the Decimal column matches an Integer literal.
|
||||
assert_eq!(eval_in_sales(r#"CALCULATE(SUM(Sales[Amount]), Sales[Amount] IN { 10 })"#), Scalar::Decimal(10.0));
|
||||
// The scalar IN operator keeps working.
|
||||
assert_eq!(eval("1 IN { 1, 2 }"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("3 IN { 1, 2 }"), Scalar::Boolean(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn if_requires_a_boolean_condition() {
|
||||
// Excel rejects a condition it cannot read as logical; it does not take the false branch.
|
||||
assert!(error(r#"IF("x", 1, 2)"#).contains("IF argument 1 must be Boolean"));
|
||||
assert!(error(r#"IF("x", 1, 2)"#).contains("String"));
|
||||
// The documented conditions still work: TRUE, FALSE and BLANK (which converts to FALSE).
|
||||
assert_eq!(eval("IF(TRUE(), 1, 2)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("IF(FALSE(), 1, 2)"), Scalar::Integer(2));
|
||||
assert_eq!(eval("IF(BLANK(), 1, 2)"), Scalar::Integer(2));
|
||||
assert_eq!(eval("IF(1 > 0, 1, 2)"), Scalar::Integer(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_equality_compares_values_and_keeps_blank_strict() {
|
||||
// `==` is strict only about BLANK; every other pair follows DAX comparison, so a number
|
||||
// compares by value and text ignores case.
|
||||
assert_eq!(eval("2 == 2.0"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("1 == 2"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("\"a\" == \"A\""), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() == BLANK()"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() == 0"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("BLANK() == \"\""), Scalar::Boolean(false));
|
||||
// `=` keeps coercing BLANK, as before.
|
||||
assert_eq!(eval("BLANK() = 0"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_equality_matches_a_decimal_column_against_an_integer_literal() {
|
||||
// A Decimal column compared with an integer literal compares numerically: `Sales[Amount]` is
|
||||
// `Scalar::Decimal`, the literal `Scalar::Integer`.
|
||||
assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Amount] == 10))"), Scalar::Integer(1));
|
||||
assert_eq!(eval_in_sales("COUNTROWS(FILTER(Sales, Sales[Region] == \"east\"))"), Scalar::Integer(2));
|
||||
// `strict_eq` keeps text case-sensitive but joins numeric keys across variants, so a
|
||||
// relationship whose keys are Integer on one side and Decimal on the other still matches.
|
||||
assert!(gridcraft_dax::Scalar::Integer(2).strict_eq(&Scalar::Decimal(2.0)));
|
||||
assert!(!gridcraft_dax::Scalar::Integer(2).strict_eq(&Scalar::Decimal(2.5)));
|
||||
assert!(!Scalar::String("a".into()).strict_eq(&Scalar::String("A".into())));
|
||||
// Beyond 2^53 two integers share an `f64`, and they must stay distinct keys.
|
||||
assert!(!Scalar::Integer(9_007_199_254_740_992).strict_eq(&Scalar::Integer(9_007_199_254_740_993)));
|
||||
// A large key still matches itself, in the same variant and through currency.
|
||||
assert!(Scalar::Integer(9_007_199_254_740_993).strict_eq(&Scalar::Integer(9_007_199_254_740_993)));
|
||||
assert!(Scalar::Currency(9_007_199_254_740_993).strict_eq(&Scalar::Currency(9_007_199_254_740_993)));
|
||||
// `compare` keeps the same exactness, so `IN` and `=` do not conflate large integers either.
|
||||
assert_eq!(Scalar::Integer(9_007_199_254_740_992).compare(&Scalar::Integer(9_007_199_254_740_993)), Some(std::cmp::Ordering::Less));
|
||||
assert!(Scalar::Integer(9_007_199_254_740_993).compare(&Scalar::Integer(9_007_199_254_740_993)) == Some(std::cmp::Ordering::Equal));
|
||||
// A large integer against an integral decimal stays exact instead of rounding into it.
|
||||
assert_eq!(Scalar::Integer(9_007_199_254_740_993).compare(&Scalar::Decimal(9_007_199_254_740_992.0)), Some(std::cmp::Ordering::Greater));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_applies_removal_modifiers_before_its_filters() {
|
||||
// `ALL(Sales)` clears the outer context first, whatever its position, and the explicit filters
|
||||
// then apply: both argument orders leave the Region filter in force.
|
||||
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Region] = \"East\", ALL(Sales))"), Scalar::Integer(2));
|
||||
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), ALL(Sales), Sales[Region] = \"East\")"), Scalar::Integer(2));
|
||||
// ALL on a column clears only that column, so the Amount filter survives.
|
||||
assert_eq!(eval_in_sales("CALCULATE(COUNTROWS(Sales), Sales[Amount] = 10, ALL(Sales[Region]))"), Scalar::Integer(1));
|
||||
}
|
||||
@@ -0,0 +1,864 @@
|
||||
//! Evaluator tests for the non-metadata information functions.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, ScalarKey, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, FilterContext, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Color".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Price".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Cost".into(), data_type: Some("Currency".into()) },
|
||||
ModelColumn { name: "Active".into(), data_type: Some("Boolean".into()) },
|
||||
ModelColumn { name: "LaunchDate".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![
|
||||
Scalar::Integer(1),
|
||||
Scalar::String("Wireless Headphones".into()),
|
||||
Scalar::String("Red".into()),
|
||||
Scalar::String("Audio".into()),
|
||||
Scalar::Decimal(20.0),
|
||||
Scalar::Currency(150_000),
|
||||
Scalar::Boolean(true),
|
||||
Scalar::DateTime(45292.0),
|
||||
],
|
||||
vec![
|
||||
Scalar::Integer(2),
|
||||
Scalar::String("Red Widget".into()),
|
||||
Scalar::String("Red".into()),
|
||||
Scalar::String("Audio".into()),
|
||||
Scalar::Decimal(30.5),
|
||||
Scalar::Currency(200_000),
|
||||
Scalar::Boolean(true),
|
||||
Scalar::DateTime(45300.0),
|
||||
],
|
||||
vec![
|
||||
Scalar::Integer(3),
|
||||
Scalar::String("Blue Gadget".into()),
|
||||
Scalar::String("Blue".into()),
|
||||
Scalar::String("Computers".into()),
|
||||
Scalar::Decimal(10.0),
|
||||
Scalar::Currency(50_000),
|
||||
Scalar::Boolean(false),
|
||||
Scalar::DateTime(45310.0),
|
||||
],
|
||||
vec![
|
||||
Scalar::Integer(4),
|
||||
Scalar::String("Noise Cancel Headphones".into()),
|
||||
Scalar::String("Blue".into()),
|
||||
Scalar::String("Audio".into()),
|
||||
Scalar::Decimal(40.0),
|
||||
Scalar::Currency(300_000),
|
||||
Scalar::Boolean(true),
|
||||
Scalar::DateTime(45320.0),
|
||||
],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(10.0), Scalar::Integer(2), Scalar::Integer(1)],
|
||||
vec![Scalar::String("West".into()), Scalar::Decimal(20.0), Scalar::Integer(3), Scalar::Integer(2)],
|
||||
vec![Scalar::String("East".into()), Scalar::Decimal(30.0), Scalar::Integer(4), Scalar::Integer(1)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "EmptyStats".into(),
|
||||
columns: vec![ModelColumn { name: "Empty Value".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
Measure {
|
||||
name: "Total Sales".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: Some("#,0.00".into()),
|
||||
expr: None,
|
||||
},
|
||||
Measure { name: "Total Quantity".into(), formula: "SUM(Sales[Quantity])".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn eval(src: &str) -> Result<Scalar, String> {
|
||||
evaluate(src, FilterContext::default())
|
||||
}
|
||||
|
||||
fn eval_with(src: &str, build_filters: impl FnOnce(&DataModel) -> FilterContext) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
let filters = build_filters(&model);
|
||||
evaluate_with_model(&model, src, filters)
|
||||
}
|
||||
|
||||
fn evaluate(src: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
evaluate_with_model(&model, src, filters)
|
||||
}
|
||||
|
||||
fn evaluate_with_model(model: &DataModel, src: &str, filters: FilterContext) -> Result<Scalar, String> {
|
||||
let evaluator = Evaluator::new(model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_with(&bound, filters).map_err(|error| error.message)
|
||||
}
|
||||
|
||||
fn eval_table(src: &str) -> Result<TableValue, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.message)
|
||||
}
|
||||
|
||||
fn number(src: &str) -> f64 {
|
||||
match eval(src) {
|
||||
Ok(value) => value.to_number().unwrap_or_else(|| panic!("`{src}` did not evaluate to a number: {value:?}")),
|
||||
Err(error) => panic!("`{src}` failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn boolean(src: &str) -> bool {
|
||||
match eval(src) {
|
||||
Ok(Scalar::Boolean(value)) => value,
|
||||
other => panic!("`{src}` did not evaluate to a Boolean: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn error_message(src: &str) -> String {
|
||||
match eval(src) {
|
||||
Ok(value) => panic!("`{src}` should fail, got {value:?}"),
|
||||
Err(message) => message,
|
||||
}
|
||||
}
|
||||
|
||||
fn filter(model: &DataModel, table: &str, column: &str, values: &[Scalar]) -> FilterContext {
|
||||
let mut filters = FilterContext::default();
|
||||
let table = model.table_index(table).expect("table exists");
|
||||
let column = model.column_index(table, column).expect("column exists");
|
||||
filters.set(table, column, values.iter().map(ScalarKey::from));
|
||||
filters
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_statistics_reports_every_column() {
|
||||
let table = eval_table("COLUMNSTATISTICS()").expect("column statistics");
|
||||
let names: Vec<&str> = table.columns.iter().map(|column| column.name.as_str()).collect();
|
||||
assert_eq!(names, ["Table Name", "Column Name", "Min", "Max", "Cardinality", "Max Length"]);
|
||||
// Product has 8 columns, Sales has 4 and EmptyStats has 1.
|
||||
assert_eq!(table.rows.len(), 13);
|
||||
|
||||
let row = table
|
||||
.rows
|
||||
.iter()
|
||||
.find(|row| row[0] == Scalar::String("Product".into()) && row[1] == Scalar::String("Name".into()))
|
||||
.expect("Product[Name] row");
|
||||
assert_eq!(row[2], Scalar::String("Blue Gadget".into()));
|
||||
assert_eq!(row[3], Scalar::String("Wireless Headphones".into()));
|
||||
assert_eq!(row[4], Scalar::Integer(4));
|
||||
assert_eq!(row[5], Scalar::Integer(23));
|
||||
|
||||
let price = table
|
||||
.rows
|
||||
.iter()
|
||||
.find(|row| row[0] == Scalar::String("Product".into()) && row[1] == Scalar::String("Price".into()))
|
||||
.expect("Product[Price] row");
|
||||
assert_eq!(price[2], Scalar::Decimal(10.0));
|
||||
assert_eq!(price[3], Scalar::Decimal(40.0));
|
||||
assert_eq!(price[4], Scalar::Integer(4));
|
||||
assert_eq!(price[5], Scalar::Blank);
|
||||
|
||||
let empty = table.rows.iter().find(|row| row[0] == Scalar::String("EmptyStats".into())).expect("EmptyStats row");
|
||||
assert_eq!(empty[2], Scalar::Blank);
|
||||
assert_eq!(empty[3], Scalar::Blank);
|
||||
assert_eq!(empty[4], Scalar::Integer(0));
|
||||
assert_eq!(empty[5], Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_and_containsrow() {
|
||||
assert!(boolean("CONTAINS(Product, Product[Color], \"Red\")"));
|
||||
assert!(boolean("CONTAINS(Product, Product[Color], \"Red\", Product[Category], \"Audio\")"));
|
||||
assert!(!boolean("CONTAINS(Product, Product[Color], \"Red\", Product[Category], \"Computers\")"));
|
||||
// Strict equality: BLANK does not match the number 0.
|
||||
assert!(!boolean("CONTAINS(Product, Product[Color], BLANK())"));
|
||||
assert!(boolean("EVALUATEANDLOG(CONTAINS(Product, Product[ProductKey], 3))"));
|
||||
assert!(error_message("CONTAINS(Product, Product[Color], \"Red\", Product[Name])").contains("column/value pairs"));
|
||||
|
||||
assert!(boolean("CONTAINSROW({1, 2}, 2)"));
|
||||
assert!(!boolean("CONTAINSROW({1, 2}, 3)"));
|
||||
// One value per table column: `Sales` is (Region, Amount, Quantity, ProductKey).
|
||||
assert!(boolean("CONTAINSROW(Sales, \"East\", 10.0, 2, 1)"));
|
||||
assert!(!boolean("CONTAINSROW(Sales, \"West\", 10.0, 2, 1)"));
|
||||
// A value count that is not the column count is an error, never a prefix match.
|
||||
assert!(error_message("CONTAINSROW(Sales, \"East\")").contains("one value"));
|
||||
assert!(error_message("CONTAINSROW({1}, 1, 2)").contains("one value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_string_variants() {
|
||||
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"ell\")"));
|
||||
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"WORLD\")"));
|
||||
assert!(!boolean("CONTAINSSTRING(\"Hello World\", \"xyz\")"));
|
||||
// Excel wildcards: `?` one character, `*` any run, `~` escapes a wildcard.
|
||||
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"W?rld\")"));
|
||||
assert!(boolean("CONTAINSSTRING(\"Hello World\", \"H*d\")"));
|
||||
assert!(boolean("CONTAINSSTRING(\"a*b\", \"~*\")"));
|
||||
assert!(!boolean("CONTAINSSTRING(\"abc\", \"~*\")"));
|
||||
assert!(boolean("CONTAINSSTRING(BLANK(), \"\")"));
|
||||
|
||||
assert!(boolean("CONTAINSSTRINGEXACT(\"Hello World\", \"World\")"));
|
||||
assert!(!boolean("CONTAINSSTRINGEXACT(\"Hello World\", \"world\")"));
|
||||
// Exact matching does not interpret wildcards.
|
||||
assert!(boolean("CONTAINSSTRINGEXACT(\"a*b\", \"*\")"));
|
||||
assert!(!boolean("CONTAINSSTRINGEXACT(\"Hello\", \"Ell\")"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_and_connection_functions_return_defaults() {
|
||||
assert_eq!(eval("CUSTOMDATA()"), Ok(Scalar::String(String::new())));
|
||||
assert_eq!(eval("USERCULTURE()"), Ok(Scalar::String("en-US".into())));
|
||||
assert_eq!(eval("USEROBJECTID()"), Ok(Scalar::String(String::new())));
|
||||
// USERNAME is the `DOMAIN\user` identity; USERPRINCIPALNAME is the `user@domain` directory
|
||||
// principal. On a test host without a user both are empty.
|
||||
let host_user = std::env::var("USERNAME").or_else(|_| std::env::var("USER")).unwrap_or_default();
|
||||
let username = match std::env::var("USERDOMAIN") {
|
||||
Ok(domain) if !domain.is_empty() && !host_user.is_empty() => format!("{domain}\\{host_user}"),
|
||||
_ => host_user.clone(),
|
||||
};
|
||||
let principal = match (
|
||||
std::env::var("USERDNSDOMAIN").ok().filter(|domain| !domain.is_empty()),
|
||||
std::env::var("USERDOMAIN").ok().filter(|domain| !domain.is_empty()),
|
||||
host_user.as_str(),
|
||||
) {
|
||||
(_, _, "") => host_user,
|
||||
(Some(domain), _, user) | (None, Some(domain), user) => format!("{user}@{}", domain.to_ascii_lowercase()),
|
||||
(None, None, user) => user.to_string(),
|
||||
};
|
||||
assert_eq!(eval("USERNAME()"), Ok(Scalar::String(username)));
|
||||
assert_eq!(eval("USERPRINCIPALNAME()"), Ok(Scalar::String(principal)));
|
||||
// The principal name is the `user@domain` form, never the `DOMAIN\user` form.
|
||||
assert!(!matches!(eval("USERPRINCIPALNAME()"), Ok(Scalar::String(value)) if value.contains('\\')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluate_and_log_returns_its_argument() {
|
||||
assert_eq!(eval("EVALUATEANDLOG(42)"), Ok(Scalar::Integer(42)));
|
||||
assert_eq!(eval("EVALUATEANDLOG(7, \"label\", 5)"), Ok(Scalar::Integer(7)));
|
||||
let table = eval_table("EVALUATEANDLOG(Sales)").expect("logged table");
|
||||
assert_eq!(table.rows.len(), 3);
|
||||
assert_eq!(table.columns.len(), 4);
|
||||
assert!(eval("EVALUATEANDLOG()").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_context_predicates() {
|
||||
assert!(!boolean("HASONEVALUE(Product[Color])"));
|
||||
assert!(!boolean("HASONEVALUE(Product[Category])"));
|
||||
|
||||
let single_category =
|
||||
eval_with("HASONEVALUE(Product[Category])", |model| filter(model, "Product", "Category", &[Scalar::String("Audio".into())]))
|
||||
.expect("HASONEVALUE");
|
||||
assert_eq!(single_category, Scalar::Boolean(true));
|
||||
|
||||
let two_colors = eval_with("HASONEVALUE(Product[Color])", |model| {
|
||||
filter(model, "Product", "Color", &[Scalar::String("Red".into()), Scalar::String("Blue".into())])
|
||||
})
|
||||
.expect("HASONEVALUE with two values");
|
||||
assert_eq!(two_colors, Scalar::Boolean(false));
|
||||
|
||||
let single_color_filter =
|
||||
eval_with("HASONEFILTER(Product[Color])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())])).expect("HASONEFILTER");
|
||||
assert_eq!(single_color_filter, Scalar::Boolean(true));
|
||||
|
||||
let propagated = eval_with("HASONEFILTER(Product[Color])", |model| filter(model, "Product", "Category", &[Scalar::String("Computers".into())]))
|
||||
.expect("HASONEFILTER ignores propagated filters");
|
||||
assert_eq!(propagated, Scalar::Boolean(false));
|
||||
|
||||
let two_value_filter = eval_with("HASONEFILTER(Product[Color])", |model| {
|
||||
filter(model, "Product", "Color", &[Scalar::String("Red".into()), Scalar::String("Blue".into())])
|
||||
})
|
||||
.expect("HASONEFILTER with two values");
|
||||
assert_eq!(two_value_filter, Scalar::Boolean(false));
|
||||
|
||||
let empty_column = eval("HASONEVALUE(EmptyStats[Empty Value])").expect("empty column");
|
||||
assert_eq!(empty_column, Scalar::Boolean(false));
|
||||
|
||||
assert!(!boolean("ISFILTERED(Product[Color])"));
|
||||
let filtered =
|
||||
eval_with("ISFILTERED(Product[Color])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())])).expect("ISFILTERED");
|
||||
assert_eq!(filtered, Scalar::Boolean(true));
|
||||
|
||||
let unrelated = eval_with("ISFILTERED(Product[Name])", |model| filter(model, "Product", "Color", &[Scalar::String("Red".into())]))
|
||||
.expect("ISFILTERED other column");
|
||||
assert_eq!(unrelated, Scalar::Boolean(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_filtered_follows_relationship_propagation() {
|
||||
assert!(!boolean("ISCROSSFILTERED(Sales)"));
|
||||
assert!(!boolean("ISCROSSFILTERED(Product)"));
|
||||
|
||||
let from_dimension = |model: &DataModel| filter(model, "Product", "Category", &[Scalar::String("Audio".into())]);
|
||||
assert_eq!(eval_with("ISCROSSFILTERED(Sales)", from_dimension).expect("sales"), Scalar::Boolean(true));
|
||||
assert_eq!(eval_with("ISCROSSFILTERED(Sales[Amount])", from_dimension).expect("sales column"), Scalar::Boolean(true));
|
||||
assert_eq!(eval_with("ISCROSSFILTERED(Product)", from_dimension).expect("product"), Scalar::Boolean(true));
|
||||
|
||||
// Filtering the many-side fact table does not propagate to the one-side dimension.
|
||||
let from_fact = |model: &DataModel| filter(model, "Sales", "Region", &[Scalar::String("East".into())]);
|
||||
assert_eq!(eval_with("ISCROSSFILTERED(Product)", from_fact).expect("product"), Scalar::Boolean(false));
|
||||
assert_eq!(eval_with("ISCROSSFILTERED(Sales)", from_fact).expect("sales"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
/// `Sales -> Product -> Category`, plus an inactive `Product -> AltCategory` link so
|
||||
/// `USERELATIONSHIP` can switch a hop on.
|
||||
fn snowflake_model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Category".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(1), Scalar::String("Audio".into())], vec![Scalar::Integer(2), Scalar::String("Computers".into())]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "AltCategory".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(1), Scalar::String("Audio".into())], vec![Scalar::Integer(2), Scalar::String("Computers".into())]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "CategoryKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "AltCategoryKey".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(1)],
|
||||
vec![Scalar::Integer(2), Scalar::Integer(1), Scalar::Integer(2)],
|
||||
vec![Scalar::Integer(3), Scalar::Integer(2), Scalar::Integer(1)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::Integer(2), Scalar::Decimal(20.0)],
|
||||
vec![Scalar::Integer(3), Scalar::Decimal(30.0)],
|
||||
],
|
||||
},
|
||||
],
|
||||
relationships: vec![
|
||||
Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
},
|
||||
Relationship {
|
||||
from_table: "Product".into(),
|
||||
from_column: "CategoryKey".into(),
|
||||
to_table: "Category".into(),
|
||||
to_column: "CategoryKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
},
|
||||
Relationship {
|
||||
from_table: "Product".into(),
|
||||
from_column: "AltCategoryKey".into(),
|
||||
to_table: "AltCategory".into(),
|
||||
to_column: "CategoryKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: true,
|
||||
},
|
||||
],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
model
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_filtered_follows_the_whole_chain_and_relationship_overrides() {
|
||||
let model = snowflake_model();
|
||||
let with = |filters: FilterContext, src: &str| evaluate_with_model(&model, src, filters);
|
||||
|
||||
assert_eq!(with(FilterContext::default(), "ISCROSSFILTERED(Sales)").expect("unfiltered sales"), Scalar::Boolean(false));
|
||||
assert_eq!(with(FilterContext::default(), "ISCROSSFILTERED(Product)").expect("unfiltered product"), Scalar::Boolean(false));
|
||||
|
||||
// Two hops away: `Category -> Product -> Sales`. A single-hop check misses this.
|
||||
let category = filter(&model, "Category", "Name", &[Scalar::String("Audio".into())]);
|
||||
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Sales)").expect("sales"), Scalar::Boolean(true));
|
||||
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Product)").expect("product"), Scalar::Boolean(true));
|
||||
assert_eq!(with(category.clone(), "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(true));
|
||||
// The chain only runs towards the many side; the inactive branch stays out of it.
|
||||
assert_eq!(with(category.clone(), "ISCROSSFILTERED(AltCategory)").expect("alt category"), Scalar::Boolean(false));
|
||||
|
||||
// A filter on the fact table does not climb the one-way chain towards `Category`.
|
||||
let sales = filter(&model, "Sales", "Amount", &[Scalar::Decimal(10.0)]);
|
||||
assert_eq!(with(sales.clone(), "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(false));
|
||||
assert_eq!(with(sales.clone(), "ISCROSSFILTERED(Sales)").expect("sales"), Scalar::Boolean(true));
|
||||
|
||||
// An inactive relationship is ignored until `USERELATIONSHIP` activates it; the override in
|
||||
// the filter context, not the model's `inactive` flag, must decide.
|
||||
let alt_category = filter(&model, "AltCategory", "Name", &[Scalar::String("Audio".into())]);
|
||||
assert_eq!(with(alt_category.clone(), "ISCROSSFILTERED(Sales)").expect("inactive link"), Scalar::Boolean(false));
|
||||
let activation = "CALCULATE(ISCROSSFILTERED(Sales), USERELATIONSHIP(Product[AltCategoryKey], AltCategory[CategoryKey]))";
|
||||
assert_eq!(with(alt_category.clone(), activation).expect("activated link"), Scalar::Boolean(true));
|
||||
// Activating the other pair leaves the `Category` chain alone.
|
||||
assert_eq!(with(alt_category, "ISCROSSFILTERED(Category)").expect("category"), Scalar::Boolean(false));
|
||||
|
||||
// `CROSSFILTER` widens the fact-side filter back to the dimension for the surrounding
|
||||
// CALCULATE only.
|
||||
let widened = "CALCULATE(ISCROSSFILTERED(Product), CROSSFILTER(Sales[ProductKey], Product[ProductKey], BOTH))";
|
||||
assert_eq!(with(sales, widened).expect("bidirectional override"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_and_subtotal_predicates() {
|
||||
// Outside a `SUMMARIZE` group no column is in scope, and a row iterator's row context does
|
||||
// not put one there either: scope is the group-by set of the group being evaluated.
|
||||
assert!(!boolean("ISINSCOPE(Product[Color])"));
|
||||
assert_eq!(number("SUMX(Product, IF(ISINSCOPE(Product[Color]), 1, 0))"), 0.0);
|
||||
assert_eq!(number("SUMX(Sales, IF(ISINSCOPE(Product[Color]), 1, 0))"), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_empty_checks_result_rows() {
|
||||
assert!(!boolean("ISEMPTY(Sales)"));
|
||||
assert!(boolean("ISEMPTY(FILTER(Sales, Sales[Amount] > 1000))"));
|
||||
assert!(boolean("ISEMPTY(EmptyStats)"));
|
||||
assert!(boolean("ISEMPTY({})"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_predicates_are_strict() {
|
||||
assert!(boolean("ISBOOLEAN(TRUE)"));
|
||||
assert!(!boolean("ISBOOLEAN(1)"));
|
||||
assert!(!boolean("ISBOOLEAN(BLANK())"));
|
||||
assert!(boolean("ISSTRING(\"text\")"));
|
||||
assert!(!boolean("ISSTRING(1)"));
|
||||
assert!(!boolean("ISSTRING(BLANK())"));
|
||||
assert!(boolean("ISINT64(1)"));
|
||||
assert!(!boolean("ISINT64(1.5)"));
|
||||
assert!(!boolean("ISDECIMAL(1.5)"));
|
||||
assert!(boolean("ISDOUBLE(1.5)"));
|
||||
assert!(!boolean("ISDOUBLE(1)"));
|
||||
assert!(boolean("ISDATETIME(DATE(2024, 1, 1))"));
|
||||
assert!(!boolean("ISDATETIME(1)"));
|
||||
assert!(boolean("ISNUMERIC(1)"));
|
||||
assert!(boolean("ISNUMERIC(1.5)"));
|
||||
assert!(!boolean("ISNUMERIC(\"1\")"));
|
||||
assert!(!boolean("ISNUMERIC(TRUE)"));
|
||||
assert!(!boolean("ISNUMERIC(DATE(2024, 1, 1))"));
|
||||
|
||||
// Column values in a row context keep their storage types.
|
||||
assert_eq!(number("SUMX(Product, IF(ISDECIMAL(Product[Cost]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISDOUBLE(Product[Price]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISDOUBLE(Product[Cost]), 1, 0))"), 0.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISINT64(Product[ProductKey]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISNUMERIC(Product[Cost]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISNUMERIC(Product[Active]), 1, 0))"), 0.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISDATETIME(Product[LaunchDate]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISSTRING(Product[Name]), 1, 0))"), 4.0);
|
||||
assert_eq!(number("SUMX(Product, IF(ISBOOLEAN(Product[Active]), 1, 0))"), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isafter_and_isonorafter_compare_groups() {
|
||||
assert!(boolean("ISAFTER(2, 1)"));
|
||||
assert!(!boolean("ISAFTER(1, 1)"));
|
||||
assert!(!boolean("ISAFTER(1, 2)"));
|
||||
assert!(boolean("ISAFTER(1, 2, FALSE)"));
|
||||
assert!(boolean("ISAFTER(1, 2, 0)"));
|
||||
assert!(boolean("ISAFTER(\"b\", \"A\")"));
|
||||
// The first differing pair decides; equal pairs fall through to the next group.
|
||||
assert!(boolean("ISAFTER(1, 1, TRUE, 5, 4)"));
|
||||
assert!(!boolean("ISAFTER(1, 1, TRUE, 4, 5)"));
|
||||
// BLANK sorts before every value, including the empty string.
|
||||
assert!(boolean("ISAFTER(\"\", BLANK())"));
|
||||
assert!(!boolean("ISAFTER(BLANK(), \"\")"));
|
||||
assert!(error_message("ISAFTER(\"abc\", 1)").contains("cannot compare"));
|
||||
|
||||
assert!(boolean("ISONORAFTER(2, 1)"));
|
||||
assert!(boolean("ISONORAFTER(1, 1)"));
|
||||
assert!(!boolean("ISONORAFTER(0, 1)"));
|
||||
assert!(boolean("ISONORAFTER(1, 2, FALSE)"));
|
||||
assert!(!boolean("ISONORAFTER(1, 1, TRUE, 4, 5)"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, TRUE, 5, 4)"));
|
||||
assert!(!boolean("ISONORAFTER(BLANK(), \"\")"));
|
||||
assert!(eval("ISONORAFTER(1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_measure_functions_require_a_calculation_item() {
|
||||
assert!(!boolean("ISSELECTEDMEASURE([Total Sales])"));
|
||||
assert!(!boolean("ISSELECTEDMEASURE([Total Sales], [Total Quantity])"));
|
||||
assert!(error_message("SELECTEDMEASURE()").contains("selected measure"));
|
||||
assert!(error_message("SELECTEDMEASURENAME()").contains("selected measure"));
|
||||
assert!(error_message("SELECTEDMEASUREFORMATSTRING()").contains("selected measure"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nameof_formats_and_escapes_names() {
|
||||
assert_eq!(eval("NAMEOF(Sales[Amount])"), Ok(Scalar::String("'Sales'[Amount]".into())));
|
||||
assert_eq!(eval("NAMEOF([Total Sales])"), Ok(Scalar::String("'Sales'[Total Sales]".into())));
|
||||
assert_eq!(eval("NAMEOF(Sales)"), Ok(Scalar::String("'Sales'".into())));
|
||||
assert_eq!(eval("NAMEOF(Sales[Amount], \"TABLE\")"), Ok(Scalar::String("'Sales'".into())));
|
||||
assert_eq!(eval("NAMEOF([Total Sales], \"PARENT\")"), Ok(Scalar::String("'Sales'".into())));
|
||||
assert_eq!(eval("NAMEOF(Product[Name], \"SELF\")"), Ok(Scalar::String("[Name]".into())));
|
||||
assert_eq!(eval("NAMEOF(Sales[Amount], \"COLUMN\")"), Ok(Scalar::String("[Amount]".into())));
|
||||
assert_eq!(eval("NAMEOF([Total Sales], \"MEASURE\")"), Ok(Scalar::String("[Total Sales]".into())));
|
||||
assert_eq!(eval("NAMEOF(Sales, \"FULL\", \"UNESCAPED\")"), Ok(Scalar::String("Sales".into())));
|
||||
assert_eq!(eval("NAMEOF(Product[Name], \"SELF\", \"UNESCAPED\")"), Ok(Scalar::String("Name".into())));
|
||||
assert_eq!(eval("NAMEOF(Product[Name], \"FULL\", \"MINIMALLYESCAPED\")"), Ok(Scalar::String("Product[Name]".into())));
|
||||
assert_eq!(eval("NAMEOF([Total Sales], \"SELF\", \"MINIMALLYESCAPED\")"), Ok(Scalar::String("[Total Sales]".into())));
|
||||
|
||||
assert!(error_message("NAMEOF(Sales[Amount], \"FULL\", \"UNESCAPED\")").contains("fully qualified"));
|
||||
assert!(error_message("NAMEOF(Sales, \"PARENT\")").contains("no parent"));
|
||||
assert!(error_message("NAMEOF(Sales[Amount], \"CALENDAR\")").contains("no calendar"));
|
||||
assert!(error_message("NAMEOF(Sales[Amount], \"BOGUS\")").contains("does not know component"));
|
||||
assert!(error_message("NAMEOF(1)").contains("table, column or measure"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tableof_returns_the_containing_table() {
|
||||
for source in ["TABLEOF(Sales[Amount])", "TABLEOF(Sales)", "TABLEOF([Total Sales])"] {
|
||||
let table = eval_table(source).expect(source);
|
||||
assert_eq!(table.rows.len(), 3, "{source}");
|
||||
assert_eq!(table.columns.len(), 4, "{source}");
|
||||
}
|
||||
// Unqualified column names resolve when a single table carries them.
|
||||
let empty = eval_table("TABLEOF([Empty Value])").expect("TABLEOF empty column");
|
||||
assert_eq!(empty.rows.len(), 0);
|
||||
assert_eq!(empty.columns.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_contains_match_modes() {
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"wireless bluetooth\")))"), 1.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"WIRELESS\")))"), 1.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"zzz\")))"), 0.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"\")))"), 0.0);
|
||||
// Typo-tolerant matching accepts an edit distance of 1-2 for longer tokens.
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"headphone\", \"FUZZYMATCHING\")))"), 2.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"hedphone\", \"FUZZYMATCHING\")))"), 2.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"headphone\")))"), 0.0);
|
||||
// Phrase matching requires adjacent tokens in the specified order.
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"noise cancel\", \"PHRASEMATCHING\")))"), 1.0);
|
||||
assert_eq!(number("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"cancel noise\", \"PHRASEMATCHING\")))"), 0.0);
|
||||
assert!(error_message("COUNTROWS(FILTER(Product, TEXTCONTAINS(Product[Name], \"x\", \"BOGUS\")))").contains("match mode"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_scores_matches() {
|
||||
let red = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
|
||||
assert!(red > 0.0, "red score {red}");
|
||||
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"zzz\"))"), 0.0);
|
||||
assert!((number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"RED\"))") - red).abs() < 1e-12);
|
||||
|
||||
let both = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red widget\"))");
|
||||
assert!(both > red, "a two-term match ({both}) should outrank one term ({red})");
|
||||
|
||||
assert!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"hedphone\", \"FUZZYMATCHING\"))") > 0.0);
|
||||
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"hedphone\"))"), 0.0);
|
||||
assert!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"noise cancel\", \"PHRASEMATCHING\"))") > 0.0);
|
||||
assert_eq!(number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"cancel noise\", \"PHRASEMATCHING\"))"), 0.0);
|
||||
let blank = number("MAXX(Product, TEXTSIMILARITY(Product[Name], BLANK()))");
|
||||
assert_eq!(blank, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_scores_each_row_against_the_shared_corpus() {
|
||||
// `MAXX` evaluates `TEXTSIMILARITY` once per row, and every one of those calls ranks against
|
||||
// the same column corpus (4 documents, 9 tokens, `red` in one document). The statistics are
|
||||
// memoised, so the row that matches must score exactly as it does on its own.
|
||||
let score = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
|
||||
// k1 = 1.2, b = 0.75: idf = ln(1 + (4 - 1 + 0.5) / (1 + 0.5)); the target has two tokens and
|
||||
// the corpus averages 9 / 4 = 2.25, so the denominator is 1 + 1.2 * (0.25 + 0.75 * 2 / 2.25).
|
||||
assert!((score - 1.261_304_842_627_171_4).abs() < 1e-9, "unexpected score {score}");
|
||||
// The same row scored through its own filter context gets the same value.
|
||||
let scoped = evaluate("TEXTSIMILARITY(Product[Name], \"red\")", filter(&model(), "Product", "Name", &[Scalar::String("Red Widget".into())]))
|
||||
.expect("scoped score");
|
||||
assert_eq!(scoped, Scalar::Decimal(score));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_reports_an_oversized_column_instead_of_rescoring() {
|
||||
// Beyond the text work budget the function must fail: substituting a cheaper corpus would
|
||||
// silently change every score for the same column.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Notes".into(),
|
||||
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
|
||||
rows: (0..1500).map(|index| vec![Scalar::String(format!("note {index} {}", "x".repeat(1000)))]).collect(),
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
let error = evaluate_with_model(&model, "MAXX(Notes, TEXTSIMILARITY(Notes[Text], \"note\"))", FilterContext::default())
|
||||
.expect_err("a column beyond the work budget");
|
||||
assert!(error.contains("too large"), "unexpected error: {error}");
|
||||
}
|
||||
/// A one-column model whose rows are the given texts.
|
||||
fn corpus_model(documents: [&str; 3]) -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "NoteLines".into(),
|
||||
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
|
||||
rows: documents.iter().map(|document| vec![Scalar::String((*document).into())]).collect(),
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
model
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_keeps_each_model_s_corpus() {
|
||||
// The two corpora have the same shape, the same first row and the same last row; only the
|
||||
// middle document differs. Statistics memoised on anything weaker than the model itself would
|
||||
// score the second corpus with the first one's document frequencies.
|
||||
let dense = corpus_model(["red alpha", "red beta", "same tail"]);
|
||||
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
|
||||
let score =
|
||||
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
|
||||
Ok(Scalar::Decimal(value)) => value,
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
};
|
||||
let dense_score = score(&dense);
|
||||
let sparse_score = score(&sparse);
|
||||
// `red` is in two of the three documents above and in one of them below, so it is rarer and
|
||||
// scores higher.
|
||||
assert!(dense_score > 0.0, "dense score {dense_score}");
|
||||
assert!(sparse_score > dense_score, "sparse {sparse_score} should outrank dense {dense_score}");
|
||||
}
|
||||
#[test]
|
||||
fn text_similarity_sees_an_edited_corpus() {
|
||||
// The model address and row count stay the same when a caller edits a text cell, so the memo
|
||||
// must be invalidated by the corpus fingerprint rather than by those two facts alone.
|
||||
let mut model = corpus_model(["red alpha", "blue beta", "same tail"]);
|
||||
let score =
|
||||
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
|
||||
Ok(Scalar::Decimal(value)) => value,
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
};
|
||||
let rare = score(&model);
|
||||
model.tables[0].rows[1][0] = Scalar::String("red beta".into());
|
||||
// `red` now occurs in two of the three documents, so it is less distinctive and scores lower.
|
||||
let common = score(&model);
|
||||
assert!(rare > 0.0, "rare score {rare}");
|
||||
assert!(common < rare, "edited corpus {common} should score below {rare}");
|
||||
}
|
||||
#[test]
|
||||
fn text_similarity_does_not_alias_between_interleaved_evaluators() {
|
||||
// Two models scored alternately on one thread: the memo must never answer one corpus's
|
||||
// statistics for the other, in either order and across repeated evaluations.
|
||||
let dense = corpus_model(["red alpha", "red beta", "same tail"]);
|
||||
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
|
||||
let score =
|
||||
|model: &DataModel| match evaluate_with_model(model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
|
||||
Ok(Scalar::Decimal(value)) => value,
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
};
|
||||
let dense_first = score(&dense);
|
||||
let sparse_first = score(&sparse);
|
||||
assert!(sparse_first > dense_first, "sparse {sparse_first} should outrank dense {dense_first}");
|
||||
for _ in 0..3 {
|
||||
assert_eq!(score(&dense), dense_first, "dense score changed between evaluations");
|
||||
assert_eq!(score(&sparse), sparse_first, "sparse score changed between evaluations");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_error_leaves_no_stale_statistics() {
|
||||
// A call that fails on the work budget must not leave statistics behind for the next call.
|
||||
let mut oversized = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Notes".into(),
|
||||
columns: vec![ModelColumn { name: "Text".into(), data_type: Some("String".into()) }],
|
||||
rows: (0..1500).map(|index| vec![Scalar::String(format!("note {index} {}", "x".repeat(1000)))]).collect(),
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
oversized.parse_formulas().expect("fixture model parses");
|
||||
let error = evaluate_with_model(&oversized, "MAXX(Notes, TEXTSIMILARITY(Notes[Text], \"note\"))", FilterContext::default())
|
||||
.expect_err("a column beyond the work budget");
|
||||
assert!(error.contains("too large"), "unexpected error: {error}");
|
||||
// The normal corpus still scores exactly as it does on its own.
|
||||
let model = corpus_model(["red alpha", "blue beta", "same tail"]);
|
||||
let score = match evaluate_with_model(&model, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
|
||||
Ok(Scalar::Decimal(value)) => value,
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
};
|
||||
let sparse = corpus_model(["red alpha", "blue beta", "same tail"]);
|
||||
let expected = match evaluate_with_model(&sparse, "MAXX(NoteLines, TEXTSIMILARITY(NoteLines[Text], \"red\"))", FilterContext::default()) {
|
||||
Ok(Scalar::Decimal(value)) => value,
|
||||
other => panic!("unexpected result: {other:?}"),
|
||||
};
|
||||
assert_eq!(score, expected);
|
||||
}
|
||||
#[test]
|
||||
fn text_similarity_counts_numeric_text_exactly() {
|
||||
// 70,000 one-digit integers are 70,000 characters of text, not twenty each: a per-variant bound
|
||||
// that assumed twenty would reject this column although its text is tiny. The query is three
|
||||
// characters, so the old bound would have asked for 4.2 M characters.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Counts".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Int64".into()) }],
|
||||
rows: (0..70_000).map(|_| vec![Scalar::Integer(1)]).collect(),
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
let score = evaluate_with_model(&model, "MAXX(Counts, TEXTSIMILARITY(Counts[Value], \"one\"))", FilterContext::default());
|
||||
assert!(matches!(score, Ok(Scalar::Decimal(_))), "unexpected result: {score:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_rejects_a_column_whose_text_exceeds_the_budget() {
|
||||
// A large decimal formats to hundreds of characters, so a column of them must be rejected even
|
||||
// though the value count alone looks harmless.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Wide".into(),
|
||||
columns: vec![ModelColumn { name: "Value".into(), data_type: Some("Double".into()) }],
|
||||
rows: (0..20_000).map(|_| vec![Scalar::Decimal(1e308)]).collect(),
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
let error = evaluate_with_model(&model, "MAXX(Wide, TEXTSIMILARITY(Wide[Value], \"1\"))", FilterContext::default())
|
||||
.expect_err("a column whose text exceeds the budget");
|
||||
assert!(error.contains("too large"), "unexpected error: {error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_similarity_keeps_two_queries_apart_in_one_evaluation() {
|
||||
// Both queries run inside one evaluation, so they hit the same memo: each must get the
|
||||
// statistics for its own terms.
|
||||
let combined = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\")) + MAXX(Product, TEXTSIMILARITY(Product[Name], \"widget\"))");
|
||||
let red = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"red\"))");
|
||||
let widget = number("MAXX(Product, TEXTSIMILARITY(Product[Name], \"widget\"))");
|
||||
assert!(red > 0.0 && widget > 0.0);
|
||||
assert!((combined - (red + widget)).abs() < 1e-9, "combined {combined} should be {red} + {widget}");
|
||||
}
|
||||
#[test]
|
||||
fn distinct_values_fold_text_case() {
|
||||
// `"East"` and `"east"` are one distinct value under the model collation, so `HASONEVALUE`
|
||||
// agrees with `VALUES`/`DISTINCTCOUNT` and `COLUMNSTATISTICS` reports the same cardinality.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Regions".into(),
|
||||
columns: vec![ModelColumn { name: "Name".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("East".into())], vec![Scalar::String("east".into())]],
|
||||
}],
|
||||
relationships: vec![],
|
||||
measures: vec![],
|
||||
};
|
||||
model.parse_formulas().expect("fixture model parses");
|
||||
let one_value = evaluate_with_model(&model, "HASONEVALUE(Regions[Name])", FilterContext::default()).expect("has one value");
|
||||
assert_eq!(one_value, Scalar::Boolean(true));
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("COLUMNSTATISTICS()").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
let table = evaluator.evaluate_table(&bound).expect("column statistics");
|
||||
let row = table
|
||||
.rows
|
||||
.iter()
|
||||
.find(|row| row[0] == Scalar::String("Regions".into()) && row[1] == Scalar::String("Name".into()))
|
||||
.expect("Regions[Name] row");
|
||||
assert_eq!(row[4], Scalar::Integer(1), "Cardinality must fold text case");
|
||||
}
|
||||
#[test]
|
||||
fn isafter_keeps_value_pairs_that_look_like_order_flags() {
|
||||
// `0` and `1` are the documented `Order` shorthands, but here they are the second pair's
|
||||
// values: the first pair is equal, so the second one decides.
|
||||
assert!(!boolean("ISAFTER(1, 1, 0, 1)"), "0 < 1, so the pair is not after");
|
||||
assert!(boolean("ISAFTER(1, 1, 2, 1)"), "2 > 1, so the pair is after");
|
||||
// ISONORAFTER also includes equality, and the pair here is strictly before.
|
||||
assert!(!boolean("ISONORAFTER(1, 1, 0, 1)"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, 1, 1)"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, 2, 1)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isafter_accepts_a_flag_after_every_pair() {
|
||||
// A flag after each pair must still split into pairs, not into a pair plus a dangling value.
|
||||
assert!(boolean("ISAFTER(1, 1, TRUE, 2, 3, FALSE)"));
|
||||
assert!(boolean("ISAFTER(1, 1, TRUE, 3, 2)"));
|
||||
assert!(!boolean("ISAFTER(1, 1, TRUE, 2, 3)"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, TRUE, 2, 2)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isafter_rejects_an_odd_argument_count() {
|
||||
assert!(eval("ISAFTER(1)").is_err());
|
||||
// `ISAFTER(1, 1, 0)` is a pair plus the `0` shorthand flag, so only a leftover value is an
|
||||
// error: here the `3` after the second pair is neither a flag nor paired.
|
||||
assert!(eval("ISONORAFTER(1, 1, 2, 2, 3)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isafter_accepts_a_computed_order_flag() {
|
||||
// A computed `Order` flag is accepted by the pair split and decides the sort direction:
|
||||
// `TRUE` is ascending, `FALSE` is descending (as in `ISAFTER(1, 2, FALSE)` above). The
|
||||
// single-evaluation guarantee itself is structural — the cached `Scalar` feeds both the
|
||||
// split and the direction read, and `flag_direction` takes no evaluator to re-evaluate
|
||||
// with — so a constant flag cannot observe the evaluation count here.
|
||||
assert!(!boolean("ISAFTER(1, 2, IF(1 > 0, TRUE, FALSE))"));
|
||||
assert!(boolean("ISAFTER(2, 1, IF(1 > 0, TRUE, FALSE))"));
|
||||
assert!(boolean("ISAFTER(1, 2, IF(1 > 0, FALSE, TRUE))"));
|
||||
assert!(!boolean("ISAFTER(2, 1, IF(1 > 0, FALSE, TRUE))"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, IF(1 > 0, TRUE, FALSE))"));
|
||||
assert!(boolean("ISONORAFTER(1, 1, IF(1 > 0, FALSE, TRUE))"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_row_needs_one_value_per_column() {
|
||||
// `Sales` has four columns: a short value list is an error, not a leading-prefix match.
|
||||
assert!(eval("CONTAINSROW(Sales, \"East\")").is_err());
|
||||
assert!(eval("CONTAINSROW(Sales, \"East\", 10.0, 2, 1)").is_ok());
|
||||
assert!(!boolean("CONTAINSROW(Sales, \"East\", 20.0, 2, 1)"));
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Evaluator tests for bitwise integer operations and `IF.EAGER`.
|
||||
|
||||
use gridcraft_dax::model::DataModel;
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
DataModel { tables: vec![], relationships: vec![], measures: vec![] }
|
||||
}
|
||||
|
||||
fn eval_result(source: &str) -> Result<Scalar, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.to_string())?;
|
||||
let expr = parse_expression(source).map_err(|error| error.to_string())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.to_string())?;
|
||||
evaluator.evaluate(&bound).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn eval(source: &str) -> Scalar {
|
||||
eval_result(source).expect("expression evaluates")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitwise_and_or_xor() {
|
||||
assert_eq!(eval("BITAND(5, 3)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("BITAND(13, 25)"), Scalar::Integer(9));
|
||||
assert_eq!(eval("BITAND(-1, 255)"), Scalar::Integer(255));
|
||||
assert_eq!(eval("BITAND(3.9, 1)"), Scalar::Integer(1));
|
||||
|
||||
assert_eq!(eval("BITOR(5, 3)"), Scalar::Integer(7));
|
||||
assert_eq!(eval("BITOR(13, 25)"), Scalar::Integer(29));
|
||||
|
||||
assert_eq!(eval("BITXOR(5, 3)"), Scalar::Integer(6));
|
||||
assert_eq!(eval("BITXOR(13, 25)"), Scalar::Integer(20));
|
||||
assert_eq!(eval("BITXOR(0, 0)"), Scalar::Integer(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitwise_keeps_integers_above_the_f64_precision_limit() {
|
||||
// 2^53 + 1 is not representable as an `f64`; routing a native Integer through one rounds it
|
||||
// to 2^53 and drops the low bit. DAX truncates non-integers, so a whole number must stay exact.
|
||||
assert_eq!(eval("BITAND(9007199254740993, 1)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("BITOR(9007199254740992, 1)"), Scalar::Integer(9007199254740993));
|
||||
assert_eq!(eval("BITXOR(9007199254740993, 1)"), Scalar::Integer(9007199254740992));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitwise_rejects_out_of_range_values() {
|
||||
assert!(eval_result("BITAND(1e30, 1)").is_err());
|
||||
assert!(eval_result("BITOR(-1e30, 1)").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn if_eager_selects_a_branch() {
|
||||
assert_eq!(eval("IF.EAGER(TRUE, 1, 2)"), Scalar::Integer(1));
|
||||
assert_eq!(eval("IF.EAGER(FALSE, 1, 2)"), Scalar::Integer(2));
|
||||
assert_eq!(eval("IF.EAGER(1 = 1, \"yes\", \"no\")"), Scalar::String("yes".into()));
|
||||
assert_eq!(eval("IF.EAGER(FALSE, 1)"), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn if_eager_evaluates_both_branches() {
|
||||
// The unselected branch is still evaluated, so its error propagates. (`1 / 0` is not an
|
||||
// error in DAX — it is Infinity — so the fixture raises a real one.)
|
||||
assert!(eval_result("IF.EAGER(TRUE, 1, ERROR(\"boom\"))").is_err());
|
||||
assert!(eval_result("IF.EAGER(FALSE, ERROR(\"boom\"), 2)").is_err());
|
||||
assert!(eval_result("IF.EAGER(FALSE, ERROR(\"boom\"))").is_err());
|
||||
// The condition itself is also evaluated eagerly.
|
||||
assert!(eval_result("IF.EAGER(ERROR(\"boom\"), 1, 2)").is_err());
|
||||
// A non-boolean condition is rejected rather than silently treated as FALSE.
|
||||
assert!(eval_result("IF.EAGER(\"maybe\", 1, 2)").is_err());
|
||||
}
|
||||
@@ -0,0 +1,956 @@
|
||||
//! `INFO.*` metadata table functions: documented schemas and model-backed rows.
|
||||
|
||||
use gridcraft_dax::functions::catalog;
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::String("East".into()), Scalar::Decimal(10.0)],
|
||||
vec![Scalar::Integer(2), Scalar::String("West".into()), Scalar::Decimal(20.0)],
|
||||
vec![Scalar::Integer(1), Scalar::String("East".into()), Scalar::Decimal(30.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(1), Scalar::String("Widget".into())], vec![Scalar::Integer(2), Scalar::String("Gadget".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
Measure {
|
||||
name: "Total Sales".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: Some("#,0.00".into()),
|
||||
expr: None,
|
||||
},
|
||||
Measure { name: "Product Count".into(), formula: "COUNTROWS(Product)".into(), table: Some("Product".into()), format: None, expr: None },
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn try_eval_table(src: &str) -> Result<TableValue, String> {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).map_err(|error| error.message.clone())?;
|
||||
let expr = parse_expression(src).map_err(|error| error.message.clone())?;
|
||||
let bound = Binder::new(&model).bind_expression(&expr).map_err(|error| error.message.clone())?;
|
||||
evaluator.evaluate_table(&bound).map_err(|error| error.message.clone())
|
||||
}
|
||||
|
||||
fn eval_table(src: &str) -> TableValue {
|
||||
try_eval_table(src).unwrap_or_else(|error| panic!("{src}: {error}"))
|
||||
}
|
||||
|
||||
fn column_names(table: &TableValue) -> Vec<String> {
|
||||
table.columns.iter().map(|column| column.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn cell(table: &TableValue, row: usize, column: &str) -> Scalar {
|
||||
let index = table.column_index(column).unwrap_or_else(|| panic!("missing column {column}"));
|
||||
table.rows[row][index].clone()
|
||||
}
|
||||
|
||||
/// The documented column names of every `INFO.*` function in the assigned scope.
|
||||
const SCHEMAS: &[(&str, &[&str])] = &[
|
||||
("INFO.ALTERNATEOFDEFINITIONS", &["ID", "ColumnID", "BaseColumnID", "BaseTableID", "Summarization"]),
|
||||
("INFO.ANNOTATIONS", &["ID", "ObjectID", "ObjectType", "Name", "Value", "ModifiedTime"]),
|
||||
("INFO.ATTRIBUTEHIERARCHIES", &["ID", "ColumnID", "State", "AttributeHierarchyStorageID", "ModifiedTime", "RefreshedTime"]),
|
||||
(
|
||||
"INFO.ATTRIBUTEHIERARCHYSTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"AttributeHierarchyID",
|
||||
"SortOrder",
|
||||
"OptimizationLevel",
|
||||
"MaterializationType",
|
||||
"ColumnPositionToData",
|
||||
"ColumnDataToPosition",
|
||||
"DistinctDataCount",
|
||||
"DataVersion",
|
||||
"StorageFileID",
|
||||
"SystemTableID",
|
||||
"HasStatistics",
|
||||
"MinValue",
|
||||
"MaxValue",
|
||||
"StringValueMaxLength",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.CALCDEPENDENCY",
|
||||
&[
|
||||
"DATABASE_NAME",
|
||||
"OBJECT_TYPE",
|
||||
"TABLE",
|
||||
"OBJECT",
|
||||
"EXPRESSION",
|
||||
"REFERENCED_OBJECT_TYPE",
|
||||
"REFERENCED_TABLE",
|
||||
"REFERENCED_OBJECT",
|
||||
"REFERENCED_EXPRESSION",
|
||||
"QUERY",
|
||||
],
|
||||
),
|
||||
("INFO.CALCULATIONGROUPS", &["ID", "TableID", "Description", "ModifiedTime", "Precedence"]),
|
||||
(
|
||||
"INFO.CALCULATIONITEMS",
|
||||
&[
|
||||
"ID",
|
||||
"CalculationGroupID",
|
||||
"FormatStringDefinitionID",
|
||||
"Name",
|
||||
"Description",
|
||||
"ModifiedTime",
|
||||
"State",
|
||||
"ErrorMessage",
|
||||
"Expression",
|
||||
"Ordinal",
|
||||
],
|
||||
),
|
||||
("INFO.CALENDARCOLUMNGROUPS", &["ID", "CalendarID", "TimeUnit", "ModifiedTime"]),
|
||||
("INFO.CALENDARCOLUMNREFERENCES", &["ID", "CalendarColumnGroupID", "ColumnID", "IsPrimaryColumn", "ModifiedTime"]),
|
||||
("INFO.CALENDARS", &["ID", "TableID", "Name", "Description", "LineageTag", "SourceLineageTag", "ModifiedTime"]),
|
||||
(
|
||||
"INFO.CATALOGS",
|
||||
&[
|
||||
"CATALOG_NAME",
|
||||
"DESCRIPTION",
|
||||
"ROLES",
|
||||
"DATE_MODIFIED",
|
||||
"COMPATIBILITY_LEVEL",
|
||||
"TYPE",
|
||||
"VERSION",
|
||||
"DATABASE_ID",
|
||||
"DATABASE_GUID",
|
||||
"DATE_QUERIED",
|
||||
"CURRENTLY_USED",
|
||||
"POPULARITY",
|
||||
"WEIGHTEDPOPULARITY",
|
||||
"CLIENTCACHEREFRESHPOLICY",
|
||||
"ENCRYPTION_LEVEL",
|
||||
],
|
||||
),
|
||||
("INFO.CHANGEDPROPERTIES", &["ID", "ObjectID", "ObjectType", "Property"]),
|
||||
("INFO.COLUMNPARTITIONSTORAGES", &["ID", "ColumnStorageID", "PartitionStorageID", "DataVersion", "State", "SegmentStorageID", "StorageFileID"]),
|
||||
("INFO.COLUMNPERMISSIONS", &["ID", "TablePermissionID", "ColumnID", "ModifiedTime", "MetadataPermission"]),
|
||||
(
|
||||
"INFO.COLUMNS",
|
||||
&[
|
||||
"ID",
|
||||
"TableID",
|
||||
"ExplicitName",
|
||||
"InferredName",
|
||||
"ExplicitDataType",
|
||||
"InferredDataType",
|
||||
"DataCategory",
|
||||
"Description",
|
||||
"IsHidden",
|
||||
"State",
|
||||
"IsUnique",
|
||||
"IsKey",
|
||||
"IsNullable",
|
||||
"Alignment",
|
||||
"TableDetailPosition",
|
||||
"IsDefaultLabel",
|
||||
"IsDefaultImage",
|
||||
"SummarizeBy",
|
||||
"ColumnStorageID",
|
||||
"Type",
|
||||
"SourceColumn",
|
||||
"ColumnOriginID",
|
||||
"Expression",
|
||||
"FormatString",
|
||||
"IsAvailableInMDX",
|
||||
"SortByColumnID",
|
||||
"AttributeHierarchyID",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"RefreshedTime",
|
||||
"SystemFlags",
|
||||
"KeepUniqueRows",
|
||||
"DisplayOrdinal",
|
||||
"ErrorMessage",
|
||||
"SourceProviderType",
|
||||
"DisplayFolder",
|
||||
"EncodingHint",
|
||||
"RelatedColumnDetailsID",
|
||||
"AlternateOfID",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.COLUMNSTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"ColumnID",
|
||||
"Name",
|
||||
"StoragePosition",
|
||||
"DictionaryStorageID",
|
||||
"Settings",
|
||||
"ColumnFlags",
|
||||
"Collation",
|
||||
"OrderByColumn",
|
||||
"Locale",
|
||||
"BinaryCharacters",
|
||||
"Statistics_DistinctStates",
|
||||
"Statistics_MinDataID",
|
||||
"Statistics_MaxDataID",
|
||||
"Statistics_OriginalMinSegmentDataID",
|
||||
"Statistics_RLESortOrder",
|
||||
"Statistics_RowCount",
|
||||
"Statistics_HasNulls",
|
||||
"Statistics_RLERuns",
|
||||
"Statistics_OthersRLERuns",
|
||||
"Statistics_Usage",
|
||||
"Statistics_DBType",
|
||||
"Statistics_XMType",
|
||||
"Statistics_CompressionType",
|
||||
"Statistics_CompressionParam",
|
||||
"Statistics_EncodingHint",
|
||||
"IsDeltaPartitionColumn",
|
||||
"DeltaColumnMappingPhysicalName",
|
||||
"DeltaColumnMappingId",
|
||||
"FramedSourceColumn",
|
||||
],
|
||||
),
|
||||
("INFO.CSDLMETADATA", &["METADATA"]),
|
||||
("INFO.CULTURES", &["ID", "ModelID", "Name", "LinguisticMetadataID", "ModifiedTime", "StructureModifiedTime"]),
|
||||
("INFO.DATACOVERAGEDEFINITIONS", &["ID", "PartitionID", "Description", "Expression", "ModifiedTime", "State", "ErrorMessage"]),
|
||||
(
|
||||
"INFO.DATASOURCES",
|
||||
&[
|
||||
"ID",
|
||||
"ModelID",
|
||||
"Name",
|
||||
"Description",
|
||||
"Type",
|
||||
"ConnectionString",
|
||||
"ImpersonationMode",
|
||||
"Account",
|
||||
"Password",
|
||||
"MaxConnections",
|
||||
"Isolation",
|
||||
"Timeout",
|
||||
"Provider",
|
||||
"ModifiedTime",
|
||||
"ConnectionDetails",
|
||||
"Options",
|
||||
"Credential",
|
||||
"ContextExpression",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.DELTATABLEMETADATASTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"PartitionStorageID",
|
||||
"TableName",
|
||||
"RootLocation",
|
||||
"CurrentVersion",
|
||||
"TableObjectID",
|
||||
"DatamartObjectID",
|
||||
"FramedSchemaName",
|
||||
"FallbackReason",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.DEPENDENCIES",
|
||||
&[
|
||||
"DATABASE_NAME",
|
||||
"OBJECT_TYPE",
|
||||
"TABLE",
|
||||
"OBJECT",
|
||||
"EXPRESSION",
|
||||
"REFERENCED_OBJECT_TYPE",
|
||||
"REFERENCED_TABLE",
|
||||
"REFERENCED_OBJECT",
|
||||
"REFERENCED_EXPRESSION",
|
||||
"QUERY",
|
||||
],
|
||||
),
|
||||
("INFO.DETAILROWSDEFINITIONS", &["ID", "ObjectID", "ObjectType", "Expression", "ModifiedTime", "State", "ErrorMessage"]),
|
||||
(
|
||||
"INFO.DICTIONARYSTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"ColumnStorageID",
|
||||
"Type",
|
||||
"DataType",
|
||||
"DataVersion",
|
||||
"BaseId",
|
||||
"Magnitude",
|
||||
"LastId",
|
||||
"IsNullable",
|
||||
"IsUnique",
|
||||
"IsOperatingOn32",
|
||||
"DictionaryFlags",
|
||||
"StorageFileID",
|
||||
"Size",
|
||||
],
|
||||
),
|
||||
("INFO.EXCLUDEDARTIFACTS", &["ID", "ObjectID", "ObjectType", "Reason"]),
|
||||
(
|
||||
"INFO.EXPRESSIONS",
|
||||
&[
|
||||
"ID",
|
||||
"ModelID",
|
||||
"Name",
|
||||
"Description",
|
||||
"Kind",
|
||||
"Expression",
|
||||
"ModifiedTime",
|
||||
"QueryGroupID",
|
||||
"ParameterValuesColumnID",
|
||||
"MAttributes",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
"RemoteParameterName",
|
||||
"ExpressionSourceID",
|
||||
],
|
||||
),
|
||||
("INFO.EXTENDEDPROPERTIES", &["ID", "ObjectID", "ObjectType", "Name", "Type", "Value", "ModifiedTime"]),
|
||||
("INFO.FORMATSTRINGDEFINITIONS", &["ID", "ObjectID", "ObjectType", "Expression", "ModifiedTime", "State", "ErrorMessage"]),
|
||||
(
|
||||
"INFO.FUNCTIONS",
|
||||
&[
|
||||
"FUNCTION_NAME",
|
||||
"DESCRIPTION",
|
||||
"PARAMETER_LIST",
|
||||
"RETURN_TYPE",
|
||||
"ORIGIN",
|
||||
"INTERFACE_NAME",
|
||||
"LIBRARY_NAME",
|
||||
"DLL_NAME",
|
||||
"HELP_FILE",
|
||||
"HELP_CONTEXT",
|
||||
"OBJECT",
|
||||
"CAPTION",
|
||||
"PARAMETERINFO",
|
||||
"DIRECTQUERY_PUSHABLE",
|
||||
"VISUAL_CALCULATIONS_INFO",
|
||||
],
|
||||
),
|
||||
("INFO.GENERALSEGMENTMAPSEGMENTMETADATASTORAGES", &["ID", "SegmentMapStorageID", "RecordCount", "Ordinal"]),
|
||||
("INFO.GROUPBYCOLUMNS", &["ID", "RelatedColumnDetailsID", "GroupingColumnID", "ModifiedTime"]),
|
||||
(
|
||||
"INFO.HIERARCHIES",
|
||||
&[
|
||||
"ID",
|
||||
"TableID",
|
||||
"Name",
|
||||
"Description",
|
||||
"IsHidden",
|
||||
"State",
|
||||
"HierarchyStorageID",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"RefreshedTime",
|
||||
"DisplayFolder",
|
||||
"HideMembers",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
],
|
||||
),
|
||||
("INFO.HIERARCHYSTORAGES", &["ID", "HierarchyID", "Name", "LevelDefinition", "MaterializationType", "StructureType", "SystemTableID"]),
|
||||
(
|
||||
"INFO.KPIS",
|
||||
&[
|
||||
"ID",
|
||||
"MeasureID",
|
||||
"Description",
|
||||
"TargetDescription",
|
||||
"TargetExpression",
|
||||
"TargetFormatString",
|
||||
"StatusGraphic",
|
||||
"StatusDescription",
|
||||
"StatusExpression",
|
||||
"TrendGraphic",
|
||||
"TrendDescription",
|
||||
"TrendExpression",
|
||||
"ModifiedTime",
|
||||
],
|
||||
),
|
||||
("INFO.LEVELS", &["ID", "HierarchyID", "Ordinal", "Name", "Description", "ColumnID", "ModifiedTime", "LineageTag", "SourceLineageTag"]),
|
||||
("INFO.LINGUISTICMETADATA", &["ID", "CultureID", "Content", "ModifiedTime", "ContentType"]),
|
||||
(
|
||||
"INFO.MEASURES",
|
||||
&[
|
||||
"ID",
|
||||
"TableID",
|
||||
"Name",
|
||||
"Description",
|
||||
"DataType",
|
||||
"Expression",
|
||||
"FormatString",
|
||||
"IsHidden",
|
||||
"State",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"KPIID",
|
||||
"IsSimpleMeasure",
|
||||
"ErrorMessage",
|
||||
"DisplayFolder",
|
||||
"DetailRowsDefinitionID",
|
||||
"DataCategory",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.MODEL",
|
||||
&[
|
||||
"ID",
|
||||
"Name",
|
||||
"Description",
|
||||
"StorageLocation",
|
||||
"DefaultMode",
|
||||
"DefaultDataView",
|
||||
"Culture",
|
||||
"Collation",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"Version",
|
||||
"DataAccessOptions",
|
||||
"DefaultMeasureID",
|
||||
"DefaultPowerBIDataSourceVersion",
|
||||
"ForceUniqueNames",
|
||||
"DiscourageImplicitMeasures",
|
||||
"DataSourceVariablesOverrideBehavior",
|
||||
"DataSourceDefaultMaxConnections",
|
||||
"SourceQueryCulture",
|
||||
"MAttributes",
|
||||
"DiscourageCompositeModels",
|
||||
"AutomaticAggregationOptions",
|
||||
"DisableAutoExists",
|
||||
"MaxParallelismPerRefresh",
|
||||
"MaxParallelismPerQuery",
|
||||
"DirectLakeBehavior",
|
||||
"ValueFilterBehavior",
|
||||
],
|
||||
),
|
||||
("INFO.OBJECTTRANSLATIONS", &["ID", "CultureID", "ObjectID", "ObjectType", "Property", "Value", "ModifiedTime", "Altered"]),
|
||||
(
|
||||
"INFO.PARQUETFILESTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"DeltaTableMetadataStorageID",
|
||||
"Size",
|
||||
"Location",
|
||||
"CreatedVersion",
|
||||
"DeletedVersion",
|
||||
"RowgroupCount",
|
||||
"Ordinal",
|
||||
"ETag",
|
||||
"DeletionVectorFileLocation",
|
||||
"DeletionVectorBitmapOffset",
|
||||
"DeletionVectorBitmapSize",
|
||||
"DeletionVectorFileETag",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.PARTITIONS",
|
||||
&[
|
||||
"ID",
|
||||
"TableID",
|
||||
"Name",
|
||||
"Description",
|
||||
"DataSourceID",
|
||||
"QueryDefinition",
|
||||
"State",
|
||||
"Type",
|
||||
"PartitionStorageID",
|
||||
"Mode",
|
||||
"DataView",
|
||||
"ModifiedTime",
|
||||
"RefreshedTime",
|
||||
"SystemFlags",
|
||||
"ErrorMessage",
|
||||
"RetainDataTillForceCalculate",
|
||||
"RangeStart",
|
||||
"RangeEnd",
|
||||
"RangeGranularity",
|
||||
"RefreshBookmark",
|
||||
"QueryGroupID",
|
||||
"ExpressionSourceID",
|
||||
"MAttributes",
|
||||
"DataCoverageDefinitionID",
|
||||
"SchemaName",
|
||||
],
|
||||
),
|
||||
("INFO.PARTITIONSTORAGES", &["ID", "PartitionID", "Name", "StoragePosition", "SegmentMapStorageID", "DataObjectId", "StorageFolderID"]),
|
||||
("INFO.PERSPECTIVECOLUMNS", &["ID", "PerspectiveTableID", "ColumnID", "ModifiedTime"]),
|
||||
("INFO.PERSPECTIVEHIERARCHIES", &["ID", "PerspectiveTableID", "HierarchyID", "ModifiedTime"]),
|
||||
("INFO.PERSPECTIVEMEASURES", &["ID", "PerspectiveTableID", "MeasureID", "ModifiedTime"]),
|
||||
("INFO.PERSPECTIVES", &["ID", "ModelID", "Name", "Description", "ModifiedTime"]),
|
||||
("INFO.PERSPECTIVETABLES", &["ID", "PerspectiveID", "TableID", "IncludeAll", "ModifiedTime"]),
|
||||
("INFO.PROPERTIES", &["PropertyName", "PropertyDescription", "PropertyType", "PropertyAccessType", "IsRequired", "Value"]),
|
||||
("INFO.QUERYGROUPS", &["ID", "ModelID", "Folder", "Description"]),
|
||||
(
|
||||
"INFO.REFRESHPOLICIES",
|
||||
&[
|
||||
"ID",
|
||||
"TableID",
|
||||
"PolicyType",
|
||||
"RollingWindowGranularity",
|
||||
"RollingWindowPeriods",
|
||||
"IncrementalGranularity",
|
||||
"IncrementalPeriods",
|
||||
"IncrementalPeriodsOffset",
|
||||
"PollingExpression",
|
||||
"SourceExpression",
|
||||
"Mode",
|
||||
],
|
||||
),
|
||||
("INFO.RELATEDCOLUMNDETAILS", &["ID", "ColumnID", "ModifiedTime"]),
|
||||
(
|
||||
"INFO.RELATIONSHIPINDEXSTORAGES",
|
||||
&[
|
||||
"ID",
|
||||
"RelationshipStorageID",
|
||||
"IndexType",
|
||||
"Flags",
|
||||
"RecordCount",
|
||||
"SecondaryRecordCount",
|
||||
"StorageFolderID",
|
||||
"StorageFileID",
|
||||
"SystemTableID",
|
||||
"SecondarySystemTableID",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.RELATIONSHIPS",
|
||||
&[
|
||||
"ID",
|
||||
"ModelID",
|
||||
"Name",
|
||||
"IsActive",
|
||||
"Type",
|
||||
"CrossFilteringBehavior",
|
||||
"JoinOnDateBehavior",
|
||||
"RelyOnReferentialIntegrity",
|
||||
"FromTableID",
|
||||
"FromColumnID",
|
||||
"FromCardinality",
|
||||
"ToTableID",
|
||||
"ToColumnID",
|
||||
"ToCardinality",
|
||||
"State",
|
||||
"RelationshipStorageID",
|
||||
"RelationshipStorage2ID",
|
||||
"ModifiedTime",
|
||||
"RefreshedTime",
|
||||
"SecurityFilteringBehavior",
|
||||
],
|
||||
),
|
||||
("INFO.RELATIONSHIPSTORAGES", &["ID", "RelationshipID", "Name", "DefinitionType", "Cardinality", "Flags", "RelationshipIndexStorageID"]),
|
||||
("INFO.ROLEMEMBERSHIPS", &["ID", "RoleID", "MemberName", "MemberID", "IdentityProvider", "MemberType", "ModifiedTime"]),
|
||||
("INFO.ROLES", &["ID", "ModelID", "Name", "Description", "ModelPermission", "ModifiedTime"]),
|
||||
("INFO.SEGMENTMAPSTORAGES", &["ID", "PartitionStorageID", "Type", "RecordCount", "SegmentCount", "RecordsPerSegment"]),
|
||||
("INFO.SEGMENTSTORAGES", &["ID", "ColumnPartitionStorageID", "SegmentCount", "StorageFileID"]),
|
||||
("INFO.STORAGEFILES", &["ID", "OwnerID", "OwnerType", "StorageFolderID", "FileName"]),
|
||||
("INFO.STORAGEFOLDERS", &["ID", "OwnerID", "OwnerType", "Path"]),
|
||||
(
|
||||
"INFO.STORAGETABLECOLUMNS",
|
||||
&[
|
||||
"DATABASE_NAME",
|
||||
"CUBE_NAME",
|
||||
"MEASURE_GROUP_NAME",
|
||||
"DIMENSION_NAME",
|
||||
"ATTRIBUTE_NAME",
|
||||
"TABLE_ID",
|
||||
"COLUMN_ID",
|
||||
"COLUMN_TYPE",
|
||||
"COLUMN_ENCODING",
|
||||
"DATATYPE",
|
||||
"ISKEY",
|
||||
"ISUNIQUE",
|
||||
"ISNULLABLE",
|
||||
"ISROWNUMBER",
|
||||
"DICTIONARY_SIZE",
|
||||
"DICTIONARY_ISPAGEABLE",
|
||||
"DICTIONARY_ISRESIDENT",
|
||||
"DICTIONARY_TEMPERATURE",
|
||||
"DICTIONARY_LAST_ACCESSED",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.STORAGETABLECOLUMNSEGMENTS",
|
||||
&[
|
||||
"DATABASE_NAME",
|
||||
"CUBE_NAME",
|
||||
"MEASURE_GROUP_NAME",
|
||||
"PARTITION_NAME",
|
||||
"DIMENSION_NAME",
|
||||
"TABLE_ID",
|
||||
"COLUMN_ID",
|
||||
"SEGMENT_NUMBER",
|
||||
"TABLE_PARTITION_NUMBER",
|
||||
"RECORDS_COUNT",
|
||||
"ALLOCATED_SIZE",
|
||||
"USED_SIZE",
|
||||
"COMPRESSION_TYPE",
|
||||
"BITS_COUNT",
|
||||
"BOOKMARK_BITS_COUNT",
|
||||
"VERTIPAQ_STATE",
|
||||
"ISPAGEABLE",
|
||||
"ISRESIDENT",
|
||||
"TEMPERATURE",
|
||||
"LAST_ACCESSED",
|
||||
],
|
||||
),
|
||||
("INFO.TABLEPERMISSIONS", &["ID", "RoleID", "TableID", "FilterExpression", "ModifiedTime", "State", "ErrorMessage", "MetadataPermission"]),
|
||||
(
|
||||
"INFO.TABLES",
|
||||
&[
|
||||
"ID",
|
||||
"ModelID",
|
||||
"Name",
|
||||
"DataCategory",
|
||||
"Description",
|
||||
"IsHidden",
|
||||
"TableStorageID",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"SystemFlags",
|
||||
"ShowAsVariationsOnly",
|
||||
"IsPrivate",
|
||||
"DefaultDetailRowsDefinitionID",
|
||||
"AlternateSourcePrecedence",
|
||||
"RefreshPolicyID",
|
||||
"CalculationGroupID",
|
||||
"ExcludeFromModelRefresh",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
"SystemManaged",
|
||||
"ExcludeFromAutomaticAggregations",
|
||||
],
|
||||
),
|
||||
("INFO.TABLESTORAGES", &["ID", "TableID", "Name", "Version", "Settings", "RIViolationCount", "StorageFolderID"]),
|
||||
(
|
||||
"INFO.USERDEFINEDFUNCTIONS",
|
||||
&[
|
||||
"ID",
|
||||
"ModelID",
|
||||
"Name",
|
||||
"Description",
|
||||
"Expression",
|
||||
"IsHidden",
|
||||
"State",
|
||||
"ErrorMessage",
|
||||
"ModifiedTime",
|
||||
"StructureModifiedTime",
|
||||
"LineageTag",
|
||||
"SourceLineageTag",
|
||||
],
|
||||
),
|
||||
("INFO.VARIATIONS", &["ID", "ColumnID", "Name", "Description", "RelationshipID", "DefaultHierarchyID", "DefaultColumnID", "IsDefault"]),
|
||||
(
|
||||
"INFO.VIEW.COLUMNS",
|
||||
&[
|
||||
"ID",
|
||||
"Name",
|
||||
"Table",
|
||||
"DataType",
|
||||
"DataCategory",
|
||||
"Description",
|
||||
"IsHidden",
|
||||
"IsUnique",
|
||||
"IsKey",
|
||||
"IsNullable",
|
||||
"Alignment",
|
||||
"SummarizeBy",
|
||||
"ColumnStorage",
|
||||
"Type",
|
||||
"SourceColumn",
|
||||
"Expression",
|
||||
"FormatString",
|
||||
"IsAvailableInMDX",
|
||||
"SortByColumn",
|
||||
"GroupingBehavior",
|
||||
"SourceProviderType",
|
||||
"DisplayFolder",
|
||||
"AlternateOf",
|
||||
"LineageTag",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.VIEW.MEASURES",
|
||||
&[
|
||||
"ID",
|
||||
"Name",
|
||||
"Table",
|
||||
"Description",
|
||||
"DataType",
|
||||
"Expression",
|
||||
"FormatString",
|
||||
"IsHidden",
|
||||
"State",
|
||||
"KPIID",
|
||||
"IsSimpleMeasure",
|
||||
"DisplayFolder",
|
||||
"DetailRowsDefinition",
|
||||
"DataCategory",
|
||||
"FormatStringDefinition",
|
||||
"LineageTag",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.VIEW.RELATIONSHIPS",
|
||||
&[
|
||||
"ID",
|
||||
"Name",
|
||||
"Relationship",
|
||||
"Model",
|
||||
"IsActive",
|
||||
"CrossFilteringBehavior",
|
||||
"RelyOnReferentialIntegrity",
|
||||
"FromTable",
|
||||
"FromColumn",
|
||||
"FromCardinality",
|
||||
"ToTable",
|
||||
"ToColumn",
|
||||
"ToCardinality",
|
||||
"State",
|
||||
"SecurityFilteringBehavior",
|
||||
],
|
||||
),
|
||||
(
|
||||
"INFO.VIEW.TABLES",
|
||||
&[
|
||||
"ID",
|
||||
"Name",
|
||||
"Model",
|
||||
"DataCategory",
|
||||
"Description",
|
||||
"IsHidden",
|
||||
"StorageMode",
|
||||
"TableStorage",
|
||||
"Expression",
|
||||
"ShowAsVariationOnly",
|
||||
"IsPrivate",
|
||||
"CalculationGroupPrecedence",
|
||||
"LineageTag",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn every_info_function_returns_its_documented_schema() {
|
||||
assert_eq!(SCHEMAS.len(), 71, "assigned INFO.* functions");
|
||||
for (name, columns) in SCHEMAS {
|
||||
let table = eval_table(&format!("{name}()"));
|
||||
let expected: Vec<String> = columns.iter().map(|column| (*column).to_string()).collect();
|
||||
assert_eq!(column_names(&table), expected, "{name} columns");
|
||||
for row in &table.rows {
|
||||
assert_eq!(row.len(), table.columns.len(), "{name} row width");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_describe_the_model_tables() {
|
||||
let table = eval_table("INFO.TABLES()");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(cell(&table, 0, "ID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "ModelID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&table, 0, "IsHidden"), Scalar::Boolean(false));
|
||||
assert_eq!(cell(&table, 1, "ID"), Scalar::Integer(2));
|
||||
assert_eq!(cell(&table, 1, "Name"), Scalar::String("Product".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn columns_describe_the_model_columns() {
|
||||
let table = eval_table("INFO.COLUMNS()");
|
||||
assert_eq!(table.rows.len(), 5);
|
||||
let names: Vec<Scalar> = (0..5).map(|row| cell(&table, row, "ExplicitName")).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
Scalar::String("ProductKey".into()),
|
||||
Scalar::String("Region".into()),
|
||||
Scalar::String("Amount".into()),
|
||||
Scalar::String("ProductKey".into()),
|
||||
Scalar::String("Name".into()),
|
||||
]
|
||||
);
|
||||
let table_ids: Vec<Scalar> = (0..5).map(|row| cell(&table, row, "TableID")).collect();
|
||||
assert_eq!(table_ids, vec![Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(1), Scalar::Integer(2), Scalar::Integer(2)]);
|
||||
let ids: Vec<Scalar> = (0..5).map(|row| cell(&table, row, "ID")).collect();
|
||||
assert_eq!(ids, vec![Scalar::Integer(1), Scalar::Integer(2), Scalar::Integer(3), Scalar::Integer(4), Scalar::Integer(5)]);
|
||||
assert_eq!(cell(&table, 2, "ExplicitDataType"), Scalar::String("Double".into()));
|
||||
assert_eq!(cell(&table, 2, "DisplayOrdinal"), Scalar::Integer(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_expose_name_formula_and_home_table() {
|
||||
let table = eval_table("INFO.MEASURES()");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Total Sales".into()));
|
||||
assert_eq!(cell(&table, 0, "Expression"), Scalar::String("SUM(Sales[Amount])".into()));
|
||||
assert_eq!(cell(&table, 0, "TableID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "FormatString"), Scalar::String("#,0.00".into()));
|
||||
assert_eq!(cell(&table, 0, "State"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 1, "Name"), Scalar::String("Product Count".into()));
|
||||
assert_eq!(cell(&table, 1, "TableID"), Scalar::Integer(2));
|
||||
assert_eq!(cell(&table, 1, "FormatString"), Scalar::Blank);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationships_join_columns_by_id() {
|
||||
let table = eval_table("INFO.RELATIONSHIPS()");
|
||||
assert_eq!(table.rows.len(), 1);
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Sales[ProductKey] -> Product[ProductKey]".into()));
|
||||
assert_eq!(cell(&table, 0, "IsActive"), Scalar::Boolean(true));
|
||||
assert_eq!(cell(&table, 0, "FromTableID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "FromColumnID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "FromCardinality"), Scalar::Integer(2));
|
||||
assert_eq!(cell(&table, 0, "ToTableID"), Scalar::Integer(2));
|
||||
assert_eq!(cell(&table, 0, "ToColumnID"), Scalar::Integer(4));
|
||||
assert_eq!(cell(&table, 0, "ToCardinality"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "CrossFilteringBehavior"), Scalar::Integer(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partitions_cover_each_table() {
|
||||
let table = eval_table("INFO.PARTITIONS()");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(cell(&table, 0, "TableID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&table, 0, "Mode"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "State"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 1, "TableID"), Scalar::Integer(2));
|
||||
assert_eq!(cell(&table, 1, "Name"), Scalar::String("Product".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expressions_list_measure_formulas() {
|
||||
let table = eval_table("INFO.EXPRESSIONS()");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(cell(&table, 0, "ModelID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Total Sales".into()));
|
||||
assert_eq!(cell(&table, 0, "Kind"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "Expression"), Scalar::String("SUM(Sales[Amount])".into()));
|
||||
assert_eq!(cell(&table, 1, "Expression"), Scalar::String("COUNTROWS(Product)".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_match_the_catalog() {
|
||||
let table = eval_table("INFO.FUNCTIONS()");
|
||||
assert_eq!(table.rows.len(), catalog().len());
|
||||
let sum = (0..table.rows.len()).find(|row| cell(&table, *row, "FUNCTION_NAME") == Scalar::String("SUM".into())).expect("SUM row");
|
||||
assert_eq!(cell(&table, sum, "RETURN_TYPE"), Scalar::String("Numeric".into()));
|
||||
assert_eq!(cell(&table, sum, "ORIGIN"), Scalar::Integer(1));
|
||||
assert!(!cell(&table, sum, "DESCRIPTION").to_text().is_empty());
|
||||
let info_tables =
|
||||
(0..table.rows.len()).find(|row| cell(&table, *row, "FUNCTION_NAME") == Scalar::String("INFO.TABLES".into())).expect("INFO.TABLES row");
|
||||
assert_eq!(cell(&table, info_tables, "RETURN_TYPE"), Scalar::String("Table".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_has_one_synthetic_row() {
|
||||
let table = eval_table("INFO.MODEL()");
|
||||
assert_eq!(table.rows.len(), 1);
|
||||
assert_eq!(cell(&table, 0, "ID"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Model".into()));
|
||||
assert_eq!(cell(&table, 0, "Version"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "DefaultMode"), Scalar::Integer(1));
|
||||
assert_eq!(cell(&table, 0, "DiscourageImplicitMeasures"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_functions_decode_ids_to_names() {
|
||||
let columns = eval_table("INFO.VIEW.COLUMNS()");
|
||||
assert_eq!(columns.rows.len(), 5);
|
||||
assert_eq!(cell(&columns, 2, "Name"), Scalar::String("Amount".into()));
|
||||
assert_eq!(cell(&columns, 2, "Table"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&columns, 2, "DataType"), Scalar::String("Double".into()));
|
||||
assert_eq!(cell(&columns, 2, "Type"), Scalar::String("Data".into()));
|
||||
assert_eq!(cell(&columns, 2, "SourceColumn"), Scalar::String("Amount".into()));
|
||||
assert_eq!(cell(&columns, 2, "IsAvailableInMDX"), Scalar::Boolean(true));
|
||||
|
||||
let measures = eval_table("INFO.VIEW.MEASURES()");
|
||||
assert_eq!(measures.rows.len(), 2);
|
||||
assert_eq!(cell(&measures, 0, "Name"), Scalar::String("Total Sales".into()));
|
||||
assert_eq!(cell(&measures, 0, "Table"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&measures, 0, "Expression"), Scalar::String("SUM(Sales[Amount])".into()));
|
||||
assert_eq!(cell(&measures, 0, "State"), Scalar::String("Ready".into()));
|
||||
|
||||
let relationships = eval_table("INFO.VIEW.RELATIONSHIPS()");
|
||||
assert_eq!(relationships.rows.len(), 1);
|
||||
assert_eq!(cell(&relationships, 0, "Model"), Scalar::String("Model".into()));
|
||||
assert_eq!(cell(&relationships, 0, "FromTable"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&relationships, 0, "FromColumn"), Scalar::String("ProductKey".into()));
|
||||
assert_eq!(cell(&relationships, 0, "FromCardinality"), Scalar::String("Many".into()));
|
||||
assert_eq!(cell(&relationships, 0, "ToTable"), Scalar::String("Product".into()));
|
||||
assert_eq!(cell(&relationships, 0, "ToColumn"), Scalar::String("ProductKey".into()));
|
||||
assert_eq!(cell(&relationships, 0, "ToCardinality"), Scalar::String("One".into()));
|
||||
assert_eq!(cell(&relationships, 0, "CrossFilteringBehavior"), Scalar::String("OneDirection".into()));
|
||||
|
||||
let tables = eval_table("INFO.VIEW.TABLES()");
|
||||
assert_eq!(tables.rows.len(), 2);
|
||||
assert_eq!(cell(&tables, 0, "Name"), Scalar::String("Sales".into()));
|
||||
assert_eq!(cell(&tables, 0, "Model"), Scalar::String("Model".into()));
|
||||
assert_eq!(cell(&tables, 0, "StorageMode"), Scalar::String("Import".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrepresentable_objects_keep_their_columns_without_rows() {
|
||||
for name in [
|
||||
"INFO.DATASOURCES",
|
||||
"INFO.CALCDEPENDENCY",
|
||||
"INFO.CULTURES",
|
||||
"INFO.PERSPECTIVES",
|
||||
"INFO.ROLES",
|
||||
"INFO.TABLEPERMISSIONS",
|
||||
"INFO.QUERYGROUPS",
|
||||
"INFO.STORAGEFILES",
|
||||
] {
|
||||
let table = eval_table(&format!("{name}()"));
|
||||
assert!(!table.columns.is_empty(), "{name} has documented columns");
|
||||
assert!(table.rows.is_empty(), "{name} has no model-backed rows");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restrictions_are_accepted_as_pairs() {
|
||||
let table = eval_table("INFO.TABLES(\"Name\", \"Sales\")");
|
||||
// The restriction pair keeps only the row whose `Name` is `Sales`.
|
||||
assert_eq!(table.rows.len(), 1);
|
||||
assert_eq!(cell(&table, 0, "Name"), Scalar::String("Sales".into()));
|
||||
let error = try_eval_table("INFO.TABLES(\"Name\")").expect_err("dangling restriction");
|
||||
assert!(error.contains("restriction"), "unexpected error: {error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_info_calls_are_left_to_other_modules() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("SUM(Sales[Amount])").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound), Ok(Scalar::Decimal(60.0)));
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//! Differential test of the storage-backed evaluator against documented expected values.
|
||||
//!
|
||||
//! The fixture is a two-table star schema (Sales many-side, Product one-side) with blanks in the
|
||||
//! measure, quantity, region and key columns. Every expectation below is stated with its
|
||||
//! arithmetic in the comment, and was checked independently in Excel 16 against the same rows
|
||||
//! (workbook built with COM: `Sales`/`Product` sheets plus a formula summary and a real
|
||||
//! `PivotTable`). The values Excel returned were: `SUM(Amount)` 280, `AVERAGE` 46.666666666666664,
|
||||
//! `COUNT` 6, `COUNTA` 6, `COUNTBLANK` 1, distinct incl. blank 7, `MIN` 10, `MAX` 100,
|
||||
//! `PRODUCT` 2100000000, East 150, Hardware 190, extended price
|
||||
//! 150.5, related-row count 7, West 100, North 20, blank region 10, the cross-tab key totals
|
||||
//! 130/60/70/20 and the pivot's East 150 / North 20 / West 100 / (blank) 10 / Grand Total 280.
|
||||
//!
|
||||
//! These assertions are *documented values*, not a comparison of one evaluator path against
|
||||
//! another. Each one additionally asserts the matching [`StorageStats`] counter moved, so a
|
||||
//! documented value can never be produced by the row-scan fallback and still pass.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::pivot_table::{PivotFilter, PivotLayout, PivotTable};
|
||||
use gridcraft_dax::value::{Scalar, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, StorageStats, parse_expression};
|
||||
|
||||
// Product ProductKey Name Category UnitPrice
|
||||
// 1 Widget Hardware 20.00
|
||||
// 2 Gadget Hardware 5.00
|
||||
// 3 Gizmo Tools 12.50
|
||||
// 4 Doohickey Tools 0.75
|
||||
//
|
||||
// Sales ProductKey Region Amount Quantity
|
||||
// 1 East 100 2
|
||||
// 2 East 50 5
|
||||
// 1 West 30 3
|
||||
// 3 West 70 1
|
||||
// 1 East (blank) (blank)
|
||||
// 4 North 20 4
|
||||
// 2 (blank) 10 2
|
||||
fn model() -> DataModel {
|
||||
let product = |key: i64, name: &str, category: &str, price: i64| {
|
||||
vec![Scalar::Integer(key), Scalar::String(name.into()), Scalar::String(category.into()), Scalar::Currency(price)]
|
||||
};
|
||||
let sale = |key: i64, region: Scalar, amount: Scalar, quantity: Scalar| vec![Scalar::Integer(key), region, amount, quantity];
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "UnitPrice".into(), data_type: Some("Currency".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
product(1, "Widget", "Hardware", 200_000),
|
||||
product(2, "Gadget", "Hardware", 50_000),
|
||||
product(3, "Gizmo", "Tools", 125_000),
|
||||
product(4, "Doohickey", "Tools", 7_500),
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
sale(1, Scalar::String("East".into()), Scalar::Integer(100), Scalar::Integer(2)),
|
||||
sale(2, Scalar::String("East".into()), Scalar::Integer(50), Scalar::Integer(5)),
|
||||
sale(1, Scalar::String("West".into()), Scalar::Integer(30), Scalar::Integer(3)),
|
||||
sale(3, Scalar::String("West".into()), Scalar::Integer(70), Scalar::Integer(1)),
|
||||
sale(1, Scalar::String("East".into()), Scalar::Blank, Scalar::Blank),
|
||||
sale(4, Scalar::String("North".into()), Scalar::Integer(20), Scalar::Integer(4)),
|
||||
sale(2, Scalar::Blank, Scalar::Integer(10), Scalar::Integer(2)),
|
||||
],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
measure("Total Amount", "SUM(Sales[Amount])", "Sales"),
|
||||
measure("Rows", "COUNTROWS(Sales)", "Sales"),
|
||||
measure("Product Count", "DISTINCTCOUNT(Sales[ProductKey])", "Sales"),
|
||||
measure("Extended Price", "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))", "Sales"),
|
||||
measure("Sales Rows Per Product", "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))", "Product"),
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn measure(name: &str, formula: &str, table: &str) -> Measure {
|
||||
Measure { name: name.into(), formula: formula.into(), table: Some(table.into()), format: None, expr: None }
|
||||
}
|
||||
|
||||
fn text(value: &str) -> Scalar {
|
||||
Scalar::String(value.into())
|
||||
}
|
||||
|
||||
/// Evaluates a scalar formula together with the storage counters it moved.
|
||||
fn eval(model: &DataModel, formula: &str) -> (Scalar, StorageStats) {
|
||||
let evaluator = Evaluator::new(model).expect("evaluator");
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
let value = evaluator.evaluate(&bound).expect("evaluate");
|
||||
(value, evaluator.storage_stats())
|
||||
}
|
||||
|
||||
fn eval_table(model: &DataModel, formula: &str) -> (TableValue, StorageStats) {
|
||||
let evaluator = Evaluator::new(model).expect("evaluator");
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
let table = evaluator.evaluate_table(&bound).expect("table");
|
||||
(table, evaluator.storage_stats())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_is_materialized_faithfully() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let storage = evaluator.storage().expect("the fixture materializes");
|
||||
assert!(storage.is_faithful(), "every fixture cell round-trips, so storage answers for the rows");
|
||||
assert!(evaluator.storage_error().is_none());
|
||||
assert_eq!(storage.tables().len(), 2);
|
||||
assert_eq!(storage.relationships().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_aggregates_match_documented_values() {
|
||||
let model = model();
|
||||
// 100 + 50 + 30 + 70 + 20 + 10 = 280 (row 5 has a blank Amount).
|
||||
let (value, stats) = eval(&model, "SUM(Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Decimal(280.0));
|
||||
assert!(stats.aggregates > 0, "SUM must be served by storage, got {stats:?}");
|
||||
|
||||
// 280 / 6 non-blank rows.
|
||||
let (value, stats) = eval(&model, "AVERAGE(Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Decimal(280.0 / 6.0));
|
||||
assert!(stats.aggregates > 0);
|
||||
|
||||
// COUNT ignores the blank Amount; COUNTA counts it as absent; COUNTBLANK is exactly one cell.
|
||||
assert_eq!(eval(&model, "COUNT(Sales[Amount])").0, Scalar::Integer(6));
|
||||
assert_eq!(eval(&model, "COUNTA(Sales[Amount])").0, Scalar::Integer(6));
|
||||
assert_eq!(eval(&model, "COUNTBLANK(Sales[Amount])").0, Scalar::Integer(1));
|
||||
|
||||
// 100, 50, 30, 70, 20, 10 and BLANK are seven distinct values: DAX counts BLANK as one.
|
||||
let (value, stats) = eval(&model, "DISTINCTCOUNT(Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Integer(7));
|
||||
assert!(stats.aggregates > 0);
|
||||
|
||||
// MIN/MAX answer the winning value, so an Int64 column keeps its Integer type.
|
||||
let (value, stats) = eval(&model, "MIN(Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Integer(10));
|
||||
assert!(stats.aggregates > 0, "MIN must be served by storage, got {stats:?}");
|
||||
assert_eq!(eval(&model, "MAX(Sales[Amount])").0, Scalar::Integer(100));
|
||||
// 100 * 50 * 30 * 70 * 20 * 10 = 2,100,000,000.
|
||||
assert_eq!(eval(&model, "PRODUCT(Sales[Amount])").0, Scalar::Decimal(2_100_000_000.0));
|
||||
|
||||
// Currency is read in major units: MIN is 0.75 and MAX is 20.00 (Excel agrees), and the
|
||||
// result stays currency — 7,500 and 200,000 in the internal ten-thousandths scale.
|
||||
let (value, stats) = eval(&model, "MIN(Product[UnitPrice])");
|
||||
assert_eq!(value, Scalar::Currency(7_500));
|
||||
assert!(stats.aggregates > 0);
|
||||
assert_eq!(eval(&model, "MAX(Product[UnitPrice])").0, Scalar::Currency(200_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterator_aggregates_match_documented_values() {
|
||||
let model = model();
|
||||
let (value, stats) = eval(&model, "SUMX(Sales, Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Decimal(280.0));
|
||||
assert!(stats.iterators > 0, "a plain-column SUMX must be answered from the column, got {stats:?}");
|
||||
assert!(stats.rows_from_storage >= 7);
|
||||
|
||||
let (value, stats) = eval(&model, "COUNTROWS(Sales)");
|
||||
assert_eq!(value, Scalar::Integer(7));
|
||||
assert!(stats.count_rows > 0);
|
||||
|
||||
// FILTER needs a row context, so this iterator keeps the row path but must still be correct.
|
||||
// 100 + 50 + 70 = 220 are the amounts above 40.
|
||||
let (value, stats) = eval(&model, "SUMX(FILTER(Sales, Sales[Amount] > 40), Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Decimal(220.0));
|
||||
assert!(stats.iterators == 0, "a FILTER table argument cannot use the plain-column fast path");
|
||||
// The FILTER itself still reads its source table from columns.
|
||||
assert!(stats.rows_from_storage >= 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_context_aggregates_match_documented_values() {
|
||||
let model = model();
|
||||
// East rows: 100 + 50 + blank = 150.
|
||||
let (value, stats) = eval(&model, "CALCULATE(SUM(Sales[Amount]), Sales[Region] = \"East\")");
|
||||
assert_eq!(value, Scalar::Decimal(150.0));
|
||||
assert!(stats.aggregates > 0);
|
||||
assert!(stats.filter_scans > 0, "the Region filter must be a storage column filter, got {stats:?}");
|
||||
|
||||
// Rows of a related table restrict this one: Hardware products are keys 1 and 2, so
|
||||
// amounts 100 + 50 + 30 + 10 = 190 (the blank amount adds nothing).
|
||||
let (value, stats) = eval(&model, "CALCULATE(SUM(Sales[Amount]), Product[Category] = \"Hardware\")");
|
||||
assert_eq!(value, Scalar::Decimal(190.0));
|
||||
assert!(stats.relationship_lookups > 0, "filter propagation must use the relationship index, got {stats:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_joins_match_documented_values() {
|
||||
let model = model();
|
||||
// Unit price x quantity per row: 20*2 + 5*5 + 20*3 + 12.5*1 + (blank) + 0.75*4 + 5*2
|
||||
// = 40 + 25 + 60 + 12.5 + 3 + 10 = 150.5.
|
||||
let (value, stats) = eval(&model, "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))");
|
||||
assert_eq!(value, Scalar::Decimal(150.5));
|
||||
assert!(stats.related > 0, "RELATED must resolve through the relationship index, got {stats:?}");
|
||||
|
||||
// Sales rows per product: 3 (key 1) + 2 (key 2) + 1 (key 3) + 1 (key 4) = 7.
|
||||
let (value, stats) = eval(&model, "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))");
|
||||
assert_eq!(value, Scalar::Decimal(7.0));
|
||||
assert!(stats.related_table > 0, "RELATEDTABLE must use the relationship index, got {stats:?}");
|
||||
|
||||
// The one-sided price of a related row is available without an iterator too.
|
||||
let (value, _) = eval(&model, "SUMX(Product, Product[UnitPrice])");
|
||||
assert_eq!(value, Scalar::Decimal(38.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_and_distinct_match_documented_values() {
|
||||
let model = model();
|
||||
// Regions in first-appearance order with BLANK last: East, West, North, (blank).
|
||||
let (table, stats) = eval_table(&model, "VALUES(Sales[Region])");
|
||||
assert_eq!(table.columns.len(), 1);
|
||||
assert_eq!(table.rows, vec![vec![text("East")], vec![text("West")], vec![text("North")], vec![Scalar::Blank]]);
|
||||
assert_eq!(table.lineage, Some(1));
|
||||
assert!(stats.distinct_values > 0, "VALUES must dedupe through storage, got {stats:?}");
|
||||
|
||||
// DISTINCT agrees, and DISTINCTCOUNT counts the same four values.
|
||||
let (distinct, _) = eval_table(&model, "DISTINCT(Sales[Region])");
|
||||
assert_eq!(distinct.rows, table.rows);
|
||||
assert_eq!(eval(&model, "DISTINCTCOUNT(Sales[Region])").0, Scalar::Integer(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_matches_documented_values() {
|
||||
let model = model();
|
||||
let pivot = PivotTable::new("Sales by region", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render pivot");
|
||||
|
||||
assert_eq!(table.columns.iter().map(|column| column.name.clone()).collect::<Vec<_>>(), vec!["Region".to_string(), "Total Amount".to_string()]);
|
||||
// BLANK 10, East 150, North 20, West 100; total 280.
|
||||
assert_eq!(table.rows.len(), 5);
|
||||
assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Decimal(10.0)]);
|
||||
assert_eq!(table.rows[1], vec![text("East"), Scalar::Decimal(150.0)]);
|
||||
assert_eq!(table.rows[2], vec![text("North"), Scalar::Decimal(20.0)]);
|
||||
assert_eq!(table.rows[3], vec![text("West"), Scalar::Decimal(100.0)]);
|
||||
assert_eq!(table.rows[4], vec![text("Grand Total"), Scalar::Decimal(280.0)]);
|
||||
|
||||
assert!(stats.aggregates > 0, "each pivot cell is a storage aggregate, got {stats:?}");
|
||||
assert_eq!(stats.pivot_group_rows, 7, "grouping must read the seven source rows from columns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_pivot_matches_documented_values() {
|
||||
let model = model();
|
||||
// Keeping East and West only: 150 + 100 = 250, and BLANK/North rows are gone.
|
||||
let pivot = PivotTable::new("Sales in East and West", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_filter(PivotFilter::new("Sales[Region]", [text("East"), text("West")]))
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render pivot");
|
||||
|
||||
assert_eq!(table.rows.len(), 3);
|
||||
assert_eq!(table.rows[0], vec![text("East"), Scalar::Decimal(150.0)]);
|
||||
assert_eq!(table.rows[1], vec![text("West"), Scalar::Decimal(100.0)]);
|
||||
assert_eq!(table.rows[2], vec![text("Grand Total"), Scalar::Decimal(250.0)]);
|
||||
// Five rows survive the filter (East x3, West x2).
|
||||
assert_eq!(stats.pivot_group_rows, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_cross_tab_matches_documented_values() {
|
||||
let model = model();
|
||||
// Rows Region, columns ProductKey; cells are the amount per combination.
|
||||
let pivot = PivotTable::new("Region by product", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_column_fields(vec!["Sales[ProductKey]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let (table, _) = pivot.render_with_stats(&model).expect("render pivot");
|
||||
|
||||
let header: Vec<String> = table.columns.iter().map(|column| column.name.clone()).collect();
|
||||
assert_eq!(header, vec!["Region".to_string(), "1".to_string(), "2".to_string(), "3".to_string(), "4".to_string(), "Grand Total".to_string()]);
|
||||
assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Blank, Scalar::Decimal(10.0), Scalar::Blank, Scalar::Blank, Scalar::Decimal(10.0)]);
|
||||
assert_eq!(
|
||||
table.rows[1],
|
||||
vec![text("East"), Scalar::Decimal(100.0), Scalar::Decimal(50.0), Scalar::Blank, Scalar::Blank, Scalar::Decimal(150.0)]
|
||||
);
|
||||
assert_eq!(table.rows[2], vec![text("North"), Scalar::Blank, Scalar::Blank, Scalar::Blank, Scalar::Decimal(20.0), Scalar::Decimal(20.0)]);
|
||||
assert_eq!(table.rows[3], vec![text("West"), Scalar::Decimal(30.0), Scalar::Blank, Scalar::Decimal(70.0), Scalar::Blank, Scalar::Decimal(100.0)]);
|
||||
assert_eq!(
|
||||
table.rows[4],
|
||||
vec![
|
||||
text("Grand Total"),
|
||||
Scalar::Decimal(130.0),
|
||||
Scalar::Decimal(60.0),
|
||||
Scalar::Decimal(70.0),
|
||||
Scalar::Decimal(20.0),
|
||||
Scalar::Decimal(280.0)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_evaluate_through_storage() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let filtered = gridcraft_dax::FilterContext::default();
|
||||
assert_eq!(evaluator.evaluate_measure("Total Amount", filtered.clone()).expect("measure"), Scalar::Decimal(280.0));
|
||||
assert_eq!(evaluator.evaluate_measure("Rows", filtered.clone()).expect("measure"), Scalar::Integer(7));
|
||||
assert_eq!(evaluator.evaluate_measure("Product Count", filtered.clone()).expect("measure"), Scalar::Integer(4));
|
||||
assert_eq!(evaluator.evaluate_measure("Extended Price", filtered.clone()).expect("measure"), Scalar::Decimal(150.5));
|
||||
assert_eq!(evaluator.evaluate_measure("Sales Rows Per Product", filtered).expect("measure"), Scalar::Decimal(7.0));
|
||||
let stats = evaluator.storage_stats();
|
||||
// Total Amount and Product Count are column aggregates; Rows is COUNTROWS; Extended Price and
|
||||
// Sales Rows Per Product resolve their RELATED/RELATEDTABLE calls through the index (their
|
||||
// derived iterator expressions stay row-based, so `iterators` is zero here).
|
||||
assert!(stats.aggregates >= 2 && stats.count_rows == 1 && stats.related > 0 && stats.related_table > 0, "{stats:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_foreign_key_and_an_orphan_key_group_as_blank_with_an_empty_cell() {
|
||||
// `Product` has an "Unknown" row whose key is BLANK. `Sales` has a row matching `Widget`, a
|
||||
// row whose key has no `Product` at all, and a row whose key is BLANK. A relationship never
|
||||
// joins a BLANK key, and a key with no related row is an orphan, so grouping puts both under
|
||||
// `(Blank)`; the `(Blank)` cell then selects no source rows and stays empty (`SUM` over an
|
||||
// empty set). That is the model's inner-join semantics, and it is the rule the related-pivot
|
||||
// suites pin.
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(1), text("Widget")], vec![Scalar::Blank, text("Unknown")]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::Integer(10)],
|
||||
vec![Scalar::Integer(99), Scalar::Integer(20)],
|
||||
vec![Scalar::Blank, Scalar::Integer(40)],
|
||||
],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![Measure {
|
||||
name: "Total Amount".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
|
||||
let pivot = PivotTable::new("Sales by product", "Total Amount")
|
||||
.with_row_fields(vec!["Product[Name]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render pivot");
|
||||
|
||||
// (Blank) is empty, Widget is 10, and the grand total still spans every fact row (70).
|
||||
assert_eq!(table.rows.len(), 3, "{:?}", table.rows);
|
||||
assert_eq!(table.rows[0], vec![Scalar::Blank, Scalar::Blank]);
|
||||
assert_eq!(table.rows[1], vec![text("Widget"), Scalar::Decimal(10.0)]);
|
||||
assert_eq!(table.rows[2], vec![text("Grand Total"), Scalar::Decimal(70.0)]);
|
||||
assert!(stats.aggregates > 0, "each pivot cell is a storage aggregate, got {stats:?}");
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Non-faithful and unmaterializable models: storage must step aside, never change a result.
|
||||
//!
|
||||
//! `ModelStorage` is lossless only when every table is rectangular and every stored value equals
|
||||
//! the model scalar. These tests cover the three ways that can fail — ragged rows, a promoted
|
||||
//! column representation, and a model [`ModelStorage::from_model`] rejects outright — and assert
|
||||
//! that evaluation keeps its original (row-scan) DAX results and reports the fallback.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::storage::StorageError;
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, parse_expression};
|
||||
|
||||
fn eval(model: &DataModel, formula: &str) -> Scalar {
|
||||
let evaluator = Evaluator::new(model).expect("evaluator");
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
}
|
||||
|
||||
fn single_table(name: &str, columns: &[(&str, &str)], rows: Vec<Vec<Scalar>>) -> DataModel {
|
||||
DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: name.into(),
|
||||
columns: columns.iter().map(|(name, kind)| ModelColumn { name: (*name).into(), data_type: Some((*kind).into()) }).collect(),
|
||||
rows,
|
||||
}],
|
||||
..DataModel::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ragged_rows_keep_the_row_scan_semantics() {
|
||||
// Row 0 only supplies A; the missing B cell is padded to BLANK, the same value the columnar
|
||||
// copy and the integrity check read, so both paths agree.
|
||||
let model =
|
||||
single_table("Sales", &[("A", "Int64"), ("B", "Int64")], vec![vec![Scalar::Integer(1)], vec![Scalar::Integer(2), Scalar::Integer(3)]]);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let storage = evaluator.storage().expect("the ragged model still materializes");
|
||||
assert!(!storage.is_faithful(), "a ragged row cannot round-trip");
|
||||
|
||||
let expr = parse_expression("SUM(Sales[B])").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
// BLANK contributes nothing to SUM, so only row 1 counts.
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(3.0));
|
||||
assert_eq!(eval(&model, "COUNTROWS(Sales)"), Scalar::Integer(2));
|
||||
// The padded cell is a real BLANK for the filter and for `VALUES`, instead of vanishing.
|
||||
assert_eq!(eval(&model, "CALCULATE(COUNTROWS(Sales), Sales[B] = 3)"), Scalar::Integer(1));
|
||||
assert_eq!(eval(&model, "COUNTROWS(VALUES(Sales[B]))"), Scalar::Integer(2));
|
||||
assert!(evaluator.storage_stats().row_scan_fallbacks > 0, "{:?}", evaluator.storage_stats());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promoted_columns_keep_the_row_scan_semantics() {
|
||||
// Booleans mixed with an integer are promoted to dictionary-encoded text by the storage
|
||||
// inference; DAX's SUM ignores logicals (only numbers are aggregated), so storage must not
|
||||
// answer and the row-scan path must agree.
|
||||
let model = single_table("Mixed", &[("Value", "Boolean")], vec![vec![Scalar::Boolean(true)], vec![Scalar::Integer(2)], vec![Scalar::Blank]]);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
assert!(!evaluator.storage().expect("storage").is_faithful());
|
||||
|
||||
let expr = parse_expression("SUM(Mixed[Value])").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(2.0));
|
||||
assert_eq!(eval(&model, "COUNT(Mixed[Value])"), Scalar::Integer(1), "COUNT ignores booleans");
|
||||
assert_eq!(eval(&model, "COUNTA(Mixed[Value])"), Scalar::Integer(2));
|
||||
assert!(evaluator.storage_stats().row_scan_fallbacks > 0, "{:?}", evaluator.storage_stats());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmaterializable_models_still_evaluate() {
|
||||
// A relationship naming a missing table makes `ModelStorage::from_model` fail. That is not an
|
||||
// evaluation error: the row-scan path is the documented fallback and the reason is reported.
|
||||
let mut model = single_table("Sales", &[("Amount", "Int64")], vec![vec![Scalar::Integer(4)], vec![Scalar::Integer(6)]]);
|
||||
model.relationships.push(Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Amount".into(),
|
||||
to_table: "Ghost".into(),
|
||||
to_column: "Amount".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
});
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator still builds");
|
||||
assert!(evaluator.storage().is_none());
|
||||
assert_eq!(evaluator.storage_error(), Some(&StorageError::UnknownTable { table: "Ghost".into() }));
|
||||
|
||||
let expr = parse_expression("SUM(Sales[Amount])").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("evaluate"), Scalar::Decimal(10.0));
|
||||
assert!(evaluator.storage_stats().row_scan_fallbacks > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn countblank_counts_empty_text_in_both_paths() {
|
||||
// DAX COUNTBLANK counts an empty string as blank. The storage fast path reads that from the
|
||||
// string dictionary, so pin it against the documented row-path rule.
|
||||
let model = single_table(
|
||||
"Notes",
|
||||
&[("Text", "String")],
|
||||
vec![vec![Scalar::String(String::new())], vec![Scalar::String("x".into())], vec![Scalar::Blank]],
|
||||
);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
assert!(evaluator.storage().expect("storage").is_faithful());
|
||||
assert_eq!(eval(&model, "COUNTBLANK(Notes[Text])"), Scalar::Integer(2));
|
||||
assert_eq!(eval(&model, "COUNTA(Notes[Text])"), Scalar::Integer(2));
|
||||
assert_eq!(eval(&model, "DISTINCTCOUNT(Notes[Text])"), Scalar::Integer(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_numeric_columns_promote_but_keep_their_sum() {
|
||||
// Integers and decimals mix into one decimal column, which cannot round-trip. The sum is the
|
||||
// same either way, so this pins the value while the fallback keeps the representation honest.
|
||||
let model = single_table(
|
||||
"Money",
|
||||
&[("Amount", "Double")],
|
||||
vec![vec![Scalar::Integer(1)], vec![Scalar::Decimal(0.5)], vec![Scalar::Blank], vec![Scalar::Integer(3)]],
|
||||
);
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
assert!(!evaluator.storage().expect("storage").is_faithful());
|
||||
assert_eq!(eval(&model, "SUM(Money[Amount])"), Scalar::Decimal(4.5));
|
||||
assert_eq!(eval(&model, "COUNT(Money[Amount])"), Scalar::Integer(3));
|
||||
assert_eq!(eval(&model, "COUNTBLANK(Money[Amount])"), Scalar::Integer(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_over_a_non_faithful_model_groups_rows() {
|
||||
// Row 1 has no Amount cell, so the model cannot be stored faithfully and the pivot must go
|
||||
// back to grouping model rows. The blank amount makes the West cell BLANK, not zero.
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::String("East".into()), Scalar::Integer(10)], vec![Scalar::String("West".into())]],
|
||||
}],
|
||||
measures: vec![gridcraft_dax::Measure {
|
||||
name: "Total".into(),
|
||||
formula: "SUM(Sales[Amount])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
}],
|
||||
..DataModel::default()
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
|
||||
let pivot = gridcraft_dax::pivot_table::PivotTable::new("By region", "Total")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(gridcraft_dax::pivot_table::PivotLayout::Tabular);
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render");
|
||||
|
||||
assert_eq!(table.rows.len(), 3);
|
||||
assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(10.0)]);
|
||||
assert_eq!(table.rows[1], vec![Scalar::String("West".into()), Scalar::Blank]);
|
||||
assert_eq!(table.rows[2], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(10.0)]);
|
||||
assert_eq!(stats.pivot_group_rows, 0, "grouping fell back to the model rows: {stats:?}");
|
||||
assert!(stats.row_scan_fallbacks > 0);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Scale test: 100k rows through the columnar substrate.
|
||||
//!
|
||||
//! What is measured:
|
||||
//!
|
||||
//! * wall-clock time of `Evaluator::new` (one materialization), of `SUMX`/`COUNTROWS`/
|
||||
//! `DISTINCTCOUNT` and of a 8-group pivot with a grand total, printed with `--nocapture` and
|
||||
//! asserted to stay under [`BUDGET`];
|
||||
//! * the storage counters of the same calls, which prove the numbers were computed from columns
|
||||
//! and bound the work: a pivot cell may only touch rows of its own group plus one pass over the
|
||||
//! source row ids, so `rows_from_storage` has to stay linear in the row count (an accidental
|
||||
//! per-cell full scan of a 100k-row model across 100 groups would blow the budget and the
|
||||
//! bound below).
|
||||
//!
|
||||
//! Peak memory is not sampled (it is not portable across the test hosts); the bound that matters
|
||||
//! is structural: the model keeps one scalar per cell, storage adds one typed value plus one null
|
||||
//! bit per cell, and no path clones model rows — `rows_from_storage` counts rows served from
|
||||
//! columns, and the only `Vec<Vec<Scalar>>` materialized here is the pivot's own output table
|
||||
//! (9 rows).
|
||||
//!
|
||||
//! This is an integration-test binary: it is never compiled for wasm, so reading the clock here
|
||||
//! cannot hit the trap the workspace `disallowed_methods` lint guards against.
|
||||
#![allow(clippy::disallowed_methods)]
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable};
|
||||
use gridcraft_dax::pivot_table::{PivotLayout, PivotTable};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, FilterContext, StorageStats, parse_expression};
|
||||
|
||||
const ROWS: usize = 100_000;
|
||||
const REGIONS: [&str; 8] = ["East", "West", "North", "South", "Centre", "Coastal", "Inland", "Metro"];
|
||||
/// Generous upper bound: a debug build handles this fixture in well under a second on the
|
||||
/// development machine, so 60 s only catches a pathological (quadratic or repeating-scan) change.
|
||||
const BUDGET: Duration = Duration::from_secs(60);
|
||||
|
||||
fn amount(row: usize) -> i64 {
|
||||
(row % 1_000) as i64
|
||||
}
|
||||
|
||||
fn region(row: usize) -> &'static str {
|
||||
REGIONS[row % REGIONS.len()]
|
||||
}
|
||||
|
||||
fn product_key(row: usize) -> i64 {
|
||||
(row % 50) as i64 + 1
|
||||
}
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut rows = Vec::with_capacity(ROWS);
|
||||
for row in 0..ROWS {
|
||||
rows.push(vec![
|
||||
Scalar::Integer(product_key(row)),
|
||||
Scalar::String(region(row).into()),
|
||||
Scalar::Integer(amount(row)),
|
||||
Scalar::Integer((row % 7) as i64 + 1),
|
||||
]);
|
||||
}
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows,
|
||||
}],
|
||||
relationships: Vec::new(),
|
||||
measures: vec![
|
||||
Measure { name: "Total Amount".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure { name: "Rows".into(), formula: "COUNTROWS(Sales)".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure {
|
||||
name: "Products".into(),
|
||||
formula: "DISTINCTCOUNT(Sales[ProductKey])".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn evaluate(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> Scalar {
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hundred_thousand_rows_evaluate_within_the_budget() {
|
||||
let model = model();
|
||||
// Independent expectations from the generator, not from the DAX engine.
|
||||
let mut per_region = vec![0i64; REGIONS.len()];
|
||||
let mut total = 0i64;
|
||||
for row in 0..ROWS {
|
||||
per_region[row % REGIONS.len()] += amount(row);
|
||||
total += amount(row);
|
||||
}
|
||||
|
||||
let built = Instant::now();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let build_time = built.elapsed();
|
||||
let storage = evaluator.storage().expect("the generated model materializes");
|
||||
assert!(storage.is_faithful(), "the generated columns are homogeneous and rectangular");
|
||||
|
||||
let started = Instant::now();
|
||||
// sum of (row % 1000) over 100k rows = 100 blocks of 0..999 = 100 * 499_500.
|
||||
assert_eq!(evaluate(&evaluator, &model, "SUMX(Sales, Sales[Amount])"), Scalar::Decimal(total as f64));
|
||||
let sum_time = started.elapsed();
|
||||
|
||||
let started = Instant::now();
|
||||
assert_eq!(evaluate(&evaluator, &model, "COUNTROWS(Sales)"), Scalar::Integer(ROWS as i64));
|
||||
let count_time = started.elapsed();
|
||||
|
||||
let started = Instant::now();
|
||||
assert_eq!(evaluate(&evaluator, &model, "DISTINCTCOUNT(Sales[ProductKey])"), Scalar::Integer(50));
|
||||
let distinct_time = started.elapsed();
|
||||
|
||||
let pivot = PivotTable::new("Sales by region", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let started = Instant::now();
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render");
|
||||
let pivot_time = started.elapsed();
|
||||
|
||||
// One row per region in ScalarKey order plus the grand total.
|
||||
let mut sorted: Vec<(&str, i64)> = REGIONS.iter().copied().zip(per_region.iter().copied()).collect();
|
||||
sorted.sort_by(|left, right| left.0.cmp(right.0));
|
||||
let mut expected: Vec<Vec<Scalar>> =
|
||||
sorted.iter().map(|(label, sum)| vec![Scalar::String((*label).into()), Scalar::Decimal(*sum as f64)]).collect();
|
||||
expected.push(vec![Scalar::String("Grand Total".into()), Scalar::Decimal(total as f64)]);
|
||||
assert_eq!(table.rows, expected);
|
||||
assert_eq!(table.rows.len(), REGIONS.len() + 1);
|
||||
|
||||
let total_time = build_time + sum_time + count_time + distinct_time + pivot_time;
|
||||
eprintln!(
|
||||
"100k rows: build {build_time:?}, SUMX {sum_time:?}, COUNTROWS {count_time:?}, DISTINCTCOUNT {distinct_time:?}, pivot {pivot_time:?}, total {total_time:?}"
|
||||
);
|
||||
// The pivot renders through its own evaluator, so read the two counter snapshots separately.
|
||||
let direct = evaluator.storage_stats();
|
||||
eprintln!("counters for SUMX/COUNTROWS/DISTINCTCOUNT: {direct:?}");
|
||||
eprintln!("counters for the pivot render: {stats:?}");
|
||||
|
||||
// Every one of these calls was answered from columns, not from a row scan.
|
||||
assert!(direct.iterators > 0, "SUMX went through storage: {direct:?}");
|
||||
assert!(direct.count_rows > 0, "COUNTROWS went through storage: {direct:?}");
|
||||
assert!(direct.aggregates > 0, "DISTINCTCOUNT went through storage: {direct:?}");
|
||||
assert!(stats.aggregates > 0, "every pivot cell went through storage: {stats:?}");
|
||||
assert_eq!(stats.pivot_group_rows, ROWS as u64, "grouping read every source row once");
|
||||
assert_eq!(evaluator.storage_stats().row_scan_fallbacks, 0);
|
||||
|
||||
// Linear work per cell: 8 groups + the grand total + the grouping pass stay within a few
|
||||
// passes of the 100k rows (an accidental per-cell full scan of the model would not).
|
||||
assert!(stats.rows_from_storage < 20 * ROWS as u64, "rows served from columns must stay linear: {stats:?}");
|
||||
assert!(total_time < BUDGET, "100k rows took {total_time:?}, over the {BUDGET:?} budget");
|
||||
}
|
||||
|
||||
/// The filters path at scale: a single-group pivot restricted to one region.
|
||||
#[test]
|
||||
fn filtered_pivot_at_scale_counts_one_region() {
|
||||
let model = model();
|
||||
let mut expected = 0i64;
|
||||
for row in (0..ROWS).filter(|row| row % REGIONS.len() == 0) {
|
||||
expected += amount(row);
|
||||
}
|
||||
let pivot = PivotTable::new("East only", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_filter(gridcraft_dax::pivot_table::PivotFilter::new("Sales[Region]", [Scalar::String("East".into())]))
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let started = Instant::now();
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render");
|
||||
let elapsed = started.elapsed();
|
||||
eprintln!("100k rows, filtered pivot: {elapsed:?}, counters {stats:?}");
|
||||
|
||||
assert_eq!(table.rows.len(), 2, "the East leaf plus the grand total");
|
||||
assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(expected as f64)]);
|
||||
assert_eq!(table.rows[1], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(expected as f64)]);
|
||||
assert_eq!(stats.pivot_group_rows, ROWS as u64 / REGIONS.len() as u64);
|
||||
assert!(elapsed < BUDGET);
|
||||
}
|
||||
|
||||
/// Every measure evaluates at scale through storage, without a per-measure rebuild.
|
||||
#[test]
|
||||
fn measures_at_scale_share_one_substrate() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let mut total = 0i64;
|
||||
for row in 0..ROWS {
|
||||
total += amount(row);
|
||||
}
|
||||
assert_eq!(evaluator.evaluate_measure("Total Amount", FilterContext::default()).expect("measure"), Scalar::Decimal(total as f64));
|
||||
assert_eq!(evaluator.evaluate_measure("Rows", FilterContext::default()).expect("measure"), Scalar::Integer(ROWS as i64));
|
||||
assert_eq!(evaluator.evaluate_measure("Products", FilterContext::default()).expect("measure"), Scalar::Integer(50));
|
||||
let stats: StorageStats = evaluator.storage_stats();
|
||||
assert!(stats.aggregates >= 2 && stats.count_rows == 1, "{stats:?}");
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Wiring test: evaluation really reads the columnar `ModelStorage`, not just the model rows.
|
||||
//!
|
||||
//! `Evaluator::storage_stats` counts calls *served by* storage. Each test takes a snapshot, runs
|
||||
//! one formula, and asserts the counter that formula must move went up; `row_scan_fallbacks`
|
||||
//! covers the opposite direction. A formula that quietly fell back to the row scan leaves its
|
||||
//! counter at zero, so these assertions fail if the wiring is ever removed.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::pivot_table::{PivotLayout, PivotTable};
|
||||
use gridcraft_dax::value::Scalar;
|
||||
use gridcraft_dax::{Binder, Evaluator, FilterContext, StorageStats, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Product".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "UnitPrice".into(), data_type: Some("Currency".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::String("Hardware".into()), Scalar::Currency(200_000)],
|
||||
vec![Scalar::Integer(2), Scalar::String("Tools".into()), Scalar::Currency(50_000)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "ProductKey".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(1), Scalar::String("East".into()), Scalar::Integer(10), Scalar::Integer(2)],
|
||||
vec![Scalar::Integer(1), Scalar::String("West".into()), Scalar::Integer(20), Scalar::Integer(3)],
|
||||
vec![Scalar::Integer(2), Scalar::String("East".into()), Scalar::Integer(5), Scalar::Integer(1)],
|
||||
],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ProductKey".into(),
|
||||
to_table: "Product".into(),
|
||||
to_column: "ProductKey".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
Measure { name: "Total Amount".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure { name: "Rows".into(), formula: "COUNTROWS(Sales)".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure {
|
||||
name: "Extended".into(),
|
||||
formula: "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn evaluate(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> (Scalar, StorageStats) {
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
let value = evaluator.evaluate(&bound).expect("evaluate");
|
||||
(value, evaluator.storage_stats())
|
||||
}
|
||||
|
||||
fn evaluate_table(evaluator: &Evaluator<'_>, model: &DataModel, formula: &str) -> (gridcraft_dax::TableValue, StorageStats) {
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(model).bind_expression(&expr).expect("bind");
|
||||
let table = evaluator.evaluate_table(&bound).expect("table");
|
||||
(table, evaluator.storage_stats())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sumx_runs_over_a_storage_column() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
assert!(evaluator.storage().expect("storage").is_faithful());
|
||||
|
||||
let (value, stats) = evaluate(&evaluator, &model, "SUMX(Sales, Sales[Amount])");
|
||||
assert_eq!(value, Scalar::Decimal(35.0));
|
||||
assert_eq!(stats.iterators, 1, "SUMX over a plain column is one storage iterator: {stats:?}");
|
||||
assert_eq!(stats.aggregates, 1);
|
||||
assert_eq!(stats.rows_from_storage, 3);
|
||||
assert_eq!(stats.row_scan_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn countrows_uses_the_filtered_row_id_set() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let (value, stats) = evaluate(&evaluator, &model, "COUNTROWS(Sales)");
|
||||
assert_eq!(value, Scalar::Integer(3));
|
||||
assert_eq!(stats.count_rows, 1, "{stats:?}");
|
||||
assert_eq!(stats.rows_from_storage, 3);
|
||||
|
||||
// A filter becomes a storage column scan, and the count follows from the row ids.
|
||||
let mut filtered = FilterContext::default();
|
||||
filtered.set(1, 1, [gridcraft_dax::ScalarKey::String("East".into())]);
|
||||
let expr = parse_expression("COUNTROWS(Sales)").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filtered).expect("evaluate"), Scalar::Integer(2));
|
||||
let stats = evaluator.storage_stats();
|
||||
assert_eq!(stats.count_rows, 2);
|
||||
assert_eq!(stats.filter_scans, 1, "{stats:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn related_resolves_through_the_relationship_index() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
// 20*2 + 20*3 + 5*1 = 40 + 60 + 5 = 105; the derived expression keeps the iterator row-based,
|
||||
// but every RELATED call is an index probe.
|
||||
let (value, stats) = evaluate(&evaluator, &model, "SUMX(Sales, Sales[Quantity] * RELATED(Product[UnitPrice]))");
|
||||
assert_eq!(value, Scalar::Decimal(105.0));
|
||||
assert_eq!(stats.related, 3, "one index lookup per row: {stats:?}");
|
||||
assert_eq!(stats.relationship_lookups, 3);
|
||||
assert_eq!(stats.iterators, 0, "a derived expression cannot use the plain-column iterator");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relatedtable_resolves_through_the_relationship_index() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
// Product 1 has two sales rows, product 2 has one: 2 + 1 = 3.
|
||||
let (value, stats) = evaluate(&evaluator, &model, "SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))");
|
||||
assert_eq!(value, Scalar::Decimal(3.0));
|
||||
assert_eq!(stats.related_table, 2, "one join per product row: {stats:?}");
|
||||
|
||||
// Filtered related rows: West only, so product 1 has one row and product 2 none.
|
||||
let mut filtered = FilterContext::default();
|
||||
filtered.set(1, 1, [gridcraft_dax::ScalarKey::String("West".into())]);
|
||||
let expr = parse_expression("SUMX(Product, COUNTROWS(RELATEDTABLE(Sales)))").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filtered).expect("evaluate"), Scalar::Decimal(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_and_distinct_dedupe_through_storage() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let (table, stats) = evaluate_table(&evaluator, &model, "VALUES(Sales[Region])");
|
||||
assert_eq!(table.rows, vec![vec![Scalar::String("East".into())], vec![Scalar::String("West".into())]]);
|
||||
assert_eq!(stats.distinct_values, 1, "{stats:?}");
|
||||
assert_eq!(stats.rows_from_storage, 3);
|
||||
|
||||
let (distinct, stats) = evaluate_table(&evaluator, &model, "DISTINCT(Sales[Region])");
|
||||
assert_eq!(distinct.rows, table.rows);
|
||||
assert_eq!(stats.distinct_values, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_propagation_uses_the_relationship_index() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
// Hardware products are only product 1, so sales rows 1 and 2: 10 + 20 = 30.
|
||||
let (value, stats) = evaluate(&evaluator, &model, "CALCULATE(SUM(Sales[Amount]), Product[Category] = \"Hardware\")");
|
||||
assert_eq!(value, Scalar::Decimal(30.0));
|
||||
assert!(stats.relationship_lookups > 0, "propagation must probe the index: {stats:?}");
|
||||
assert_eq!(stats.aggregates, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_cells_and_grouping_are_served_by_storage() {
|
||||
let model = model();
|
||||
let pivot = PivotTable::new("Sales by region", "Total Amount")
|
||||
.with_row_fields(vec!["Sales[Region]".into()])
|
||||
.with_grand_totals(true)
|
||||
.with_layout(PivotLayout::Tabular);
|
||||
let (table, stats) = pivot.render_with_stats(&model).expect("render");
|
||||
|
||||
assert_eq!(table.rows.len(), 3);
|
||||
assert_eq!(table.rows[0], vec![Scalar::String("East".into()), Scalar::Decimal(15.0)]);
|
||||
assert_eq!(table.rows[1], vec![Scalar::String("West".into()), Scalar::Decimal(20.0)]);
|
||||
assert_eq!(table.rows[2], vec![Scalar::String("Grand Total".into()), Scalar::Decimal(35.0)]);
|
||||
|
||||
assert_eq!(stats.pivot_group_rows, 3, "grouping reads the source rows from columns: {stats:?}");
|
||||
assert!(stats.aggregates > 0, "every cell is a storage aggregate: {stats:?}");
|
||||
assert_eq!(stats.row_scan_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn measures_share_one_substrate_across_evaluations() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
assert_eq!(evaluator.evaluate_measure("Total Amount", FilterContext::default()).expect("measure"), Scalar::Decimal(35.0));
|
||||
assert_eq!(evaluator.evaluate_measure("Rows", FilterContext::default()).expect("measure"), Scalar::Integer(3));
|
||||
assert_eq!(evaluator.evaluate_measure("Extended", FilterContext::default()).expect("measure"), Scalar::Decimal(105.0));
|
||||
let stats = evaluator.storage_stats();
|
||||
assert_eq!(stats.aggregates, 1);
|
||||
assert_eq!(stats.count_rows, 1);
|
||||
assert_eq!(stats.related, 3);
|
||||
// The substrate is built once in `Evaluator::new` and shared: its table ids are the model
|
||||
// positions, so repeated evaluation never rebuilds it.
|
||||
assert_eq!(evaluator.storage().expect("storage").total_rows(), 5);
|
||||
}
|
||||
@@ -0,0 +1,640 @@
|
||||
//! Core evaluator tests over an in-memory model.
|
||||
|
||||
use gridcraft_dax::model::{DataModel, Measure, ModelColumn, ModelTable, Relationship};
|
||||
use gridcraft_dax::value::{Scalar, TableValue};
|
||||
use gridcraft_dax::{Binder, Evaluator, FilterContext, parse_expression};
|
||||
|
||||
fn model() -> DataModel {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Quantity".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Flag".into(), data_type: Some("Boolean".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(10), Scalar::Integer(2), Scalar::Boolean(true)],
|
||||
vec![Scalar::String("West".into()), Scalar::Integer(20), Scalar::Integer(3), Scalar::Boolean(false)],
|
||||
vec![Scalar::String("East".into()), Scalar::Integer(30), Scalar::Integer(4), Scalar::Boolean(true)],
|
||||
],
|
||||
},
|
||||
ModelTable { name: "Date".into(), columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }], rows: vec![] },
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Region".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![
|
||||
Measure { name: "Total Sales".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
Measure {
|
||||
name: "East Sales".into(),
|
||||
formula: "CALCULATE([Total Sales], Sales[Region] = \"East\")".into(),
|
||||
table: Some("Sales".into()),
|
||||
format: None,
|
||||
expr: None,
|
||||
},
|
||||
Measure { name: "Double Sales".into(), formula: "[Total Sales] * 2".into(), table: Some("Sales".into()), format: None, expr: None },
|
||||
],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
model
|
||||
}
|
||||
|
||||
fn eval(src: &str) -> Scalar {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(src).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
}
|
||||
|
||||
fn eval_table(src: &str) -> TableValue {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(src).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate_table(&bound).expect("table")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregates_and_measures() {
|
||||
assert_eq!(eval("SUM(Sales[Amount])"), Scalar::Decimal(60.0));
|
||||
assert_eq!(eval("AVERAGE(Sales[Amount])"), Scalar::Decimal(20.0));
|
||||
assert_eq!(eval("COUNTROWS(Sales)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("SUMX(Sales, Sales[Amount] * 2)"), Scalar::Decimal(120.0));
|
||||
assert_eq!(eval("[Total Sales]"), Scalar::Decimal(60.0));
|
||||
assert_eq!(eval("[East Sales]"), Scalar::Decimal(40.0));
|
||||
assert_eq!(eval("[Double Sales]"), Scalar::Decimal(120.0));
|
||||
assert_eq!(eval("CALCULATE([Total Sales], Sales[Region] = \"West\")"), Scalar::Decimal(20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_and_scalar_functions() {
|
||||
assert_eq!(eval("IF([Total Sales] > 50, \"big\", \"small\")"), Scalar::String("big".into()));
|
||||
assert_eq!(eval("SWITCH(2, 1, \"one\", 2, \"two\", \"other\")"), Scalar::String("two".into()));
|
||||
assert_eq!(eval("COALESCE(BLANK(), 3)"), Scalar::Integer(3));
|
||||
assert_eq!(eval("LEFT(\"abcd\", 2)"), Scalar::String("ab".into()));
|
||||
assert_eq!(eval("ROUND(1.234, 2)"), Scalar::Decimal(1.23));
|
||||
assert_eq!(eval("DATE(2024, 1, 2)"), Scalar::DateTime(45293.0));
|
||||
assert_eq!(eval("YEAR(DATE(2024, 1, 2))"), Scalar::Integer(2024));
|
||||
assert_eq!(eval("ISBLANK(BLANK())"), Scalar::Boolean(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_filters_and_values() {
|
||||
let filtered = eval_table("FILTER(Sales, Sales[Amount] > 10)");
|
||||
assert_eq!(filtered.rows.len(), 2);
|
||||
let values = eval_table("VALUES(Sales[Region])");
|
||||
assert_eq!(values.rows.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_keyword_arguments_bind() {
|
||||
let model = model();
|
||||
let binder = Binder::new(&model);
|
||||
for src in ["DATEADD('Date'[Date], -1, MONTH)", "CONVERT(1, INTEGER)"] {
|
||||
let expr = parse_expression(src).expect("parse");
|
||||
binder.bind_expression(&expr).expect("bind keyword argument");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_context_can_be_supplied() {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("[Total Sales]").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(0, 0, [gridcraft_dax::ScalarKey::String("East".into())]);
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filters).expect("eval"), Scalar::Decimal(40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_groups_and_evaluates_measures() {
|
||||
let model = model();
|
||||
let fields = gridcraft_dax::pivot_fields(&model, &["Sales[Region]".into()]).expect("fields");
|
||||
let table = gridcraft_dax::pivot(&model, "Total Sales", &fields).expect("pivot");
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(table.rows[0][0], Scalar::String("East".into()));
|
||||
assert_eq!(table.rows[0][1], Scalar::Decimal(40.0));
|
||||
assert_eq!(table.rows[1][0], Scalar::String("West".into()));
|
||||
assert_eq!(table.rows[1][1], Scalar::Decimal(20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterators_resolve_rows_of_filtered_tables() {
|
||||
// The frame must carry the row values, not the position in the filtered table.
|
||||
assert_eq!(eval("SUMX(FILTER(Sales, Sales[Region] = \"West\"), Sales[Amount])"), Scalar::Decimal(20.0));
|
||||
// Context transition inside an iterator over a filtered table.
|
||||
assert_eq!(eval("SUMX(FILTER(Sales, Sales[Amount] > 10), [Total Sales])"), Scalar::Decimal(50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_accepts_filter_table_arguments() {
|
||||
assert_eq!(eval("CALCULATE([Total Sales], FILTER(Sales, Sales[Amount] > 10))"), Scalar::Decimal(50.0));
|
||||
assert_eq!(eval("CALCULATE([Total Sales], Sales[Amount] >= 20)"), Scalar::Decimal(50.0));
|
||||
assert_eq!(eval("CALCULATE([Total Sales], 20 <= Sales[Amount])"), Scalar::Decimal(50.0));
|
||||
assert_eq!(eval("CALCULATE([Total Sales], Sales[Amount] < 20)"), Scalar::Decimal(10.0));
|
||||
assert_eq!(eval("CALCULATE([Total Sales], KEEPFILTERS(Sales[Region] = \"East\"))"), Scalar::Decimal(40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cyclic_measures_are_rejected_before_evaluation() {
|
||||
let mut model = model();
|
||||
model.measures.push(Measure { name: "Cycle A".into(), formula: "[Cycle B] + 1".into(), table: Some("Sales".into()), format: None, expr: None });
|
||||
model.measures.push(Measure { name: "Cycle B".into(), formula: "[Cycle A] + 1".into(), table: Some("Sales".into()), format: None, expr: None });
|
||||
model.parse_formulas().expect("model parses");
|
||||
let error = match Evaluator::new(&model) {
|
||||
Ok(_) => panic!("cyclic measures must be rejected"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert!(error.message.contains("Cycle"), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bidirectional_filters_do_not_recurse() {
|
||||
let mut model = model();
|
||||
model.tables.push(ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![ModelColumn { name: "Region".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("East".into())], vec![Scalar::String("West".into())]],
|
||||
});
|
||||
model.relationships.push(Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Region".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Region".into(),
|
||||
bidirectional: true,
|
||||
inactive: false,
|
||||
});
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("CALCULATE(SUM(Sales[Amount]), Products[Region] = \"East\")").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("bidirectional filter"), Scalar::Decimal(40.0));
|
||||
|
||||
model.relationships.last_mut().expect("relationship").inactive = true;
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("inactive relationship is ignored"), Scalar::Decimal(60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relatedtable_returns_rows_from_the_many_side() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(10), Scalar::String("A".into())],
|
||||
vec![Scalar::Integer(20), Scalar::String("A".into())],
|
||||
vec![Scalar::Integer(30), Scalar::String("B".into())],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Product".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Product".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("SUMX(Products, COUNTROWS(RELATEDTABLE(Sales)))").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("relatedtable"), Scalar::Decimal(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_performs_context_transition() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(10), Scalar::String("A".into())],
|
||||
vec![Scalar::Integer(20), Scalar::String("A".into())],
|
||||
vec![Scalar::Integer(30), Scalar::String("B".into())],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Product".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Product".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
// An explicit `CALCULATE` in a row context transitions that row, the way a measure
|
||||
// reference does: A reports its own 30 and B its 30, not the 60 grand total.
|
||||
for (formula, expected) in [("SUMX(Products, CALCULATE(SUM(Sales[Amount])))", 60.0), ("SUMX(Sales, CALCULATE(SUM(Sales[Amount])))", 60.0)] {
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("calculate"), Scalar::Decimal(expected), "{formula}");
|
||||
}
|
||||
let expr = parse_expression("ADDCOLUMNS(Products, \"Total\", CALCULATE(SUM(Sales[Amount])))").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
let table = evaluator.evaluate_table(&bound).expect("addcolumns");
|
||||
let totals: Vec<Scalar> = table.rows.iter().map(|row| row[1].clone()).collect();
|
||||
assert_eq!(totals, vec![Scalar::Decimal(30.0), Scalar::Decimal(30.0)], "each row reports its own product, not the total");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_propagate_across_several_relationships() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(10), Scalar::String("A".into())], vec![Scalar::Integer(20), Scalar::String("B".into())]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("A".into()), Scalar::String("East".into())],
|
||||
vec![Scalar::String("B".into()), Scalar::String("West".into())],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Categories".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Category".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::String("East".into()), Scalar::String("Group East".into())],
|
||||
vec![Scalar::String("West".into()), Scalar::String("Group West".into())],
|
||||
],
|
||||
},
|
||||
],
|
||||
relationships: vec![
|
||||
Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Product".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Product".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
},
|
||||
Relationship {
|
||||
from_table: "Products".into(),
|
||||
from_column: "Category".into(),
|
||||
to_table: "Categories".into(),
|
||||
to_column: "Category".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
},
|
||||
],
|
||||
measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("CALCULATE([Total], Categories[Name] = \"Group East\")").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("multi-hop filter"), Scalar::Decimal(10.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bidirectional_filters_keep_orphan_rows() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
ModelColumn { name: "Region".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(10), Scalar::String("A".into()), Scalar::String("East".into())],
|
||||
// No matching Products row: a bidirectional relationship must keep it.
|
||||
vec![Scalar::Integer(20), Scalar::String("Orphan".into()), Scalar::String("East".into())],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Product".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Product".into(),
|
||||
bidirectional: true,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("CALCULATE([Total], Sales[Region] = \"East\")").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert_eq!(evaluator.evaluate(&bound).expect("bidirectional filter"), Scalar::Decimal(30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn userelationship_selects_the_matching_relationship_by_column() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "OrderDate".into(), data_type: Some("DateTime".into()) },
|
||||
ModelColumn { name: "ShipDate".into(), data_type: Some("DateTime".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(10), Scalar::DateTime(45292.0), Scalar::DateTime(45293.0)],
|
||||
vec![Scalar::Integer(20), Scalar::DateTime(45293.0), Scalar::DateTime(45292.0)],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Date".into(),
|
||||
columns: vec![ModelColumn { name: "Date".into(), data_type: Some("DateTime".into()) }],
|
||||
rows: vec![vec![Scalar::DateTime(45292.0)], vec![Scalar::DateTime(45293.0)]],
|
||||
},
|
||||
],
|
||||
relationships: vec![
|
||||
Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "OrderDate".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
},
|
||||
Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "ShipDate".into(),
|
||||
to_table: "Date".into(),
|
||||
to_column: "Date".into(),
|
||||
bidirectional: false,
|
||||
inactive: true,
|
||||
},
|
||||
],
|
||||
measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let evaluate = |src: &str| {
|
||||
let expr = parse_expression(src).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
};
|
||||
// The active OrderDate relationship sees the Jan 2 order row.
|
||||
assert_eq!(evaluate("CALCULATE([Total], Date[Date] = DATE(2024,1,2))"), Scalar::Decimal(20.0));
|
||||
// USERELATIONSHIP picks ShipDate even though OrderDate is the first relationship in the model.
|
||||
assert_eq!(evaluate("CALCULATE([Total], USERELATIONSHIP(Sales[ShipDate], Date[Date]), Date[Date] = DATE(2024,1,2))"), Scalar::Decimal(10.0));
|
||||
assert_eq!(evaluate("CALCULATE([Total], USERELATIONSHIP(Sales[ShipDate], Date[Date]), Date[Date] = DATE(2024,1,1))"), Scalar::Decimal(20.0));
|
||||
// CROSSFILTER cannot activate ShipDate: only USERELATIONSHIP may do that.
|
||||
let crossfilter = parse_expression("CALCULATE([Total], CROSSFILTER(Sales[ShipDate], Date[Date], BOTH))").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&crossfilter).expect("bind");
|
||||
let error = evaluator.evaluate(&bound).expect_err("CROSSFILTER must not activate an inactive relationship");
|
||||
assert!(error.message.contains("USERELATIONSHIP"), "{error}");
|
||||
// CROSSFILTER accepts both documented spellings and leaves the active relationship in place.
|
||||
assert_eq!(evaluate("CALCULATE([Total], CROSSFILTER(Sales[OrderDate], Date[Date], OneWay))"), Scalar::Decimal(30.0));
|
||||
assert_eq!(evaluate("CALCULATE([Total], CROSSFILTER(Sales[OrderDate], Date[Date], BOTH))"), Scalar::Decimal(30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calculate_filters_replace_the_target_column_and_map_by_name() {
|
||||
// The outer filter on Region must not suppress the candidates for the CALCULATE filter.
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression("CALCULATE([Total Sales], Sales[Region] = \"East\")").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(0, 0, [gridcraft_dax::ScalarKey::String("West".into())]);
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filters).expect("evaluate"), Scalar::Decimal(40.0));
|
||||
|
||||
// VALUES(Sales[Amount]) exposes one column at position 0; it must filter Amount, not Region.
|
||||
assert_eq!(eval("CALCULATE([Total Sales], VALUES(Sales[Amount]))"), Scalar::Decimal(60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relationship_modifiers_apply_inside_calculate() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Double".into()) },
|
||||
ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(10), Scalar::Integer(1)], vec![Scalar::Integer(20), Scalar::Integer(2)]],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Dim".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Key".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Name".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![vec![Scalar::Integer(1), Scalar::String("A".into())], vec![Scalar::Integer(2), Scalar::String("B".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Key".into(),
|
||||
to_table: "Dim".into(),
|
||||
to_column: "Key".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: Vec::new(),
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let evaluate = |src: &str| {
|
||||
let expr = parse_expression(src).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
};
|
||||
// A Sales filter reaches Dim only when CROSSFILTER makes the relationship bidirectional.
|
||||
assert_eq!(evaluate("CALCULATE(COUNTROWS(Dim), Sales[Key] = 1)"), Scalar::Integer(2));
|
||||
assert_eq!(evaluate("CALCULATE(COUNTROWS(Dim), Sales[Key] = 1, CROSSFILTER(Sales[Key], Dim[Key], BOTH))"), Scalar::Integer(1));
|
||||
// The modifier itself is not a scalar.
|
||||
let expr = parse_expression("USERELATIONSHIP(Sales[Key], Dim[Key])").expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert!(evaluator.evaluate(&bound).is_err(), "a modifier cannot be a standalone scalar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbounded_scalar_functions_return_errors() {
|
||||
for formula in ["FACT(171)", "REPT(\"x\", 100000)"] {
|
||||
let model = model();
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let expr = parse_expression(formula).expect("parse");
|
||||
let bound = Binder::new(&model).bind_expression(&expr).expect("bind");
|
||||
assert!(evaluator.evaluate(&bound).is_err(), "{formula} must fail");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_json_round_trip_preserves_variants() {
|
||||
for value in [Scalar::Currency(123_456), Scalar::DateTime(45293.5), Scalar::Integer(7), Scalar::Decimal(1.5), Scalar::Blank] {
|
||||
let json = serde_json::to_value(&value).expect("serialize");
|
||||
let back: Scalar = serde_json::from_value(json.clone()).expect("deserialize");
|
||||
assert_eq!(back, value, "round trip through {json}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_keys_sort_numerically() {
|
||||
let mut keys: Vec<gridcraft_dax::ScalarKey> =
|
||||
[-2.5, -1.0, 0.0, 1.0, 2.5].into_iter().map(|value| gridcraft_dax::ScalarKey::from(&Scalar::Decimal(value))).collect();
|
||||
keys.sort();
|
||||
let back: Vec<f64> = keys.iter().map(|key| key.to_scalar().to_number().unwrap_or_default()).collect();
|
||||
assert_eq!(back, vec![-2.5, -1.0, 0.0, 1.0, 2.5]);
|
||||
assert_eq!(gridcraft_dax::ScalarKey::from(&Scalar::Decimal(-0.0)), gridcraft_dax::ScalarKey::from(&Scalar::Decimal(0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pivot_cross_puts_column_groups_in_columns() {
|
||||
let model = model();
|
||||
let rows = gridcraft_dax::pivot_fields(&model, &["Sales[Region]".into()]).expect("rows");
|
||||
let columns = gridcraft_dax::pivot_fields(&model, &["Sales[Flag]".into()]).expect("columns");
|
||||
let table = gridcraft_dax::pivot_cross(&model, "Total Sales", &rows, &columns).expect("pivot");
|
||||
assert_eq!(table.columns.len(), 3);
|
||||
assert_eq!(table.rows.len(), 2);
|
||||
assert_eq!(table.rows[0][0], Scalar::String("East".into()));
|
||||
// FALSE sorts before TRUE; East has TRUE rows only (10 + 30).
|
||||
assert_eq!(table.rows[0][1], Scalar::Blank);
|
||||
assert_eq!(table.rows[0][2], Scalar::Decimal(40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_not_compared_with_numbers() {
|
||||
// DAX refuses to compare text with a number, so `=` answers FALSE instead of coercing "3".
|
||||
assert_eq!(eval("\"3\" = 3"), Scalar::Boolean(false));
|
||||
// The negation of an incomparable pair is TRUE: two contradictory comparisons cannot both be
|
||||
// FALSE, and the evaluator maps "no ordering" to inequality.
|
||||
assert_eq!(eval("\"3\" <> 3"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("\"3\" < 3"), Scalar::Boolean(false));
|
||||
assert_eq!(eval("\"3\" = \"3\""), Scalar::Boolean(true));
|
||||
// `IN` is DAX equality rather than representation equality: numbers compare by value across
|
||||
// variants and text ignores case, while BLANK still matches only BLANK.
|
||||
assert_eq!(eval("2 IN {2.0}"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("\"a\" IN {\"A\"}"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("BLANK() IN {BLANK()}"), Scalar::Boolean(true));
|
||||
assert_eq!(eval("1 IN {2.0, 3.0}"), Scalar::Boolean(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_count_folds_text_case() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![ModelTable {
|
||||
name: "Labels".into(),
|
||||
columns: vec![ModelColumn { name: "Name".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())], vec![Scalar::String("a".into())], vec![Scalar::String("B".into())], vec![Scalar::Blank]],
|
||||
}],
|
||||
..DataModel::default()
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let evaluate = |src: &str| {
|
||||
let bound = Binder::new(&model).bind_expression(&parse_expression(src).expect("parse")).expect("bind");
|
||||
evaluator.evaluate(&bound).expect("evaluate")
|
||||
};
|
||||
// The model collation is case-insensitive: A/a are one value, and BLANK counts as one more.
|
||||
assert_eq!(evaluate("DISTINCTCOUNT(Labels[Name])"), Scalar::Integer(3));
|
||||
// A filter set from that key matches every spelling, so COUNTROWS agrees with the count.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(0, 0, [gridcraft_dax::ScalarKey::String("A".into())]);
|
||||
let bound = Binder::new(&model).bind_expression(&parse_expression("COUNTROWS(Labels)").expect("parse")).expect("bind");
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filters).expect("filtered count"), Scalar::Integer(2));
|
||||
// VALUES reports the same distinct set, keeping the first spelling it saw.
|
||||
let bound = Binder::new(&model).bind_expression(&parse_expression("VALUES(Labels[Name])").expect("parse")).expect("bind");
|
||||
let table = evaluator.evaluate_table(&bound).expect("values");
|
||||
assert_eq!(table.rows, vec![vec![Scalar::String("A".into())], vec![Scalar::String("B".into())], vec![Scalar::Blank]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blank_dimension_member_drops_orphan_fact_rows() {
|
||||
let mut model = DataModel {
|
||||
tables: vec![
|
||||
ModelTable {
|
||||
name: "Sales".into(),
|
||||
columns: vec![
|
||||
ModelColumn { name: "Amount".into(), data_type: Some("Int64".into()) },
|
||||
ModelColumn { name: "Product".into(), data_type: Some("String".into()) },
|
||||
],
|
||||
rows: vec![
|
||||
vec![Scalar::Integer(10), Scalar::String("A".into())],
|
||||
// No Products row: an orphan key belongs to Products' BLANK member.
|
||||
vec![Scalar::Integer(20), Scalar::String("Orphan".into())],
|
||||
],
|
||||
},
|
||||
ModelTable {
|
||||
name: "Products".into(),
|
||||
columns: vec![ModelColumn { name: "Product".into(), data_type: Some("String".into()) }],
|
||||
rows: vec![vec![Scalar::String("A".into())]],
|
||||
},
|
||||
],
|
||||
relationships: vec![Relationship {
|
||||
from_table: "Sales".into(),
|
||||
from_column: "Product".into(),
|
||||
to_table: "Products".into(),
|
||||
to_column: "Product".into(),
|
||||
bidirectional: false,
|
||||
inactive: false,
|
||||
}],
|
||||
measures: vec![Measure { name: "Total".into(), formula: "SUM(Sales[Amount])".into(), table: Some("Sales".into()), format: None, expr: None }],
|
||||
};
|
||||
model.parse_formulas().expect("model parses");
|
||||
let evaluator = Evaluator::new(&model).expect("evaluator");
|
||||
let bound = Binder::new(&model).bind_expression(&parse_expression("[Total]").expect("parse")).expect("bind");
|
||||
|
||||
// A filter on Products' BLANK member keeps no orphan fact rows: an orphan key does not join,
|
||||
// so `SUM` over the empty set is BLANK (the model's inner-join semantics).
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(1, 0, [gridcraft_dax::ScalarKey::Blank]);
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filters).expect("blank member"), Scalar::Blank);
|
||||
|
||||
// A concrete member still sees only its own rows: the orphan stays out of `"A"`.
|
||||
let mut filters = FilterContext::default();
|
||||
filters.set(1, 0, [gridcraft_dax::ScalarKey::String("A".into())]);
|
||||
assert_eq!(evaluator.evaluate_with(&bound, filters).expect("matched member"), Scalar::Decimal(10.0));
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Integration tests for the date and time catalog.
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup};
|
||||
use gridcraft_dax::{Expr, ExprKind, ValidationErrorKind, parse_expression, validate_call, validate_expression};
|
||||
|
||||
const FUNCTIONS: [(&str, usize, usize); 24] = [
|
||||
("CALENDAR", 2, 2),
|
||||
("CALENDARAUTO", 0, 1),
|
||||
("DATE", 3, 3),
|
||||
("DATEDIFF", 3, 3),
|
||||
("DATEVALUE", 1, 1),
|
||||
("DAY", 1, 1),
|
||||
("EDATE", 2, 2),
|
||||
("EOMONTH", 2, 2),
|
||||
("HOUR", 1, 1),
|
||||
("MINUTE", 1, 1),
|
||||
("MONTH", 1, 1),
|
||||
("NETWORKDAYS", 2, 4),
|
||||
("NOW", 0, 0),
|
||||
("QUARTER", 1, 1),
|
||||
("SECOND", 1, 1),
|
||||
("TIME", 3, 3),
|
||||
("TIMEVALUE", 1, 1),
|
||||
("TODAY", 0, 0),
|
||||
("UTCNOW", 0, 0),
|
||||
("UTCTODAY", 0, 0),
|
||||
("WEEKDAY", 1, 2),
|
||||
("WEEKNUM", 1, 2),
|
||||
("YEAR", 1, 1),
|
||||
("YEARFRAC", 2, 3),
|
||||
];
|
||||
|
||||
fn date_time_catalog() -> Vec<&'static FunctionSpec> {
|
||||
catalog().iter().filter(|spec| spec.category == FunctionCategory::DateAndTime).collect()
|
||||
}
|
||||
|
||||
fn parse(src: &str) -> Expr {
|
||||
match parse_expression(src) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("{src:?} did not parse: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn spec(name: &str) -> &'static FunctionSpec {
|
||||
match lookup(name) {
|
||||
Some(spec) => spec,
|
||||
None => panic!("{name} is missing from the catalog"),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_errors(src: &str) -> Vec<gridcraft_dax::ValidationError> {
|
||||
let expr = parse(src);
|
||||
match &expr.kind {
|
||||
ExprKind::Call(call) => validate_call(call),
|
||||
other => panic!("{src:?} is not a call: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn has_arity_error(src: &str) -> bool {
|
||||
call_errors(src).iter().any(|error| error.kind == ValidationErrorKind::Arity)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_has_every_date_and_time_function_exactly_once_with_documented_arity() {
|
||||
let specs = date_time_catalog();
|
||||
assert_eq!(specs.len(), FUNCTIONS.len());
|
||||
|
||||
for (name, min_args, max_args) in FUNCTIONS {
|
||||
let matches: Vec<&FunctionSpec> = specs.iter().copied().filter(|spec| spec.name == name).collect();
|
||||
assert_eq!(matches.len(), 1, "{name} should appear exactly once");
|
||||
assert_eq!(matches[0].min_args, min_args, "{name} min arity");
|
||||
assert_eq!(matches[0].max_args, max_args, "{name} max arity");
|
||||
assert_eq!(matches[0].category, FunctionCategory::DateAndTime);
|
||||
}
|
||||
|
||||
let catalogued: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.name).collect();
|
||||
let documented: std::collections::BTreeSet<&str> = FUNCTIONS.iter().map(|(name, _, _)| *name).collect();
|
||||
assert_eq!(catalogued, documented);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_is_case_insensitive() {
|
||||
for (name, _, _) in FUNCTIONS {
|
||||
assert_eq!(lookup(name).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_lowercase()).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_uppercase()).map(|spec| spec.name), Some(name));
|
||||
}
|
||||
assert_eq!(lookup("EoMonth").map(|spec| spec.name), Some("EOMONTH"));
|
||||
assert_eq!(lookup("DateValue").map(|spec| spec.name), Some("DATEVALUE"));
|
||||
assert!(lookup("SUMMARY").is_none());
|
||||
assert!(lookup("DATE(").is_none());
|
||||
assert!(lookup("").is_none());
|
||||
assert!(lookup("DAY ").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_record_has_consistent_signature_and_metadata() {
|
||||
for spec in date_time_catalog() {
|
||||
assert!(!spec.description.is_empty(), "{} description", spec.name);
|
||||
assert!(!spec.examples.is_empty(), "{} examples", spec.name);
|
||||
assert!(spec.min_args <= spec.max_args, "{} min <= max", spec.name);
|
||||
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
|
||||
|
||||
let required = spec.params.iter().filter(|param| !param.optional).count();
|
||||
let optional = spec.params.iter().filter(|param| param.optional).count();
|
||||
assert_eq!(required, spec.min_args, "{} required params", spec.name);
|
||||
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
|
||||
for param in spec.params {
|
||||
assert!(!param.name.is_empty(), "{} parameter name", spec.name);
|
||||
}
|
||||
|
||||
assert!(!spec.overloads.is_empty(), "{} overloads", spec.name);
|
||||
for arity in spec.min_args..=spec.max_args {
|
||||
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
|
||||
}
|
||||
let arities: Vec<usize> = spec.overloads.iter().map(|overload| overload.arity()).collect();
|
||||
assert_eq!(arities.iter().min().copied(), Some(spec.min_args), "{} overload min", spec.name);
|
||||
assert_eq!(arities.iter().max().copied(), Some(spec.max_args), "{} overload max", spec.name);
|
||||
|
||||
for overload in spec.overloads {
|
||||
assert_eq!(overload.params.len(), overload.arity(), "{} overload arity", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_example_parses_as_an_expression() {
|
||||
for spec in date_time_catalog() {
|
||||
for example in spec.examples {
|
||||
let expr = parse(example);
|
||||
assert!(validate_expression(&expr).is_empty(), "{} example {example:?} validates", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameter_kinds_and_return_types_are_precise() {
|
||||
assert_eq!(spec("DATE").return_type, ReturnType::DateTime);
|
||||
assert_eq!(spec("DAY").return_type, ReturnType::Integer);
|
||||
assert_eq!(spec("YEAR").return_type, ReturnType::Integer);
|
||||
assert_eq!(spec("DATEDIFF").return_type, ReturnType::Integer);
|
||||
assert_eq!(spec("NETWORKDAYS").return_type, ReturnType::Integer);
|
||||
assert_eq!(spec("CALENDAR").return_type, ReturnType::Table);
|
||||
assert_eq!(spec("CALENDARAUTO").return_type, ReturnType::Table);
|
||||
assert_eq!(spec("YEARFRAC").return_type, ReturnType::Decimal);
|
||||
assert_eq!(spec("TIMEVALUE").return_type, ReturnType::DateTime);
|
||||
|
||||
assert_eq!(spec("DATEVALUE").params[0].kind, ParamKind::Text);
|
||||
assert_eq!(spec("TIMEVALUE").params[0].kind, ParamKind::Text);
|
||||
assert_eq!(spec("DATE").params[0].kind, ParamKind::Number);
|
||||
assert_eq!(spec("DAY").params[0].kind, ParamKind::Date);
|
||||
assert_eq!(spec("EDATE").params[1].kind, ParamKind::Number);
|
||||
assert_eq!(spec("NETWORKDAYS").params[3].kind, ParamKind::Table);
|
||||
assert!(spec("NETWORKDAYS").params[2].optional);
|
||||
assert!(spec("NETWORKDAYS").params[3].optional);
|
||||
assert!(spec("WEEKDAY").params[1].optional);
|
||||
assert!(spec("YEARFRAC").params[2].optional);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volatile_and_host_flags_are_honest() {
|
||||
let volatile = ["NOW", "TODAY", "UTCNOW", "UTCTODAY"];
|
||||
for spec in date_time_catalog() {
|
||||
assert_eq!(spec.flags.volatile, volatile.contains(&spec.name), "{} volatile flag", spec.name);
|
||||
assert!(!spec.flags.iterator, "{} is not an iterator", spec.name);
|
||||
assert!(!spec.flags.not_recommended, "{} is recommended", spec.name);
|
||||
assert_eq!(spec.flags.excel_compatible, spec.name != "NETWORKDAYS", "{} excel flag", spec.name);
|
||||
assert!(!spec.is_iterator(), "{} is_iterator", spec.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::cognitive_complexity)] // The lint budget is for the engine; tests keep one readable assertion table.
|
||||
fn arity_boundaries_are_enforced_for_representative_functions() {
|
||||
// Zero-argument functions reject any argument.
|
||||
assert!(!has_arity_error("NOW ()"));
|
||||
assert!(has_arity_error("NOW ( 1 )"));
|
||||
assert!(!has_arity_error("TODAY ()"));
|
||||
assert!(has_arity_error("TODAY ( 1 )"));
|
||||
assert!(!has_arity_error("UTCNOW ()"));
|
||||
assert!(!has_arity_error("UTCTODAY ()"));
|
||||
assert!(has_arity_error("UTCTODAY ( 0 )"));
|
||||
|
||||
// Optional argument: CALENDARAUTO () and CALENDARAUTO ( 3 ), not two arguments.
|
||||
assert!(!has_arity_error("CALENDARAUTO ()"));
|
||||
assert!(!has_arity_error("CALENDARAUTO ( 3 )"));
|
||||
assert!(has_arity_error("CALENDARAUTO ( 3, 4 )"));
|
||||
|
||||
// Fixed arity: DATE takes exactly three arguments.
|
||||
assert!(has_arity_error("DATE ( 2024, 1 )"));
|
||||
assert!(!has_arity_error("DATE ( 2024, 1, 1 )"));
|
||||
assert!(has_arity_error("DATE ( 2024, 1, 1, 1 )"));
|
||||
|
||||
// Optional trailing arguments: WEEKDAY, WEEKNUM, YEARFRAC.
|
||||
assert!(has_arity_error("WEEKDAY ()"));
|
||||
assert!(!has_arity_error("WEEKDAY ( DATE ( 2024, 1, 1 ) )"));
|
||||
assert!(!has_arity_error("WEEKDAY ( DATE ( 2024, 1, 1 ), 2 )"));
|
||||
assert!(has_arity_error("WEEKDAY ( DATE ( 2024, 1, 1 ), 2, 3 )"));
|
||||
|
||||
assert!(!has_arity_error("WEEKNUM ( DATE ( 2024, 1, 1 ) )"));
|
||||
assert!(!has_arity_error("WEEKNUM ( DATE ( 2024, 1, 1 ), 21 )"));
|
||||
assert!(has_arity_error("WEEKNUM ( DATE ( 2024, 1, 1 ), 21, 1 )"));
|
||||
|
||||
assert!(has_arity_error("YEARFRAC ( DATE ( 2024, 1, 1 ) )"));
|
||||
assert!(!has_arity_error("YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ) )"));
|
||||
assert!(!has_arity_error("YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), 1 )"));
|
||||
assert!(has_arity_error("YEARFRAC ( DATE ( 2024, 1, 1 ), DATE ( 2024, 12, 31 ), 1, 0 )"));
|
||||
|
||||
// Four arities: NETWORKDAYS.
|
||||
assert!(has_arity_error("NETWORKDAYS ( DATE ( 2024, 1, 1 ) )"));
|
||||
assert!(!has_arity_error("NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ) )"));
|
||||
assert!(!has_arity_error("NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1 )"));
|
||||
assert!(!has_arity_error("NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, { DATE ( 2024, 1, 15 ) } )"));
|
||||
assert!(has_arity_error("NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, { DATE ( 2024, 1, 15 ) }, 2 )"));
|
||||
|
||||
// Statically decidable table parameter: the holidays argument must not be a scalar literal.
|
||||
let errors = call_errors("NETWORKDAYS ( DATE ( 2024, 1, 1 ), DATE ( 2024, 1, 31 ), 1, 1 )");
|
||||
assert!(errors.iter().any(|error| error.kind == ValidationErrorKind::ArgumentKind), "scalar holidays should be rejected, got {errors:?}");
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
//! Integration tests for the filter catalog.
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup};
|
||||
use gridcraft_dax::{Expr, ExprKind, ValidationError, ValidationErrorKind, parse_expression, validate_call, validate_expression};
|
||||
|
||||
fn filter_catalog() -> Vec<&'static FunctionSpec> {
|
||||
catalog().iter().filter(|spec| spec.category == FunctionCategory::Filter).collect()
|
||||
}
|
||||
|
||||
const FUNCTIONS: [(&str, usize, usize); 29] = [
|
||||
("ALL", 0, usize::MAX),
|
||||
("ALLCROSSFILTERED", 1, 1),
|
||||
("ALLEXCEPT", 2, usize::MAX),
|
||||
("ALLNOBLANKROW", 1, usize::MAX),
|
||||
("ALLSELECTED", 0, usize::MAX),
|
||||
("ALLSELECTEDAPPLY", 1, 1),
|
||||
("ALLSELECTEDREMOVE", 1, usize::MAX),
|
||||
("ALWAYSAPPLY", 1, 1),
|
||||
("CALCULATE", 1, usize::MAX),
|
||||
("CALCULATETABLE", 1, usize::MAX),
|
||||
("DEPENDON", 2, usize::MAX),
|
||||
("FILTER", 2, 2),
|
||||
("FILTERCLUSTER", 4, usize::MAX),
|
||||
("GROUPCROSSAPPLY", 2, usize::MAX),
|
||||
("GROUPCROSSAPPLYTABLE", 2, usize::MAX),
|
||||
("INDEX", 1, 7),
|
||||
("KEEPFILTERS", 1, 1),
|
||||
("LOOKUP", 3, usize::MAX),
|
||||
("LOOKUPVALUE", 3, usize::MAX),
|
||||
("LOOKUPWITHTOTALS", 3, usize::MAX),
|
||||
("MATCHBY", 0, usize::MAX),
|
||||
("NONFILTER", 1, 1),
|
||||
("OFFSET", 1, 7),
|
||||
("ORDERBY", 0, usize::MAX),
|
||||
("PARTITIONBY", 0, usize::MAX),
|
||||
("REMOVEFILTERS", 0, usize::MAX),
|
||||
("SELECTEDVALUE", 1, 2),
|
||||
("SHADOWCLUSTER", 1, 1),
|
||||
("WINDOW", 2, 10),
|
||||
];
|
||||
|
||||
const EXCEL_COMPATIBLE: [&str; 12] = [
|
||||
"ALL",
|
||||
"ALLCROSSFILTERED",
|
||||
"ALLEXCEPT",
|
||||
"ALLNOBLANKROW",
|
||||
"ALLSELECTED",
|
||||
"CALCULATE",
|
||||
"CALCULATETABLE",
|
||||
"FILTER",
|
||||
"KEEPFILTERS",
|
||||
"LOOKUPVALUE",
|
||||
"REMOVEFILTERS",
|
||||
"SELECTEDVALUE",
|
||||
];
|
||||
|
||||
fn parse(src: &str) -> Expr {
|
||||
match parse_expression(src) {
|
||||
Ok(expr) => expr,
|
||||
Err(error) => panic!("{src:?} did not parse: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn spec(name: &str) -> &'static FunctionSpec {
|
||||
match lookup(name) {
|
||||
Some(spec) => spec,
|
||||
None => panic!("{name} is missing from the catalog"),
|
||||
}
|
||||
}
|
||||
|
||||
fn expression_errors(src: &str) -> Vec<ValidationError> {
|
||||
validate_expression(&parse(src))
|
||||
}
|
||||
|
||||
fn call_errors(src: &str) -> Vec<ValidationError> {
|
||||
let expr = parse(src);
|
||||
match &expr.kind {
|
||||
ExprKind::Call(call) => validate_call(call),
|
||||
other => panic!("{src:?} is not a call: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_valid(src: &str) {
|
||||
let errors = expression_errors(src);
|
||||
assert!(errors.is_empty(), "{src:?} should validate, got {errors:?}");
|
||||
}
|
||||
|
||||
fn assert_invalid_kind(src: &str, kind: ValidationErrorKind) -> Vec<ValidationError> {
|
||||
let errors = expression_errors(src);
|
||||
assert!(!errors.is_empty(), "{src:?} should be rejected");
|
||||
assert!(errors.iter().any(|error| error.kind == kind), "{src:?} should report {kind:?}, got {errors:?}");
|
||||
errors
|
||||
}
|
||||
|
||||
fn overload_kinds(spec: &FunctionSpec, arity: usize) -> Option<Vec<ParamKind>> {
|
||||
spec.overload_for(arity).map(|overload| overload.params.to_vec())
|
||||
}
|
||||
|
||||
fn arity_errors(src: &str) -> Vec<ValidationError> {
|
||||
expression_errors(src).into_iter().filter(|error| error.kind == ValidationErrorKind::Arity).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_has_every_filter_function_exactly_once_in_dax_guide_order() {
|
||||
let specs = filter_catalog();
|
||||
assert_eq!(specs.len(), FUNCTIONS.len());
|
||||
|
||||
for (index, (name, min_args, max_args)) in FUNCTIONS.iter().enumerate() {
|
||||
let matches: Vec<&FunctionSpec> = specs.iter().copied().filter(|spec| spec.name == *name).collect();
|
||||
assert_eq!(matches.len(), 1, "{name} should appear exactly once");
|
||||
assert_eq!(specs[index].name, *name, "catalog order at {index}");
|
||||
assert_eq!(matches[0].min_args, *min_args, "{name} min arity");
|
||||
assert_eq!(matches[0].max_args, *max_args, "{name} max arity");
|
||||
assert_eq!(matches[0].category, FunctionCategory::Filter);
|
||||
}
|
||||
|
||||
let catalogued: std::collections::BTreeSet<&str> = specs.iter().map(|spec| spec.name).collect();
|
||||
let documented: std::collections::BTreeSet<&str> = FUNCTIONS.iter().map(|(name, _, _)| *name).collect();
|
||||
assert_eq!(catalogued, documented);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_is_case_insensitive() {
|
||||
for (name, _, _) in FUNCTIONS {
|
||||
assert_eq!(lookup(name).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_lowercase()).map(|spec| spec.name), Some(name));
|
||||
assert_eq!(lookup(&name.to_ascii_uppercase()).map(|spec| spec.name), Some(name));
|
||||
}
|
||||
assert_eq!(lookup("FiLtEr").map(|spec| spec.name), Some("FILTER"));
|
||||
assert_eq!(lookup("allselected").map(|spec| spec.name), Some("ALLSELECTED"));
|
||||
assert!(lookup("FILTERX").is_none());
|
||||
assert!(lookup("FILTER ").is_none());
|
||||
assert!(lookup("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_record_has_consistent_signature_and_metadata() {
|
||||
for spec in filter_catalog() {
|
||||
assert!(!spec.description.is_empty(), "{} description", spec.name);
|
||||
assert!(!spec.examples.is_empty(), "{} examples", spec.name);
|
||||
for example in spec.examples {
|
||||
assert!(!example.is_empty(), "{} has an empty example", spec.name);
|
||||
assert!(example.to_ascii_uppercase().starts_with(spec.name), "{} example {example:?} must call the function", spec.name);
|
||||
}
|
||||
|
||||
let required = spec.params.iter().filter(|param| !param.optional).count();
|
||||
let optional = spec.params.iter().filter(|param| param.optional).count();
|
||||
assert_eq!(required, spec.min_args, "{} required params", spec.name);
|
||||
|
||||
if spec.max_args == usize::MAX {
|
||||
assert!(spec.params.len() >= spec.min_args, "{} descriptive params", spec.name);
|
||||
assert!(spec.overloads.iter().any(|overload| overload.variadic), "{} unbounded arity needs a variadic overload", spec.name);
|
||||
} else {
|
||||
assert_eq!(spec.params.len(), spec.max_args, "{} descriptive params", spec.name);
|
||||
assert_eq!(optional, spec.max_args - spec.min_args, "{} optional params", spec.name);
|
||||
assert_eq!(spec.overloads.iter().map(|overload| overload.arity()).max(), Some(spec.max_args), "{} overload max", spec.name);
|
||||
}
|
||||
|
||||
assert!(!spec.overloads.is_empty(), "{} overloads", spec.name);
|
||||
assert_eq!(spec.overloads.iter().map(|overload| overload.arity()).min(), Some(spec.min_args), "{} overload min", spec.name);
|
||||
let probe = std::cmp::min(spec.max_args, spec.min_args + 4);
|
||||
for arity in spec.min_args..=probe {
|
||||
assert!(spec.overload_for(arity).is_some(), "{} has no overload for arity {arity}", spec.name);
|
||||
}
|
||||
assert!(spec.overload_for(spec.min_args).is_some(), "{} minimum arity overload", spec.name);
|
||||
if spec.min_args > 0 {
|
||||
assert!(spec.overload_for(spec.min_args - 1).is_none(), "{} accepts too few arguments", spec.name);
|
||||
}
|
||||
if spec.max_args != usize::MAX {
|
||||
assert!(spec.overload_for(spec.max_args + 1).is_none(), "{} accepts too many arguments", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_types_and_iterator_flags_are_documented() {
|
||||
for (name, return_type) in [
|
||||
("ALL", ReturnType::Table),
|
||||
("ALLCROSSFILTERED", ReturnType::Table),
|
||||
("ALLEXCEPT", ReturnType::Table),
|
||||
("ALLNOBLANKROW", ReturnType::Table),
|
||||
("ALLSELECTED", ReturnType::Table),
|
||||
("ALLSELECTEDAPPLY", ReturnType::Table),
|
||||
("ALLSELECTEDREMOVE", ReturnType::Table),
|
||||
("ALWAYSAPPLY", ReturnType::Table),
|
||||
("CALCULATE", ReturnType::Any),
|
||||
("CALCULATETABLE", ReturnType::Table),
|
||||
("DEPENDON", ReturnType::Table),
|
||||
("FILTER", ReturnType::Table),
|
||||
("FILTERCLUSTER", ReturnType::Table),
|
||||
("GROUPCROSSAPPLY", ReturnType::Table),
|
||||
("GROUPCROSSAPPLYTABLE", ReturnType::Table),
|
||||
("INDEX", ReturnType::Table),
|
||||
("KEEPFILTERS", ReturnType::Any),
|
||||
("LOOKUP", ReturnType::Any),
|
||||
("LOOKUPVALUE", ReturnType::Any),
|
||||
("LOOKUPWITHTOTALS", ReturnType::Any),
|
||||
("MATCHBY", ReturnType::Any),
|
||||
("NONFILTER", ReturnType::Table),
|
||||
("OFFSET", ReturnType::Table),
|
||||
("ORDERBY", ReturnType::Any),
|
||||
("PARTITIONBY", ReturnType::Any),
|
||||
("REMOVEFILTERS", ReturnType::Any),
|
||||
("SELECTEDVALUE", ReturnType::Any),
|
||||
("SHADOWCLUSTER", ReturnType::Table),
|
||||
("WINDOW", ReturnType::Table),
|
||||
] {
|
||||
assert_eq!(spec(name).return_type, return_type, "{name} return type");
|
||||
}
|
||||
|
||||
for spec in filter_catalog() {
|
||||
assert_eq!(spec.flags.iterator, spec.name == "FILTER", "{} iterator flag", spec.name);
|
||||
assert_eq!(spec.is_iterator(), spec.flags.iterator, "{} is_iterator", spec.name);
|
||||
assert!(!spec.flags.volatile, "{} must not be volatile", spec.name);
|
||||
assert!(!spec.flags.not_recommended, "{} must not be marked not recommended", spec.name);
|
||||
assert!(spec.flags.direct_query_limited, "{} DirectQuery note", spec.name);
|
||||
assert_eq!(spec.flags.excel_compatible, EXCEL_COMPATIBLE.contains(&spec.name), "{} Excel compatibility", spec.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_catalog_example_parses_and_validates() {
|
||||
for spec in filter_catalog() {
|
||||
for example in spec.examples {
|
||||
let expr = parse(example);
|
||||
let errors = validate_expression(&expr);
|
||||
assert!(errors.is_empty(), "{} example {example:?} should validate, got {errors:?}", spec.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameter_kinds_track_the_dax_guide_signatures() {
|
||||
assert_eq!(overload_kinds(spec("FILTER"), 2), Some(vec![ParamKind::Table, ParamKind::Logical]));
|
||||
assert_eq!(overload_kinds(spec("ALL"), 0), Some(Vec::new()));
|
||||
assert_eq!(overload_kinds(spec("ALL"), 1), Some(vec![ParamKind::Reference]));
|
||||
assert_eq!(overload_kinds(spec("ALL"), 2), Some(vec![ParamKind::Reference, ParamKind::Column]));
|
||||
// Variadic overloads report their declared prefix; the last kind repeats.
|
||||
assert_eq!(overload_kinds(spec("ALLEXCEPT"), 3), Some(vec![ParamKind::Table, ParamKind::Column]));
|
||||
assert_eq!(spec("ALLEXCEPT").overload_for(3).and_then(|overload| overload.kind_at(2)), Some(ParamKind::Column));
|
||||
assert_eq!(overload_kinds(spec("SELECTEDVALUE"), 1), Some(vec![ParamKind::Column]));
|
||||
assert_eq!(overload_kinds(spec("SELECTEDVALUE"), 2), Some(vec![ParamKind::Column, ParamKind::Any]));
|
||||
assert_eq!(overload_kinds(spec("CALCULATE"), 1), Some(vec![ParamKind::Expression]));
|
||||
assert_eq!(overload_kinds(spec("CALCULATE"), 3), Some(vec![ParamKind::Expression, ParamKind::Any]));
|
||||
assert_eq!(overload_kinds(spec("CALCULATETABLE"), 1), Some(vec![ParamKind::Table]));
|
||||
assert_eq!(overload_kinds(spec("INDEX"), 1), Some(vec![ParamKind::Number]));
|
||||
assert_eq!(overload_kinds(spec("INDEX"), 3), Some(vec![ParamKind::Number, ParamKind::Table, ParamKind::Any]));
|
||||
assert_eq!(overload_kinds(spec("WINDOW"), 2), Some(vec![ParamKind::Number, ParamKind::Number]));
|
||||
assert_eq!(overload_kinds(spec("WINDOW"), 5), Some(vec![ParamKind::Number, ParamKind::Any, ParamKind::Number, ParamKind::Any, ParamKind::Table]));
|
||||
assert_eq!(overload_kinds(spec("LOOKUP"), 3), Some(vec![ParamKind::Any, ParamKind::Column, ParamKind::Any]));
|
||||
assert_eq!(overload_kinds(spec("LOOKUPVALUE"), 3), Some(vec![ParamKind::Column, ParamKind::Column, ParamKind::Any]));
|
||||
assert_eq!(overload_kinds(spec("PARTITIONBY"), 0), Some(Vec::new()));
|
||||
assert_eq!(overload_kinds(spec("PARTITIONBY"), 1), Some(vec![ParamKind::Column]));
|
||||
assert_eq!(overload_kinds(spec("MATCHBY"), 0), Some(Vec::new()));
|
||||
assert_eq!(overload_kinds(spec("MATCHBY"), 2), Some(vec![ParamKind::Column]));
|
||||
|
||||
// The descriptive signature keeps the documented parameter names and optional markers.
|
||||
let window = spec("WINDOW");
|
||||
let names: Vec<&str> = window.params.iter().map(|param| param.name).collect();
|
||||
assert_eq!(names, ["From", "FromType", "To", "ToType", "Relation", "OrderBy", "Blanks", "PartitionBy", "MatchBy", "Reset"]);
|
||||
assert!(window.params[1].optional && !window.params[2].optional);
|
||||
assert_eq!(spec("FILTER").params[1].name, "FilterExpression");
|
||||
assert_eq!(spec("ALLEXCEPT").params[0].kind, ParamKind::Table);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arity_boundaries_accept_and_reject_the_right_calls() {
|
||||
for src in [
|
||||
"ALL ( )",
|
||||
"ALL ( Sales )",
|
||||
"ALL ( Sales[Region], Sales[Country] )",
|
||||
"ALLCROSSFILTERED ( Sales )",
|
||||
"ALLEXCEPT ( Sales, Sales[Region] )",
|
||||
"ALLNOBLANKROW ( Customer )",
|
||||
"ALLSELECTED ( )",
|
||||
"ALLSELECTED ( Sales[Region] )",
|
||||
"CALCULATE ( [Sales Amount], ALL ( Sales ) )",
|
||||
"CALCULATETABLE ( Sales, Sales[Region] = \"East\" )",
|
||||
"FILTER ( Sales, Sales[Amount] > 0 )",
|
||||
"SELECTEDVALUE ( Product[Color] )",
|
||||
"SELECTEDVALUE ( Product[Color], \"Multiple colors\" )",
|
||||
"KEEPFILTERS ( Product[Color] = \"Red\" )",
|
||||
"LOOKUP ( [Sales Amount], 'Date'[Year], 2018, \"Inferred\" )",
|
||||
"LOOKUPVALUE ( Product[Color], Product[ProductKey], 1, \"Unknown\" )",
|
||||
"LOOKUPWITHTOTALS ( [Sales Amount], [Year], 2018 )",
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[OrderDate] ) )",
|
||||
"INDEX ( -1, ALLSELECTED ( Sales ) )",
|
||||
"OFFSET ( -1, Sales )",
|
||||
"WINDOW ( 1, ABS, 1, ABS, Sales )",
|
||||
"WINDOW ( -1, REL, 1, REL, Sales, ORDERBY ( Sales[OrderDate] ), KEEP, PARTITIONBY ( Sales[Region] ) )",
|
||||
"MATCHBY ( Sales[OrderKey] )",
|
||||
"ORDERBY ( Sales[Amount], DESC )",
|
||||
"PARTITIONBY ( Sales[Region] )",
|
||||
"REMOVEFILTERS ( Sales[Region] )",
|
||||
"DEPENDON ( Sales, Sales[OrderDate] )",
|
||||
"NONFILTER ( VALUES ( Product[Color] ) )",
|
||||
"SHADOWCLUSTER ( VALUES ( Product[Color] ) )",
|
||||
"ALWAYSAPPLY ( FILTER ( VALUES ( Product[Color] ), FALSE ) )",
|
||||
"ALLSELECTEDAPPLY ( VALUES ( Product[Color] ) )",
|
||||
"ALLSELECTEDREMOVE ( VALUES ( Product[Color] ), Product[Color] )",
|
||||
"GROUPCROSSAPPLY ( 'Date'[Year], ALL ( 'Date' ), \"Sales\", [Sales Amount] )",
|
||||
"GROUPCROSSAPPLYTABLE ( 'Date'[Year], ALL ( 'Date' ), \"Colors\", VALUES ( 'Product'[Color] ) )",
|
||||
"FILTERCLUSTER ( Product[Category], ALL ( Product ), \"\", ALL ( Sales ) )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
|
||||
for src in [
|
||||
"ALLCROSSFILTERED ( )",
|
||||
"ALLCROSSFILTERED ( Sales, Sales )",
|
||||
"ALLEXCEPT ( Sales )",
|
||||
"ALLNOBLANKROW ( )",
|
||||
"ALLSELECTEDAPPLY ( )",
|
||||
"ALWAYSAPPLY ( Sales, Sales )",
|
||||
"CALCULATE ( )",
|
||||
"CALCULATETABLE ( )",
|
||||
"DEPENDON ( Sales )",
|
||||
"FILTER ( Sales )",
|
||||
"FILTER ( Sales, TRUE, FALSE )",
|
||||
"FILTERCLUSTER ( Product[Category], ALL ( Product ), \"\" )",
|
||||
"GROUPCROSSAPPLY ( 'Date'[Year] )",
|
||||
"GROUPCROSSAPPLYTABLE ( 'Date'[Year] )",
|
||||
"INDEX ( )",
|
||||
"INDEX ( 1, Sales, ORDERBY ( Sales[Amount] ), KEEP, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[OrderKey] ), NONE, 1 )",
|
||||
"KEEPFILTERS ( )",
|
||||
"KEEPFILTERS ( TRUE, FALSE )",
|
||||
"LOOKUP ( [Sales Amount], 'Date'[Year] )",
|
||||
"LOOKUPVALUE ( Product[Color], Product[ProductKey] )",
|
||||
"LOOKUPWITHTOTALS ( [Sales Amount], [Year] )",
|
||||
"NONFILTER ( )",
|
||||
"OFFSET ( )",
|
||||
"SELECTEDVALUE ( )",
|
||||
"SELECTEDVALUE ( Product[Color], \"x\", \"y\" )",
|
||||
"SHADOWCLUSTER ( )",
|
||||
"WINDOW ( 1 )",
|
||||
"WINDOW ( 1, ABS, 1, ABS, Sales, ORDERBY ( Sales[OrderDate] ), KEEP, PARTITIONBY ( Sales[Region] ), MATCHBY ( Sales[OrderKey] ), NONE, 1 )",
|
||||
] {
|
||||
let errors = assert_invalid_kind(src, ValidationErrorKind::Arity);
|
||||
assert_eq!(errors.len(), 1, "{src:?} should report exactly one arity error: {errors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_documented_arity_boundary_is_enforced() {
|
||||
for spec in filter_catalog() {
|
||||
let arities: Vec<usize> = if spec.max_args == usize::MAX {
|
||||
let mut probe = vec![spec.min_args, spec.min_args + 1, spec.min_args + 5];
|
||||
if spec.min_args > 0 {
|
||||
probe.push(spec.min_args - 1);
|
||||
}
|
||||
probe
|
||||
} else {
|
||||
(0..=spec.max_args).collect()
|
||||
};
|
||||
for arity in arities {
|
||||
let arguments = vec!["1"; arity].join(", ");
|
||||
let src = format!("{} ( {arguments} )", spec.name);
|
||||
let errors = arity_errors(&src);
|
||||
if arity < spec.min_args || arity > spec.max_args {
|
||||
assert_eq!(errors.len(), 1, "{src:?} should report one arity error: {errors:?}");
|
||||
} else {
|
||||
assert!(errors.is_empty(), "{src:?} has a documented overload and must not report an arity error: {errors:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statically_decidable_kinds_are_enforced() {
|
||||
for src in [
|
||||
"FILTER ( 1, TRUE )",
|
||||
"FILTER ( Sales[Amount], TRUE )",
|
||||
"ALLCROSSFILTERED ( 1 )",
|
||||
"ALLCROSSFILTERED ( Sales[Region] )",
|
||||
"SELECTEDVALUE ( 1 )",
|
||||
"SELECTEDVALUE ( \"Color\", \"Unknown\" )",
|
||||
"ALLEXCEPT ( Sales, 1 )",
|
||||
"PARTITIONBY ( 1 )",
|
||||
"MATCHBY ( \"OrderKey\" )",
|
||||
"INDEX ( 1, 2 )",
|
||||
"OFFSET ( 1, 2 )",
|
||||
"WINDOW ( 1, ABS, 1, ABS, 2 )",
|
||||
] {
|
||||
assert_invalid_kind(src, ValidationErrorKind::ArgumentKind);
|
||||
}
|
||||
|
||||
for src in [
|
||||
"FILTER ( Sales, TRUE )",
|
||||
"ALLCROSSFILTERED ( 'Product' )",
|
||||
"SELECTEDVALUE ( 'Product'[Color] )",
|
||||
"ALLEXCEPT ( Sales, Sales[Region] )",
|
||||
"PARTITIONBY ( Sales[Region] )",
|
||||
"MATCHBY ( Sales[OrderKey] )",
|
||||
"INDEX ( 1, ALLSELECTED ( Sales ) )",
|
||||
] {
|
||||
assert_valid(src);
|
||||
}
|
||||
|
||||
let errors = assert_invalid_kind("FILTER ( 1, TRUE )", ValidationErrorKind::ArgumentKind);
|
||||
assert!(errors[0].message.contains("FILTER"), "{errors:?}");
|
||||
assert!(errors[0].message.contains("table expression"), "{errors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_call_reports_arities_and_kinds() {
|
||||
let errors = call_errors("FILTER ( Sales )");
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::Arity);
|
||||
assert!(errors[0].span.is_empty());
|
||||
|
||||
let errors = call_errors("ALLCROSSFILTERED ( 1 )");
|
||||
assert_eq!(errors.len(), 1);
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
|
||||
assert!(!errors[0].span.is_empty());
|
||||
|
||||
assert!(call_errors("FILTER ( Sales, Sales[Amount] > 0 )").is_empty());
|
||||
assert!(call_errors("ALL ( )").is_empty());
|
||||
assert!(call_errors("CALCULATE ( [Sales Amount], ALL ( Sales ) )").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_expression_reports_nested_filter_calls() {
|
||||
let src = "CALCULATE ( [Sales Amount], FILTER ( 1, TRUE ) )";
|
||||
let errors = expression_errors(src);
|
||||
assert_eq!(errors.len(), 1, "{errors:?}");
|
||||
assert_eq!(errors[0].function, "FILTER");
|
||||
assert_eq!(errors[0].kind, ValidationErrorKind::ArgumentKind);
|
||||
assert_eq!(&src[errors[0].span.start..errors[0].span.end], "1");
|
||||
|
||||
let src = "FILTER ( Sales, Sales[Amount] > 0 )";
|
||||
assert!(expression_errors(src).is_empty());
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Integration tests for the financial catalog.
|
||||
|
||||
use gridcraft_dax::functions::{FunctionCategory, FunctionSpec, ParamKind, ReturnType, catalog, lookup};
|
||||
use gridcraft_dax::{Expr, ValidationErrorKind, parse_expression, validate_expression};
|
||||
|
||||
fn financial_catalog() -> Vec<&'static FunctionSpec> {
|
||||
catalog().iter().filter(|spec| spec.category == FunctionCategory::Financial).collect()
|
||||
}
|
||||
|
||||
/// Every financial function in dax.guide index order, with its documented arity.
|
||||
const FUNCTIONS: [(&str, usize, usize); 51] = [
|
||||
("ACCRINT", 6, 8),
|
||||
("ACCRINTM", 4, 5),
|
||||
("AMORDEGRC", 6, 7),
|
||||
("AMORLINC", 6, 7),
|
||||
("COUPDAYBS", 3, 4),
|
||||
("COUPDAYS", 3, 4),
|
||||
("COUPDAYSNC", 3, 4),
|
||||
("COUPNCD", 3, 4),
|
||||
("COUPNUM", 3, 4),
|
||||
("COUPPCD", 3, 4),
|
||||
("CUMIPMT", 6, 6),
|
||||
("CUMPRINC", 6, 6),
|
||||
("DB", 4, 5),
|
||||
("DDB", 4, 5),
|
||||
("DISC", 4, 5),
|
||||
("DOLLARDE", 2, 2),
|
||||
("DOLLARFR", 2, 2),
|
||||
("DURATION", 5, 6),
|
||||
("EFFECT", 2, 2),
|
||||
("FV", 3, 5),
|
||||
("INTRATE", 4, 5),
|
||||
("IPMT", 4, 6),
|
||||
("ISPMT", 4, 4),
|
||||
("MDURATION", 5, 6),
|
||||
("NOMINAL", 2, 2),
|
||||
("NPER", 3, 5),
|
||||
("ODDFPRICE", 8, 9),
|
||||
("ODDFYIELD", 8, 9),
|
||||
("ODDLPRICE", 7, 8),
|
||||
("ODDLYIELD", 7, 8),
|
||||
("PDURATION", 3, 3),
|
||||
("PMT", 3, 5),
|
||||
("PPMT", 4, 6),
|
||||
("PRICE", 6, 7),
|
||||
("PRICEDISC", 4, 5),
|
||||
("PRICEMAT", 5, 6),
|
||||
("PV", 3, 5),
|
||||
("RATE", 3, 6),
|
||||
("RECEIVED", 4, 5),
|
||||
("RRI", 3, 3),
|
||||
("SLN", 3, 3),
|
||||
("SYD", 4, 4),
|
||||
("TBILLEQ", 3, 3),
|
||||
("TBILLPRICE", 3, 3),
|
||||
("TBILLYIELD", 3, 3),
|
||||
("VDB", 5, 7),
|
||||
("XIRR", 3, 5),
|
||||
("XNPV", 4, 4),
|
||||
("YIELD", 6, 7),
|
||||
("YIELDDISC", 4, 5),
|
||||
("YIELDMAT", 5, 6),
|
||||
];
|
||||
|
||||
fn parse(src: &str) -> Expr {
|
||||
parse_expression(src).unwrap_or_else(|error| panic!("failed to parse `{src}`: {error}"))
|
||||
}
|
||||
|
||||
fn spec(name: &str) -> &'static FunctionSpec {
|
||||
lookup(name).unwrap_or_else(|| panic!("{name} is missing from the catalog"))
|
||||
}
|
||||
|
||||
fn errors(src: &str) -> Vec<gridcraft_dax::ValidationError> {
|
||||
validate_expression(&parse(src))
|
||||
}
|
||||
|
||||
/// A parseable argument of the requested kind.
|
||||
fn sample(kind: ParamKind) -> &'static str {
|
||||
match kind {
|
||||
ParamKind::Date => "DATE ( 2020, 1, 1 )",
|
||||
ParamKind::Table => "CashFlows",
|
||||
ParamKind::Boolean | ParamKind::Logical => "TRUE",
|
||||
ParamKind::Column | ParamKind::Reference => "Sales[Amount]",
|
||||
ParamKind::Text => "\"text\"",
|
||||
ParamKind::Function => "SUM",
|
||||
ParamKind::Json => "\"{}\"",
|
||||
ParamKind::Expression | ParamKind::Scalar | ParamKind::Any | ParamKind::Number | ParamKind::Variant => "1",
|
||||
}
|
||||
}
|
||||
|
||||
fn call(name: &str, arity: usize, params: &[ParamKind]) -> String {
|
||||
let arguments: Vec<&str> = (0..arity).map(|index| sample(params[index])).collect();
|
||||
format!("{name} ( {} )", arguments.join(", "))
|
||||
}
|
||||
|
||||
fn overload_kinds(spec: &FunctionSpec, arity: usize) -> Option<Vec<ParamKind>> {
|
||||
spec.overload_for(arity).map(|overload| overload.params.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_has_every_financial_function_exactly_once_in_index_order() {
|
||||
let specs = financial_catalog();
|
||||
assert_eq!(specs.len(), FUNCTIONS.len(), "financial function count changed");
|
||||
for (record, (name, min, max)) in specs.iter().zip(FUNCTIONS) {
|
||||
assert_eq!(record.name, name, "unexpected financial function order");
|
||||
assert_eq!(record.category, FunctionCategory::Financial);
|
||||
assert_eq!((record.min_args, record.max_args), (min, max), "{name} arity changed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_is_case_insensitive() {
|
||||
for (name, _, _) in FUNCTIONS {
|
||||
for variant in [name.to_string(), name.to_ascii_lowercase(), format!("{name} ").trim().to_ascii_lowercase()] {
|
||||
let found = lookup(&variant).unwrap_or_else(|| panic!("lookup failed for {variant}"));
|
||||
assert_eq!(found.name, name);
|
||||
assert_eq!(found.category, FunctionCategory::Financial);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_record_has_consistent_signature_and_metadata() {
|
||||
for record in financial_catalog() {
|
||||
let name = record.name;
|
||||
assert_eq!(name, name.to_ascii_uppercase(), "{name} must be catalogued in upper case");
|
||||
assert!(record.min_args <= record.max_args, "{name} has an inverted arity range");
|
||||
assert!(!record.params.is_empty(), "{name} must document its parameters");
|
||||
assert_eq!(record.params.len(), record.max_args, "{name} parameter count must equal max_args");
|
||||
|
||||
let required = record.params.iter().take_while(|parameter| !parameter.optional).count();
|
||||
assert_eq!(required, record.min_args, "{name} optional markers must form a suffix");
|
||||
assert!(record.params.iter().skip(required).all(|parameter| parameter.optional), "{name} has a required parameter after an optional one");
|
||||
|
||||
// Exactly one non-variadic overload per accepted arity, matching the documented prefix.
|
||||
assert_eq!(record.overloads.len(), record.max_args - record.min_args + 1, "{name} must enumerate every accepted arity");
|
||||
for arity in record.min_args..=record.max_args {
|
||||
let matching: Vec<_> = record.overloads.iter().filter(|overload| overload.matches(arity)).collect();
|
||||
assert_eq!(matching.len(), 1, "{name} must accept arity {arity} exactly once");
|
||||
let overload = matching[0];
|
||||
assert!(!overload.variadic, "{name} uses a variadic overload");
|
||||
let expected: Vec<ParamKind> = record.params[..arity].iter().map(|parameter| parameter.kind).collect();
|
||||
assert_eq!(overload.params, expected.as_slice(), "{name} overload kinds for arity {arity}");
|
||||
}
|
||||
assert!(record.overload_for(record.min_args - 1).is_none(), "{name} accepts too few arguments");
|
||||
assert!(record.overload_for(record.max_args + 1).is_none(), "{name} accepts too many arguments");
|
||||
|
||||
assert!(!record.description.is_empty(), "{name} needs a description");
|
||||
assert!(!record.examples.is_empty(), "{name} needs at least one example");
|
||||
for example in record.examples {
|
||||
assert!(example.to_ascii_uppercase().contains(name), "{name} example does not mention the function: {example}");
|
||||
}
|
||||
|
||||
assert!(record.flags.excel_compatible, "{name} is an Excel financial function");
|
||||
assert!(record.flags.direct_query_limited, "{name} has DirectQuery restrictions");
|
||||
assert!(!record.flags.not_recommended, "{name} is not marked not recommended by dax.guide");
|
||||
assert_eq!(record.flags.iterator, matches!(name, "XIRR" | "XNPV"), "{name} iterator flag");
|
||||
assert_eq!(record.sugar_of, None, "{name} is not syntax sugar");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn return_types_match_the_documented_values() {
|
||||
for record in financial_catalog() {
|
||||
let expected = match record.name {
|
||||
"COUPDAYBS" | "COUPDAYSNC" | "COUPNUM" => ReturnType::Integer,
|
||||
"COUPNCD" | "COUPPCD" => ReturnType::DateTime,
|
||||
_ => ReturnType::Decimal,
|
||||
};
|
||||
assert_eq!(record.return_type, expected, "{} return type", record.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_catalog_example_parses_and_validates() {
|
||||
for record in financial_catalog() {
|
||||
for example in record.examples {
|
||||
let parsed = parse(example);
|
||||
let errors = validate_expression(&parsed);
|
||||
assert!(errors.is_empty(), "{} example `{example}`: {errors:?}", record.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arity_boundaries_accept_and_reject_the_right_calls() {
|
||||
for (name, min, max) in FUNCTIONS {
|
||||
let record = spec(name);
|
||||
let kinds: Vec<ParamKind> = record.params.iter().map(|parameter| parameter.kind).collect();
|
||||
|
||||
for arity in min..=max {
|
||||
let source = call(name, arity, &kinds);
|
||||
let errors = errors(&source);
|
||||
assert!(!errors.iter().any(|error| error.kind == ValidationErrorKind::Arity), "{name} should accept {arity} arguments: {errors:?}");
|
||||
}
|
||||
|
||||
if min > 0 {
|
||||
let too_few = call(name, min - 1, &kinds);
|
||||
let errors = errors(&too_few);
|
||||
assert!(errors.iter().any(|error| error.kind == ValidationErrorKind::Arity), "{name} should reject {} arguments", min - 1);
|
||||
}
|
||||
|
||||
let too_many_kinds: Vec<ParamKind> = kinds.iter().copied().chain(std::iter::repeat_n(ParamKind::Number, 1)).collect();
|
||||
let too_many = call(name, max + 1, &too_many_kinds);
|
||||
let errors = errors(&too_many);
|
||||
assert!(errors.iter().any(|error| error.kind == ValidationErrorKind::Arity), "{name} should reject {} arguments", max + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_accepted_arity_matches_its_overload_kinds() {
|
||||
for (name, min, max) in FUNCTIONS {
|
||||
let record = spec(name);
|
||||
for arity in min..=max {
|
||||
let expected: Vec<ParamKind> = record.params[..arity].iter().map(|parameter| parameter.kind).collect();
|
||||
assert_eq!(overload_kinds(record, arity).as_deref(), Some(expected.as_slice()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_arguments_are_only_used_by_the_two_iterators() {
|
||||
let with_table: Vec<&str> = financial_catalog()
|
||||
.iter()
|
||||
.filter(|record| record.params.iter().any(|parameter| parameter.kind == ParamKind::Table))
|
||||
.map(|record| record.name)
|
||||
.collect();
|
||||
assert_eq!(with_table, ["XIRR", "XNPV"]);
|
||||
|
||||
for name in with_table {
|
||||
let record = spec(name);
|
||||
assert!(record.flags.iterator, "{name} must be flagged as an iterator");
|
||||
let table = record.params[0];
|
||||
assert_eq!(table.kind, ParamKind::Table);
|
||||
assert_eq!(table.name, "Table");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user