Files
Docwell/Server/internal/convert/database.go
T
tajniak81andClaude Opus 5.5 8814293988
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
Add formula properties to databases
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>
2026-11-17 13:34:04 +01:00

521 lines
13 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"encoding/json"
"math"
"sort"
"strings"
"time"
)
// Databases (ADR-13) reach the converters as "database" nodes whose
// attrs.data holds the records, written by yrs from the page's Y.Doc. Every
// export draws one as its title and a table of the first view's visible
// columns, in the rows' own order.
// expandDatabases replaces database nodes, at any depth, with a title and a table.
// Relations and rollups read the page's other databases; one on another page
// shows how many records it links to.
func expandDatabases(n Node) Node {
all := map[string]map[string]any{}
var collect func(Node)
collect = func(x Node) {
if x.Type == "database" {
if data, _ := x.Attrs["data"].(map[string]any); data != nil {
all[str(x.Attrs["id"])] = data
}
}
for _, c := range x.Content {
collect(c)
}
}
collect(n)
return expandWith(n, all)
}
func expandWith(n Node, all map[string]map[string]any) Node {
if len(n.Content) == 0 {
return n
}
out := make([]Node, 0, len(n.Content))
for _, c := range n.Content {
if c.Type == "database" {
out = append(out, databaseNodes(c, all)...)
} else {
out = append(out, expandWith(c, all))
}
}
n.Content = out
return n
}
type dbColumn struct {
id, name, typ string
options map[string]string
// relation: the related database (same page only; empty when on another page).
// relBack, when set, makes this the two-way side of the related database's
// relation column relBack: its links are read from there, not stored here.
relPage, relDB, relBack string
// rollup: the relation column, the related property ("" = the records) and the function.
rollRel, rollProp, rollFn string
// formula: the expression of a formula column (formula.go).
formula string
}
func readColumns(data map[string]any) []dbColumn {
var cols []dbColumn
for _, raw := range list(data["columns"]) {
c, _ := raw.(map[string]any)
id, _ := c["id"].(string)
if id == "" {
continue
}
col := dbColumn{id: id, typ: str(c["type"]), name: str(c["name"]), options: map[string]string{}}
for _, o := range list(c["options"]) {
if om, ok := o.(map[string]any); ok {
col.options[str(om["id"])] = str(om["name"])
}
}
if r, ok := c["relation"].(map[string]any); ok {
col.relPage, col.relDB, col.relBack = str(r["page"]), str(r["database"]), str(r["back"])
}
if r, ok := c["rollup"].(map[string]any); ok {
col.rollRel, col.rollProp, col.rollFn = str(r["relation"]), str(r["property"]), str(r["fn"])
}
col.formula = str(c["formula"])
cols = append(cols, col)
}
return cols
}
func databaseNodes(n Node, all map[string]map[string]any) []Node {
data, _ := n.Attrs["data"].(map[string]any)
if data == nil {
return nil
}
cols := readColumns(data)
// The first view decides which columns show.
hidden := map[string]bool{}
if views := list(data["views"]); len(views) > 0 {
if v, ok := views[0].(map[string]any); ok {
for _, h := range list(v["hidden"]) {
hidden[str(h)] = true
}
}
}
shown := cols[:0:0]
for _, c := range cols {
if c.typ == "title" || !hidden[c.id] {
shown = append(shown, c)
}
}
if len(shown) == 0 {
return nil
}
cell := func(typ, text string) Node {
p := Node{Type: "paragraph"}
if text != "" {
p.Content = []Node{{Type: "text", Text: text}}
}
return Node{Type: typ, Content: []Node{p}}
}
head := Node{Type: "tableRow"}
for _, c := range shown {
head.Content = append(head.Content, cell("tableHeader", c.name))
}
table := Node{Type: "table", Content: []Node{head}}
for _, raw := range list(data["rows"]) {
r, _ := raw.(map[string]any)
if r == nil {
continue
}
row := Node{Type: "tableRow"}
var text func(c dbColumn) string
formulas := newRowFormulas(cols, r, func(c dbColumn) string { return text(c) }, formulaNow())
text = func(c dbColumn) string {
switch c.typ {
case "relation":
return relationText(c, r, all)
case "rollup":
return rollupText(c, cols, r, all)
case "formula":
return formulas.formulaText(c)
}
return cellText(c, r)
}
for _, c := range shown {
text := text(c)
row.Content = append(row.Content, cell("tableCell", text))
}
table.Content = append(table.Content, row)
}
var out []Node
if title := str(data["title"]); title != "" {
out = append(out, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: title, Marks: []Mark{{Type: "bold"}}}}})
}
return append(out, table)
}
// formulaNow is the time formulas see in exports (a variable for tests).
var formulaNow = func() time.Time { return time.Now().UTC() }
// cellText is a cell as text, like cellText in Packages/editor/src/database/model.ts.
func cellText(c dbColumn, row map[string]any) string {
cells, _ := row["cells"].(map[string]any)
v := cells[c.id]
switch c.typ {
case "createdTime":
if ms, ok := row["createdAt"].(float64); ok && ms > 0 {
return time.UnixMilli(int64(ms)).UTC().Format("2006-01-02")
}
return ""
case "createdBy":
if p, ok := row["createdBy"].(map[string]any); ok {
return str(p["name"])
}
return ""
case "checkbox":
if v == true {
return "✓"
}
return ""
case "select":
return c.options[str(v)]
case "multiSelect":
var names []string
for _, id := range list(v) {
if name := c.options[str(id)]; name != "" {
names = append(names, name)
}
}
return strings.Join(names, ", ")
case "member", "attachment":
var names []string
for _, x := range list(v) {
if m, ok := x.(map[string]any); ok && str(m["name"]) != "" {
names = append(names, str(m["name"]))
}
}
return strings.Join(names, ", ")
case "progress":
if f, ok := v.(float64); ok {
return formatNumber(f) + "%"
}
return ""
}
switch x := v.(type) {
case string:
return x
case float64:
return formatNumber(x)
}
return ""
}
func list(v any) []any {
l, _ := v.([]any)
return l
}
func str(v any) string {
s, _ := v.(string)
return s
}
// Record is one database record as search sees it (ADR-13).
type Record struct {
Database, Row string
Title string // the title property
Text string // the other properties and the record's body
}
// Records lists the records of every database in a page's content_json.
func Records(raw json.RawMessage) ([]Record, error) {
doc, err := Parse(raw)
if err != nil {
return nil, err
}
var out []Record
var walk func(n Node)
walk = func(n Node) {
if n.Type == "database" {
out = append(out, databaseRecords(n)...)
return
}
for _, c := range n.Content {
walk(c)
}
}
walk(doc)
return out, nil
}
func databaseRecords(n Node) []Record {
data, _ := n.Attrs["data"].(map[string]any)
db := n.attr("id")
if data == nil || db == "" {
return nil
}
var cols []dbColumn
for _, raw := range list(data["columns"]) {
c, _ := raw.(map[string]any)
col := dbColumn{id: str(c["id"]), typ: str(c["type"]), options: map[string]string{}}
for _, o := range list(c["options"]) {
if om, ok := o.(map[string]any); ok {
col.options[str(om["id"])] = str(om["name"])
}
}
if col.id != "" {
cols = append(cols, col)
}
}
var out []Record
for _, raw := range list(data["rows"]) {
r, _ := raw.(map[string]any)
if r == nil || str(r["id"]) == "" {
continue
}
rec := Record{Database: db, Row: str(r["id"])}
var parts []string
for _, c := range cols {
// Checkmarks and dates the record was made say nothing to search for.
if c.typ == "checkbox" || c.typ == "createdTime" {
continue
}
t := cellText(c, r)
if c.typ == "title" {
rec.Title = t
} else if t != "" {
parts = append(parts, t)
}
}
parts = jsonText(r["body"], parts)
rec.Text = strings.Join(parts, " ")
out = append(out, rec)
}
return out
}
// jsonText appends the text of ProseMirror JSON (a node or a list of them).
func jsonText(v any, parts []string) []string {
switch x := v.(type) {
case []any:
for _, c := range x {
parts = jsonText(c, parts)
}
case map[string]any:
if t, ok := x["text"].(string); ok && t != "" {
parts = append(parts, t)
}
parts = jsonText(x["content"], parts)
}
return parts
}
// related returns the rows a relation cell links to and the related
// database's columns; ok is false when the database is on another page.
func related(c dbColumn, row map[string]any, all map[string]map[string]any) (rows []map[string]any, cols []dbColumn, ids []string, ok bool) {
target := all[c.relDB]
if c.relBack != "" {
// Two-way: the related records are those whose relBack cell links to this row.
if c.relPage != "" || target == nil {
return nil, nil, nil, false
}
self := str(row["id"])
for _, raw := range list(target["rows"]) {
r, _ := raw.(map[string]any)
cells, _ := r["cells"].(map[string]any)
for _, id := range list(cells[c.relBack]) {
if str(id) == self && self != "" {
rows = append(rows, r)
ids = append(ids, str(r["id"]))
break
}
}
}
return rows, readColumns(target), ids, true
}
cells, _ := row["cells"].(map[string]any)
for _, id := range list(cells[c.id]) {
if s := str(id); s != "" {
ids = append(ids, s)
}
}
if c.relPage != "" || target == nil {
return nil, nil, ids, false
}
byID := map[string]map[string]any{}
for _, raw := range list(target["rows"]) {
if r, _ := raw.(map[string]any); r != nil {
byID[str(r["id"])] = r
}
}
for _, id := range ids {
if r := byID[id]; r != nil {
rows = append(rows, r)
}
}
return rows, readColumns(target), ids, true
}
func titleOf(cols []dbColumn) *dbColumn {
for i := range cols {
if cols[i].typ == "title" {
return &cols[i]
}
}
return nil
}
// relationText is the related records' titles, like computeLinked in linked.ts.
func relationText(c dbColumn, row map[string]any, all map[string]map[string]any) string {
rows, cols, ids, ok := related(c, row, all)
if !ok {
if len(ids) == 0 {
return ""
}
return formatNumber(float64(len(ids))) + " linked"
}
title := titleOf(cols)
var names []string
for _, r := range rows {
if title != nil {
names = append(names, cellText(*title, r))
}
}
return strings.Join(names, ", ")
}
// rollupText works out a rollup cell, like rollup in linked.ts.
func rollupText(c dbColumn, cols []dbColumn, row map[string]any, all map[string]map[string]any) string {
var rel *dbColumn
for i := range cols {
if cols[i].id == c.rollRel && cols[i].typ == "relation" {
rel = &cols[i]
}
}
if rel == nil {
return ""
}
rows, tcols, _, ok := related(*rel, row, all)
if !ok {
return ""
}
prop := titleOf(tcols)
if c.rollProp != "" {
prop = nil
for i := range tcols {
if tcols[i].id == c.rollProp {
prop = &tcols[i]
}
}
}
var texts []string
var nums []float64
var dates []string
checked := 0
for _, r := range rows {
if prop == nil {
texts = append(texts, "")
continue
}
t := cellText(*prop, r)
cells, _ := r["cells"].(map[string]any)
if prop.typ == "checkbox" {
if cells[prop.id] == true {
checked++
t = "✓"
} else {
t = ""
}
}
texts = append(texts, t)
if f, ok := cells[prop.id].(float64); ok {
nums = append(nums, f)
}
if len(t) >= 10 && (prop.typ == "date" || prop.typ == "createdTime") {
dates = append(dates, t[:10])
}
}
filled := 0
unique := map[string]bool{}
for _, t := range texts {
if t != "" {
filled++
unique[t] = true
}
}
sort.Float64s(nums)
sort.Strings(dates)
num := func(f float64) string { return formatNumber(math.Round(f*100) / 100) }
pct := func(n int) string {
if len(rows) == 0 {
return ""
}
return num(float64(n)*100/float64(len(rows))) + "%"
}
sum := 0.0
for _, f := range nums {
sum += f
}
switch c.rollFn {
case "count", "":
return num(float64(len(rows)))
case "countValues", "countNotEmpty":
return num(float64(filled))
case "countUnique":
return num(float64(len(unique)))
case "countEmpty":
return num(float64(len(rows) - filled))
case "percentNotEmpty":
return pct(filled)
case "checked":
return num(float64(checked))
case "percentChecked":
return pct(checked)
case "earliest":
if len(dates) > 0 {
return dates[0]
}
return ""
case "latest":
if len(dates) > 0 {
return dates[len(dates)-1]
}
return ""
case "showOriginal":
var shown []string
for _, t := range texts {
if t != "" {
shown = append(shown, t)
}
}
return strings.Join(shown, ", ")
}
if len(nums) == 0 {
return ""
}
switch c.rollFn {
case "sum":
return num(sum)
case "average":
return num(sum / float64(len(nums)))
case "median":
m := len(nums) / 2
if len(nums)%2 == 1 {
return num(nums[m])
}
return num((nums[m-1] + nums[m]) / 2)
case "min":
return num(nums[0])
case "max":
return num(nums[len(nums)-1])
case "range":
return num(nums[len(nums)-1] - nums[0])
}
return ""
}