askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_computed.py · 13.5 KB · 374 lines
| 1 | """Formula and rollup fields: derived values, materialized on write. |
| 2 | |
| 3 | The spreadsheet feature (plan/formula-rollup-spec.md): a `type: computed` |
| 4 | field may declare either |
| 5 | |
| 6 | {"name": "full_name", "type": "computed", |
| 7 | "formula": "first_name + \" \" + last_name"} |
| 8 | |
| 9 | {"name": "debit_total_cents", "type": "computed", |
| 10 | "rollup": {"collection": "fin_journal_lines", "fk_field": "journal_id", |
| 11 | "op": "sum", "field": "debit_cents"}} |
| 12 | |
| 13 | and object_records keeps the stored value current: formulas recompute on |
| 14 | every write of the record itself; rollups recompute on writes/deletes in the |
| 15 | source collection (see object_records._recompute_rollups_for_source). Values |
| 16 | are STORED in the TSV — so lists, tables, detail, search, 58 filters, sort, |
| 17 | realtime, and backups all see them with zero UI changes. |
| 18 | |
| 19 | The formula language is deliberately tiny and is evaluated by a |
| 20 | recursive-descent interpreter in this module — never Python eval. Grammar: |
| 21 | |
| 22 | expr := term (("+" | "-") term)* |
| 23 | term := factor (("*" | "/") factor)* |
| 24 | factor := NUMBER | STRING | IDENT | "(" expr ")" | "-" factor |
| 25 | |
| 26 | call := IDENT "(" expr ("," expr)* ")" -- round(x[, places]), floor(x) |
| 27 | |
| 28 | `+` is numeric addition when both operands parse as numbers, else string |
| 29 | concatenation. |
| 30 | |
| 31 | ## Numbers are exact (decision 3, 2026-11-30) |
| 32 | |
| 33 | Operands used to be parsed through float, so `total_cents - |
| 34 | amount_paid_cents` restated a total of 2**53 + 1 as 2**53 and `amount_cents |
| 35 | * rate_bps / 10000` stored "101.805" in a cents field. Both are money |
| 36 | errors (doctrine #10: no float touches money). Now: |
| 37 | |
| 38 | - An operand that is a whole number is a Python int, and +, -, * on ints |
| 39 | stay ints: exact at any size (an ETH balance in wei is 10**18 and up). |
| 40 | - A fractional operand ("1.5") is a Decimal, never a float. |
| 41 | - `/` divides in Decimal (the only place a fraction can appear from |
| 42 | integers). A formula whose operands are ALL whole numbers is an integer |
| 43 | formula -- it fills an integer field such as a *_cents one -- so its |
| 44 | result is rounded half-up to a whole number once, at the end, not at |
| 45 | each division. 1234 * 825 / 10000 = 101.805 is stored as 102. |
| 46 | - A formula with any fractional operand keeps its fraction (a measure, a |
| 47 | rate), printed without float noise. |
| 48 | - round(x) rounds half-up to a whole number, round(x, n) to n places, and |
| 49 | floor(x) rounds down, for a formula that wants its rounding said out |
| 50 | loud (a floor where the shop wants to give the customer the half cent). |
| 51 | |
| 52 | Failure posture: a broken formula (unknown token, division by |
| 53 | zero, non-numeric arithmetic) yields an EMPTY value and never fails the |
| 54 | caller's write — derived values are non-authoritative, the opposite of |
| 55 | pre-write hooks (a broken gate must fail closed; a broken caption must not |
| 56 | block a save). |
| 57 | """ |
| 58 | |
| 59 | from __future__ import annotations |
| 60 | |
| 61 | import re |
| 62 | from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation, localcontext |
| 63 | from typing import Any, Iterable, Mapping |
| 64 | |
| 65 | ROLLUP_OPS = ("sum", "count", "min", "max", "avg") |
| 66 | |
| 67 | |
| 68 | class FormulaError(ValueError): |
| 69 | """Raised internally for any formula parse/eval problem.""" |
| 70 | |
| 71 | |
| 72 | # --------------------------------------------------------------------------- |
| 73 | # Tokenizer |
| 74 | # --------------------------------------------------------------------------- |
| 75 | |
| 76 | _OPS = set("+-*/(),") |
| 77 | |
| 78 | |
| 79 | def _tokenize(text: str) -> list[tuple[str, str]]: |
| 80 | tokens: list[tuple[str, str]] = [] |
| 81 | i, n = 0, len(text) |
| 82 | while i < n: |
| 83 | ch = text[i] |
| 84 | if ch.isspace(): |
| 85 | i += 1 |
| 86 | continue |
| 87 | if ch in _OPS: |
| 88 | tokens.append(("op", ch)) |
| 89 | i += 1 |
| 90 | continue |
| 91 | if ch == '"': |
| 92 | j = i + 1 |
| 93 | while j < n and text[j] != '"': |
| 94 | j += 1 |
| 95 | if j >= n: |
| 96 | raise FormulaError("Unterminated string literal") |
| 97 | tokens.append(("str", text[i + 1 : j])) |
| 98 | i = j + 1 |
| 99 | continue |
| 100 | if ch.isdigit() or (ch == "." and i + 1 < n and text[i + 1].isdigit()): |
| 101 | j = i |
| 102 | while j < n and (text[j].isdigit() or text[j] == "."): |
| 103 | j += 1 |
| 104 | tokens.append(("num", text[i:j])) |
| 105 | i = j |
| 106 | continue |
| 107 | if ch.isalpha() or ch == "_": |
| 108 | j = i |
| 109 | while j < n and (text[j].isalnum() or text[j] == "_"): |
| 110 | j += 1 |
| 111 | tokens.append(("ident", text[i:j])) |
| 112 | i = j |
| 113 | continue |
| 114 | raise FormulaError(f"Unexpected character in formula: {ch!r}") |
| 115 | return tokens |
| 116 | |
| 117 | |
| 118 | # --------------------------------------------------------------------------- |
| 119 | # Parser / evaluator |
| 120 | # --------------------------------------------------------------------------- |
| 121 | |
| 122 | |
| 123 | _FUNCTIONS = ("round", "floor") |
| 124 | |
| 125 | |
| 126 | def _to_number(value: Any): |
| 127 | """int for a whole number, Decimal for a fraction, None for text. |
| 128 | |
| 129 | Never float: a float operand (a caller passing one in) is read through |
| 130 | its repr so 0.1 is 0.1, and a non-finite value is not a number.""" |
| 131 | if isinstance(value, bool): |
| 132 | return None |
| 133 | if isinstance(value, int): |
| 134 | return value |
| 135 | if isinstance(value, Decimal): |
| 136 | number = value |
| 137 | elif isinstance(value, float): |
| 138 | number = Decimal(repr(value)) |
| 139 | else: |
| 140 | text = str(value).strip() |
| 141 | if not text: |
| 142 | return None |
| 143 | if _INT_RE.match(text): |
| 144 | return int(text) |
| 145 | try: |
| 146 | number = Decimal(text) |
| 147 | except (InvalidOperation, ValueError): |
| 148 | return None |
| 149 | if not number.is_finite(): |
| 150 | return None |
| 151 | if number == number.to_integral_value(): |
| 152 | return int(number) |
| 153 | return number |
| 154 | |
| 155 | |
| 156 | _INT_RE = re.compile(r"^[+-]?\d+$") |
| 157 | |
| 158 | |
| 159 | class _Evaluator: |
| 160 | def __init__(self, tokens: list[tuple[str, str]], record: Mapping[str, Any]): |
| 161 | self.tokens = tokens |
| 162 | self.pos = 0 |
| 163 | self.record = record |
| 164 | # Did any operand carry a fraction? Decides whether the result is |
| 165 | # an integer formula (rounded half-up at the end) or a decimal one. |
| 166 | self.fractional = False |
| 167 | self.explicit = False |
| 168 | |
| 169 | def _peek(self): |
| 170 | return self.tokens[self.pos] if self.pos < len(self.tokens) else (None, None) |
| 171 | |
| 172 | def _next(self): |
| 173 | token = self._peek() |
| 174 | self.pos += 1 |
| 175 | return token |
| 176 | |
| 177 | def _operand(self, value): |
| 178 | """A leaf of the expression (a literal or a field): notes whether it |
| 179 | carries a fraction. Intermediate results never count, or (a / b) * c |
| 180 | would turn an integer formula into a decimal one.""" |
| 181 | number = _to_number(value) |
| 182 | if isinstance(number, Decimal): |
| 183 | self.fractional = True |
| 184 | return number |
| 185 | |
| 186 | def expr(self): |
| 187 | value = self.term() |
| 188 | while self._peek() == ("op", "+") or self._peek() == ("op", "-"): |
| 189 | _, op = self._next() |
| 190 | right = self.term() |
| 191 | if op == "+": |
| 192 | left_n, right_n = _to_number(value), _to_number(right) |
| 193 | if left_n is not None and right_n is not None: |
| 194 | value = left_n + right_n |
| 195 | else: |
| 196 | value = str(value) + str(right) |
| 197 | else: |
| 198 | value = self._arith(value, right, "-") |
| 199 | return value |
| 200 | |
| 201 | def term(self): |
| 202 | value = self.factor() |
| 203 | while self._peek() == ("op", "*") or self._peek() == ("op", "/"): |
| 204 | _, op = self._next() |
| 205 | right = self.factor() |
| 206 | value = self._arith(value, right, op) |
| 207 | return value |
| 208 | |
| 209 | def factor(self): |
| 210 | kind, text = self._next() |
| 211 | if kind == "num": |
| 212 | return self._operand(text) |
| 213 | if kind == "str": |
| 214 | return text |
| 215 | if kind == "ident": |
| 216 | if self._peek() == ("op", "(") and text in _FUNCTIONS: |
| 217 | return self._call(text) |
| 218 | value = self.record.get(text, "") |
| 219 | self._operand(value) |
| 220 | return value |
| 221 | if (kind, text) == ("op", "("): |
| 222 | value = self.expr() |
| 223 | if self._next() != ("op", ")"): |
| 224 | raise FormulaError("Missing closing parenthesis") |
| 225 | return value |
| 226 | if (kind, text) == ("op", "-"): |
| 227 | inner = _to_number(self.factor()) |
| 228 | if inner is None: |
| 229 | raise FormulaError("Cannot negate a non-number") |
| 230 | return -inner |
| 231 | raise FormulaError(f"Unexpected token: {text!r}") |
| 232 | |
| 233 | def _call(self, name): |
| 234 | self._next() # "(" |
| 235 | args = [self.expr()] |
| 236 | while self._peek() == ("op", ","): |
| 237 | self._next() |
| 238 | args.append(self.expr()) |
| 239 | if self._next() != ("op", ")"): |
| 240 | raise FormulaError("Missing closing parenthesis") |
| 241 | number = _to_number(args[0]) |
| 242 | if number is None: |
| 243 | raise FormulaError(f"Non-numeric argument to {name}()") |
| 244 | if name == "floor": |
| 245 | if len(args) != 1: |
| 246 | raise FormulaError("floor() takes one argument") |
| 247 | return int(Decimal(number).to_integral_value(rounding=ROUND_FLOOR)) |
| 248 | if len(args) > 2: |
| 249 | raise FormulaError("round() takes one or two arguments") |
| 250 | places = _to_number(args[1]) if len(args) == 2 else 0 |
| 251 | if not isinstance(places, int) or places < 0: |
| 252 | raise FormulaError("round()'s places is a whole number, 0 or more") |
| 253 | if places == 0: |
| 254 | return int(Decimal(number).to_integral_value(rounding=ROUND_HALF_UP)) |
| 255 | # An explicit number of places is a decimal result by request. |
| 256 | self.explicit = True |
| 257 | return _to_number(Decimal(number).quantize(Decimal(1).scaleb(-places), |
| 258 | rounding=ROUND_HALF_UP)) |
| 259 | |
| 260 | def _arith(self, left, right, op): |
| 261 | left_n, right_n = _to_number(left), _to_number(right) |
| 262 | if left_n is None or right_n is None: |
| 263 | raise FormulaError(f"Non-numeric operand for {op!r}") |
| 264 | if op == "-": |
| 265 | return left_n - right_n |
| 266 | if op == "*": |
| 267 | return left_n * right_n |
| 268 | if right_n == 0: |
| 269 | raise FormulaError("Division by zero") |
| 270 | with localcontext() as ctx: |
| 271 | ctx.prec = _PRECISION |
| 272 | return _to_number(Decimal(left_n) / Decimal(right_n)) |
| 273 | |
| 274 | |
| 275 | # Enough digits for any integer a ledger holds (an 18-decimal coin's |
| 276 | # balance has ~30) with room for the fraction a division produces. |
| 277 | _PRECISION = 60 |
| 278 | |
| 279 | |
| 280 | def _result_to_string(value: Any) -> str: |
| 281 | if isinstance(value, str): |
| 282 | return value |
| 283 | number = _to_number(value) |
| 284 | if number is None: |
| 285 | return str(value) |
| 286 | if isinstance(number, int): |
| 287 | return str(number) |
| 288 | return format(number.normalize(), "f") |
| 289 | |
| 290 | |
| 291 | def evaluate_formula(formula: str, record: Mapping[str, Any]) -> str: |
| 292 | """Evaluate one formula against a record; raises FormulaError on problems. |
| 293 | |
| 294 | A formula over whole numbers only is an integer formula and its result |
| 295 | is rounded half-up once (see the module docstring).""" |
| 296 | evaluator = _Evaluator(_tokenize(formula), record) |
| 297 | value = evaluator.expr() |
| 298 | if evaluator.pos != len(evaluator.tokens): |
| 299 | raise FormulaError("Trailing tokens in formula") |
| 300 | if (isinstance(value, Decimal) and not evaluator.fractional |
| 301 | and not evaluator.explicit): |
| 302 | value = int(value.to_integral_value(rounding=ROUND_HALF_UP)) |
| 303 | return _result_to_string(value) |
| 304 | |
| 305 | |
| 306 | # --------------------------------------------------------------------------- |
| 307 | # Field helpers (used by object_records) |
| 308 | # --------------------------------------------------------------------------- |
| 309 | |
| 310 | |
| 311 | def _is_computed(field: Mapping[str, Any]) -> bool: |
| 312 | return bool(field.get("computed")) or str(field.get("type") or "").lower() == "computed" |
| 313 | |
| 314 | |
| 315 | def formula_fields(fields: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]: |
| 316 | return [ |
| 317 | f for f in fields |
| 318 | if _is_computed(f) and isinstance(f.get("formula"), str) and f["formula"].strip() |
| 319 | ] |
| 320 | |
| 321 | |
| 322 | def rollup_fields(fields: Iterable[Mapping[str, Any]]) -> list[Mapping[str, Any]]: |
| 323 | out = [] |
| 324 | for f in fields: |
| 325 | rollup = f.get("rollup") |
| 326 | if _is_computed(f) and isinstance(rollup, Mapping): |
| 327 | if rollup.get("collection") and rollup.get("fk_field") and rollup.get("op") in ROLLUP_OPS: |
| 328 | out.append(f) |
| 329 | return out |
| 330 | |
| 331 | |
| 332 | def apply_formulas(fields: Iterable[Mapping[str, Any]], record: dict[str, Any]) -> dict[str, Any]: |
| 333 | """Return record with every formula field recomputed (rollup values on the |
| 334 | record are visible to formulas -- callers apply rollups first).""" |
| 335 | specs = formula_fields(fields) |
| 336 | if not specs: |
| 337 | return record |
| 338 | out = dict(record) |
| 339 | for field in specs: |
| 340 | name = field["name"] |
| 341 | try: |
| 342 | out[name] = evaluate_formula(field["formula"], out) |
| 343 | except FormulaError: |
| 344 | out[name] = "" |
| 345 | return out |
| 346 | |
| 347 | |
| 348 | def compute_rollup(rollup: Mapping[str, Any], children: list[Mapping[str, Any]]) -> str: |
| 349 | """Aggregate child rows per the rollup spec; returns the stored string.""" |
| 350 | where = rollup.get("where") |
| 351 | if isinstance(where, Mapping) and where: |
| 352 | children = [ |
| 353 | c for c in children |
| 354 | if all(str(c.get(k, "")) == str(v) for k, v in where.items()) |
| 355 | ] |
| 356 | op = rollup["op"] |
| 357 | if op == "count": |
| 358 | return str(len(children)) |
| 359 | values = [] |
| 360 | for child in children: |
| 361 | number = _to_number(child.get(rollup.get("field", ""), "")) |
| 362 | if number is not None: |
| 363 | values.append(number) |
| 364 | if not values: |
| 365 | return "0" if op == "sum" else "" |
| 366 | if op == "sum": |
| 367 | return _result_to_string(sum(values)) |
| 368 | if op == "min": |
| 369 | return _result_to_string(min(values)) |
| 370 | if op == "max": |
| 371 | return _result_to_string(max(values)) |
| 372 | with localcontext() as ctx: |
| 373 | ctx.prec = _PRECISION |
| 374 | return _result_to_string(Decimal(sum(values)) / Decimal(len(values))) |