Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Refresh chained database rollups transitively

Danield07c4719a8c8
diff --git a/kernel/av/relation.go b/kernel/av/relation.go
index 2ac37ab448..cf36ab4b7b 100644
--- a/kernel/av/relation.go
+++ b/kernel/av/relation.go
@@ -99,6 +99,35 @@ func GetSrcAvIDs(destAvID string) []string {
return srcAvIDs
}
+// GetSrcAvIDsForRefresh 按广度优先顺序收集需要刷新的直接和间接关联源,不包含起始数据库。
+func GetSrcAvIDsForRefresh(destAvIDs []string) []string {
+ return collectSrcAvIDsForRefresh(destAvIDs, GetSrcAvIDs)
+}
+
+func collectSrcAvIDsForRefresh(destAvIDs []string, getSrcAvIDs func(string) []string) (ret []string) {
+ visited := map[string]bool{}
+ var queue []string
+ for _, avID := range destAvIDs {
+ if visited[avID] {
+ continue
+ }
+ visited[avID] = true
+ queue = append(queue, avID)
+ }
+
+ for i := 0; i < len(queue); i++ {
+ for _, srcAvID := range getSrcAvIDs(queue[i]) {
+ if visited[srcAvID] {
+ continue
+ }
+ visited[srcAvID] = true
+ queue = append(queue, srcAvID)
+ ret = append(ret, srcAvID)
+ }
+ }
+ return
+}
+
func RemoveAvRel(srcAvID, destAvID string) {
attributeViewRelationsLock.Lock()
defer attributeViewRelationsLock.Unlock()
diff --git a/kernel/av/relation_refresh_test.go b/kernel/av/relation_refresh_test.go
new file mode 100644
index 0000000000..a591c216f4
--- /dev/null
+++ b/kernel/av/relation_refresh_test.go
@@ -0,0 +1,195 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package av
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestCollectSrcAvIDsForRefresh(t *testing.T) {
+ tests := []struct {
+ name string
+ seeds []string
+ graph map[string][]string
+ want []string
+ }{
+ {
+ name: "empty seeds",
+ graph: map[string][]string{"A": {"B"}},
+ },
+ {
+ name: "three databases",
+ seeds: []string{"A"},
+ graph: map[string][]string{"A": {"B"}, "B": {"C"}},
+ want: []string{"B", "C"},
+ },
+ {
+ name: "four databases",
+ seeds: []string{"A"},
+ graph: map[string][]string{"A": {"B"}, "B": {"C"}, "C": {"D"}},
+ want: []string{"B", "C", "D"},
+ },
+ {
+ name: "diamond",
+ seeds: []string{"A"},
+ graph: map[string][]string{"A": {"B", "C"}, "B": {"D"}, "C": {"D"}},
+ want: []string{"B", "C", "D"},
+ },
+ {
+ name: "cycle with dependent",
+ seeds: []string{"A"},
+ graph: map[string][]string{"A": {"B"}, "B": {"C"}, "C": {"A", "D"}},
+ want: []string{"B", "C", "D"},
+ },
+ {
+ name: "self loops",
+ seeds: []string{"A"},
+ graph: map[string][]string{"A": {"A", "B"}, "B": {"B", "C"}, "C": {"C"}},
+ want: []string{"B", "C"},
+ },
+ {
+ name: "duplicates and multiple connected seeds",
+ seeds: []string{"A", "B", "A"},
+ graph: map[string][]string{"A": {"B", "B", "C"}, "B": {"D", "C"}, "C": {"D", "A"}},
+ want: []string{"C", "D"},
+ },
+ {
+ name: "multiple independent seeds and disconnected graph",
+ seeds: []string{"A", "X"},
+ graph: map[string][]string{"A": {"B"}, "B": {"C"}, "X": {"Y"}, "Y": {"Z"}, "Q": {"R"}},
+ want: []string{"B", "Y", "C", "Z"},
+ },
+ {
+ name: "no dependents",
+ seeds: []string{"A"},
+ graph: map[string][]string{"Q": {"R"}},
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ originalSeeds := append([]string(nil), test.seeds...)
+ calls := map[string]int{}
+ got := collectSrcAvIDsForRefresh(test.seeds, func(avID string) []string {
+ calls[avID]++
+ if calls[avID] != 1 {
+ t.Fatalf("database %s was visited more than once", avID)
+ }
+ return test.graph[avID]
+ })
+ if !reflect.DeepEqual(got, test.want) {
+ t.Fatalf("unexpected dependent databases: got %v, want %v", got, test.want)
+ }
+ if !reflect.DeepEqual(test.seeds, originalSeeds) {
+ t.Fatalf("refresh traversal changed its seeds: got %v, want %v", test.seeds, originalSeeds)
+ }
+ wantCalls := map[string]int{}
+ for _, avID := range append(originalSeeds, test.want...) {
+ wantCalls[avID] = 1
+ }
+ if !reflect.DeepEqual(calls, wantCalls) {
+ t.Fatalf("unexpected database lookups: got %v, want %v", calls, wantCalls)
+ }
+ })
+ }
+}
+
+func TestGetSrcAvIDsForRefreshUsesPersistedBoxRelations(t *testing.T) {
+ previousDataDir := util.DataDir
+ previousDEKProvider := AVDEKProvider
+ previousEncryptedBoxIDs := AVEncryptedBoxIDs
+ previousLockAcquire, previousLockRelease := AVLockAcquire, AVLockRelease
+ util.DataDir = t.TempDir()
+ AVLockAcquire, AVLockRelease = nil, nil
+ t.Cleanup(func() {
+ util.DataDir = previousDataDir
+ AVDEKProvider = previousDEKProvider
+ AVEncryptedBoxIDs = previousEncryptedBoxIDs
+ AVLockAcquire, AVLockRelease = previousLockAcquire, previousLockRelease
+ })
+
+ scopes := []struct {
+ name string
+ boxID string
+ ids []string
+ }{
+ {name: "plain", ids: []string{ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()}},
+ {name: "encrypted box one", boxID: ast.NewNodeID(), ids: []string{ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()}},
+ {name: "encrypted box two", boxID: ast.NewNodeID(), ids: []string{ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()}},
+ }
+ keys := map[string][]byte{
+ scopes[1].boxID: []byte("0123456789abcdef0123456789abcdef"),
+ scopes[2].boxID: []byte("abcdef0123456789abcdef0123456789"),
+ }
+ AVDEKProvider = func(boxID string) ([]byte, error) { return keys[boxID], nil }
+ AVEncryptedBoxIDs = func() []string { return []string{scopes[1].boxID, scopes[2].boxID} }
+ for _, scope := range scopes {
+ for _, avID := range scope.ids {
+ avPath := attributeViewDataPathByBox(avID, scope.boxID)
+ if err := os.MkdirAll(filepath.Dir(avPath), 0755); nil != err {
+ t.Fatalf("create database directory failed: %v", err)
+ }
+ data, err := encryptAVData(scope.boxID, avID, []byte("{}"))
+ if nil != err {
+ t.Fatalf("encrypt database fixture failed: %v", err)
+ }
+ if err = os.WriteFile(avPath, data, 0644); nil != err {
+ t.Fatalf("write database fixture failed: %v", err)
+ }
+ }
+ }
+
+ for _, scope := range scopes {
+ relations := map[string][]string{
+ scope.ids[0]: {scope.ids[1]},
+ scope.ids[1]: {scope.ids[2]},
+ scope.ids[2]: {scope.ids[0]},
+ }
+ // 其他分箱中的同名索引项不能影响当前数据库的通知范围。
+ for _, otherScope := range scopes {
+ if scope.boxID == otherScope.boxID {
+ continue
+ }
+ for _, avID := range otherScope.ids {
+ relations[avID] = []string{ast.NewNodeID()}
+ }
+ }
+ writeRelations(scope.boxID, relations)
+ }
+
+ for _, scope := range scopes {
+ t.Run(scope.name, func(t *testing.T) {
+ if got := GetSrcAvIDs(scope.ids[0]); !reflect.DeepEqual(got, scope.ids[1:2]) {
+ t.Fatalf("direct relation lookup changed: got %v, want %v", got, scope.ids[1:2])
+ }
+ if got := GetSrcAvIDsForRefresh(scope.ids[:1]); !reflect.DeepEqual(got, scope.ids[1:]) {
+ t.Fatalf("unexpected box-scoped dependents: got %v, want %v", got, scope.ids[1:])
+ }
+ })
+ }
+
+ seeds := []string{scopes[0].ids[0], scopes[1].ids[0], scopes[2].ids[0]}
+ want := []string{scopes[0].ids[1], scopes[1].ids[1], scopes[2].ids[1], scopes[0].ids[2], scopes[1].ids[2], scopes[2].ids[2]}
+ if got := GetSrcAvIDsForRefresh(seeds); !reflect.DeepEqual(got, want) {
+ t.Fatalf("unexpected mixed-scope dependents: got %v, want %v", got, want)
+ }
+}
diff --git a/kernel/av/rollup_nested_test.go b/kernel/av/rollup_nested_test.go
new file mode 100644
index 0000000000..b2929d6401
--- /dev/null
+++ b/kernel/av/rollup_nested_test.go
@@ -0,0 +1,104 @@
+package av
+
+import (
+ "encoding/json"
+ "fmt"
+ "reflect"
+ "testing"
+)
+
+func TestNestedRollupBuildContentsUsesCalculatedValues(t *testing.T) {
+ for _, innerOperator := range []CalcOperator{CalcOperatorNone, CalcOperatorSum} {
+ for _, outerOperator := range []CalcOperator{CalcOperatorNone, CalcOperatorSum, CalcOperatorCountAll} {
+ t.Run(fmt.Sprintf("%s/%s", innerOperator, outerOperator), func(t *testing.T) {
+ numberKey := &Key{ID: "number", Type: KeyTypeNumber}
+ leaf := &AttributeView{ID: "leaf", KeyValues: []*KeyValues{{Key: numberKey, Values: []*Value{
+ {KeyID: numberKey.ID, BlockID: "first", Type: KeyTypeNumber,
+ Number: &ValueNumber{Content: 3, IsNotEmpty: true}},
+ {KeyID: numberKey.ID, BlockID: "second", Type: KeyTypeNumber,
+ Number: &ValueNumber{Content: 7, IsNotEmpty: true}},
+ }}}}
+ inner := &ValueRollup{}
+ inner.BuildContents(leaf, numberKey,
+ &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"first", "second"}}},
+ &RollupCalc{Operator: innerOperator}, nil)
+ targetKey := &Key{ID: "rollup", Type: KeyTypeRollup}
+ stored := &Value{KeyID: targetKey.ID, BlockID: "target", Type: KeyTypeRollup,
+ Rollup: &ValueRollup{Contents: []*Value{{Type: KeyTypeNumber,
+ Number: &ValueNumber{Content: 999, IsNotEmpty: true}}}}}
+ target := &AttributeView{ID: "target", KeyValues: []*KeyValues{{Key: targetKey, Values: []*Value{stored}}}}
+ rendered := &Value{KeyID: targetKey.ID, BlockID: "target", Type: KeyTypeRollup, Rollup: inner}
+ collection := &Table{Rows: []*TableRow{{ID: "target", Cells: []*TableCell{{
+ BaseValue: &BaseValue{Value: rendered, ValueType: KeyTypeRollup},
+ }}}}}
+ before, err := json.Marshal([]*Value{stored, rendered})
+ if err != nil {
+ t.Fatal(err)
+ }
+ outer := &ValueRollup{}
+ outer.BuildContents(target, targetKey,
+ &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"target"}}},
+ &RollupCalc{Operator: outerOperator}, &RollupRenderContext{FurtherCollection: collection})
+ want := []float64{3, 7}
+ if innerOperator == CalcOperatorSum || outerOperator == CalcOperatorSum {
+ want = []float64{10}
+ }
+ if outerOperator == CalcOperatorCountAll {
+ want = []float64{float64(len(inner.Contents))}
+ }
+ var got []float64
+ for _, value := range outer.Contents {
+ if value.Type != KeyTypeNumber || value.Number == nil || !value.Number.IsNotEmpty {
+ t.Fatalf("nested calculation left a wrapper or invalid scalar: %+v", value)
+ }
+ got = append(got, value.Number.Content)
+ value.Number.Content = -1
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("outer calculation = %v, want %v", got, want)
+ }
+ after, err := json.Marshal([]*Value{stored, rendered})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(after) != string(before) {
+ t.Fatal("outer calculation or result mutation changed stored or rendered target values")
+ }
+ })
+ }
+ }
+}
+
+func TestNestedRollupBuildContentsDoesNotFallBackToStaleStoredValues(t *testing.T) {
+ key := &Key{ID: "rollup", Type: KeyTypeRollup}
+ stored := &Value{KeyID: key.ID, BlockID: "target", Type: KeyTypeRollup,
+ Rollup: &ValueRollup{Contents: []*Value{{Type: KeyTypeText, Text: &ValueText{Content: "stale"}}}}}
+ target := &AttributeView{KeyValues: []*KeyValues{{Key: key, Values: []*Value{stored}}}}
+ for _, state := range []string{"missing-row", "nil-rollup", "empty-rollup", "nil-content"} {
+ t.Run(state, func(t *testing.T) {
+ collection := &Table{}
+ if state != "missing-row" {
+ value := &Value{KeyID: key.ID, BlockID: "target", Type: KeyTypeRollup}
+ if state != "nil-rollup" {
+ value.Rollup = &ValueRollup{}
+ if state == "nil-content" {
+ value.Rollup.Contents = []*Value{nil}
+ }
+ }
+ collection.Rows = []*TableRow{{ID: "target", Cells: []*TableCell{{
+ BaseValue: &BaseValue{Value: value, ValueType: KeyTypeRollup},
+ }}}}
+ }
+ result := &ValueRollup{Contents: []*Value{{Type: KeyTypeText, Text: &ValueText{Content: "old outer"}}}}
+ result.BuildContents(target, key,
+ &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"target"}}},
+ &RollupCalc{Operator: CalcOperatorNone}, &RollupRenderContext{FurtherCollection: collection})
+ if len(result.Contents) != 0 {
+ t.Fatalf("%s reused old results: %+v", state, result.Contents)
+ }
+ if stored.String(true) != "stale" {
+ t.Fatal("empty calculated target changed the stored rollup")
+ }
+ })
+ }
+}
diff --git a/kernel/av/value.go b/kernel/av/value.go
index 3592b075d1..19fb8494dd 100644
--- a/kernel/av/value.go
+++ b/kernel/av/value.go
@@ -2718,7 +2718,7 @@ func (r *ValueRollup) BuildContents(attrView *AttributeView, destKey *Key, relat
destVal := GetValue(attrView.KeyValues, destKey.ID, blockID)
if nil != context && nil != context.FurtherCollection &&
- (KeyTypeTemplate == destKey.Type || KeyTypeUpdated == destKey.Type || KeyTypeCreated == destKey.Type) {
+ (KeyTypeTemplate == destKey.Type || KeyTypeUpdated == destKey.Type || KeyTypeCreated == destKey.Type || KeyTypeRollup == destKey.Type) {
destVal = context.FurtherCollection.GetValue(blockID, destKey.ID)
}
@@ -2731,6 +2731,17 @@ func (r *ValueRollup) BuildContents(attrView *AttributeView, destKey *Key, relat
continue
}
+ if KeyTypeRollup == destKey.Type {
+ // 嵌套汇总使用目标字段的计算结果,保持外层显示、筛选和统计的值类型一致。
+ if nil != destVal.Rollup {
+ for _, content := range destVal.Rollup.Contents {
+ if nil != content {
+ r.Contents = append(r.Contents, content.Clone())
+ }
+ }
+ }
+ continue
+ }
if val := destVal.GetValByType(destKey.Type); nil == val || reflect.ValueOf(val).IsNil() {
// 目标字段因为修改类型导致空值
continue
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index a6c27d1a0d..f0f73d5985 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -8482,18 +8482,7 @@ func refreshRelatedSrcAvs(destAvID string, tx *Transaction) {
}
func refreshRelatedSrcAvsInBlock(destAvID, blockID string, tx *Transaction) {
- relatedAvIDs := av.GetSrcAvIDs(destAvID)
-
- var tmp []string
- for _, relatedAvID := range relatedAvIDs {
- if relatedAvID == destAvID {
- // 目标和源相同则跳过
- continue
- }
-
- tmp = append(tmp, relatedAvID)
- }
- relatedAvIDs = tmp
+ relatedAvIDs := av.GetSrcAvIDsForRefresh([]string{destAvID})
if nil != tx {
tx.relatedAvIDs = append(tx.relatedAvIDs, relatedAvIDs...)
diff --git a/kernel/model/attribute_view_refresh_test.go b/kernel/model/attribute_view_refresh_test.go
new file mode 100644
index 0000000000..3d8019c66a
--- /dev/null
+++ b/kernel/model/attribute_view_refresh_test.go
@@ -0,0 +1,86 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestRefreshRelatedSrcAvsQueuesTransitiveDependents(t *testing.T) {
+ tests := []struct {
+ name string
+ relations [][2]string
+ want []string
+ }{
+ {
+ name: "chain",
+ relations: [][2]string{{"B", "A"}, {"C", "B"}},
+ want: []string{"B", "C"},
+ },
+ {
+ name: "diamond with cycles and self loops",
+ relations: [][2]string{
+ {"A", "A"}, {"B", "A"}, {"C", "A"}, {"D", "B"},
+ {"D", "C"}, {"A", "D"}, {"B", "B"}, {"D", "D"},
+ },
+ want: []string{"B", "C", "D"},
+ },
+ {
+ name: "self loop only",
+ relations: [][2]string{{"A", "A"}},
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ previousDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() { util.DataDir = previousDataDir })
+
+ avDir := filepath.Join(util.DataDir, "storage", "av")
+ if err := os.MkdirAll(avDir, 0755); nil != err {
+ t.Fatal(err)
+ }
+ ids := map[string]string{}
+ for _, name := range []string{"A", "B", "C", "D"} {
+ ids[name] = ast.NewNodeID()
+ if err := os.WriteFile(filepath.Join(avDir, ids[name]+".json"), []byte("{}"), 0644); nil != err {
+ t.Fatal(err)
+ }
+ }
+ for _, relation := range test.relations {
+ av.UpsertAvBackRel(ids[relation[0]], ids[relation[1]])
+ }
+
+ tx := &Transaction{}
+ refreshRelatedSrcAvs(ids["A"], tx)
+ var want []string
+ for _, name := range test.want {
+ want = append(want, ids[name])
+ }
+ if !reflect.DeepEqual(tx.relatedAvIDs, want) {
+ t.Fatalf("unexpected queued refreshes: got %v, want %v", tx.relatedAvIDs, want)
+ }
+ })
+ }
+}
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index c8590ff280..089eae3ccd 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -2321,12 +2321,8 @@ func upsertAvBlockRel(node *ast.Node) {
time.Sleep(100 * time.Millisecond)
affectedAvIDs = gulu.Str.RemoveDuplicatedElem(affectedAvIDs)
- var relatedAvIDs []string
- for _, avID := range affectedAvIDs {
- relatedAvIDs = append(relatedAvIDs, av.GetSrcAvIDs(avID)...)
- }
+ relatedAvIDs := av.GetSrcAvIDsForRefresh(affectedAvIDs)
affectedAvIDs = append(affectedAvIDs, relatedAvIDs...)
- affectedAvIDs = gulu.Str.RemoveDuplicatedElem(affectedAvIDs)
for _, avID := range affectedAvIDs {
attrView, _ := av.ParseAttributeView(avID)
if nil != attrView {
diff --git a/kernel/sql/av.go b/kernel/sql/av.go
index 255ff9f38b..a326888ee9 100644
--- a/kernel/sql/av.go
+++ b/kernel/sql/av.go
@@ -47,6 +47,7 @@ type GroupViewRenderSource struct {
type AttributeViewRenderContext struct {
templateErrors map[string]*attributeViewTemplateRenderError
renderingRelationTemplates bool
+ renderingRollupTargets map[rollupTargetID]bool
ReadOnly bool // 预览只允许修正内存副本,不保存缺失字段等订正结果。
}
@@ -782,7 +783,9 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collection
isSameAv := destAv.ID == attrView.ID
var furtherCollection av.Collection
- if av.KeyTypeTemplate == destKey.Type || (!isSameAv && (av.KeyTypeUpdated == destKey.Type || av.KeyTypeCreated == destKey.Type || av.KeyTypeRelation == destKey.Type)) {
+ if av.KeyTypeRollup == destKey.Type {
+ furtherCollection = renderRollupTarget(destAv, destKey, depth, cachedAttrViews, renderContext)
+ } else if av.KeyTypeTemplate == destKey.Type || (!isSameAv && (av.KeyTypeUpdated == destKey.Type || av.KeyTypeCreated == destKey.Type || av.KeyTypeRelation == destKey.Type)) {
viewable := renderView(destAv, destAv.Views[0], "", depth, cachedAttrViews, false, false, renderContext)
if nil != viewable {
furtherCollection = viewable.(av.Collection)
@@ -793,7 +796,8 @@ func fillAttributeViewAutoGeneratedValues(attrView *av.AttributeView, collection
}
context := &av.RollupRenderContext{FurtherCollection: furtherCollection}
if hasFilterConditions(rollupKey.Rollup.Filters) {
- context.EligibleItemIDs = filterAttributeViewItemIDs(destAv, rollupKey.Rollup.Filters, depth,
+ filterDepth := *depth
+ context.EligibleItemIDs = filterAttributeViewItemIDs(destAv, rollupKey.Rollup.Filters, &filterDepth,
cachedAttrViews, renderContext)
}
rollupRenderContexts[rollupKey.ID] = context
@@ -945,7 +949,9 @@ func getFurtherCollections(attrView *av.AttributeView, cachedAttrViews map[strin
isSameAv := destAv.ID == attrView.ID
var furtherCollection av.Collection
- if av.KeyTypeTemplate == destKey.Type || (!isSameAv && (av.KeyTypeUpdated == destKey.Type || av.KeyTypeCreated == destKey.Type || av.KeyTypeRelation == destKey.Type)) {
+ if av.KeyTypeRollup == destKey.Type {
+ furtherCollection = renderRollupTarget(destAv, destKey, depth, cachedAttrViews, renderContext)
+ } else if av.KeyTypeTemplate == destKey.Type || (!isSameAv && (av.KeyTypeUpdated == destKey.Type || av.KeyTypeCreated == destKey.Type || av.KeyTypeRelation == destKey.Type)) {
viewable := renderView(destAv, destAv.Views[0], "", depth, cachedAttrViews, false, false, renderContext)
if nil != viewable {
furtherCollection = viewable.(av.Collection)
@@ -953,7 +959,8 @@ func getFurtherCollections(attrView *av.AttributeView, cachedAttrViews map[strin
}
context := &av.RollupRenderContext{FurtherCollection: furtherCollection}
if hasFilterConditions(kv.Key.Rollup.Filters) {
- context.EligibleItemIDs = filterAttributeViewItemIDs(destAv, kv.Key.Rollup.Filters, depth,
+ filterDepth := *depth
+ context.EligibleItemIDs = filterAttributeViewItemIDs(destAv, kv.Key.Rollup.Filters, &filterDepth,
cachedAttrViews, renderContext)
}
ret[kv.Key.ID] = context
diff --git a/kernel/sql/av_rollup_target.go b/kernel/sql/av_rollup_target.go
new file mode 100644
index 0000000000..29890424d3
--- /dev/null
+++ b/kernel/sql/av_rollup_target.go
@@ -0,0 +1,71 @@
+package sql
+
+import (
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+type rollupTargetID struct {
+ avID string
+ keyID string
+}
+
+// renderRollupTarget 按目标字段计算完整条目集合,不受目标视图的布局、分组和分页影响。
+func renderRollupTarget(target *av.AttributeView, key *av.Key, depth *int,
+ cachedAttrViews map[string]*av.AttributeView, context *AttributeViewRenderContext) av.Collection {
+ // 循环依赖或深度受限时返回空集合,禁止读取持久化的过期汇总内容。
+ empty := &av.Table{}
+ if nil == target || nil == key || nil == key.Rollup || 7 < *depth {
+ return empty
+ }
+ id := rollupTargetID{avID: target.ID, keyID: key.ID}
+ if context.renderingRollupTargets[id] {
+ return empty
+ }
+ if nil == context.renderingRollupTargets {
+ context.renderingRollupTargets = map[rollupTargetID]bool{}
+ }
+ context.renderingRollupTargets[id] = true
+ defer delete(context.renderingRollupTargets, id)
+
+ // 独立副本避免自关联和菱形依赖修改外层正在计算的值。
+ cloned := *target
+ cloned.KeyValues = nil
+ cloned.RenderedViewables = nil
+ view := &av.View{ID: ast.NewNodeID(), LayoutType: av.LayoutTypeTable, Table: av.NewLayoutTable()}
+ for _, keyValues := range target.KeyValues {
+ if nil == keyValues || nil == keyValues.Key {
+ continue
+ }
+ copiedKey := *keyValues.Key
+ copiedKey.RenderTemplate = ""
+ copied := &av.KeyValues{Key: &copiedKey}
+ for _, value := range keyValues.Values {
+ if nil != value {
+ clonedValue := av.CloneStoredValue(value).Clone()
+ if copiedKey.ID == key.ID {
+ // 关联条目或目标字段已删除时,不能保留上次渲染的汇总内容。
+ clonedValue.Rollup = &av.ValueRollup{}
+ }
+ copied.Values = append(copied.Values, clonedValue)
+ }
+ }
+ cloned.KeyValues = append(cloned.KeyValues, copied)
+ if av.KeyTypeBlock == copiedKey.Type || copiedKey.ID == key.ID || copiedKey.ID == key.Rollup.RelationKeyID {
+ view.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: copiedKey.ID}})
+ }
+ }
+ cache := make(map[string]*av.AttributeView, len(cachedAttrViews)+1)
+ for avID, attrView := range cachedAttrViews {
+ cache[avID] = attrView
+ }
+ cache[target.ID] = &cloned
+
+ // 每条依赖分支使用独立深度,兄弟字段不会消耗彼此的递归预算。
+ nestedDepth := *depth
+ viewable := renderView(&cloned, view, "", &nestedDepth, cache, false, false, context)
+ if nil == viewable {
+ return empty
+ }
+ return viewable.(av.Collection)
+}
diff --git a/kernel/sql/av_rollup_target_test.go b/kernel/sql/av_rollup_target_test.go
new file mode 100644
index 0000000000..797bcadabd
--- /dev/null
+++ b/kernel/sql/av_rollup_target_test.go
@@ -0,0 +1,435 @@
+package sql
+
+import (
+ "encoding/json"
+ "fmt"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+)
+
+func TestNestedRollupRefreshWithoutRenderingIntermediate(t *testing.T) {
+ for _, typ := range []av.KeyType{av.KeyTypeText, av.KeyTypeNumber, av.KeyTypeBlock} {
+ for _, stale := range []bool{false, true} {
+ for _, levels := range []int{3, 4} {
+ t.Run(fmt.Sprintf("%s/stale=%v/levels=%d", typ, stale, levels), func(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(typ)
+ cache := map[string]*av.AttributeView{leaf.ID: leaf}
+ outer, outerKey := leaf, leafKey
+ var intermediate []*av.AttributeView
+ for level := 1; level < levels; level++ {
+ outer, outerKey = newNestedRollupTestLevel(fmt.Sprintf("level-%d", level), outer, outerKey, stale)
+ cache[outer.ID] = outer
+ if level < levels-1 {
+ intermediate = append(intermediate, outer)
+ }
+ }
+ before := nestedRollupTestSnapshot(t, intermediate)
+ for update := 0; update < 4; update++ {
+ for row, value := range nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values {
+ switch typ {
+ case av.KeyTypeText:
+ value.Text.Content = fmt.Sprintf("updated-%d-%d", update, row)
+ case av.KeyTypeNumber:
+ value.Number.Content = float64(update*10 + row + 1)
+ case av.KeyTypeBlock:
+ value.Block.Content = fmt.Sprintf("updated-%d-%d", update, row)
+ }
+ }
+ collection := renderNestedRollupTestView(t, outer, cache)
+ for row, block := range outer.GetBlockKeyValues().Values {
+ got := collection.GetValue(block.BlockID, outerKey.ID)
+ want := nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values[row].String(true)
+ if got == nil || got.String(true) != want {
+ t.Fatalf("update %d row %d: got %v, want %q", update, row, got, want)
+ }
+ if len(got.Rollup.Contents) != 1 || got.Rollup.Contents[0].Type != typ {
+ t.Fatalf("nested result did not preserve scalar type %s: %+v", typ, got.Rollup.Contents)
+ }
+ }
+ if after := nestedRollupTestSnapshot(t, intermediate); after != before {
+ t.Fatal("rendering the outer rollup changed stored intermediate values")
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestRenderRollupTargetIgnoresPresentationAndPreservesSource(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ target, key := newNestedRollupTestLevel("target", leaf, leafKey, true)
+ view := target.Views[0]
+ view.Table.Columns = view.Table.Columns[:1]
+ view.Table.Columns[0].Hidden = true
+ view.Group = &av.ViewGroup{Field: target.GetBlockKey().ID}
+ view.GroupItemIDs = []string{target.GetBlockKeyValues().Values[1].BlockID}
+ view.PageSize = 1
+ view.Filters = []*av.ViewFilter{{Column: target.GetBlockKey().ID, Operator: av.FilterOperatorIsEqual,
+ Value: &av.Value{Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "excluded"}}}}
+ key.RenderTemplate = "should not become stored rollup content"
+ staleRendered := &av.Table{BaseInstance: av.NewViewBaseInstance(view)}
+ target.RenderedViewables[view.ID] = staleRendered
+ before := nestedRollupTestSnapshot(t, []*av.AttributeView{leaf, target})
+ depth := 2
+ context := NewAttributeViewRenderContext()
+ collection := renderRollupTarget(target, key, &depth,
+ map[string]*av.AttributeView{target.ID: target, leaf.ID: leaf}, context)
+ if len(collection.GetItems()) != 2 {
+ t.Fatalf("target presentation removed related items: %d", len(collection.GetItems()))
+ }
+ for row, block := range target.GetBlockKeyValues().Values {
+ value := collection.GetValue(block.BlockID, key.ID)
+ if value == nil || value.String(true) != nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values[row].String(true) {
+ t.Fatalf("target row %d was not freshly calculated: %+v", row, value)
+ }
+ value.Rollup.Contents[0].Text.Content = "mutated rendered clone"
+ }
+ if after := nestedRollupTestSnapshot(t, []*av.AttributeView{leaf, target}); after != before {
+ t.Fatal("target rendering changed original keys, stored values, or views")
+ }
+ if target.RenderedViewables[view.ID] != staleRendered || depth != 2 || len(context.renderingRollupTargets) != 0 {
+ t.Fatal("target rendering changed the original view cache or leaked recursion state")
+ }
+}
+
+func TestNestedRollupDiamondDoesNotConsumeSiblingDepth(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ shared, sharedKey := newNestedRollupTestLevel("shared", leaf, leafKey, true)
+ cache := map[string]*av.AttributeView{leaf.ID: leaf, shared.ID: shared}
+ outer := newNestedRollupTestDatabase("outer")
+ var keys []*av.Key
+ for branch := 0; branch < 12; branch++ {
+ target, targetKey := newNestedRollupTestLevel(fmt.Sprintf("branch-%d", branch), shared, sharedKey, true)
+ cache[target.ID] = target
+ keys = append(keys, addNestedRollupTestFields(outer, target, targetKey, false))
+ }
+ cache[outer.ID] = outer
+ for repeat := 0; repeat < 2; repeat++ {
+ if repeat == 1 {
+ for _, key := range keys {
+ key.Rollup.Filters = nestedRollupTestFilters(key.Rollup.KeyID, "fresh-0")
+ }
+ }
+ collection := renderNestedRollupTestView(t, outer, cache)
+ for _, key := range keys {
+ for row, block := range outer.GetBlockKeyValues().Values {
+ value := collection.GetValue(block.BlockID, key.ID)
+ want := nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values[row].String(true)
+ if repeat == 1 && row == 1 {
+ want = ""
+ }
+ if value == nil || value.String(true) != want {
+ t.Fatalf("sibling %s row %d lost its dependency: %+v", key.ID, row, value)
+ }
+ }
+ }
+ }
+}
+
+func TestRenderRollupTargetCyclesAndDepthDoNotUseStoredContents(t *testing.T) {
+ for _, self := range []bool{true, false} {
+ t.Run(fmt.Sprintf("self=%v", self), func(t *testing.T) {
+ first := newNestedRollupTestDatabase("first")
+ second := first
+ if !self {
+ second = newNestedRollupTestDatabase("second")
+ }
+ firstKey := addNestedRollupTestFields(first, second, second.GetBlockKey(), true)
+ secondKey := firstKey
+ if !self {
+ secondKey = addNestedRollupTestFields(second, first, firstKey, true)
+ }
+ firstKey.Rollup.KeyID = secondKey.ID
+ cache := map[string]*av.AttributeView{first.ID: first, second.ID: second}
+ before := nestedRollupTestSnapshot(t, []*av.AttributeView{first, second})
+ context := NewAttributeViewRenderContext()
+ depth := 2
+ for repeat := 0; repeat < 2; repeat++ {
+ collection := renderRollupTarget(first, firstKey, &depth, cache, context)
+ for _, item := range collection.GetItems() {
+ if value := collection.GetValue(item.GetID(), firstKey.ID); value == nil || value.String(true) != "" {
+ t.Fatalf("cycle reused stored contents: %+v", value)
+ }
+ }
+ if depth != 2 || len(context.renderingRollupTargets) != 0 {
+ t.Fatal("cycle detection leaked its guard or consumed outer depth")
+ }
+ }
+ depth = 8
+ if collection := renderRollupTarget(first, firstKey, &depth, cache, context); len(collection.GetItems()) != 0 {
+ t.Fatal("depth-limited rendering reused stored contents")
+ }
+ if nestedRollupTestSnapshot(t, []*av.AttributeView{first, second}) != before {
+ t.Fatal("cycle rendering modified original values")
+ }
+ })
+ }
+}
+
+func TestRenderRollupTargetAllowsDifferentFieldsInSameDatabase(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ first := addNestedRollupTestFields(leaf, leaf, leafKey, true)
+ second := addNestedRollupTestFields(leaf, leaf, first, true)
+ outer, outerKey := newNestedRollupTestLevel("outer", leaf, second, true)
+ collection := renderNestedRollupTestView(t, outer, map[string]*av.AttributeView{leaf.ID: leaf, outer.ID: outer})
+ for row, block := range outer.GetBlockKeyValues().Values {
+ value := collection.GetValue(block.BlockID, outerKey.ID)
+ if value == nil || value.String(true) != nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values[row].String(true) {
+ t.Fatalf("different fields in the same database were treated as a cycle: %+v", value)
+ }
+ }
+}
+
+func TestRenderRollupTargetCyclicFilterDependencyTerminates(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ target, key := newNestedRollupTestLevel("target", leaf, leafKey, true)
+ backlink := addNestedRollupTestFields(leaf, target, key, true)
+ key.Rollup.Filters = nestedRollupTestFilters(backlink.ID, "fresh-0")
+ cache := map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target}
+ context := NewAttributeViewRenderContext()
+ depth := 2
+ for repeat := 0; repeat < 2; repeat++ {
+ collection := renderRollupTarget(target, key, &depth, cache, context)
+ for _, item := range collection.GetItems() {
+ if value := collection.GetValue(item.GetID(), key.ID); value == nil || value.String(true) != "" {
+ t.Fatalf("cyclic filter reused stale contents: %+v", value)
+ }
+ }
+ if depth != 2 || len(context.renderingRollupTargets) != 0 {
+ t.Fatalf("cyclic filter leaked state: depth=%d, active=%v", depth, context.renderingRollupTargets)
+ }
+ }
+}
+
+func TestRenderRollupTargetMissingDependencyClearsStoredContents(t *testing.T) {
+ for _, missing := range []string{"relation-key", "relation-config", "relation-value", "target-key", "rollup-config"} {
+ t.Run(missing, func(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ target, key := newNestedRollupTestLevel("target", leaf, leafKey, true)
+ switch missing {
+ case "relation-key":
+ key.Rollup.RelationKeyID = "missing"
+ case "relation-config":
+ relationKey, _ := target.GetKey(key.Rollup.RelationKeyID)
+ relationKey.Relation = nil
+ case "relation-value":
+ nestedRollupTestKeyValues(t, target, key.Rollup.RelationKeyID).Values = nil
+ case "target-key":
+ key.Rollup.KeyID = "missing"
+ case "rollup-config":
+ key.Rollup = nil
+ }
+ before := nestedRollupTestSnapshot(t, []*av.AttributeView{target})
+ depth := 2
+ collection := renderRollupTarget(target, key, &depth,
+ map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target}, NewAttributeViewRenderContext())
+ for _, item := range collection.GetItems() {
+ value := collection.GetValue(item.GetID(), key.ID)
+ if value != nil && value.String(true) != "" {
+ t.Fatalf("missing %s reused stored contents: %+v", missing, value)
+ }
+ }
+ if nestedRollupTestSnapshot(t, []*av.AttributeView{target}) != before {
+ t.Fatal("missing dependency handling modified stored values")
+ }
+ })
+ }
+}
+
+func TestNestedRollupTargetFiltersAndSortUseFreshValues(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ target, targetKey := newNestedRollupTestLevel("target", leaf, leafKey, true)
+ outer, outerKey := newNestedRollupTestLevel("outer", target, targetKey, true)
+ cache := map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target, outer.ID: outer}
+ for update := 0; update < 2; update++ {
+ values := nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values
+ values[update].Text.Content = "alpha"
+ values[1-update].Text.Content = "zulu"
+ outer.Views[0].Sorts = []*av.ViewSort{{Column: outerKey.ID, Order: av.SortOrderAsc}}
+ collection := renderNestedRollupTestView(t, outer, cache)
+ av.Sort(collection, outer)
+ if got := collection.GetItems()[0].GetID(); got != outer.GetBlockKeyValues().Values[update].BlockID {
+ t.Fatalf("sort retained stale order after update %d: %s", update, got)
+ }
+ outer.Views[0].Filters = nestedRollupTestFilters(outerKey.ID, "alpha")
+ viewable := renderNestedRollupTestView(t, outer, cache)
+ depth := 1
+ av.Filter(viewable, outer, getFurtherCollections(outer, cache, &depth, NewAttributeViewRenderContext()), cache)
+ if items := viewable.GetItems(); len(items) != 1 || items[0].GetID() != outer.GetBlockKeyValues().Values[update].BlockID {
+ t.Fatalf("outer rollup view filter retained stale values after update %d: %+v", update, items)
+ }
+ outer.Views[0].Filters = nil
+ outerKey.Rollup.Filters = nestedRollupTestFilters(targetKey.ID, "alpha")
+ context := NewAttributeViewRenderContext()
+ depth = 1
+ further := getFurtherCollections(outer, cache, &depth, context)
+ eligible := further[outerKey.ID].EligibleItemIDs
+ if len(eligible) != 1 || !eligible[target.GetBlockKeyValues().Values[update].BlockID] {
+ t.Fatalf("rollup target filter retained stale values after update %d: %+v", update, eligible)
+ }
+ filtered := renderNestedRollupTestView(t, outer, cache)
+ for row, block := range outer.GetBlockKeyValues().Values {
+ want := ""
+ if row == update {
+ want = "alpha"
+ }
+ if value := filtered.GetValue(block.BlockID, outerKey.ID); value == nil || value.String(true) != want {
+ t.Fatalf("filtered row %d after update %d: got %v, want %q", row, update, value, want)
+ }
+ }
+ outerKey.Rollup.Filters = nil
+ }
+}
+
+func TestNestedRollupQuantifiedEmptyFiltersUseFreshValues(t *testing.T) {
+ for _, qualifier := range []av.FilterQuantifier{av.FilterQuantifierAny, av.FilterQuantifierAll, av.FilterQuantifierNone} {
+ for _, operator := range []av.FilterOperator{av.FilterOperatorIsEmpty, av.FilterOperatorIsNotEmpty} {
+ t.Run(fmt.Sprintf("%s/%s", qualifier, operator), func(t *testing.T) {
+ leaf, leafKey := newNestedRollupTestLeaf(av.KeyTypeText)
+ target, targetKey := newNestedRollupTestLevel("target", leaf, leafKey, true)
+ outer, outerKey := newNestedRollupTestLevel("outer", target, targetKey, true)
+ cache := map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target, outer.ID: outer}
+ outer.Views[0].Filters = []*av.ViewFilter{{Column: outerKey.ID, Qualifier: qualifier, Operator: operator,
+ Value: &av.Value{Type: av.KeyTypeRollup, Rollup: &av.ValueRollup{}}}}
+ relations := nestedRollupTestKeyValues(t, target, targetKey.Rollup.RelationKeyID).Values
+ for emptyRow := 0; emptyRow < 2; emptyRow++ {
+ for row, value := range relations {
+ value.Relation.BlockIDs = nil
+ if row != emptyRow {
+ value.Relation.BlockIDs = []string{leaf.GetBlockKeyValues().Values[row].BlockID}
+ }
+ }
+ table := renderNestedRollupTestView(t, outer, cache)
+ depth := 1
+ av.Filter(table, outer, getFurtherCollections(outer, cache, &depth, NewAttributeViewRenderContext()), cache)
+ wantEmpty := operator == av.FilterOperatorIsEmpty
+ if qualifier == av.FilterQuantifierNone {
+ wantEmpty = !wantEmpty
+ }
+ wantRow := emptyRow
+ if !wantEmpty {
+ wantRow = 1 - emptyRow
+ }
+ wantID := outer.GetBlockKeyValues().Values[wantRow].BlockID
+ if len(table.Rows) != 1 || table.Rows[0].ID != wantID {
+ t.Fatalf("empty inner row %d: got %+v, want only %s", emptyRow, table.Rows, wantID)
+ }
+ }
+ })
+ }
+ }
+}
+
+func newNestedRollupTestDatabase(id string) *av.AttributeView {
+ key := &av.Key{ID: id + "-primary", Name: "Primary", Type: av.KeyTypeBlock}
+ values := &av.KeyValues{Key: key}
+ for row := 0; row < 2; row++ {
+ itemID := fmt.Sprintf("2026100800000%d-%s", row, id)
+ values.Values = append(values.Values, &av.Value{
+ ID: itemID + "-primary", KeyID: key.ID, BlockID: itemID, Type: key.Type,
+ IsDetached: true, Block: &av.ValueBlock{Content: fmt.Sprintf("%s %d", id, row)},
+ })
+ }
+ view := &av.View{ID: id + "-view", LayoutType: av.LayoutTypeTable, Table: av.NewLayoutTable()}
+ view.Table.Columns = []*av.ViewTableColumn{{BaseField: &av.BaseField{ID: key.ID}}}
+ return &av.AttributeView{ID: id, KeyValues: []*av.KeyValues{values}, Views: []*av.View{view},
+ RenderedViewables: map[string]av.Viewable{}}
+}
+
+func newNestedRollupTestLeaf(typ av.KeyType) (*av.AttributeView, *av.Key) {
+ attrView := newNestedRollupTestDatabase("leaf")
+ if typ == av.KeyTypeBlock {
+ return attrView, attrView.GetBlockKey()
+ }
+ key := &av.Key{ID: "leaf-value", Name: "Value", Type: typ}
+ values := &av.KeyValues{Key: key}
+ for row, block := range attrView.GetBlockKeyValues().Values {
+ value := &av.Value{ID: block.BlockID + "-value", KeyID: key.ID, BlockID: block.BlockID, Type: typ}
+ if typ == av.KeyTypeNumber {
+ value.Number = &av.ValueNumber{Content: float64(row + 1), IsNotEmpty: true}
+ } else {
+ value.Text = &av.ValueText{Content: fmt.Sprintf("fresh-%d", row)}
+ }
+ values.Values = append(values.Values, value)
+ }
+ attrView.KeyValues = append(attrView.KeyValues, values)
+ attrView.Views[0].Table.Columns = append(attrView.Views[0].Table.Columns,
+ &av.ViewTableColumn{BaseField: &av.BaseField{ID: key.ID}})
+ return attrView, key
+}
+
+func newNestedRollupTestLevel(id string, target *av.AttributeView, targetKey *av.Key,
+ stale bool) (*av.AttributeView, *av.Key) {
+ attrView := newNestedRollupTestDatabase(id)
+ return attrView, addNestedRollupTestFields(attrView, target, targetKey, stale)
+}
+
+func addNestedRollupTestFields(attrView, target *av.AttributeView, targetKey *av.Key, stale bool) *av.Key {
+ prefix := fmt.Sprintf("%s-%d", attrView.ID, len(attrView.KeyValues))
+ relation := &av.Key{ID: prefix + "-relation", Name: prefix + " relation", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: target.ID}}
+ rollup := &av.Key{ID: prefix + "-rollup", Name: prefix + " rollup", Type: av.KeyTypeRollup,
+ Rollup: &av.Rollup{RelationKeyID: relation.ID, KeyID: targetKey.ID,
+ Calc: &av.RollupCalc{Operator: av.CalcOperatorNone}}}
+ relations, rollups := &av.KeyValues{Key: relation}, &av.KeyValues{Key: rollup}
+ for row, block := range attrView.GetBlockKeyValues().Values {
+ relations.Values = append(relations.Values, &av.Value{
+ ID: block.BlockID + relation.ID, KeyID: relation.ID, BlockID: block.BlockID, Type: relation.Type,
+ Relation: &av.ValueRelation{BlockIDs: []string{target.GetBlockKeyValues().Values[row].BlockID}},
+ })
+ if stale {
+ rollups.Values = append(rollups.Values, &av.Value{
+ ID: block.BlockID + rollup.ID, KeyID: rollup.ID, BlockID: block.BlockID, Type: rollup.Type,
+ Rollup: &av.ValueRollup{Contents: []*av.Value{{Type: av.KeyTypeText, Text: &av.ValueText{Content: "stale"}}}},
+ })
+ }
+ }
+ attrView.KeyValues = append(attrView.KeyValues, relations, rollups)
+ for _, key := range []*av.Key{relation, rollup} {
+ attrView.Views[0].Table.Columns = append(attrView.Views[0].Table.Columns,
+ &av.ViewTableColumn{BaseField: &av.BaseField{ID: key.ID}})
+ }
+ return rollup
+}
+
+func renderNestedRollupTestView(t *testing.T, attrView *av.AttributeView,
+ cache map[string]*av.AttributeView) *av.Table {
+ t.Helper()
+ context := NewAttributeViewRenderContext()
+ depth := 1
+ viewable := renderView(attrView, attrView.Views[0], "", &depth, cache, false, false, context)
+ if viewable == nil {
+ t.Fatal("outer view did not render")
+ }
+ if depth != 2 || len(context.renderingRollupTargets) != 0 {
+ t.Fatalf("nested calculation leaked state: depth=%d, active=%v", depth, context.renderingRollupTargets)
+ }
+ return viewable.(*av.Table)
+}
+
+func nestedRollupTestFilters(keyID, text string) []*av.ViewFilter {
+ return []*av.ViewFilter{{Column: keyID, Qualifier: av.FilterQuantifierAny, Operator: av.FilterOperatorIsEqual,
+ Value: &av.Value{Type: av.KeyTypeRollup, Rollup: &av.ValueRollup{Contents: []*av.Value{{
+ Type: av.KeyTypeText, Text: &av.ValueText{Content: text},
+ }}}}}}
+}
+
+func nestedRollupTestSnapshot(t *testing.T, attrViews []*av.AttributeView) string {
+ t.Helper()
+ data, err := json.Marshal(attrViews)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(data)
+}
+
+func nestedRollupTestKeyValues(t *testing.T, attrView *av.AttributeView, keyID string) *av.KeyValues {
+ t.Helper()
+ values, err := attrView.GetKeyValues(keyID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return values
+}