An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Move relation rollup filtering to dev https://github.com/siyuan-note/siyuan/issues/20085
Daniel572abc5bcc2a
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.syindex 0e5e8747a6..ba8c22f43c 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy@@ -7,7 +7,7 @@"id": "20240208172514-9dsv6na","title": "Database","type": "doc",- "updated": "20261004032313"+ "updated": "20260927123058"},"Children": [{@@ -1554,7 +1554,7 @@"HeadingLevel": 4,"Properties": {"id": "20260613171129-5zjv62o",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1583,7 +1583,7 @@"ListData": {},"Properties": {"id": "20260613171129-438l9c3",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1868,7 +1868,7 @@},"Properties": {"id": "20260904022100-t3p2t45",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1876,7 +1876,7 @@"Type": "NodeParagraph","Properties": {"id": "20260904022100-h1drat7",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1895,7 +1895,7 @@},{"Type": "NodeText",- "Data": " from the database block toolbar and select a configured Relation field, or a Rollup targeting a Relation field with Show original values or Show unique values. The panel lists all eligible fields in the database, but only one can be enabled at a time. Select another field to switch to it; select the checked field again to turn off the context filter. Once enabled, the fixed condition “Contains any item - Current document” applies to every view in this database block. Each view’s ordinary filters remain independent and are combined with the context filter using AND. The current document must already be bound to an item in the final related database; otherwise, no matching items are shown and you cannot add items from this database block. With a direct Relation field, new items automatically relate to the current document. With a Rollup, new items do not fill the computed value or change relations in the intermediate database, and may be hidden by the filter. Eligible Rollups also support Contains any item and Does not contain any item in ordinary filters: search and select items from the final related database to match the entire rolled-up item set. Items with identical names are distinguished by item ID. Existing keyword filters and their Any, All, and None quantifiers keep their existing behavior"+ "Data": " from the database block toolbar and select a configured Relation field. The panel lists all configured Relation fields in the database, but only one can be enabled at a time. Select another field to switch to it; select the checked field again to turn off the context filter. Once enabled, the fixed condition “Contains any item - Current document” applies to every view in this database block. Each view’s ordinary filters remain independent and are combined with the context filter using AND. When you add an item from this database block, the current document is automatically added to the selected Relation field. For filtering and adding items to work, the current document must already be bound to an item in the selected Relation field’s target database; otherwise, no matching items are shown and you cannot add items from this database block"}]}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.syindex b6ebf65bec..61509b5c48 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy@@ -7,7 +7,7 @@"id": "20240208113259-nykkvaq","title": "数据库","type": "doc",- "updated": "20261004032313"+ "updated": "20260927123058"},"Children": [{@@ -1554,7 +1554,7 @@"HeadingLevel": 4,"Properties": {"id": "20260613170258-kfaoevw",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1583,7 +1583,7 @@"ListData": {},"Properties": {"id": "20260613170258-stvvay1",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1868,7 +1868,7 @@},"Properties": {"id": "20260904022100-u8yv871",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1876,7 +1876,7 @@"Type": "NodeParagraph","Properties": {"id": "20260904022100-k06aj5m",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1895,7 +1895,7 @@},{"Type": "NodeText",- "Data": ",并选择一个已配置的关联字段,或目标为关联字段且计算方式为“显示原始值”或“显示唯一值”的汇总字段。面板会列出数据库中所有符合条件的字段,但同时只能启用一个。点击其他字段可切换;再次点击当前已勾选字段可关闭上下文筛选。启用后,系统会对该数据库块的所有视图应用固定条件“包含任一 - 当前文档”;各视图原有筛选仍保持独立,并与上下文筛选按“且”组合。当前文档必须已经绑定为最终关联目标数据库中的条目,否则不会显示匹配项,也无法从该数据库块新增条目。选择直接关联字段时,新增条目会自动关联当前文档;选择汇总字段时,新增条目不会回填汇总值,也不会修改中间数据库的关联,可能因不满足条件而被隐藏。符合上述条件的汇总字段也支持普通筛选中的“包含任一”和“不包含任一”:可以搜索并勾选最终关联数据库的条目,按整个汇总条目集合匹配,同名条目通过条目 ID 区分;原有关键词筛选及其“任一”“所有”“没有”量词保持原有行为"+ "Data": ",并选择一个已配置的关联字段。面板会列出数据库中所有已配置的关联字段,但同时只能启用一个。点击其他字段可切换;再次点击当前已勾选字段可关闭上下文筛选。启用后,系统会对该数据库块的所有视图应用固定条件“包含任一 - 当前文档”;各视图原有筛选仍保持独立,并与上下文筛选按“且”组合。从该数据库块新增条目时,系统会自动将当前文档填入所选关联字段。要正常筛选和新增条目,当前文档必须已经绑定为所选关联字段目标数据库中的条目;否则不会显示匹配项,也无法从该数据库块新增条目"}]}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.syindex 66b45c7134..b9e8144905 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy@@ -7,7 +7,7 @@"id": "20240208171522-y7dxcno","title": "資料庫","type": "doc",- "updated": "20261004032313"+ "updated": "20260927123058"},"Children": [{@@ -1554,7 +1554,7 @@"HeadingLevel": 4,"Properties": {"id": "20260613171246-qovn46w",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1583,7 +1583,7 @@"ListData": {},"Properties": {"id": "20260613171246-frygk48",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1868,7 +1868,7 @@},"Properties": {"id": "20260904022100-5x68nm2",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1876,7 +1876,7 @@"Type": "NodeParagraph","Properties": {"id": "20260904022100-ivb080o",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1895,7 +1895,7 @@},{"Type": "NodeText",- "Data": ",並選取一個已設定的關聯欄位,或目標為關聯欄位且計算方式為「顯示原始值」或「顯示唯一值」的彙總欄位。面板會列出資料庫中所有符合條件的欄位,但一次只能啟用一個。選取其他欄位即可切換;再次選取目前已勾選的欄位即可關閉情境篩選。啟用後,固定條件「包含任一項 - 目前文件」會套用於此資料庫區塊的所有檢視;各檢視原有篩選仍保持獨立,並與情境篩選以「且」組合。目前文件必須已綁定為最終關聯目標資料庫中的項目,否則不會顯示相符項目,也無法從此資料庫區塊新增項目。選取直接關聯欄位時,新增項目會自動關聯目前文件;選取彙總欄位時,新增項目不會回填彙總值,也不會修改中間資料庫的關聯,可能因不符合條件而被隱藏。符合上述條件的彙總欄位也支援一般篩選中的「包含任一項」與「不包含任一項」:可搜尋並勾選最終關聯資料庫的項目,依整個彙總項目集合比對,同名項目透過項目 ID 區分;既有關鍵字篩選及其「任一」「所有」「沒有」量詞維持原有行為"+ "Data": ",並選取一個已設定的關聯欄位。面板會列出資料庫中所有已設定的關聯欄位,但一次只能啟用一個。選取其他欄位即可切換;再次選取目前已勾選的欄位即可關閉情境篩選。啟用後,固定條件「包含任一項 - 目前文件」會套用於此資料庫區塊的所有檢視;各檢視原有篩選仍保持獨立,並與情境篩選以「且」組合。從此資料庫區塊新增項目時,系統會自動將目前文件加入所選的關聯欄位。若要正常篩選與新增項目,目前文件必須已綁定為所選關聯欄位所指向之資料庫中的項目;否則不會顯示相符項目,也無法從此資料庫區塊新增項目"}]}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.syindex 4e074ef6e6..0df4d6c11e 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy@@ -8,7 +8,7 @@"id": "20240530101000-3eaevtp","title": "データベース","type": "doc",- "updated": "20261004032313"+ "updated": "20260927123058"},"Children": [{@@ -1555,7 +1555,7 @@"HeadingLevel": 4,"Properties": {"id": "20260613171234-x40bu7m",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1584,7 +1584,7 @@"ListData": {},"Properties": {"id": "20260613171234-lbxo0ro",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1869,7 +1869,7 @@},"Properties": {"id": "20260904022100-hzqmv7b",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1877,7 +1877,7 @@"Type": "NodeParagraph","Properties": {"id": "20260904022100-mif3i0m",- "updated": "20261004032313"+ "updated": "20260904121106"},"Children": [{@@ -1896,7 +1896,7 @@},{"Type": "NodeText",- "Data": " を開き、設定済みのリレーションフィールド、またはリレーションフィールドを対象とし、計算方法が「元の値を表示」か「一意の値を表示」のロールアップフィールドを1つ選択します。パネルにはデータベース内の条件を満たすフィールドがすべて表示されますが、一度に有効にできるのは1つだけです。別のフィールドを選択すると切り替わり、チェック済みのフィールドをもう一度選択するとコンテキストフィルターが無効になります。有効にすると、固定条件「いずれかを含む - 現在の文書」がこのデータベースブロックのすべてのビューに適用されます。通常のビューフィルターは各ビューで独立したままで、コンテキストフィルターとは AND で組み合わせられます。現在の文書は、最終的な関連先データベースの項目としてあらかじめ紐付けられている必要があります。紐付けられていない場合、一致する項目は表示されず、このデータベースブロックから項目を追加することもできません。直接のリレーションフィールドを選択した場合、新しい項目は現在の文書に自動的に関連付けられます。ロールアップを選択した場合、計算値の入力や中間データベースの関連付けの変更は行われず、新しい項目がフィルターによって非表示になることがあります。条件を満たすロールアップは通常のフィルターでも「いずれかを含む」「いずれも含まない」を使用できます。最終的な関連先データベースの項目を検索して選択し、集計された項目全体と照合します。同名の項目は項目 ID で区別されます。既存のキーワードフィルターと 「いずれか」「すべて」「なし」の量化子の動作は変わりません"+ "Data": " を開き、設定済みのリレーションフィールドを1つ選択します。パネルにはデータベース内の設定済みリレーションフィールドがすべて表示されますが、一度に有効にできるのは1つだけです。別のフィールドを選択すると切り替わり、チェック済みのフィールドをもう一度選択するとコンテキストフィルターが無効になります。有効にすると、固定条件「いずれかを含む - 現在の文書」がこのデータベースブロックのすべてのビューに適用されます。通常のビューフィルターは各ビューで独立したままで、コンテキストフィルターとは AND で組み合わせられます。このデータベースブロックから項目を追加すると、現在の文書が選択中のリレーションフィールドに自動的に追加されます。フィルターと項目追加を正しく機能させるには、現在の文書が、選択するリレーションフィールドの関連先データベース内の項目としてあらかじめ紐付けられている必要があります。紐付けられていない場合、一致する項目は表示されず、このデータベースブロックから項目を追加することもできません"}]}diff --git a/app/src/protyle/render/av/filter.ts b/app/src/protyle/render/av/filter.tsindex 4286484447..1d40617dcb 100644--- a/app/src/protyle/render/av/filter.ts+++ b/app/src/protyle/render/av/filter.ts@@ -447,13 +447,6 @@ const getOperatorSelectByType = (type: TAVCol, currentOperator: string, isRollupconst rollupTargetColumns = new WeakMap<IAVColumn, IAVColumn>();const relationFilterLabelCache = new Map<string, string>();-const isRelationRollupColumn = (column: IAVColumn, target = rollupTargetColumns.get(column)) =>- column?.type === "rollup" && target?.type === "relation" && !!target.relation?.avID &&- (!column.rollup?.calc?.operator || column.rollup.calc.operator === "Unique values");--const wrapFilterCellValue = (filter: IAVFilter, value: IAVCellValue): IAVCellValue =>- filter.value?.type === "rollup" ? {type: "rollup", rollup: {contents: [value]}} as IAVCellValue : value;-const getRelationFilterCacheKey = (avID: string, blockID: string) => `${avID}\n${blockID}`;const parseRelationFilterBlockIDs = (value: string | string[]): string[] => {@@ -481,7 +474,6 @@ export const prepareFilterColumns = async (data: IAV) => {const fields = getFieldsByData(data);const avRequests = new Map<string, Promise<IAVColumn[]>>();const tasks = fields.filter((column) => column.type === "rollup" && column.rollup?.relationKeyID && column.rollup?.keyID).map(async (column) => {- rollupTargetColumns.delete(column);const relationColumn = fields.find((item) => item.id === column.rollup.relationKeyID);const targetAVID = relationColumn?.relation?.avID;if (!targetAVID) {@@ -500,7 +492,6 @@ export const prepareFilterColumns = async (data: IAV) => {rollupTargetColumns.set(column, targetColumn);}});- await Promise.all(tasks);const relationSelections = new Map<string, Set<string>>();const collectRelationSelections = (filters: IAVFilter[]) => {filters.forEach((filter) => {@@ -512,8 +503,7 @@ export const prepareFilterColumns = async (data: IAV) => {return;}const column = fields.find((item) => item.id === filter.column);- const targetAVID = column?.type === "relation" ? column.relation?.avID :- isRelationRollupColumn(column) ? rollupTargetColumns.get(column).relation.avID : "";+ const targetAVID = column?.type === "relation" ? column.relation?.avID : "";if (!targetAVID) {return;}@@ -522,7 +512,7 @@ export const prepareFilterColumns = async (data: IAV) => {blockIDs = new Set<string>();relationSelections.set(targetAVID, blockIDs);}- getFilterCellValue(filter)?.relation?.blockIDs?.forEach((blockID) => blockIDs.add(blockID));+ filter.value?.relation?.blockIDs?.forEach((blockID) => blockIDs.add(blockID));});};collectRelationSelections(getRootFilters(data));@@ -540,7 +530,7 @@ export const prepareFilterColumns = async (data: IAV) => {// 候选显示名加载失败不应阻止筛选面板打开,控件会保留行 ID 并允许重新搜索。}});- await Promise.all(relationTasks);+ await Promise.all([...tasks, ...relationTasks]);};// resolveFilterValueType 解析 filter 实际的值类型。@@ -594,7 +584,7 @@ export const genEmptyFilterValue = (column: IAVColumn, valueSource: "stored" | "const emptyRollup = {type: "rollup", rollup: {contents: []}} as IAVCellValue;const {type} = resolveFilterValueType({value: emptyRollup} as IAVFilter, column);return {- operator: getDefaultOperatorByType(type, !isRelationRollupColumn(column)),+ operator: getDefaultOperatorByType(type, true),value: {type: "rollup",rollup: {contents: [genEmptyCellValue(type)]},@@ -611,11 +601,10 @@ const genInlineFilterHTML = (filter: IAVFilter, colData: IAVColumn, path: stringconst valueHidden = isEmptyOp ? " fn__none" : "";// 操作符 select- const relationRollup = isRelationRollupColumn(colData);- const operatorSelect = `<select class="b3-select" data-type="operation" data-path="${path}">${getOperatorSelectByType(valueType, operator, isRollup && !relationRollup)}</select>`;+ const operatorSelect = `<select class="b3-select" data-type="operation" data-path="${path}">${getOperatorSelectByType(valueType, operator, isRollup)}</select>`;// 量化器 select(rollup/mAsset 才有)- const quantifierSelect = ((isRollup && !(relationRollup && isExactRelationOperator(operator))) || valueType === "mAsset")+ const quantifierSelect = (isRollup || valueType === "mAsset")? `<select class="b3-select" data-type="quantifier" data-path="${path}"><option ${(!filter.quantifier || filter.quantifier === "Any") ? "selected" : ""} value="Any">${window.siyuan.languages.filterQuantifierAny}</option><option ${filter.quantifier === "All" ? "selected" : ""} value="All">${window.siyuan.languages.filterQuantifierAll}</option>@@ -655,7 +644,7 @@ const genInlineFilterHTML = (filter: IAVFilter, colData: IAVColumn, path: stringconst {trigger, dropdown} = genInlineSelectHTML(filter, valueColumn, path, valueType, allowMultiple);valueHTML = trigger;extraHTML = dropdown; // 下拉面板放 valueContainer 外,fixed 定位不影响行宽- } else if (valueType === "relation" && (!isRollup || relationRollup) && isExactRelationOperator(operator)) {+ } else if (valueType === "relation" && !isRollup && isExactRelationOperator(operator)) {const {trigger, dropdown} = genInlineRelationHTML(filter, valueColumn, path);valueHTML = trigger;extraHTML = dropdown;@@ -896,7 +885,9 @@ const readInlineValue = (rowElement: HTMLElement, valueType: TAVCol, operator: s}// rollup 包装- newValue = wrapFilterCellValue(filter, newValue);+ if (filter.value?.type === "rollup") {+ newValue = {type: "rollup", rollup: {contents: [newValue]}} as IAVCellValue;+ }return {newValue, relativeDate, relativeDate2};};@@ -1048,10 +1039,10 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro}const newFilter: IAVFilter = {...filter,- value: wrapFilterCellValue(filter, {+ value: {type: "relation",relation: {blockIDs: selectedBlockIDs, contents: []},- } as IAVCellValue),+ },};commitFilter(data, path, newFilter, protyle, blockID, avID, menuElement, false, filterOperation);renderRelationFilterSelection(path, dropdown, selectedBlockIDs);@@ -1151,7 +1142,7 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, proconst structureChange = (["date", "created", "updated"].includes(valueType) &&((newOp === "Is between") !== (oldOp === "Is between"))) ||((newOp === "Is empty" || newOp === "Is not empty") !== (oldOp === "Is empty" || oldOp === "Is not empty")) ||- (valueType === "relation" && (!isRollup || isRelationRollupColumn(colData)) &&+ (valueType === "relation" && !isRollup &&(isExactRelationOperator(newOp) !== isExactRelationOperator(oldOp)));saveRow(row, path, structureChange);} else if (type === "quantifier" || type === "dateEndpoint" || type?.startsWith("dataDirection") || type === "dateType") {diff --git a/app/src/protyle/render/av/filterRelationRollup.test.ts b/app/src/protyle/render/av/filterRelationRollup.test.tsdeleted file mode 100644index 43927b5a85..0000000000--- a/app/src/protyle/render/av/filterRelationRollup.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import * as assert from "node:assert/strict";-import {readFileSync} from "node:fs";-import {test} from "node:test";-import {runInNewContext} from "node:vm";-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";--const createEditor = () => {- const rollup = {id: "employees", name: "Employees", type: "rollup",- rollup: {relationKeyID: "tasks", keyID: "staff"}} as IAVColumn;- const fields = [rollup, {id: "tasks", type: "relation", relation: {avID: "tasks-db"}}];- const requests: Array<{url: string, data: {id: string, blockIDs?: string[]}}> = [];- const methods = {} as typeof import("./filter");- runInNewContext(transpileModule(readFileSync("src/protyle/render/av/filter.ts", "utf8"), {- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},- }).outputText, {- exports: methods,- window: {siyuan: {languages: new Proxy({}, {get: (_, name) => String(name)})}},- document: {createElement: () => ({style: {}, offsetWidth: 10}), body: {appendChild() {}, removeChild() {}}},- require: (name: string) => ({- "./view": {getFieldsByData: () => fields},- "./col": {getColIconByType: () => "iconDatabase"},- "../../../util/escape": {escapeAttr: String, escapeHtml: String},- "../../../constants": {Constants: {}},- "../../../util/fetch": {fetchSyncPost: async (url: string, data: {id: string, blockIDs?: string[]}) => {- requests.push({url, data});- return {code: 0, data: url === "/api/av/getAttributeView" ? {av: {keyValues: [{key: {- id: "staff", type: "relation", relation: {avID: "employees-db"},- }}]}} : {rows: {values: [{blockID: "alice", block: {content: "Alice"}}]}}};- }},- })[name] || {},- });- const data = {view: {filters: [{column: rollup.id, operator: "Contains any item", value: {- type: "rollup", rollup: {contents: [{type: "relation", relation: {blockIDs: ["alice"], contents: []}}]},- }}]}} as IAV;- return {methods, rollup, data, requests};-};--test("relation rollups load selected labels from the final database and expose exact selection", async () => {- const {methods, rollup, data, requests} = createEditor();- await methods.prepareFilterColumns(data);- assert.equal(requests[0].data.id, "tasks-db");- assert.equal(requests[1].data.id, "employees-db");- assert.deepEqual(Array.from(requests[1].data.blockIDs), ["alice"]);- const html = methods.getFiltersHTML(data, true);- assert.match(html, /data-type="relationFilterTrigger"[^>]*data-av-id="employees-db"/);- assert.match(html, />Alice</);- assert.doesNotMatch(html, /data-type="quantifier"/);- assert.equal(methods.genEmptyFilterValue(rollup).operator, "Contains any item");-- rollup.rollup.calc = {operator: "Unique values"};- assert.equal(methods.genEmptyFilterValue(rollup).operator, "Contains any item");- rollup.rollup.calc = {operator: "Count all"};- assert.equal(methods.genEmptyFilterValue(rollup).value.rollup.contents[0].type, "number");- assert.doesNotMatch(methods.getFiltersHTML(data, true), /data-type="relationFilterTrigger"/);-- rollup.rollup.calc = undefined;- data.view.filters[0].operator = "Contains";- data.view.filters[0].value.rollup.contents[0].relation.blockIDs = ["keyword"];- const keywordHTML = methods.getFiltersHTML(data, true);- assert.match(keywordHTML, /data-type-rel="relation"/);- assert.match(keywordHTML, /data-type="quantifier"/);-});--test("selecting, removing and clearing rollup relation candidates preserves the rollup wrapper", async () => {- const {methods, data} = createEditor();- await methods.prepareFilterColumns(data);- const listeners = new Map<string, Array<(event: unknown) => void>>();- const dropdown = {- dataset: {path: "0", avId: "employees-db", selected: '["alice"]'},- style: {display: "none"}, querySelector: (): HTMLElement => null, querySelectorAll: (): HTMLElement[] => [],- };- let saves = 0;- const panel = {- dataset: {}, querySelector: (): HTMLElement => null, querySelectorAll: (): HTMLElement[] => [],- addEventListener: (type: string, listener: (event: unknown) => void) => {- listeners.set(type, [...listeners.get(type) || [], listener]);- },- };- methods.bindInlineFilterEvents(panel as unknown as HTMLElement, data, {} as IProtyle, "block", "database", {- root: panel as unknown as HTMLElement, save: () => { saves++; },- });- const click = (type: string, id?: string) => {- const action = {dataset: {path: "0", id}, closest: () => dropdown};- const target = {closest: (selector: string) => selector === '[data-filter-events-bound="true"]' ? panel :- selector === `[data-type="${type}"]` ? action : null};- for (const listener of listeners.get("click")) {- listener({target, stopImmediatePropagation() {}});- }- };- click("relationFilterOption", "bob");- assert.equal(data.view.filters[0].value.type, "rollup");- assert.deepEqual(Array.from(data.view.filters[0].value.rollup.contents[0].relation.blockIDs), ["alice", "bob"]);- click("relationFilterRemove", "alice");- assert.deepEqual(Array.from(data.view.filters[0].value.rollup.contents[0].relation.blockIDs), ["bob"]);- click("relationFilterClear");- assert.deepEqual(Array.from(data.view.filters[0].value.rollup.contents[0].relation.blockIDs), []);- assert.equal(saves, 3);-});diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex 2c858be634..4eaa93fdef 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -1149,7 +1149,6 @@ interface IAV {interface IAVContextFilter {spec: 1;- /** 直接关联或目标为关联且显示原值/唯一值的汇总字段;汇总仅用于筛选,不回填新增条目 */keyID: string;}@@ -1157,7 +1156,6 @@ interface IAVContextFilterField {id: string;name: string;icon: string;- /** 最终关联目标数据库的 ID;汇总字段返回关联目标,而非中间数据库 */targetAvID: string;}diff --git a/kernel/api/av_context_filter_test.go b/kernel/api/av_context_filter_test.goindex 21a3c34782..4d08b13283 100644--- a/kernel/api/av_context_filter_test.go+++ b/kernel/api/av_context_filter_test.go@@ -18,15 +18,11 @@ package apiimport ("bytes"- "context""encoding/json""net/http""net/http/httptest"- "os"- "os/exec""path/filepath""testing"- "time""github.com/88250/lute/ast""github.com/gin-gonic/gin"@@ -35,7 +31,6 @@ import ("github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model"- "github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -89,64 +84,6 @@ func TestSetAttrViewContextFilterHandler(t *testing.T) {}}-func TestAPIContractAVRelationRollupContextFilter(t *testing.T) {- if os.Getenv("SIYUAN_TEST_API_RELATION_ROLLUP") != "1" {- // 写入数据库块需要进程级索引队列,使用独立进程初始化,避免污染其他 API 测试。- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)- defer cancel()- command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestAPIContractAVRelationRollupContextFilter$", "-test.v")- command.Env = append(os.Environ(), "SIYUAN_TEST_API_RELATION_ROLLUP=1")- if output, err := command.CombinedOutput(); nil != err {- t.Fatalf("relation rollup API subprocess failed: %v\n%s", err, output)- }- return- }- root := t.TempDir()- util.DataDir, util.TempDir, util.ConfDir = root, root, root- util.QueueDir = filepath.Join(root, "queue")- util.DBPath, util.HistoryDBPath = filepath.Join(root, "siyuan.db"), filepath.Join(root, "history.db")- util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(root, "asset_content.db"), filepath.Join(root, "blocktree.db")- sql.InitDatabase(true)- sql.InitHistoryDatabase(true)- sql.InitAssetContentDatabase(true)- t.Cleanup(sql.CloseDatabase)- fixture := setupAttributeViewContextFilterAPITest(t)- util.TimeLangs["en"] = map[string]any{}- for _, key := range []string{"albl", "blbl", "now", "1s", "xs", "1m", "xm", "1h", "xh", "1d", "xd", "1w", "xw", "1M", "xM", "1y", "2y", "xy", "max"} {- util.TimeLangs["en"][key] = "time"- }- rollup := &av.Key{ID: "rollup-employees", Name: "Employees", Type: av.KeyTypeRollup,- Rollup: &av.Rollup{RelationKeyID: fixture.relationKeyID, KeyID: fixture.relationKeyID}}- fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: rollup})- if err := av.SaveAttributeView(fixture.attrView); nil != err {- t.Fatal(err)- }- response := callAttributeViewContextFilterAPI(t, "/api/av/setAttrViewContextFilter", map[string]any{- "avID": fixture.attrView.ID, "blockID": fixture.databaseID, "keyID": rollup.ID,- }, setAttrViewContextFilter)- var result struct {- Code int `json:"code"`- Data struct {- ContextFilter *av.AttributeViewContextFilter `json:"contextFilter"`- } `json:"data"`- }- decodeAttributeViewContextFilterAPIResponse(t, response, &result)- if result.Code != 0 || nil == result.Data.ContextFilter || result.Data.ContextFilter.KeyID != rollup.ID {- t.Fatalf("valid relation rollup rejected: %s", response.Body.String())- }- rollup.Rollup.Calc = &av.RollupCalc{Operator: av.CalcOperatorCountAll}- if err := av.SaveAttributeView(fixture.attrView); nil != err {- t.Fatal(err)- }- response = callAttributeViewContextFilterAPI(t, "/api/av/setAttrViewContextFilter", map[string]any{- "avID": fixture.attrView.ID, "blockID": fixture.databaseID, "keyID": rollup.ID,- }, setAttrViewContextFilter)- decodeAttributeViewContextFilterAPIResponse(t, response, &result)- if result.Code != -1 {- t.Fatalf("numeric rollup accepted as a relation: %s", response.Body.String())- }-}-func TestRenderAttributeViewReturnsContextFilterMetadata(t *testing.T) {fixture := setupAttributeViewContextFilterAPITest(t)payload := map[string]any{diff --git a/kernel/api/av_contract_render.go b/kernel/api/av_contract_render.goindex 8f61fa09d9..d544bf3983 100644--- a/kernel/api/av_contract_render.go+++ b/kernel/api/av_contract_render.go@@ -54,7 +54,7 @@ func renderAttrView(blockID, avID, viewID, query string, page, pageSize int, groif err != nil {return apicontract.Failure[apicontract.AVRenderResult](-1, err.Error())}- data := apicontract.AVRenderData{AVArchiveRenderData: avArchiveRenderData(attrView, view), ContextFilter: toContractAVAttributeViewContextFilter(contextFilter), ContextFilterFields: avContractSlice(model.GetAttributeViewContextFilterFields(attrView, blockID), toContractAVAttributeViewContextFilterField), Target: toContractAVAttributeViewRenderTarget(target)}+ data := apicontract.AVRenderData{AVArchiveRenderData: avArchiveRenderData(attrView, view), ContextFilter: toContractAVAttributeViewContextFilter(contextFilter), ContextFilterFields: avContractSlice(attrView.ContextFilterFields(), toContractAVAttributeViewContextFilterField), Target: toContractAVAttributeViewRenderTarget(target)}if filter != nil {view = filter(view)if calendar, ok := view.(*av.Calendar); ok {diff --git a/kernel/apicontract/av_requests.go b/kernel/apicontract/av_requests.goindex aeb0017617..1ef53eacc5 100644--- a/kernel/apicontract/av_requests.go+++ b/kernel/apicontract/av_requests.go@@ -53,9 +53,7 @@ type SetAttrViewFiltersRequest struct {type SetAttrViewContextFilterRequest struct {AvID string `json:"avID"`BlockID string `json:"blockID"`- // KeyID 允许直接关联或目标为关联且显示原值/唯一值的汇总字段;省略或为空时关闭筛选。- // 汇总按最终目标条目 ID 匹配,不为新增条目回填计算值或修改中间关联。- KeyID string `json:"keyID" api:"optional,nullable,ignoretype"`+ KeyID string `json:"keyID" api:"optional,nullable,ignoretype"`}type SetAttrViewSortsRequest struct {diff --git a/kernel/av/context_filter.go b/kernel/av/context_filter.goindex 9e722461f7..634cbe1822 100644--- a/kernel/av/context_filter.go+++ b/kernel/av/context_filter.go@@ -95,7 +95,9 @@ func (filter *AttributeViewContextFilter) Validate(attrView *AttributeView) erroif nil == filter || AttributeViewContextFilterSpec != filter.Spec || nil == attrView {return ErrInvalidAttributeViewContextFilter}- if _, err := attrView.ResolveRelationKey(filter.KeyID, nil); nil != err {+ key, err := attrView.GetKey(filter.KeyID)+ if nil != err || nil == key || KeyTypeRelation != key.Type || nil == key.Relation ||+ "" == strings.TrimSpace(key.Relation.AvID) {return ErrInvalidAttributeViewContextFilter}return nil@@ -114,35 +116,21 @@ func (filter *AttributeViewContextFilter) Marshal() (string, error) {}// ContextFilterFields 返回整个数据库中可用于上下文筛选的关联字段,不受当前视图布局限制。-func (av *AttributeView) ContextFilterFields(loaders ...func(string) (*AttributeView, error)) (ret []*AttributeViewContextFilterField) {+func (av *AttributeView) ContextFilterFields() (ret []*AttributeViewContextFilterField) {ret = []*AttributeViewContextFilterField{}if nil == av {return}- load := ParseAttributeView- if 0 < len(loaders) && nil != loaders[0] {- load = loaders[0]- }- cache := map[string]*AttributeView{}- loadCached := func(id string) (*AttributeView, error) {- if target, ok := cache[id]; ok {- return target, nil- }- target, err := load(id)- cache[id] = target- return target, err- }for _, keyValues := range av.KeyValues {if nil == keyValues || nil == keyValues.Key {continue}key := keyValues.Key- relation, err := av.ResolveRelationKey(key.ID, loadCached)- if nil != err {+ if KeyTypeRelation != key.Type || nil == key.Relation || "" == strings.TrimSpace(key.Relation.AvID) {continue}ret = append(ret, &AttributeViewContextFilterField{- ID: key.ID, Name: key.Name, Icon: key.Icon, TargetAvID: relation.Relation.AvID,+ ID: key.ID, Name: key.Name, Icon: key.Icon, TargetAvID: key.Relation.AvID,})}returndiff --git a/kernel/av/filter.go b/kernel/av/filter.goindex 8248c0c08c..238323c2ce 100644--- a/kernel/av/filter.go+++ b/kernel/av/filter.go@@ -172,9 +172,6 @@ func filterByContext(collection Collection, attrView *AttributeView,},},}- if KeyTypeRollup == keyValues.Key.Type {- filter.Value = &Value{Type: KeyTypeRollup, Rollup: &ValueRollup{Contents: []*Value{filter.Value}}}- }valuesByItemID := make(map[string]*Value, len(keyValues.Values))for _, value := range keyValues.Values {if nil == value {@@ -187,9 +184,6 @@ func filterByContext(collection Collection, attrView *AttributeView,var items []Itemfor _, item := range collection.GetItems() {value := valuesByItemID[item.GetID()]- if nil == value && KeyTypeRollup == keyValues.Key.Type {- value = &Value{KeyID: context.KeyID, BlockID: item.GetID(), Type: KeyTypeRollup, Rollup: &ValueRollup{}}- }if nil != value && value.Filter(filter, attrView, item.GetID(), rollupFurtherCollections, cachedAttrViews) {items = append(items, item)}@@ -343,13 +337,8 @@ func evalMissingLeaf(filter *ViewFilter) bool {case FilterOperatorIsNotEmpty:return falsecase FilterOperatorContainsAnyItem, FilterOperatorDoesNotContainAnyItem:- comparison := filter- if nil != filter.Value && KeyTypeRollup == filter.Value.Type && nil != filter.Value.Rollup &&- 0 < len(filter.Value.Rollup.Contents) {- comparison = &ViewFilter{Operator: filter.Operator, Value: filter.Value.Rollup.Contents[0]}- }- if !isExactRelationFilter(comparison) || nil == comparison.Value.Relation ||- 1 > len(comparison.Value.Relation.BlockIDs) {+ if !isExactRelationFilter(filter) || nil == filter.Value.Relation ||+ 1 > len(filter.Value.Relation.BlockIDs) {return true}return FilterOperatorDoesNotContainAnyItem == filter.Operator@@ -674,24 +663,25 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID s// 单独处理汇总if nil != value.Rollup && KeyTypeRollup == value.Type && nil != filter.Value && KeyTypeRollup == filter.Value.Type && nil != filter.Value.Rollup {key, _ := attrView.GetKey(value.KeyID)- if nil == key || nil == key.Rollup {+ if nil == key {return false}relKey, _ := attrView.GetKey(key.Rollup.RelationKeyID)- if !isConfiguredRelationKey(relKey) {+ if nil == relKey {return false}relVal := attrView.GetValue(relKey.ID, itemID)+ if nil == relVal || nil == relVal.Relation {+ return false+ }destAv := cachedAttrViews[relKey.Relation.AvID]if nil == destAv {destAv, _ = ParseAttributeView(relKey.Relation.AvID)if nil != destAv {- if nil != cachedAttrViews {- cachedAttrViews[relKey.Relation.AvID] = destAv- }+ cachedAttrViews[relKey.Relation.AvID] = destAv}}if nil == destAv {@@ -703,27 +693,8 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sif nil == destKey {return false}- var comparison *ViewFilter- if 0 < len(filter.Value.Rollup.Contents) {- candidate := &ViewFilter{Operator: filter.Operator, Value: filter.Value.Rollup.Contents[0]}- if isExactRelationFilter(candidate) {- if !isRollupValueList(key) || !isConfiguredRelationKey(destKey) {- return false- }- comparison = candidate- }- }- if nil == relVal || nil == relVal.Relation {- return nil != comparison && filterRelationRollupItems(nil, comparison)- }rollupContext := rollupFurtherCollections[key.ID]- if nil != comparison {- // 精确筛选按条目 ID 匹配,不能让显示值按名称去重后丢失同名条目。- contents := &ValueRollup{}- contents.BuildContents(destAv, destKey, relVal, nil, rollupContext)- return filterRelationRollupItems(contents.Contents, comparison)- }value.Rollup.BuildContents(destAv, destKey, relVal, key.Rollup.Calc, rollupContext)relationContentCount := len(relVal.Relation.Contents)if nil != rollupContext && nil != rollupContext.EligibleItemIDs {diff --git a/kernel/av/relation_rollup.go b/kernel/av/relation_rollup.godeleted file mode 100644index 2e888fb40b..0000000000--- a/kernel/av/relation_rollup.go+++ /dev/null@@ -1,104 +0,0 @@-// 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 "strings"--// isRollupValueList 判断汇总是否保留目标字段的条目值。-func isRollupValueList(key *Key) bool {- return nil != key && KeyTypeRollup == key.Type && nil != key.Rollup &&- (nil == key.Rollup.Calc || CalcOperatorNone == key.Rollup.Calc.Operator ||- CalcOperatorUniqueValues == key.Rollup.Calc.Operator)-}--// ResolveRelationKey 解析直接关联或保留原值的汇总所指向的最终关联字段。-// load 由调用方提供,以保留关联数据库的缓存和笔记本读取边界。-func (attrView *AttributeView) ResolveRelationKey(keyID string,- load func(string) (*AttributeView, error)) (*Key, error) {- if nil == attrView {- return nil, ErrInvalidAttributeViewContextFilter- }- key := getRelationFilterKey(attrView, keyID)- if nil == key {- return nil, ErrInvalidAttributeViewContextFilter- }- if isRollupValueList(key) {- relation := getRelationFilterKey(attrView, key.Rollup.RelationKeyID)- if !isConfiguredRelationKey(relation) {- return nil, ErrInvalidAttributeViewContextFilter- }- target := attrView- if relation.Relation.AvID != attrView.ID {- if nil == load {- load = ParseAttributeView- }- var err error- if target, err = load(relation.Relation.AvID); nil != err {- return nil, err- }- }- if nil == target {- return nil, ErrAttributeViewNotFound- }- key = getRelationFilterKey(target, key.Rollup.KeyID)- }- if !isConfiguredRelationKey(key) {- return nil, ErrInvalidAttributeViewContextFilter- }- return key, nil-}--func getRelationFilterKey(attrView *AttributeView, id string) *Key {- if "" == strings.TrimSpace(id) {- return nil- }- for _, values := range attrView.KeyValues {- if nil != values && nil != values.Key && values.Key.ID == id {- return values.Key- }- }- return nil-}--func isConfiguredRelationKey(key *Key) bool {- return nil != key && KeyTypeRelation == key.Type && nil != key.Relation &&- "" != strings.TrimSpace(key.Relation.AvID)-}--// filterRelationRollupItems 对汇总中的全部关联条目做精确集合匹配,不按中间行分别匹配。-func filterRelationRollupItems(contents []*Value, filter *ViewFilter) bool {- if nil == filter.Value.Relation || 0 == len(filter.Value.Relation.BlockIDs) {- return true- }- selected := map[string]bool{}- for _, id := range filter.Value.Relation.BlockIDs {- if "" != id {- selected[id] = true- }- }- for _, content := range contents {- if nil == content || nil == content.Relation {- continue- }- for _, id := range content.Relation.BlockIDs {- if selected[id] {- return FilterOperatorContainsAnyItem == filter.Operator- }- }- }- return FilterOperatorDoesNotContainAnyItem == filter.Operator-}diff --git a/kernel/av/relation_rollup_test.go b/kernel/av/relation_rollup_test.godeleted file mode 100644index 06efc19126..0000000000--- a/kernel/av/relation_rollup_test.go+++ /dev/null@@ -1,160 +0,0 @@-// 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 (- "errors"- "reflect"- "testing"-)--func relationRollupFixture() (*AttributeView, *AttributeView, *Key) {- relation := &Key{ID: "tasks", Type: KeyTypeRelation, Relation: &Relation{AvID: "tasks-db"}}- rollup := &Key{ID: "employees", Name: "Employees", Type: KeyTypeRollup,- Rollup: &Rollup{RelationKeyID: relation.ID, KeyID: "staff"}}- source := &AttributeView{ID: "projects-db", KeyValues: []*KeyValues{- {Key: relation, Values: []*Value{- {KeyID: relation.ID, BlockID: "project", Type: KeyTypeRelation,- Relation: &ValueRelation{BlockIDs: []string{"task-a", "task-b"}}},- }},- {Key: rollup},- }}- target := &AttributeView{ID: "tasks-db", KeyValues: []*KeyValues{{- Key: &Key{ID: "staff", Type: KeyTypeRelation, Relation: &Relation{AvID: "employees-db"}},- Values: []*Value{- {KeyID: "staff", BlockID: "task-a", Type: KeyTypeRelation,- Relation: &ValueRelation{BlockIDs: []string{"alice", "alice"}, Contents: []*Value{- {BlockID: "alice", Type: KeyTypeBlock, Block: &ValueBlock{ID: "alice", Content: "Same name"}},- }}},- {KeyID: "staff", BlockID: "task-b", Type: KeyTypeRelation,- Relation: &ValueRelation{BlockIDs: []string{"bob"}, Contents: []*Value{- {BlockID: "bob", Type: KeyTypeBlock, Block: &ValueBlock{ID: "bob", Content: "Same name"}},- }}},- },- }}}- return source, target, rollup-}--func TestRollupRelationTargetAndContextFields(t *testing.T) {- source, target, rollup := relationRollupFixture()- loads := 0- load := func(id string) (*AttributeView, error) {- loads++- if id != target.ID {- t.Fatalf("unexpected intermediate database: %s", id)- }- return target, nil- }- for _, operator := range []CalcOperator{CalcOperatorNone, CalcOperatorUniqueValues} {- rollup.Rollup.Calc = &RollupCalc{Operator: operator}- key, err := source.ResolveRelationKey(rollup.ID, load)- if nil != err || key.Relation.AvID != "employees-db" {- t.Fatalf("unexpected final relation: %+v, %v", key, err)- }- fields := source.ContextFilterFields(load)- if 2 != len(fields) || fields[1].ID != rollup.ID || fields[1].TargetAvID != "employees-db" {- t.Fatalf("unexpected context candidates: %+v", fields)- }- }- if loads != 4 {- t.Fatalf("unexpected database loads: %d", loads)- }- for _, operator := range []CalcOperator{CalcOperatorCountAll, CalcOperatorTemplate} {- rollup.Rollup.Calc = &RollupCalc{Operator: operator}- if _, err := source.ResolveRelationKey(rollup.ID, load); nil == err {- t.Fatalf("calculated rollup %s accepted as relation", operator)- }- }- rollup.Rollup.Calc = nil- target.KeyValues[0].Key.Type = KeyTypeText- if _, err := source.ResolveRelationKey(rollup.ID, load); nil == err {- t.Fatal("changed destination field should invalidate relation rollup")- }- target.KeyValues[0].Key.Type = KeyTypeRelation- if _, err := source.ResolveRelationKey(rollup.ID, func(string) (*AttributeView, error) {- return nil, errors.New("database unavailable")- }); nil == err {- t.Fatal("unavailable intermediate database should invalidate relation rollup")- }-}--func TestRollupExactRelationFilterUsesWholeSet(t *testing.T) {- source, target, rollup := relationRollupFixture()- value := &Value{KeyID: rollup.ID, Type: KeyTypeRollup, Rollup: &ValueRollup{}}- comparison := &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"alice"}}}- filter := &ViewFilter{Column: rollup.ID, Value: &Value{Type: KeyTypeRollup,- Rollup: &ValueRollup{Contents: []*Value{comparison}}}}- cache := map[string]*AttributeView{target.ID: target}- for _, operator := range []CalcOperator{CalcOperatorNone, CalcOperatorUniqueValues} {- rollup.Rollup.Calc = &RollupCalc{Operator: operator}- comparison.Relation.BlockIDs = []string{"bob"}- filter.Operator = FilterOperatorContainsAnyItem- if !value.Filter(filter, source, "project", nil, cache) {- t.Fatal("unique display names must not remove a different employee ID from exact matching")- }- comparison.Relation.BlockIDs = []string{"alice"}- for _, qualifier := range []FilterQuantifier{FilterQuantifierAny, FilterQuantifierAll, FilterQuantifierNone} {- filter.Qualifier = qualifier- filter.Operator = FilterOperatorContainsAnyItem- if !value.Filter(filter, source, "project", nil, cache) {- t.Fatal("matching employee should pass exact set filter")- }- filter.Operator = FilterOperatorDoesNotContainAnyItem- if value.Filter(filter, source, "project", nil, cache) {- t.Fatal("one unrelated task must not make the negative filter pass")- }- }- }- comparison.Relation.BlockIDs = []string{"different-id-same-name"}- filter.Operator = FilterOperatorContainsAnyItem- if value.Filter(filter, source, "project", nil, cache) {- t.Fatal("names must not match different employee IDs")- }- comparison.Relation.BlockIDs = []string{"alice"}- eligible := map[string]*RollupRenderContext{rollup.ID: {EligibleItemIDs: map[string]bool{"task-b": true}}}- if value.Filter(filter, source, "project", eligible, cache) {- t.Fatal("excluded task employee must not match")- }- filter.Operator = FilterOperatorDoesNotContainAnyItem- if !value.Filter(filter, source, "project", eligible, cache) {- t.Fatal("negative filter should pass when employee only belongs to an excluded task")- }- if !value.Filter(filter, source, "empty-project", nil, cache) {- t.Fatal("empty rollup should pass the negative filter")- }- filter.Operator = FilterOperatorContainsAnyItem- if value.Filter(filter, source, "empty-project", nil, cache) || evalMissingLeaf(filter) {- t.Fatal("empty rollup must fail the positive filter")- }- comparison.Relation.BlockIDs = nil- if !value.Filter(filter, source, "empty-project", nil, cache) {- t.Fatal("unconfigured filter should be ignored")- }-}--func TestRollupRelationContextFilterUsesDerivedValues(t *testing.T) {- source, target, rollup := relationRollupFixture()- table := &Table{Rows: []*TableRow{{ID: "project"}, {ID: "empty-project"}}}- filterByContext(table, source, nil, map[string]*AttributeView{target.ID: target},- &FilterContext{KeyID: rollup.ID, CurrentDocumentItemIDs: []string{"alice"}})- if len(table.Rows) != 1 || table.Rows[0].ID != "project" {- t.Fatalf("unexpected context rows: %+v", table.Rows)- }- if !reflect.DeepEqual(source.KeyValues[0].Values[0].Relation.BlockIDs, []string{"task-a", "task-b"}) {- t.Fatal("context filtering changed the source relations")- }-}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex b87f50c855..6940429b6b 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -5494,6 +5494,9 @@ func setAttributeViewContextFilter(tx *Transaction, blockID, avID,ret = &av.AttributeViewContextFilter{Spec: av.AttributeViewContextFilterSpec, KeyID: keyID}// undo/redo 重放需要能恢复字段删除或改型后留下的旧配置;普通事务和公开 API 仍严格校验。if nil == tx || !tx.isReplay {+ if err = ret.Validate(attrView); nil != err {+ return nil, err+ }if _, err = resolveAttributeViewContextFilterTarget(attrView, ret, tree.Box); nil != err {return nil, fmt.Errorf("validate attribute view context filter target: %w", err)}@@ -5540,6 +5543,13 @@ func resolveAttributeViewFilterContext(attrView *av.AttributeView, view *av.Viewcontext := &av.FilterContext{KeyID: contextFilter.KeyID}// 字段删除、改型或关联目标失效时保留块级配置,并以空上下文安全渲染。// 这样撤销字段变更后配置可自动恢复,用户也可在界面中显式禁用。+ if err = contextFilter.Validate(attrView); nil != err {+ return context, nil+ }+ key, err := attrView.GetKey(contextFilter.KeyID)+ if nil != err || nil == key || nil == key.Relation {+ return context, nil+ }_, tree, err := getAttributeViewInstanceNode(attrView, blockID)if nil != err {return nil, err@@ -5557,46 +5567,26 @@ func resolveAttributeViewFilterContext(attrView *av.AttributeView, view *av.Viewfunc resolveAttributeViewContextFilterTarget(attrView *av.AttributeView, contextFilter *av.AttributeViewContextFilter,carrierBoxID string) (ret *av.AttributeView, err error) {- if nil == contextFilter || av.AttributeViewContextFilterSpec != contextFilter.Spec {- return nil, av.ErrInvalidAttributeViewContextFilter- }- load := attributeViewContextFilterLoader(attrView, carrierBoxID)- key, err := attrView.ResolveRelationKey(contextFilter.KeyID, load)- if nil != err {+ if err = contextFilter.Validate(attrView); nil != err {return nil, err}- return load(key.Relation.AvID)-}--// GetAttributeViewContextFilterFields 在承载数据库块的笔记本范围内解析上下文筛选候选。-func GetAttributeViewContextFilterFields(attrView *av.AttributeView, blockID string) []*av.AttributeViewContextFilterField {- boxID, _, err := resolveAttributeViewCarrierBoxID(blockID)+ key, _ := attrView.GetKey(contextFilter.KeyID)+ if key.Relation.AvID == attrView.ID {+ return attrView, nil+ }+ targetBoxID := ""+ if IsEncryptedBox(carrierBoxID) {+ targetBoxID = carrierBoxID+ }+ av.SetAVBoxID(key.Relation.AvID, targetBoxID)+ ret, err = av.ParseAttributeViewInBox(key.Relation.AvID, targetBoxID)if nil != err {- return []*av.AttributeViewContextFilterField{}+ return nil, err}- return attrView.ContextFilterFields(attributeViewContextFilterLoader(attrView, boxID))-}--func attributeViewContextFilterLoader(attrView *av.AttributeView,- carrierBoxID string) func(string) (*av.AttributeView, error) {- return func(avID string) (*av.AttributeView, error) {- if nil != attrView && avID == attrView.ID {- return attrView, nil- }- targetBoxID := ""- if IsEncryptedBox(carrierBoxID) {- targetBoxID = carrierBoxID- }- av.SetAVBoxID(avID, targetBoxID)- ret, err := av.ParseAttributeViewInBox(avID, targetBoxID)- if nil != err {- return nil, err- }- if nil == ret {- return nil, av.ErrAttributeViewNotFound- }- return ret, nil+ if nil == ret {+ return nil, av.ErrAttributeViewNotFound}+ return}func getAttributeViewCarrierBlockTree(blockID string) *treenode.BlockTree {diff --git a/kernel/model/attribute_view_box_test.go b/kernel/model/attribute_view_box_test.goindex 94085788fc..f28dfffe74 100644--- a/kernel/model/attribute_view_box_test.go+++ b/kernel/model/attribute_view_box_test.go@@ -100,27 +100,6 @@ func TestAttributeViewCarrierUsesExactCryptoBoundary(t *testing.T) {0 != len(context.CurrentDocumentItemIDs) {t.Fatalf("cross-boundary context target should fail closed with no matched items: %#v, %v", context, contextErr)}-- rollupKey := &av.Key{ID: "foreign-rollup", Type: av.KeyTypeRollup,- Rollup: &av.Rollup{RelationKeyID: relationKey.ID, KeyID: "foreign-staff"}}- fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: rollupKey})- rollupContext := &av.AttributeViewContextFilter{Spec: av.AttributeViewContextFilterSpec, KeyID: rollupKey.ID}- if _, err = resolveAttributeViewContextFilterTarget(fixture.attrView, rollupContext, fixture.tree.Box); nil == err {- t.Fatal("rollup must not load an intermediate database across the carrier crypto boundary")- }- for _, field := range GetAttributeViewContextFilterFields(fixture.attrView, carrierBlockID) {- if field.ID == rollupKey.ID {- t.Fatal("rollup metadata must not expose an inaccessible intermediate database")- }- }-- localRelation := &av.Key{ID: "local-relation", Type: av.KeyTypeRelation,- Relation: &av.Relation{AvID: fixture.attrView.ID}}- fixture.attrView.KeyValues = append(fixture.attrView.KeyValues, &av.KeyValues{Key: localRelation})- rollupKey.Rollup.RelationKeyID, rollupKey.Rollup.KeyID = localRelation.ID, relationKey.ID- if _, err = resolveAttributeViewContextFilterTarget(fixture.attrView, rollupContext, fixture.tree.Box); nil == err {- t.Fatal("rollup must not load the final relation database across the carrier crypto boundary")- }}func TestTwoWayRelationWriteUsesCarrierCryptoBoundary(t *testing.T) {diff --git a/kernel/model/attribute_view_relation_rollup_test.go b/kernel/model/attribute_view_relation_rollup_test.godeleted file mode 100644index 5f33f6798e..0000000000--- a/kernel/model/attribute_view_relation_rollup_test.go+++ /dev/null@@ -1,79 +0,0 @@-// 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 (- "testing"-- "github.com/88250/lute/ast"- "github.com/siyuan-note/siyuan/kernel/av"-)--func TestAttributeViewContextFilterRelationRollup(t *testing.T) {- fixture := setupDatabaseBlockTransactionTest(t, true)- const blockID = "20260803091003-avblock"- employees := av.NewAttributeView(ast.NewNodeID())- employees.GetBlockKeyValues().Values = append(employees.GetBlockKeyValues().Values, &av.Value{- KeyID: employees.GetBlockKey().ID, BlockID: "employee", Type: av.KeyTypeBlock,- Block: &av.ValueBlock{ID: fixture.tree.Root.ID},- })- tasks := av.NewAttributeView(ast.NewNodeID())- staff := &av.Key{ID: ast.NewNodeID(), Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: employees.ID}}- tasks.KeyValues = append(tasks.KeyValues, &av.KeyValues{Key: staff})- projects := fixture.attrView- relation := &av.Key{ID: ast.NewNodeID(), Type: av.KeyTypeRelation, Relation: &av.Relation{AvID: tasks.ID}}- rollup := &av.Key{ID: ast.NewNodeID(), Name: "Employees", Type: av.KeyTypeRollup,- Rollup: &av.Rollup{RelationKeyID: relation.ID, KeyID: staff.ID}}- projects.KeyValues = append(projects.KeyValues, &av.KeyValues{Key: relation}, &av.KeyValues{Key: rollup})- for _, database := range []*av.AttributeView{employees, tasks, projects} {- if err := av.SaveAttributeView(database); nil != err {- t.Fatal(err)- }- }- t.Cleanup(func() {- av.SetAVBoxID(employees.ID, "")- av.SetAVBoxID(tasks.ID, "")- })- if _, err := setAttributeViewContextFilterForTest(blockID, projects.ID, rollup.ID); nil != err {- t.Fatal(err)- }- context, err := resolveAttributeViewFilterContext(projects, fixture.tableView, blockID)- if nil != err || nil == context || len(context.CurrentDocumentItemIDs) != 1 ||- context.CurrentDocumentItemIDs[0] != "employee" {- t.Fatalf("context did not resolve the final employee database: %+v, %v", context, err)- }- fields := GetAttributeViewContextFilterFields(projects, blockID)- found := false- for _, field := range fields {- if field.ID == rollup.ID {- found = field.TargetAvID == employees.ID- }- }- if !found {- t.Fatal("rollup context candidate did not expose the final database")- }- values := map[string]*av.Value{}- applyAttributeViewContextFilterDefaultValue(projects, "new-project", context, values)- if len(values) != 0 {- t.Fatal("read-only rollup context must not write defaults or intermediate relations")- }- rollup.Rollup.Calc = &av.RollupCalc{Operator: av.CalcOperatorCountAll}- context, err = resolveAttributeViewFilterContext(projects, fixture.tableView, blockID)- if nil != err || nil == context || len(context.CurrentDocumentItemIDs) != 0 {- t.Fatalf("invalidated rollup context must retain configuration and match nothing: %+v, %v", context, err)- }-}