CI / frontend (push) Successful in 14m34s
CI / desktop (ubuntu-latest) (push) Successful in 1h16m25s
CI / docker (push) Successful in 31m59s
CI / mobile (push) Failing after 4m3s
CI / go (Media) (push) Successful in 14m9s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / go (Server) (push) Failing after 20m28s
CI / desktop (windows-latest) (push) Canceled after 0s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / go (Web-App) (push) Canceled after 0s
A formula column keeps an expression and works it out for each record
when the database is read, after relations and rollups, like rollups;
nothing is stored per record. The language is small and hand-parsed:
prop("Name"), numbers, text, yes/no and days, arithmetic, comparisons,
and/or/not, if(), rounding, min/max, text functions and date arithmetic
(today, dateAdd, dateBetween, year/month/day). Errors, loops between
formulas included, stay in their cells with the reason as a tooltip.
The column's editor shows the first record's result or the error as
you type and inserts properties by name. Formulas sort, filter and chart
like numbers when they are numbers. The server evaluates the same
language for exports (convert/formula.go), with the same test cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
878 lines
20 KiB
Go
878 lines
20 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package convert
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Formula columns (ADR-20), for exports: the same language as
|
|
// Packages/editor/src/database/formula.ts, which documents it. Keep the two
|
|
// in step. A formula that fails exports as an empty cell.
|
|
|
|
type fvDay struct{ day string }
|
|
|
|
// fval is a formula value: float64, string, bool, fvDay or nil.
|
|
type fval = any
|
|
|
|
type formulaError struct{ msg string }
|
|
|
|
func (e *formulaError) Error() string { return e.msg }
|
|
|
|
func ferr(format string, a ...any) error { return &formulaError{fmt.Sprintf(format, a...)} }
|
|
|
|
type fnode struct {
|
|
kind string // num, str, bool, prop, un, bin, call
|
|
num float64
|
|
str string // string literal, property name, operator or function
|
|
b bool
|
|
args []*fnode
|
|
}
|
|
|
|
type ftoken struct {
|
|
t string // num, str, id, op, end
|
|
v string
|
|
at int
|
|
}
|
|
|
|
const (
|
|
formulaMaxLength = 2000
|
|
formulaMaxDepth = 64
|
|
)
|
|
|
|
var numberToken = regexp.MustCompile(`^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?`)
|
|
|
|
func ftokenize(src string) ([]ftoken, error) {
|
|
var out []ftoken
|
|
rs := []rune(src)
|
|
for i := 0; i < len(rs); {
|
|
c := rs[i]
|
|
switch {
|
|
case unicode.IsSpace(c):
|
|
i++
|
|
case c >= '0' && c <= '9' || c == '.':
|
|
m := numberToken.FindString(string(rs[i:]))
|
|
if m == "" {
|
|
return nil, ferr("Unexpected %q at %d", string(c), i+1)
|
|
}
|
|
out = append(out, ftoken{"num", m, i})
|
|
i += utf8.RuneCountInString(m)
|
|
case c == '"':
|
|
var sb strings.Builder
|
|
j := i + 1
|
|
for ; j < len(rs) && rs[j] != '"'; j++ {
|
|
if rs[j] == '\\' && j+1 < len(rs) {
|
|
j++
|
|
if rs[j] == 'n' {
|
|
sb.WriteRune('\n')
|
|
} else {
|
|
sb.WriteRune(rs[j])
|
|
}
|
|
} else {
|
|
sb.WriteRune(rs[j])
|
|
}
|
|
}
|
|
if j >= len(rs) {
|
|
return nil, ferr("Text starting at %d has no closing quote", i+1)
|
|
}
|
|
out = append(out, ftoken{"str", sb.String(), i})
|
|
i = j + 1
|
|
case c == '_' || c < 128 && unicode.IsLetter(c):
|
|
j := i
|
|
for j < len(rs) && (rs[j] == '_' || rs[j] < 128 && (unicode.IsLetter(rs[j]) || unicode.IsDigit(rs[j]))) {
|
|
j++
|
|
}
|
|
out = append(out, ftoken{"id", string(rs[i:j]), i})
|
|
i = j
|
|
default:
|
|
if i+1 < len(rs) {
|
|
two := string(rs[i : i+2])
|
|
switch two {
|
|
case "<=", ">=", "==", "!=", "&&", "||":
|
|
out = append(out, ftoken{"op", two, i})
|
|
i += 2
|
|
continue
|
|
}
|
|
}
|
|
if strings.ContainsRune("+-*/%<>(),!", c) {
|
|
out = append(out, ftoken{"op", string(c), i})
|
|
i++
|
|
continue
|
|
}
|
|
return nil, ferr("Unexpected %q at %d", string(c), i+1)
|
|
}
|
|
}
|
|
return append(out, ftoken{"end", "", len(rs)}), nil
|
|
}
|
|
|
|
var formulaFuncs = map[string][2]int{
|
|
"if": {3, 3}, "abs": {1, 1}, "round": {1, 2}, "floor": {1, 1}, "ceil": {1, 1}, "min": {1, -1}, "max": {1, -1},
|
|
"length": {1, 1}, "lower": {1, 1}, "upper": {1, 1}, "contains": {2, 2}, "concat": {1, -1}, "empty": {1, 1},
|
|
"tonumber": {1, 1}, "format": {1, 1}, "today": {0, 0}, "now": {0, 0}, "dateadd": {3, 3}, "datebetween": {3, 3},
|
|
"year": {1, 1}, "month": {1, 1}, "day": {1, 1},
|
|
}
|
|
|
|
type fparser struct {
|
|
toks []ftoken
|
|
p int
|
|
depth int
|
|
}
|
|
|
|
func (ps *fparser) peek() ftoken { return ps.toks[ps.p] }
|
|
func (ps *fparser) isOp(ops ...string) bool {
|
|
t := ps.peek()
|
|
if t.t != "op" {
|
|
return false
|
|
}
|
|
for _, o := range ops {
|
|
if t.v == o {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
func (ps *fparser) isWord(w string) bool {
|
|
t := ps.peek()
|
|
return t.t == "id" && strings.ToLower(t.v) == w
|
|
}
|
|
func (ps *fparser) deeper() error {
|
|
ps.depth++
|
|
if ps.depth > formulaMaxDepth {
|
|
return ferr("The formula is nested too deeply")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (ps *fparser) binary(next func() (*fnode, error), match func() string) (*fnode, error) {
|
|
a, err := next()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for op := match(); op != ""; op = match() {
|
|
b, err := next()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
a = &fnode{kind: "bin", str: op, args: []*fnode{a, b}}
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
func (ps *fparser) or() (*fnode, error) {
|
|
return ps.binary(ps.and, func() string {
|
|
if ps.isOp("||") || ps.isWord("or") {
|
|
ps.p++
|
|
return "or"
|
|
}
|
|
return ""
|
|
})
|
|
}
|
|
func (ps *fparser) and() (*fnode, error) {
|
|
return ps.binary(ps.eq, func() string {
|
|
if ps.isOp("&&") || ps.isWord("and") {
|
|
ps.p++
|
|
return "and"
|
|
}
|
|
return ""
|
|
})
|
|
}
|
|
func (ps *fparser) take(ops ...string) func() string {
|
|
return func() string {
|
|
if ps.isOp(ops...) {
|
|
ps.p++
|
|
return ps.toks[ps.p-1].v
|
|
}
|
|
return ""
|
|
}
|
|
}
|
|
func (ps *fparser) eq() (*fnode, error) { return ps.binary(ps.cmp, ps.take("==", "!=")) }
|
|
func (ps *fparser) cmp() (*fnode, error) { return ps.binary(ps.add, ps.take("<", "<=", ">", ">=")) }
|
|
func (ps *fparser) add() (*fnode, error) { return ps.binary(ps.mul, ps.take("+", "-")) }
|
|
func (ps *fparser) mul() (*fnode, error) { return ps.binary(ps.unary, ps.take("*", "/", "%")) }
|
|
|
|
func (ps *fparser) unary() (*fnode, error) {
|
|
op := ""
|
|
if ps.isOp("-") {
|
|
op = "-"
|
|
} else if ps.isOp("!") || ps.isWord("not") {
|
|
op = "not"
|
|
}
|
|
if op == "" {
|
|
return ps.atom()
|
|
}
|
|
ps.p++
|
|
if err := ps.deeper(); err != nil {
|
|
return nil, err
|
|
}
|
|
a, err := ps.unary()
|
|
ps.depth--
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &fnode{kind: "un", str: op, args: []*fnode{a}}, nil
|
|
}
|
|
|
|
func (ps *fparser) expect(v string) error {
|
|
if !ps.isOp(v) {
|
|
return ferr("Expected %q at %d", v, ps.peek().at+1)
|
|
}
|
|
ps.p++
|
|
return nil
|
|
}
|
|
|
|
func (ps *fparser) atom() (*fnode, error) {
|
|
tok := ps.peek()
|
|
switch {
|
|
case tok.t == "num":
|
|
ps.p++
|
|
f, _ := strconv.ParseFloat(tok.v, 64)
|
|
return &fnode{kind: "num", num: f}, nil
|
|
case tok.t == "str":
|
|
ps.p++
|
|
return &fnode{kind: "str", str: tok.v}, nil
|
|
case ps.isOp("("):
|
|
ps.p++
|
|
if err := ps.deeper(); err != nil {
|
|
return nil, err
|
|
}
|
|
e, err := ps.or()
|
|
ps.depth--
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return e, ps.expect(")")
|
|
case tok.t == "id":
|
|
ps.p++
|
|
word := strings.ToLower(tok.v)
|
|
if word == "true" || word == "false" {
|
|
return &fnode{kind: "bool", b: word == "true"}, nil
|
|
}
|
|
if !ps.isOp("(") {
|
|
return nil, ferr("Unknown name %q at %d; write prop(%q) for a property", tok.v, tok.at+1, tok.v)
|
|
}
|
|
ps.p++
|
|
if err := ps.deeper(); err != nil {
|
|
return nil, err
|
|
}
|
|
var args []*fnode
|
|
if !ps.isOp(")") {
|
|
for {
|
|
a, err := ps.or()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
args = append(args, a)
|
|
if !ps.isOp(",") {
|
|
break
|
|
}
|
|
ps.p++
|
|
}
|
|
}
|
|
ps.depth--
|
|
if err := ps.expect(")"); err != nil {
|
|
return nil, err
|
|
}
|
|
if word == "prop" {
|
|
if len(args) != 1 || args[0].kind != "str" {
|
|
return nil, ferr("prop() takes a property name in quotes, at %d", tok.at+1)
|
|
}
|
|
return &fnode{kind: "prop", str: args[0].str}, nil
|
|
}
|
|
arity, ok := formulaFuncs[word]
|
|
if !ok {
|
|
return nil, ferr("Unknown function %q at %d", tok.v, tok.at+1)
|
|
}
|
|
if len(args) < arity[0] || arity[1] >= 0 && len(args) > arity[1] {
|
|
return nil, ferr("%s() takes a different number of arguments", tok.v)
|
|
}
|
|
return &fnode{kind: "call", str: word, args: args}, nil
|
|
}
|
|
if tok.t == "end" {
|
|
return nil, ferr("The formula ends too early")
|
|
}
|
|
return nil, ferr("Unexpected %q at %d", tok.v, tok.at+1)
|
|
}
|
|
|
|
func parseFormula(src string) (*fnode, error) {
|
|
if utf8.RuneCountInString(src) > formulaMaxLength {
|
|
return nil, ferr("A formula can have at most %d characters", formulaMaxLength)
|
|
}
|
|
if strings.TrimSpace(src) == "" {
|
|
return nil, ferr("The formula is empty")
|
|
}
|
|
toks, err := ftokenize(src)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
ps := &fparser{toks: toks}
|
|
tree, err := ps.or()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if ps.peek().t != "end" {
|
|
return nil, ferr("Unexpected %q at %d", ps.peek().v, ps.peek().at+1)
|
|
}
|
|
return tree, nil
|
|
}
|
|
|
|
// ---- Values ----
|
|
|
|
func formatFormula(v fval) string {
|
|
switch x := v.(type) {
|
|
case nil:
|
|
return ""
|
|
case float64:
|
|
if math.IsInf(x, 0) || math.IsNaN(x) {
|
|
return ""
|
|
}
|
|
return formatNumber(math.Round(x*1e10) / 1e10)
|
|
case bool:
|
|
if x {
|
|
return "true"
|
|
}
|
|
return "false"
|
|
case fvDay:
|
|
return x.day
|
|
case string:
|
|
return x
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func fnum(v fval, fn string) (float64, error) {
|
|
switch x := v.(type) {
|
|
case float64:
|
|
return x, nil
|
|
case nil:
|
|
return 0, nil
|
|
case bool:
|
|
if x {
|
|
return 1, nil
|
|
}
|
|
return 0, nil
|
|
case string:
|
|
if x == "" {
|
|
return 0, nil
|
|
}
|
|
if f, err := strconv.ParseFloat(strings.Replace(strings.TrimSpace(x), ",", ".", 1), 64); err == nil {
|
|
return f, nil
|
|
}
|
|
}
|
|
return 0, ferr("%s needs a number, not %q", fn, formatFormula(v))
|
|
}
|
|
|
|
var isoDay = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
|
|
|
|
func fday(v fval, fn string) (string, error) {
|
|
if d, ok := v.(fvDay); ok {
|
|
return d.day, nil
|
|
}
|
|
if s, ok := v.(string); ok && isoDay.MatchString(s) {
|
|
return s, nil
|
|
}
|
|
return "", ferr("%s needs a date", fn)
|
|
}
|
|
|
|
func truthy(v fval) bool {
|
|
switch x := v.(type) {
|
|
case bool:
|
|
return x
|
|
case float64:
|
|
return x != 0
|
|
case fvDay:
|
|
return true
|
|
case string:
|
|
return x != ""
|
|
}
|
|
return false
|
|
}
|
|
|
|
func parseDay(d string) time.Time {
|
|
t, _ := time.Parse("2006-01-02", d)
|
|
return t
|
|
}
|
|
|
|
func shiftDay(d string, n float64, unit string) (string, error) {
|
|
t := parseDay(d)
|
|
whole := int(n)
|
|
switch unit {
|
|
case "days":
|
|
return t.AddDate(0, 0, whole).Format("2006-01-02"), nil
|
|
case "weeks":
|
|
return t.AddDate(0, 0, whole*7).Format("2006-01-02"), nil
|
|
case "months", "years":
|
|
months := whole
|
|
if unit == "years" {
|
|
months *= 12
|
|
}
|
|
first := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, months, 0)
|
|
last := first.AddDate(0, 1, -1).Day()
|
|
dd := t.Day()
|
|
if dd > last {
|
|
dd = last
|
|
}
|
|
return time.Date(first.Year(), first.Month(), dd, 0, 0, 0, 0, time.UTC).Format("2006-01-02"), nil
|
|
}
|
|
return "", ferr("Unknown unit %q; use days, weeks, months or years", unit)
|
|
}
|
|
|
|
func daysBetween(a, b string, unit string) (float64, error) {
|
|
ta, tb := parseDay(a), parseDay(b)
|
|
days := math.Round(ta.Sub(tb).Hours() / 24)
|
|
switch unit {
|
|
case "days":
|
|
return days, nil
|
|
case "weeks":
|
|
return math.Trunc(days / 7), nil
|
|
case "months", "years":
|
|
months := (ta.Year()-tb.Year())*12 + int(ta.Month()) - int(tb.Month())
|
|
if months > 0 && ta.Day() < tb.Day() {
|
|
months--
|
|
}
|
|
if months < 0 && ta.Day() > tb.Day() {
|
|
months++
|
|
}
|
|
if unit == "years" {
|
|
return math.Trunc(float64(months) / 12), nil
|
|
}
|
|
return float64(months), nil
|
|
}
|
|
return 0, ferr("Unknown unit %q; use days, weeks, months or years", unit)
|
|
}
|
|
|
|
func fequal(a, b fval) bool {
|
|
_, da := a.(fvDay)
|
|
_, db := b.(fvDay)
|
|
if da || db {
|
|
return formatFormula(a) == formatFormula(b)
|
|
}
|
|
_, na := a.(float64)
|
|
_, nb := b.(float64)
|
|
if na || nb {
|
|
if a == nil || b == nil {
|
|
return a == b
|
|
}
|
|
x, err1 := fnum(a, "==")
|
|
y, err2 := fnum(b, "==")
|
|
return err1 == nil && err2 == nil && x == y
|
|
}
|
|
// Like (a ?? "") === (b ?? "") in formula.ts: nothing equals empty text,
|
|
// and a yes/no only equals another yes/no.
|
|
ba, isBa := a.(bool)
|
|
bb, isBb := b.(bool)
|
|
if isBa || isBb {
|
|
return isBa && isBb && ba == bb
|
|
}
|
|
return formatFormula(a) == formatFormula(b)
|
|
}
|
|
|
|
func fcompare(a, b fval) (float64, error) {
|
|
_, da := a.(fvDay)
|
|
_, db := b.(fvDay)
|
|
if da || db {
|
|
return float64(strings.Compare(formatFormula(a), formatFormula(b))), nil
|
|
}
|
|
sa, oka := a.(string)
|
|
sb, okb := b.(string)
|
|
if oka && okb {
|
|
return float64(strings.Compare(sa, sb)), nil
|
|
}
|
|
x, err := fnum(a, "Comparing")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
y, err := fnum(b, "Comparing")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return x - y, nil
|
|
}
|
|
|
|
type formulaScope struct {
|
|
prop func(name string) (fval, error)
|
|
today, now string
|
|
}
|
|
|
|
func (sc *formulaScope) eval(n *fnode) (fval, error) {
|
|
switch n.kind {
|
|
case "num":
|
|
return n.num, nil
|
|
case "str":
|
|
return n.str, nil
|
|
case "bool":
|
|
return n.b, nil
|
|
case "prop":
|
|
return sc.prop(n.str)
|
|
case "un":
|
|
a, err := sc.eval(n.args[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n.str == "-" {
|
|
x, err := fnum(a, "-")
|
|
return -x, err
|
|
}
|
|
return !truthy(a), nil
|
|
case "bin":
|
|
if n.str == "and" || n.str == "or" {
|
|
a, err := sc.eval(n.args[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if n.str == "and" && !truthy(a) || n.str == "or" && truthy(a) {
|
|
return n.str == "or", nil
|
|
}
|
|
b, err := sc.eval(n.args[1])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return truthy(b), nil
|
|
}
|
|
a, err := sc.eval(n.args[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
b, err := sc.eval(n.args[1])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return binaryOp(n.str, a, b)
|
|
case "call":
|
|
return sc.call(n.str, n.args)
|
|
}
|
|
return nil, ferr("Unknown formula part")
|
|
}
|
|
|
|
func binaryOp(op string, a, b fval) (fval, error) {
|
|
ad, aDay := a.(fvDay)
|
|
bd, bDay := b.(fvDay)
|
|
_, aStr := a.(string)
|
|
_, bStr := b.(string)
|
|
_, aBool := a.(bool)
|
|
_, bBool := b.(bool)
|
|
switch op {
|
|
case "+":
|
|
if aStr || bStr || aBool || bBool {
|
|
if aDay {
|
|
if x, ok := b.(float64); ok {
|
|
d, err := shiftDay(ad.day, x, "days")
|
|
return fvDay{d}, err
|
|
}
|
|
}
|
|
return formatFormula(a) + formatFormula(b), nil
|
|
}
|
|
if aDay {
|
|
x, err := fnum(b, "+")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
d, err := shiftDay(ad.day, x, "days")
|
|
return fvDay{d}, err
|
|
}
|
|
if bDay {
|
|
x, err := fnum(a, "+")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
d, err := shiftDay(bd.day, x, "days")
|
|
return fvDay{d}, err
|
|
}
|
|
case "-":
|
|
if aDay && bDay {
|
|
return daysBetween(ad.day, bd.day, "days")
|
|
}
|
|
if aDay {
|
|
x, err := fnum(b, "-")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
d, err := shiftDay(ad.day, -x, "days")
|
|
return fvDay{d}, err
|
|
}
|
|
case "==":
|
|
return fequal(a, b), nil
|
|
case "!=":
|
|
return !fequal(a, b), nil
|
|
case "<", "<=", ">", ">=":
|
|
c, err := fcompare(a, b)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]bool{"<": c < 0, "<=": c <= 0, ">": c > 0, ">=": c >= 0}[op], nil
|
|
}
|
|
x, err := fnum(a, op)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
y, err := fnum(b, op)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
switch op {
|
|
case "+":
|
|
return x + y, nil
|
|
case "-":
|
|
return x - y, nil
|
|
case "*":
|
|
return x * y, nil
|
|
case "/", "%":
|
|
if y == 0 {
|
|
return nil, ferr("Division by zero")
|
|
}
|
|
if op == "/" {
|
|
return x / y, nil
|
|
}
|
|
return math.Mod(x, y), nil
|
|
}
|
|
return nil, ferr("Unknown operator %s", op)
|
|
}
|
|
|
|
func (sc *formulaScope) call(fn string, args []*fnode) (fval, error) {
|
|
if fn == "if" {
|
|
c, err := sc.eval(args[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if truthy(c) {
|
|
return sc.eval(args[1])
|
|
}
|
|
return sc.eval(args[2])
|
|
}
|
|
v := make([]fval, len(args))
|
|
for i, a := range args {
|
|
x, err := sc.eval(a)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
v[i] = x
|
|
}
|
|
one := func(name string, f func(float64) float64) (fval, error) {
|
|
x, err := fnum(v[0], name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return f(x), nil
|
|
}
|
|
switch fn {
|
|
case "abs":
|
|
return one("abs", math.Abs)
|
|
case "floor":
|
|
return one("floor", math.Floor)
|
|
case "ceil":
|
|
return one("ceil", math.Ceil)
|
|
case "round":
|
|
digits := 0.0
|
|
if len(v) > 1 {
|
|
d, err := fnum(v[1], "round")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
digits = math.Min(math.Max(math.Trunc(d), 0), 10)
|
|
}
|
|
f := math.Pow(10, digits)
|
|
// Halves round up, like JavaScript's Math.round.
|
|
return one("round", func(x float64) float64 { return math.Floor(x*f+0.5) / f })
|
|
case "min", "max":
|
|
var best float64
|
|
for i, x := range v {
|
|
n, err := fnum(x, fn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if i == 0 || fn == "min" && n < best || fn == "max" && n > best {
|
|
best = n
|
|
}
|
|
}
|
|
return best, nil
|
|
case "length":
|
|
return float64(utf8.RuneCountInString(formatFormula(v[0]))), nil
|
|
case "lower":
|
|
return strings.ToLower(formatFormula(v[0])), nil
|
|
case "upper":
|
|
return strings.ToUpper(formatFormula(v[0])), nil
|
|
case "contains":
|
|
return strings.Contains(strings.ToLower(formatFormula(v[0])), strings.ToLower(formatFormula(v[1]))), nil
|
|
case "concat":
|
|
var sb strings.Builder
|
|
for _, x := range v {
|
|
sb.WriteString(formatFormula(x))
|
|
}
|
|
return sb.String(), nil
|
|
case "empty":
|
|
return v[0] == nil || formatFormula(v[0]) == "", nil
|
|
case "tonumber":
|
|
n, err := fnum(v[0], "toNumber")
|
|
if err != nil {
|
|
return nil, nil
|
|
}
|
|
return n, nil
|
|
case "format":
|
|
return formatFormula(v[0]), nil
|
|
case "today":
|
|
return fvDay{sc.today}, nil
|
|
case "now":
|
|
return sc.now, nil
|
|
case "dateadd":
|
|
d, err := fday(v[0], "dateAdd")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
n, err := fnum(v[1], "dateAdd")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out, err := shiftDay(d, n, formatFormula(v[2]))
|
|
return fvDay{out}, err
|
|
case "datebetween":
|
|
a, err := fday(v[0], "dateBetween")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
b, err := fday(v[1], "dateBetween")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return daysBetween(a, b, formatFormula(v[2]))
|
|
case "year", "month", "day":
|
|
d, err := fday(v[0], fn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
t := parseDay(d)
|
|
return float64(map[string]int{"year": t.Year(), "month": int(t.Month()), "day": t.Day()}[fn]), nil
|
|
}
|
|
return nil, ferr("Unknown function %q", fn)
|
|
}
|
|
|
|
// ---- Records ----
|
|
|
|
// rowFormulas works out the formula cells of one record for an export. text
|
|
// gives another column's cell as text (relations and rollups included).
|
|
type rowFormulas struct {
|
|
cols []dbColumn
|
|
row map[string]any
|
|
text func(c dbColumn) string
|
|
results map[string]fval
|
|
errs map[string]error
|
|
busy map[string]bool
|
|
now time.Time
|
|
}
|
|
|
|
func newRowFormulas(cols []dbColumn, row map[string]any, text func(c dbColumn) string, now time.Time) *rowFormulas {
|
|
return &rowFormulas{cols: cols, row: row, text: text, results: map[string]fval{}, errs: map[string]error{}, busy: map[string]bool{}, now: now}
|
|
}
|
|
|
|
func (rf *rowFormulas) byName(name string) *dbColumn {
|
|
for i := range rf.cols {
|
|
if rf.cols[i].name == name {
|
|
return &rf.cols[i]
|
|
}
|
|
}
|
|
for i := range rf.cols {
|
|
if strings.EqualFold(rf.cols[i].name, name) {
|
|
return &rf.cols[i]
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// propValue is a property as a formula sees it, like propValue in formula.ts.
|
|
func (rf *rowFormulas) propValue(c dbColumn) (fval, error) {
|
|
cells, _ := rf.row["cells"].(map[string]any)
|
|
switch c.typ {
|
|
case "number", "progress":
|
|
if f, ok := cells[c.id].(float64); ok {
|
|
return f, nil
|
|
}
|
|
return nil, nil
|
|
case "checkbox":
|
|
return cells[c.id] == true, nil
|
|
case "date", "createdTime":
|
|
if d := cellText(c, rf.row); len(d) >= 10 && isoDay.MatchString(d[:10]) {
|
|
return fvDay{d[:10]}, nil
|
|
}
|
|
return nil, nil
|
|
case "rollup":
|
|
t := rf.text(c)
|
|
if f, err := strconv.ParseFloat(t, 64); err == nil {
|
|
return f, nil
|
|
}
|
|
if t == "" {
|
|
return nil, nil
|
|
}
|
|
return t, nil
|
|
case "formula":
|
|
v, err := rf.value(c)
|
|
if err != nil {
|
|
var fe *formulaError
|
|
if e, ok := err.(*formulaError); ok && strings.HasPrefix(e.msg, fmt.Sprintf("%q", c.name)) {
|
|
fe = e
|
|
}
|
|
if fe != nil {
|
|
return nil, fe
|
|
}
|
|
return nil, ferr("%q has an error", c.name)
|
|
}
|
|
return v, nil
|
|
}
|
|
if t := rf.text(c); t != "" {
|
|
return t, nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
func (rf *rowFormulas) value(c dbColumn) (fval, error) {
|
|
if v, ok := rf.results[c.id]; ok {
|
|
return v, rf.errs[c.id]
|
|
}
|
|
if rf.busy[c.id] {
|
|
return nil, ferr("%q refers to itself through other formulas", c.name)
|
|
}
|
|
rf.busy[c.id] = true
|
|
defer delete(rf.busy, c.id)
|
|
var v fval
|
|
tree, err := parseFormula(c.formula)
|
|
if err == nil {
|
|
sc := &formulaScope{
|
|
today: rf.now.Format("2006-01-02"),
|
|
now: rf.now.Format("2006-01-02 15:04"),
|
|
prop: func(name string) (fval, error) {
|
|
col := rf.byName(name)
|
|
if col == nil {
|
|
return nil, ferr("No property called %q", name)
|
|
}
|
|
return rf.propValue(*col)
|
|
},
|
|
}
|
|
v, err = sc.eval(tree)
|
|
if f, ok := v.(float64); ok && (math.IsInf(f, 0) || math.IsNaN(f)) {
|
|
v = nil
|
|
}
|
|
}
|
|
rf.results[c.id], rf.errs[c.id] = v, err
|
|
return v, err
|
|
}
|
|
|
|
// formulaText is a formula cell as an export shows it: "" when it fails, ✓
|
|
// for a true one like a checkbox.
|
|
func (rf *rowFormulas) formulaText(c dbColumn) string {
|
|
v, err := rf.value(c)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
if b, ok := v.(bool); ok {
|
|
if b {
|
|
return "✓"
|
|
}
|
|
return ""
|
|
}
|
|
return formatFormula(v)
|
|
}
|