Skip to content

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

:memo: Complete agent SQL embed guidance https://github.com/siyuan-note/siyuan/issues/20383

Daniel0ee3cdb2a4f0
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy
index 0fba72d054..6cac195cec 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy
@@ -6,7 +6,7 @@
"id": "20260804171004-aiagt03",
"title": "AI Agent",
"type": "doc",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
@@ -1140,12 +1140,12 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261010113646-aewwqju",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Structured SQL search"
+ "Data": "SQL queries, search and dynamic embeds"
}
],
"HeadingLevel": 2
@@ -1164,6 +1164,71 @@
}
]
},
+ {
+ "ID": "20261010172554-3btkysw",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-3btkysw",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "To display matching blocks dynamically in a document, ask the agent to create a native SQL query embed with block.insert, block.append or block.prepend. General SQL queries serve statistics and analysis; the search interface serves inspection and navigation; embeds store the query and display current matches. Displaying blocks requires complete block columns, rather than aggregates or projections."
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-6q4hhil",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-6q4hhil",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "A native SQL embed is a standalone Markdown block, for example "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "{{SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10}}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". When writing it, omit code fences and inline code markers, and separate it from surrounding content with blank lines."
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-kw579hi",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-kw579hi",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Before modifying an existing embed, read its stored SQL and block attributes with block.get_kramdown. Change only the SQL inside the outer double braces, retain the block ID, returned attributes and embed display settings, then update the same block with block.update and explicitly set lockType=true. Do not delete/recreate it or replace the whole document. Read it again to confirm the update. To reuse its SQL with sql.query or search, remove only the outer double braces. Unlock encrypted notebooks first and pass the owning notebook on block read/write and SQL query calls; their embeds query that notebook's isolated index."
+ }
+ ]
+ },
+ {
+ "ID": "20261010173100-8r4pamm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010173100-8r4pamm",
+ "updated": "20261010173100"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "The double braces and SQL of a Markdown embed must be on one physical line. For SQL requiring newlines, especially -- line comments, create a NodeBlockQueryEmbed using block.insert, block.append or block.prepend with dataType=dom. Put HTML-escaped SQL in data-content; encode a newline as 
. To modify it, read block.dom, preserve data-node-id and other attributes, change only data-content, then use block.update with dataType=dom and lockType=true. Never remove newlines or replace them with spaces. Kramdown may serialize embed newlines as _esc_newline_; restore actual newlines before querying or searching, or extract and decode SQL from block DOM."
+ }
+ ]
+ },
{
"ID": "20260804170109-sbl6g5j",
"Type": "NodeHeading",
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy
index b2a67b8f11..1a403bae2a 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy
@@ -6,7 +6,7 @@
"id": "20260804171000-aiagt01",
"title": "AI 智能体",
"type": "doc",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
@@ -1140,12 +1140,12 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261010113646-kdzs7xm",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
"Type": "NodeText",
- "Data": "结构化 SQL 搜索"
+ "Data": "SQL 查询、搜索与动态嵌入"
}
],
"HeadingLevel": 2
@@ -1164,6 +1164,71 @@
}
]
},
+ {
+ "ID": "20261010172554-83sbnfz",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-83sbnfz",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "如需在文档中动态展示匹配块,可让智能体通过 block.insert、block.append 或 block.prepend 创建原生 SQL 嵌入块。通用 SQL 查询用于统计与分析,搜索窗口用于查看与定位,嵌入块保存查询并显示当前匹配内容。展示块时应返回完整块字段,不能直接使用统计结果或部分字段。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-0t7vxgc",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-0t7vxgc",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "原生 SQL 嵌入使用独立的 Markdown 块,例如 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "{{SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10}}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。实际写入时不要包裹代码围栏或行内代码标记,并与前后内容之间保留空行。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-8tye4pw",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-8tye4pw",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "修改已有嵌入块时,先通过 block.get_kramdown 读取原始 SQL 和块属性,只修改外层双花括号中的 SQL,保留块 ID、返回的属性与嵌入显示设置,再用 block.update 更新同一块,并显式设置 lockType=true。不要删除重建或替换整个文档。更新后再次读取确认;将查询复用于 sql.query 或搜索窗口时,只去掉外层双花括号。加密笔记本需先解锁,并在块读写与 SQL 查询中传入所属 notebook;其中的嵌入查询使用该笔记本的隔离索引。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010173100-w3ijcw3",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010173100-w3ijcw3",
+ "updated": "20261010173100"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Markdown 嵌入的双花括号和 SQL 必须在同一行。对于需要换行的 SQL,特别是含 -- 行注释的查询,应通过 block.insert、block.append 或 block.prepend 使用 dataType=dom 创建 NodeBlockQueryEmbed,将 HTML 转义后的 SQL 放入 data-content 属性,换行可写为 
。修改时通过 block.dom 读取,保留 data-node-id 和其他属性,只改 data-content,再用 block.update、dataType=dom 和 lockType=true 更新。不要将换行直接删除或替换为空格。Kramdown 可能用 _esc_newline_ 保存嵌入的换行;将 SQL 用于查询或搜索前应恢复实际换行,或从块 DOM 中提取并解码 SQL。"
+ }
+ ]
+ },
{
"ID": "20260804170109-njpec5z",
"Type": "NodeHeading",
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy
index e82972d07f..53107b288e 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy
@@ -6,7 +6,7 @@
"id": "20260804171002-aiagt02",
"title": "AI 智能體",
"type": "doc",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
@@ -1140,12 +1140,12 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261010113646-gmbl8rw",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
"Type": "NodeText",
- "Data": "結構化 SQL 搜尋"
+ "Data": "SQL 查詢、搜尋與動態嵌入"
}
],
"HeadingLevel": 2
@@ -1164,6 +1164,71 @@
}
]
},
+ {
+ "ID": "20261010172554-kw70ky7",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-kw70ky7",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "如需在文件中動態顯示匹配區塊,可讓智能體透過 block.insert、block.append 或 block.prepend 建立原生 SQL 嵌入區塊。通用 SQL 查詢用於統計與分析,搜尋視窗用於查看與定位,嵌入區塊儲存查詢並顯示目前匹配內容。顯示區塊時應回傳完整區塊欄位,不能直接使用統計結果或部分欄位。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-evbp7ng",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-evbp7ng",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "原生 SQL 嵌入使用獨立的 Markdown 區塊,例如 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "{{SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10}}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。實際寫入時不要包覆程式碼圍欄或行內程式碼標記,並與前後內容之間保留空行。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-d86vd45",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-d86vd45",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "修改既有嵌入區塊時,先透過 block.get_kramdown 讀取原始 SQL 與區塊屬性,只修改外層雙大括號中的 SQL,保留區塊 ID、回傳的屬性與嵌入顯示設定,再用 block.update 更新同一個區塊,並明確設定 lockType=true。不要刪除重建或取代整份文件。更新後再次讀取確認;將查詢重用於 sql.query 或搜尋視窗時,只移除外層雙大括號。加密筆記本需先解鎖,並在區塊讀寫與 SQL 查詢中傳入所屬 notebook;其中的嵌入查詢使用該筆記本的隔離索引。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010173100-2229ah9",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010173100-2229ah9",
+ "updated": "20261010173100"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Markdown 嵌入的雙大括號與 SQL 必須在同一行。對於需要換行的 SQL,特別是含 -- 行註解的查詢,應透過 block.insert、block.append 或 block.prepend 使用 dataType=dom 建立 NodeBlockQueryEmbed,將 HTML 跳脫後的 SQL 放入 data-content 屬性,換行可寫為 
。修改時透過 block.dom 讀取,保留 data-node-id 與其他屬性,只改 data-content,再用 block.update、dataType=dom 與 lockType=true 更新。不要直接刪除換行或將其取代為空格。Kramdown 可能用 _esc_newline_ 儲存嵌入的換行;將 SQL 用於查詢或搜尋前應恢復實際換行,或從區塊 DOM 中擷取並解碼 SQL。"
+ }
+ ]
+ },
{
"ID": "20260804170109-gephumz",
"Type": "NodeHeading",
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy
index f81c0fe56f..1fb98d0d6d 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy
@@ -6,7 +6,7 @@
"id": "20260804171006-aiagt04",
"title": "AI エージェント",
"type": "doc",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
@@ -1128,12 +1128,12 @@
"Type": "NodeHeading",
"Properties": {
"id": "20261010113646-e4bfwsj",
- "updated": "20261010113646"
+ "updated": "20261010173100"
},
"Children": [
{
"Type": "NodeText",
- "Data": "構造に基づく SQL 検索"
+ "Data": "SQL クエリ、検索、動的埋め込み"
}
],
"HeadingLevel": 2
@@ -1152,6 +1152,71 @@
}
]
},
+ {
+ "ID": "20261010172554-3gmocso",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-3gmocso",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "文書内に一致するブロックを動的に表示するには、block.insert、block.append または block.prepend でネイティブ SQL 埋め込みブロックを作成するようエージェントに依頼します。汎用 SQL クエリは集計や分析、検索画面は結果の確認や移動に使用し、埋め込みはクエリを保存して現在の一致結果を表示します。ブロック表示には完全なブロック列が必要で、集計結果や一部の列は使用できません。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-los4ny5",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-los4ny5",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ネイティブ SQL 埋め込みには、独立した Markdown ブロックを使用します。例:"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "code",
+ "TextMarkTextContent": "{{SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10}}"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。実際に書き込む際はコードフェンスやインラインコード記号で囲まず、前後の内容と空行で区切ります。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010172554-nkhymve",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010172554-nkhymve",
+ "updated": "20261010172554"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "既存の埋め込みを変更する前に、block.get_kramdown で元の SQL とブロック属性を読み取ります。外側の二重波括弧内の SQL だけを変更し、ブロック ID、取得した属性と埋め込みの表示設定を保持したまま、block.update で同じブロックを更新し、lockType=true を明示します。削除して再作成したり、文書全体を置き換えたりしないでください。更新後は再度読み取り、確認します。sql.query や検索画面で再利用する場合は、外側の二重波括弧だけを取り除きます。暗号化ノートブックは先にロックを解除し、ブロックの読み書きと SQL クエリで所属する notebook を指定します。その埋め込みは当該ノートブックの分離された索引を使用します。"
+ }
+ ]
+ },
+ {
+ "ID": "20261010173100-j0996f2",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261010173100-j0996f2",
+ "updated": "20261010173100"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Markdown 埋め込みの二重波括弧と SQL は、同じ物理行に記述する必要があります。改行が必要な SQL、特に -- 行コメントを含むクエリには、block.insert、block.append または block.prepend の dataType=dom で NodeBlockQueryEmbed を作成します。HTML エスケープした SQL を data-content 属性に入れ、改行は 
 で表せます。変更時は block.dom で読み取り、data-node-id と他の属性を保持して data-content だけを編集し、block.update、dataType=dom、lockType=true で更新します。改行を削除したり空白に置き換えたりしないでください。Kramdown は埋め込みの改行を _esc_newline_ として保存することがあるため、クエリや検索に再利用する前に実際の改行へ戻すか、ブロック DOM から SQL を取得してデコードします。"
+ }
+ ]
+ },
{
"ID": "20260804170109-yrnzqjt",
"Type": "NodeHeading",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index ca43eaded9..27b6fc5fc5 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -59,6 +59,7 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their
## Tool Usage Patterns
- Find: search.fulltext (keyword) → block.get (by ID). For semantic search use search.semantic.
- Structural search: for block types, inline formats, ancestry or statistics, first fetch sql.schema, then use sql.query. To show matching blocks in the frontend, use native/frontend/open_search(query, method=2) with SELECT b.* FROM blocks b; use projections and aggregates only with sql.query.
+- Dynamic SQL in documents: reuse a complete-block query in a native {{SQL}} embed via block.insert/append/prepend. For single-line embeds, read block.get_kramdown, preserve ID and IAL, and update that block with lockType=true. For multiline SQL or -- comments, read block.dom and write dataType=dom with preserved metadata. Consult sql.schema for the workflow; never replace a dynamic embed with static results unless requested.
- Explore structure: document.list (children under an hPath) → document.get → block.get_children → block.get. Use block breadcrumb to trace a block's location.
- Create content: document.create (notebook + hPath) → block.append/prepend/insert.
- Modify: block.update replaces ONE block's content — it does NOT create or append new blocks. To both modify and add, call block.update first, then block.append/prepend/insert as separate calls.
diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.go
index 30781263f3..b5050533a2 100644
--- a/kernel/mcp/tools/block.go
+++ b/kernel/mcp/tools/block.go
@@ -37,6 +37,11 @@ Block placement:
- Headings (h1-h6) are leaf blocks; content shown below a heading is its following siblings, not its children. To place a block below a heading, use the heading ID (or the last block currently below it) as previousID, never as parentID.
- A list-item must have a NodeList parent and cannot directly contain another list-item. To nest lists, create a NodeList inside the outer list-item, then add list-items to the inner list.
+Native SQL query embeds (NodeBlockQueryEmbed):
+- Create a dynamic single-line {{SQL}} block using insert/append/prepend with dataType=markdown; see the data syntax and sql.schema for examples and how query, search and embeds differ.
+- Read a single-line embed's stored query and IAL with get_kramdown(id), edit only the SQL inside {{...}}, then update the same ID with dataType=markdown and lockType=true. Preserve the returned IAL and embed display settings; never replace the embed with static results or delete/recreate it.
+- Markdown embeds require one physical line. For multiline SQL or -- comments, use dom(id), edit only the HTML-escaped data-content attribute, and update with dataType=dom and lockType=true while retaining the ID and all other attributes. See sql.schema for newline encoding and reuse.
+
Native container structure and operations:
- These are native, editable blocks; do not substitute HTML widgets, Mermaid diagrams, or plugins unless requested.
- Tabs: NodeTabs contains only NodeTabItem; each item contains at least one body block and may contain nested tabs. Use an empty paragraph for an empty body. Use attr.set for tabs-position (top/left) and tabs-active-id (an existing direct item ID).
diff --git a/kernel/mcp/tools/content_syntax.go b/kernel/mcp/tools/content_syntax.go
index daa8805dbc..ca2cac7716 100644
--- a/kernel/mcp/tools/content_syntax.go
+++ b/kernel/mcp/tools/content_syntax.go
@@ -3,11 +3,22 @@
package tools
+// SQL 嵌入语法在内容写入说明和按需 SQL 指引中复用。
+const sqlEmbedMarkdownSyntax = `SQL query embeds (NodeBlockQueryEmbed):
+Use {{SQL}} as a standalone Markdown block to dynamically display matching blocks inside a document. For example:
+{{SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10}}
+Keep {{, the SQL and }} on one physical line and separate the embed from surrounding blocks with blank lines. Return complete block rows (SELECT * or SELECT b.* FROM blocks b); projections and aggregates belong in sql.query. Send the actual {{...}} text with dataType=markdown, without a code fence or inline backticks. A code fence displays SQL source as an ordinary code block. The embed stores the query and renders current matches; it is not a copied snapshot of the results.
+For SQL requiring newlines (especially -- comments), use block.insert/append/prepend with dataType=dom, a native NodeBlockQueryEmbed and SQL in its HTML-escaped data-content attribute. Example:
+<div data-type="NodeBlockQueryEmbed" data-content="-- recent paragraphs&#10;SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10"></div>
+Here &#10; retains the newline terminating the comment. Never flatten SQL comments or literal newlines to spaces; use block.dom to read/edit multiline embeds and preserve their attributes.`
+
// markdownContentSyntax 统一各内容写入工具的 Markdown 语法说明。
const markdownContentSyntax = `SiYuan Markdown syntax:
- Prefer standard Markdown for ordinary blocks and inline formatting: **bold**, *italic*, ~~strikethrough~~, ==mark==, and backticks for inline code.
- Block references must include anchor text. Use ((<blockID> "<static anchor text>")) for fixed text, required whenever the anchor text differs from the referenced block's content. Use ((<blockID> '<dynamic anchor text>')) for text that follows the target block's content, only when the anchor text is the target block's own content. Never use ((<blockID>)) or [[<blockID>]]. These forms are for note content; use normal SiYuan links in chat responses.
+` + sqlEmbedMarkdownSyntax + `
+
Super-block Markdown:
Prefer Markdown for creating super-blocks. Despite the token names, col is horizontal and row is vertical; never infer the visual direction from the English token alone. A horizontal super-block with two paragraphs is:
{{{col
diff --git a/kernel/mcp/tools/content_syntax_test.go b/kernel/mcp/tools/content_syntax_test.go
index e0cd4fe296..851ae203c8 100644
--- a/kernel/mcp/tools/content_syntax_test.go
+++ b/kernel/mcp/tools/content_syntax_test.go
@@ -6,6 +6,10 @@ package tools
import (
"strings"
"testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/editor"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestContentToolsShareMarkdownSyntax(t *testing.T) {
@@ -67,3 +71,58 @@ func TestDocumentedMarkdownExamplesCreateNativeContent(t *testing.T) {
})
}
}
+
+func TestDocumentedSQLQueryEmbedCreatesNativeBlock(t *testing.T) {
+ start := strings.Index(sqlEmbedMarkdownSyntax, "{{SELECT *")
+ if start < 0 {
+ t.Fatal("missing SQL embed example")
+ }
+ end := strings.Index(sqlEmbedMarkdownSyntax[start:], "}}")
+ if end < 0 {
+ t.Fatal("missing SQL embed example")
+ }
+ markdown := sqlEmbedMarkdownSyntax[start : start+end+2]
+ for _, data := range []string{markdown, "before\n\n" + markdown + "\n\nafter"} {
+ dom, err := prepareBlockWriteData(data, "markdown")
+ if err != nil {
+ t.Fatal(err)
+ }
+ tree := util.NewLute().BlockDOM2Tree(dom)
+ count := 0
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.Type == ast.NodeBlockQueryEmbed {
+ count++
+ if script := node.ChildByType(ast.NodeBlockQueryEmbedScript); script == nil ||
+ string(script.Tokens) != strings.TrimSuffix(strings.TrimPrefix(markdown, "{{"), "}}") {
+ t.Fatalf("embedded SQL changed: %+v", script)
+ }
+ }
+ return ast.WalkContinue
+ })
+ if count != 1 {
+ t.Fatalf("expected one native SQL embed, got %d: %s", count, dom)
+ }
+ }
+ codeDOM, err := prepareBlockWriteData("```sql\n"+markdown+"\n```", "markdown")
+ if err != nil || !strings.Contains(codeDOM, `data-type="NodeCodeBlock"`) ||
+ strings.Contains(codeDOM, `data-type="NodeBlockQueryEmbed"`) {
+ t.Fatalf("code fence must remain a code block: %s, %v", codeDOM, err)
+ }
+}
+
+func TestSQLQueryEmbedDOMPreservesMultilineSQL(t *testing.T) {
+ const query = "-- first comment\nSELECT * FROM blocks WHERE content = 'A&B'"
+ const data = `<div data-type="NodeBlockQueryEmbed" data-content="-- first comment&#10;SELECT * FROM blocks WHERE content = 'A&amp;B'"></div>`
+ dom, err := prepareBlockWriteData(data, "dom")
+ if err != nil {
+ t.Fatal(err)
+ }
+ node := util.NewLute().BlockDOM2Tree(dom).Root.FirstChild
+ if node.Type != ast.NodeBlockQueryEmbed {
+ t.Fatalf("expected native embed, got %s", node.Type)
+ }
+ script := node.ChildByType(ast.NodeBlockQueryEmbedScript)
+ if script == nil || strings.ReplaceAll(string(script.Tokens), editor.IALValEscNewLine, "\n") != query {
+ t.Fatalf("multiline SQL changed: %+v", script)
+ }
+}
diff --git a/kernel/mcp/tools/sql.go b/kernel/mcp/tools/sql.go
index ae79ae9b5e..5f2b63d332 100644
--- a/kernel/mcp/tools/sql.go
+++ b/kernel/mcp/tools/sql.go
@@ -29,7 +29,7 @@ const sqlQueryDefaultLimit = 100
var SQLTool = &Tool{
Name: "sql",
- Description: "Read-only SQL on SiYuan's database. Actions: schema() for table definitions, type codes, hierarchy and search examples; query(stmt) for statistics, arbitrary projections and structural searches. Results include raw structured rows and verified block links. Results default to at most 100 rows; use explicit LIMIT and OFFSET for pagination. For the frontend SQL search interface, use SELECT b.* FROM blocks b to return complete block rows; ordinary search filters do not apply to SQL.",
+ Description: "Read-only SQL on SiYuan's database. Actions: schema() for table definitions, type codes, hierarchy, search examples and native SQL embed create/read/update guidance; query(stmt) for statistics, arbitrary projections and structural searches. Results include raw structured rows and verified block links. Results default to at most 100 rows; use explicit LIMIT and OFFSET for pagination. For the frontend SQL search interface or dynamic document embeds, use SELECT b.* FROM blocks b to return complete block rows; ordinary search filters do not apply to SQL. Create or update document embeds through block tools, not SQL writes.",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
diff --git a/kernel/mcp/tools/sql_schema.go b/kernel/mcp/tools/sql_schema.go
index 88a1b3403f..ad745b35fd 100644
--- a/kernel/mcp/tools/sql_schema.go
+++ b/kernel/mcp/tools/sql_schema.go
@@ -7,6 +7,19 @@ Choose keyword search.fulltext for words; method=1 for query syntax, method=3 fo
To show blocks in the frontend, call native/frontend/open_search with method=2 and a query returning complete block rows (SELECT b.* FROM blocks b). Projections and aggregates belong in sql.query, not the search window. Newlines terminate -- comments; preserve them. Query results include original rows, columns, rowCount, defaultLimit, possiblyTruncated and verified blocks {id,url}. A possible truncation warning is conservative, not a total count. URLs use siyuan://blocks/ID; retrieve full content with block.get.
+## Dynamic SQL embeds in documents
+` + sqlEmbedMarkdownSyntax + `
+
+Choose sql.query for data or statistics, open_search(method=2) for inspecting matching blocks in the search interface, and a native SQL query embed for displaying current matches in a document. Reuse the same full-block SELECT statement, adding {{ and }} only when writing an embed; remove only those outer delimiters when passing its SQL to query/search tools. Never substitute an HTML widget or replace the embed with static query results.
+
+Create with block.insert(data="{{SELECT ...}}", dataType="markdown", parentID or previousID or nextID); append/prepend can add it under a parent container. Use the returned block ID for later operations. A heading is not a parent container: insert after its ID with previousID.
+
+Read an existing single-line embed with block.get_kramdown(id). This returns the stored {{SQL}} source plus block IAL attributes, not its rendered matches. Change only the SQL between the outer delimiters, preserve the returned IAL and existing ID, and call block.update(id, data=<modified Kramdown>, dataType="markdown", lockType=true). This replaces that embed in place and rejects an unintended block-type change; do not delete/recreate the block or update its whole document. Keep user attributes and embed display settings; the kernel maintains modification timestamps. Read it again to confirm the stored query and metadata. If the returned source is not an embed, inspect its type before editing.
+
+For multiline SQL, read block.dom(id), change only the data-content SQL on its NodeBlockQueryEmbed element and call block.update with dataType="dom" and lockType=true. Keep data-node-id and all other returned attributes. Decode HTML attribute entities when extracting SQL for query/search and HTML-escape them when writing DOM, including newline as &#10;. Kramdown may serialize embed newlines as _esc_newline_; this is an internal escape marker, not SQL text. Restore those markers to actual newlines before reusing SQL, or extract it from block.dom. Do not submit multiline {{SQL}} as raw Markdown, which does not create a native embed.
+
+For encrypted notebooks, pass the owning notebook ID as notebook on block read/write calls and on sql.query, and unlock it first. An embed in an encrypted notebook uses that notebook's isolated index; do not assume that it can query the global ordinary-notebook index. Use the existing tools rather than writing .sy files or database indexes directly.
+
## Indexed tables
- blocks(id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated): id is a block ID; parent_id is the immediate container block; root_id is its document ID (document id=root_id). box is the notebook ID. path is an internal ID-based document path; hpath is the title path. content is searchable plain text, markdown is formatted Markdown, fcontent is the first child content used for containers. Containers can aggregate descendant content: select leaf types to avoid duplicate matches. ial is serialized block attributes; created/updated are YYYYMMDDHHMMSS strings, sort is sibling ordering. Headings are leaf siblings, not parents of following sections.
- spans(id, block_id, root_id, box, path, content, markdown, type, ial): indexed inline elements. id is an index record ID, NOT an addressable block; join block_id=blocks.id. Images use type='img'; formatted text uses space-separated tokens beginning with 'textmark', e.g. 'textmark code', 'textmark strong code', 'textmark tag', 'textmark a', 'textmark block-ref'. Match tokens with (' ' || type || ' ') LIKE '% code %', not equality, when combined formats should match. Ordinary plain text is not a code span. content is the inline plain text; markdown preserves formatting.
diff --git a/kernel/model/block_update_test.go b/kernel/model/block_update_test.go
index 9dacbcda0f..38bf08c341 100644
--- a/kernel/model/block_update_test.go
+++ b/kernel/model/block_update_test.go
@@ -21,6 +21,7 @@ import (
"testing"
"github.com/88250/lute/ast"
+ "github.com/88250/lute/editor"
"github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -49,6 +50,92 @@ func TestNormalizeListItemBlockUpdateTree(t *testing.T) {
}
}
+func TestSQLQueryEmbedKramdownUpdatePreservesIdentityAndAttributes(t *testing.T) {
+ const (
+ id = "20261010180000-sqlembd"
+ rootID = "20261010180000-sqldocu"
+ boxID = "20261010180000-sqlbox1"
+ originalSQL = "SELECT * FROM blocks WHERE type = 'p' ORDER BY updated DESC LIMIT 10"
+ updatedSQL = "SELECT * FROM blocks WHERE type = 'h' ORDER BY updated DESC LIMIT 5"
+ )
+ luteEngine := util.NewLute()
+ original := "{{" + originalSQL + "}}\n{: id=\"" + id + "\" updated=\"20261010180000\" " +
+ "custom-test=\"kept\" custom-heading-mode=\"1\" style=\"color: red;\"}\n"
+ load := func() *parse.Tree {
+ dom, err := DataBlockDOM(original, luteEngine)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tree := luteEngine.BlockDOM2Tree(dom)
+ tree.ID, tree.Box, tree.Root.ID = rootID, boxID, rootID
+ return tree
+ }
+ reading := getBlockKramdown0(load(), id, "md", luteEngine)
+ if !strings.Contains(reading, "{{"+originalSQL+"}}") || !strings.Contains(reading, `custom-test="kept"`) {
+ t.Fatalf("Kramdown must return the query and attributes, not rendered matches: %q", reading)
+ }
+ tree := load()
+ build := func(data string) ([]*Operation, error) {
+ operations, _, err := buildBlockUpdateOperations([]BlockUpdateInput{
+ {ID: id, Data: data, DataType: "markdown", LockType: true},
+ }, func(string) *treenode.BlockTree {
+ return &treenode.BlockTree{ID: id, RootID: rootID, BoxID: boxID}
+ }, func(string) (*parse.Tree, error) { return tree, nil })
+ return operations, err
+ }
+ operations, err := build(strings.Replace(reading, originalSQL, updatedSQL, 1))
+ if err != nil || len(operations) != 1 || operations[0].ID != id || !operations[0].LockType {
+ t.Fatalf("embed update failed: %+v, %v", operations, err)
+ }
+ updated := treenode.GetNodeInTree(luteEngine.BlockDOM2Tree(operations[0].Data.(string)), id)
+ if updated == nil || updated.Type != ast.NodeBlockQueryEmbed {
+ t.Fatalf("embed identity, type or SQL changed: %+v", updated)
+ }
+ if script := updated.ChildByType(ast.NodeBlockQueryEmbedScript); script == nil || string(script.Tokens) != updatedSQL {
+ t.Fatalf("updated SQL changed: %+v", script)
+ }
+ for _, attribute := range []string{"custom-test", "custom-heading-mode", "style"} {
+ old := treenode.GetNodeInTree(tree, id)
+ if updated.IALAttr(attribute) != old.IALAttr(attribute) {
+ t.Fatalf("attribute %s changed", attribute)
+ }
+ }
+ if _, err = build("ordinary paragraph"); err == nil {
+ t.Fatal("locked SQL embed must reject conversion to a paragraph")
+ }
+}
+
+func TestSQLQueryEmbedDOMUpdatePreservesCommentsAndAttributes(t *testing.T) {
+ const (
+ id = "20261010190000-sqlembd"
+ rootID = "20261010190000-sqldocu"
+ query = "-- literal case and ampersand\nSELECT * FROM blocks WHERE content = 'A&B'"
+ )
+ luteEngine := util.NewLute()
+ data := `<div data-type="NodeBlockQueryEmbed" data-node-id="` + id +
+ `" custom-test="kept" custom-heading-mode="1" data-content="-- literal case and ampersand&#10;SELECT * FROM blocks WHERE content = 'A&amp;B'"></div>`
+ tree := luteEngine.BlockDOM2Tree(data)
+ tree.ID, tree.Root.ID = rootID, rootID
+ readDOM := luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)
+ updatedDOM := strings.Replace(readDOM, "A&amp;B", "C&amp;D", 1)
+ operations, _, err := buildBlockUpdateOperations([]BlockUpdateInput{
+ {ID: id, Data: updatedDOM, DataType: "dom", LockType: true},
+ }, func(string) *treenode.BlockTree { return &treenode.BlockTree{ID: id, RootID: rootID} },
+ func(string) (*parse.Tree, error) { return tree, nil })
+ if err != nil || len(operations) != 1 || operations[0].ID != id {
+ t.Fatalf("DOM embed update failed: %+v, %v", operations, err)
+ }
+ node := treenode.GetNodeInTree(luteEngine.BlockDOM2Tree(operations[0].Data.(string)), id)
+ if node == nil || node.Type != ast.NodeBlockQueryEmbed || node.IALAttr("custom-test") != "kept" ||
+ node.IALAttr("custom-heading-mode") != "1" {
+ t.Fatalf("DOM embed metadata changed: %+v", node)
+ }
+ script := node.ChildByType(ast.NodeBlockQueryEmbedScript)
+ if script == nil || strings.ReplaceAll(string(script.Tokens), editor.IALValEscNewLine, "\n") != strings.Replace(query, "A&B", "C&D", 1) {
+ t.Fatalf("DOM embed SQL changed: %+v", script)
+ }
+}
+
func TestResolveSuperBlockListItemAfterBlockDOMRoundTrip(t *testing.T) {
const oldID = "20260731010000-olditem"