Skip to content

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

:recycle: Migrate SQL query API contract https://github.com/siyuan-note/siyuan/issues/19378

Daniel2b26d96ec6b6
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index aabead1cc0..2ff6840edb 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -156,9 +156,9 @@ export type CriterionReplaceTypes = { "aHref": boolean; "aText": boolean; "aTitl
export type CriterionReplaceTypesInput = { "aHref"?: boolean | null; "aText"?: boolean | null; "aTitle"?: boolean | null; "blockRef"?: boolean | null; "code"?: boolean | null; "codeBlock"?: boolean | null; "docTitle"?: boolean | null; "em"?: boolean | null; "fileAnnotationRef"?: boolean | null; "htmlBlock"?: boolean | null; "imgSrc"?: boolean | null; "imgText"?: boolean | null; "imgTitle"?: boolean | null; "inlineMath"?: boolean | null; "inlineMemo"?: boolean | null; "kbd"?: boolean | null; "mark"?: boolean | null; "mathBlock"?: boolean | null; "s"?: boolean | null; "strong"?: boolean | null; "sub"?: boolean | null; "sup"?: boolean | null; "tag"?: boolean | null; "text"?: boolean | null; "u"?: boolean | null; };
-export type CriterionTypes = { "audioBlock": boolean; "blockquote": boolean; "callout": boolean; "codeBlock": boolean; "databaseBlock": boolean; "document": boolean; "embedBlock": boolean; "heading": boolean; "htmlBlock": boolean; "iframeBlock": boolean; "list": boolean; "listItem": boolean; "mathBlock": boolean; "paragraph": boolean; "superBlock": boolean; "table": boolean; "videoBlock": boolean; "widgetBlock": boolean; };
+export type CriterionTypes = { "audioBlock": boolean; "blockquote": boolean; "callout": boolean; "codeBlock": boolean; "databaseBlock": boolean; "document": boolean; "embedBlock": boolean; "heading": boolean; "htmlBlock": boolean; "iframeBlock": boolean; "list": boolean; "listItem": boolean; "mathBlock": boolean; "paragraph": boolean; "superBlock": boolean; "tabItem": boolean; "table": boolean; "tabs": boolean; "videoBlock": boolean; "widgetBlock": boolean; };
-export type CriterionTypesInput = { "audioBlock"?: boolean | null; "blockquote"?: boolean | null; "callout"?: boolean | null; "codeBlock"?: boolean | null; "databaseBlock"?: boolean | null; "document"?: boolean | null; "embedBlock"?: boolean | null; "heading"?: boolean | null; "htmlBlock"?: boolean | null; "iframeBlock"?: boolean | null; "list"?: boolean | null; "listItem"?: boolean | null; "mathBlock"?: boolean | null; "paragraph"?: boolean | null; "superBlock"?: boolean | null; "table"?: boolean | null; "videoBlock"?: boolean | null; "widgetBlock"?: boolean | null; };
+export type CriterionTypesInput = { "audioBlock"?: boolean | null; "blockquote"?: boolean | null; "callout"?: boolean | null; "codeBlock"?: boolean | null; "databaseBlock"?: boolean | null; "document"?: boolean | null; "embedBlock"?: boolean | null; "heading"?: boolean | null; "htmlBlock"?: boolean | null; "iframeBlock"?: boolean | null; "list"?: boolean | null; "listItem"?: boolean | null; "mathBlock"?: boolean | null; "paragraph"?: boolean | null; "superBlock"?: boolean | null; "tabItem"?: boolean | null; "table"?: boolean | null; "tabs"?: boolean | null; "videoBlock"?: boolean | null; "widgetBlock"?: boolean | null; };
export type DOMData = { "dom": string; };
@@ -388,6 +388,8 @@ export type RichClipboardPrepared = { "assets": Array<RichClipboardPreparedAsset
export type RichClipboardPreparedAsset = { "index": number; "path": string; };
+export type SQLQueryRequestInput = { "mode"?: string | null; "stmt": string; };
+
export type SearchBlock = { "alias": string; "box": string; "children": Array<SearchBlock | null> | null; "content": string; "count": number; "created": string; "defID": string; "defPath": string; "depth": number; "fcontent": string; "folded": boolean; "hPath": string; "ial": Record<string, string> | null; "id": string; "markdown": string; "memo": string; "name": string; "number"?: string; "parentID": string; "path": string; "refCount": number; "refText": string; "refs": Array<SearchBlock | null> | null; "riffCard": SearchBlockCard | null; "riffCardID": string; "rootID": string; "sort": number; "subType": string; "tag": string; "type": string; "updated": string; };
export type SearchBlockCard = { "due": string; "lapses": number; "lastReview": string; "reps": number; "state": number; };
@@ -772,7 +774,6 @@ export type APILegacyPOSTPath =
"/api/plugin/listLoadedPlugins" |
"/api/plugin/rpc" |
"/api/plugin/rpc/:name" |
- "/api/query/sql" |
"/api/ref/getBacklink2" |
"/api/ref/getBacklinkDoc" |
"/api/ref/getBackmentionDoc" |
@@ -1666,6 +1667,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": Petal | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/query/sql": {
+ request: SQLQueryRequestInput;
+ response: { "code": 0; "data": Array<Record<string, null | string | number | boolean> | null>; "limit": number; "msg": string; "truncated": boolean; } | ({ "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; } & { "limit"?: never; "truncated"?: never; });
+ body: "json";
+ };
"/api/repo/checkSnapshot": {
request: EmptyRequestInput;
response: { "code": 0; "data": CheckSnapshotData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.ts
index f7f1e4b29d..ae0ea1bfa5 100644
--- a/app/tests/api-contract.types.ts
+++ b/app/tests/api-contract.types.ts
@@ -6,6 +6,19 @@ declare const fetchGet: FetchGet;
declare const fetchSyncPost: FetchSyncPost;
declare const dynamicURL: string;
+fetchPost("/api/query/sql", {stmt: "SELECT 1", mode: "readonly"}, response => {
+ if (response.code === 0) {
+ const limit: number = response.limit;
+ const truncated: boolean = response.truncated;
+ const value: string | number | boolean | null | undefined = response.data[0]?.n;
+ void [limit, truncated, value];
+ }
+});
+// @ts-expect-error 查询语句不可缺省。
+fetchPost("/api/query/sql", {});
+// @ts-expect-error 查询模式必须为字符串或空值。
+fetchPost("/api/query/sql", {stmt: "SELECT 1", mode: true});
+
fetchPost("/api/file/getFile", {path: "data/storage/plugin.json"}, response => {
const content: JSONValue = response;
// @ts-expect-error 文件内容可能是文本、数组或空值,不能直接按信封读取。
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 0a87f0f5f2..67b069ce48 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -24,6 +24,8 @@ Encrypted notebook lifecycle endpoints use typed requests and responses while re
## Compatibility requirements
+SQL query contracts retain `limit` and `truncated` at the success envelope's top level. `SuccessSQL` attaches this metadata while failures omit it. Row names come from the query; each value is a JSON scalar, preserving integer digits and Base64 serialization of binary values. Statement trimming, optional mode handling, single-statement and read-only checks, and code `1` query errors remain unchanged.
+
Contract maintenance must preserve existing observable API behavior. Changes to type definitions or handler structure alone must not change call semantics:
- Request semantics: preserve body requirements, field optionality, and distinctions between an empty body, missing fields, `null`, empty strings, empty objects, and empty arrays
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index af4808599a..c2034bb7cb 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -24,6 +24,8 @@
## 兼容要求
+SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQL` 附加这些信息,失败响应不包含它们。结果列名由查询决定,每个值为 JSON 标量,保留整数位数和二进制值的 Base64 序列化。语句去除首尾空白、可选模式、单语句与只读检查,以及查询错误码 `1` 均保持不变。
+
契约维护必须保留接口已有的可观察行为,不能仅因类型定义或处理函数重构而改变调用语义:
- 请求语义:保持请求体是否必需、字段是否可缺省,以及空请求体、缺失字段、`null`、空字符串、空对象和空数组的区别
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 6abd939f74..5a803974ed 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -2758,7 +2758,7 @@
* `idPath`:検索範囲のパス配列
* `k`:検索キーワード
* `r`:置換キーワード
-* `types`:ブロックタイプのフラグ。`mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock`、`callout` を使用できます
+* `types`:ブロックタイプのフラグ。`mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock`、`callout`、`tabs`、`tabItem` を使用できます
* `subTypes`:独立したサブタイプグループです。`heading` は `h1` から `h6`、`list` と `listItem` はそれぞれ `o`(順序付き)、`u`(順序なし)、`t`(タスク)を指定します。グループが省略、空、または全フラグが `false` の場合、その親タイプのサブタイプは制限されません。親タイプは `types` で有効にする必要があります。旧形式の `h1` から `h6` および `o`、`u`、`t` を含む未知のトップレベルキーはエラーなく無視されるため、旧形式で保存したサブタイプは選択して保存し直してください
* `replaceTypes`:置換タイプのフラグ。`text`、`imgText`、`imgTitle`、`imgSrc`、`aText`、`aTitle`、`aHref`、`code`、`em`、`strong`、`inlineMath`、`inlineMemo`、`blockRef`、`fileAnnotationRef`、`kbd`、`mark`、`s`、`sub`、`sup`、`tag`、`u`、`docTitle`、`codeBlock`、`mathBlock`、`htmlBlock` を使用できます
diff --git a/docs/API.md b/docs/API.md
index 84ab7a29d0..7ac0a0d6c6 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -2821,7 +2821,7 @@ Saved search criteria use the following fields:
* `idPath`: Search scope path array
* `k`: Search keyword
* `r`: Replacement keyword
-* `types`: Block type flags. Supported keys are `mathBlock`, `table`, `blockquote`, `superBlock`, `paragraph`, `document`, `heading`, `list`, `listItem`, `codeBlock`, `htmlBlock`, `embedBlock`, `databaseBlock`, `audioBlock`, `videoBlock`, `iframeBlock`, `widgetBlock`, and `callout`
+* `types`: Block type flags. Supported keys are `mathBlock`, `table`, `blockquote`, `superBlock`, `paragraph`, `document`, `heading`, `list`, `listItem`, `codeBlock`, `htmlBlock`, `embedBlock`, `databaseBlock`, `audioBlock`, `videoBlock`, `iframeBlock`, `widgetBlock`, `callout`, `tabs`, and `tabItem`
* `subTypes`: Independent subtype groups: `heading` accepts `h1` through `h6`; `list` and `listItem` each accept `o` (ordered), `u` (unordered), and `t` (task). A missing or empty group, or a group with all flags `false`, leaves that parent type unrestricted by subtype. The parent must still be enabled in `types`. Unknown top-level keys, including the former flat `h1`–`h6` and `o`/`u`/`t` flags, are ignored without error; saved subtype selections in that format must be selected and saved again
* `replaceTypes`: Replacement type flags. Supported keys are `text`, `imgText`, `imgTitle`, `imgSrc`, `aText`, `aTitle`, `aHref`, `code`, `em`, `strong`, `inlineMath`, `inlineMemo`, `blockRef`, `fileAnnotationRef`, `kbd`, `mark`, `s`, `sub`, `sup`, `tag`, `u`, `docTitle`, `codeBlock`, `mathBlock`, and `htmlBlock`
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index bbf2537db9..96074cd8bd 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -2776,7 +2776,7 @@ if (response.code === 0 && response.data) {
* `idPath`:搜索范围路径数组
* `k`:搜索关键字
* `r`:替换关键字
-* `types`:块类型开关,支持 `mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock` 和 `callout`
+* `types`:块类型开关,支持 `mathBlock`、`table`、`blockquote`、`superBlock`、`paragraph`、`document`、`heading`、`list`、`listItem`、`codeBlock`、`htmlBlock`、`embedBlock`、`databaseBlock`、`audioBlock`、`videoBlock`、`iframeBlock`、`widgetBlock`、`callout`、`tabs` 和 `tabItem`
* `subTypes`:独立的子类型分组,`heading` 使用 `h1` 至 `h6`,`list` 和 `listItem` 分别使用 `o`(有序)、`u`(无序)和 `t`(任务)。分组缺省、为空或所有开关为 `false` 时,不限制该父类型的子类型;父类型仍须在 `types` 中启用。未知顶层键(包括旧扁平格式的 `h1` 至 `h6` 和 `o`、`u`、`t`)会被忽略且不报错,旧格式中保存的子类型选择需要重新选择并保存
* `replaceTypes`:替换类型开关,支持 `text`、`imgText`、`imgTitle`、`imgSrc`、`aText`、`aTitle`、`aHref`、`code`、`em`、`strong`、`inlineMath`、`inlineMemo`、`blockRef`、`fileAnnotationRef`、`kbd`、`mark`、`s`、`sub`、`sup`、`tag`、`u`、`docTitle`、`codeBlock`、`mathBlock` 和 `htmlBlock`
diff --git a/kernel/api/contract_query_test.go b/kernel/api/contract_query_test.go
new file mode 100644
index 0000000000..e19b01f6db
--- /dev/null
+++ b/kernel/api/contract_query_test.go
@@ -0,0 +1,56 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+// testSQLContractQueries 使用契约测试进程的独立数据库,避免修改运行中的工作空间。
+func testSQLContractQueries(t *testing.T) {
+ t.Helper()
+ limit := model.Conf.Search.Limit
+ model.Conf.Search.Limit = 2
+ defer func() { model.Conf.Search.Limit = limit }()
+ engine := gin.New()
+ engine.POST("/api/query/sql", SQL)
+ for _, entry := range []struct {
+ body string
+ code, count, limit int
+ truncated bool
+ }{
+ {`{"stmt":" SELECT 1 AS n UNION SELECT 2 UNION SELECT 3 "}`, 0, 2, 2, true},
+ {`{"stmt":"SELECT 1 AS n UNION SELECT 2 UNION SELECT 3 LIMIT 3","mode":"readonly"}`, 0, 3, 0, false},
+ {`{"stmt":"SELECT 1 AS n WHERE 0","mode":null}`, 0, 0, 2, false},
+ {`{"stmt":"SELECT 1; SELECT 2 AS n","mode":"multiple"}`, 0, 1, 2, false},
+ {`{"stmt":"SELECT * FROM missing_contract_table"}`, 1, 0, 0, false},
+ {`{"stmt":"SELECT 1; SELECT 2"}`, -1, 0, 0, false},
+ {`{"stmt":"DELETE FROM blocks","mode":"readonly"}`, -1, 0, 0, false},
+ {`{"stmt":"SELECT 1","mode":" readonly "}`, -1, 0, 0, false},
+ {`{"stmt":null}`, -1, 0, 0, false},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/query/sql", strings.NewReader(entry.body)))
+ requireAPIContract(t, "POST", "/api/query/sql", recorder)
+ var response struct {
+ Code int `json:"code"`
+ Data []map[string]json.RawMessage `json:"data"`
+ Limit *int `json:"limit"`
+ Truncated *bool `json:"truncated"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != entry.code {
+ t.Fatalf("query response changed: %s, %v", recorder.Body.String(), err)
+ }
+ if entry.code != 0 {
+ if response.Limit != nil || response.Truncated != nil || response.Data != nil {
+ t.Fatalf("query failure leaked success metadata: %s", recorder.Body.String())
+ }
+ } else if response.Data == nil || len(response.Data) != entry.count || response.Limit == nil || *response.Limit != entry.limit || response.Truncated == nil || *response.Truncated != entry.truncated {
+ t.Fatalf("query limit behavior changed: %s", recorder.Body.String())
+ }
+ }
+}
diff --git a/kernel/api/contract_test.go b/kernel/api/contract_test.go
index 547932b183..e720d42349 100644
--- a/kernel/api/contract_test.go
+++ b/kernel/api/contract_test.go
@@ -158,6 +158,7 @@ func TestAPIContractHandlers(t *testing.T) {
return response
}
admin := model.RoleAdministrator
+ testSQLContractQueries(t)
blockQueries := []struct {
path string
handler gin.HandlerFunc
diff --git a/kernel/api/sql.go b/kernel/api/sql.go
index dc12837c7d..3c9c0e3161 100644
--- a/kernel/api/sql.go
+++ b/kernel/api/sql.go
@@ -17,14 +17,12 @@
package api
import (
- "github.com/siyuan-note/siyuan/kernel/apicontract"
- "net/http"
+ "encoding/json"
- "github.com/88250/gulu"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/sql"
- "github.com/siyuan-note/siyuan/kernel/util"
)
var flushTransaction = contractHandler(apicontract.FlushTransaction, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.Null] {
@@ -36,65 +34,41 @@ var flushTransaction = contractHandler(apicontract.FlushTransaction, func(c *gin
return apicontract.Success(apicontract.Null{})
})
-func SQL(c *gin.Context) {
- ret := gulu.Ret.NewResult()
- var limitInfo *sql.QueryLimitInfo
- defer func() {
- c.JSON(http.StatusOK, struct {
- *gulu.Result
- *sql.QueryLimitInfo
- }{ret, limitInfo})
- }()
-
- arg, ok := util.JsonArg(c, ret)
- if !ok {
- return
- }
-
- var stmt, mode string
- if !util.ParseJsonArgs(arg, ret,
- util.BindJsonArg("stmt", &stmt, true, true),
- util.BindJsonArg("mode", &mode, false, false),
- ) {
- return
- }
-
+var SQL = contractHandler(apicontract.QuerySQL, func(c *gin.Context, request apicontract.SQLQueryRequest) apicontract.Response[apicontract.SQLRows] {
+ stmt, mode := request.Stmt, request.Mode
switch mode {
case "":
// 默认模式,允许单条语句
if err := sql.CheckSingleStatement(stmt); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.SQLRows](-1, err.Error())
}
case "readonly":
// 只读模式,允许单条语句
if err := sql.CheckSingleStatement(stmt); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.SQLRows](-1, err.Error())
}
if err := sql.CheckReadonlyStatement(stmt); err != nil {
- ret.Code = -1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.SQLRows](-1, err.Error())
}
case "multiple":
// 多语句模式,不做校验
default:
// 未知模式
- ret.Code = -1
- ret.Msg = "unknown [mode]"
- return
+ return apicontract.Failure[apicontract.SQLRows](-1, "unknown [mode]")
}
result, info, err := sql.QueryWithLimitInfo(stmt, model.Conf.Search.Limit)
if err != nil {
- ret.Code = 1
- ret.Msg = err.Error()
- return
+ return apicontract.Failure[apicontract.SQLRows](1, err.Error())
}
- ret.Data = result
- limitInfo = &info
-}
+ data, err := json.Marshal(result)
+ if err != nil {
+ return apicontract.Failure[apicontract.SQLRows](1, err.Error())
+ }
+ var rows apicontract.SQLRows
+ if err = json.Unmarshal(data, &rows); err != nil {
+ return apicontract.Failure[apicontract.SQLRows](1, err.Error())
+ }
+ return apicontract.SuccessSQL(rows, info.Limit, info.Truncated)
+})
diff --git a/kernel/api/storage_test.go b/kernel/api/storage_test.go
index a800672959..a8ef2f8eba 100644
--- a/kernel/api/storage_test.go
+++ b/kernel/api/storage_test.go
@@ -20,6 +20,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "reflect"
"strings"
"testing"
@@ -52,6 +53,7 @@ func TestCriteriaCRUD(t *testing.T) {
}
type criterionData struct {
Name string `json:"name"`
+ Types map[string]bool `json:"types"`
SubTypes model.SearchSubTypes `json:"subTypes"`
}
getCriteria := func() []criterionData {
@@ -88,6 +90,32 @@ func TestCriteriaCRUD(t *testing.T) {
t.Fatalf("criterion was not overwritten: %#v", criteria)
}
+ typeKeys := []string{
+ "document", "heading", "paragraph", "list", "listItem", "codeBlock", "mathBlock", "table",
+ "blockquote", "superBlock", "htmlBlock", "embedBlock", "databaseBlock", "audioBlock",
+ "videoBlock", "iframeBlock", "widgetBlock", "callout", "tabs", "tabItem",
+ }
+ for _, enabled := range []bool{true, false} {
+ wantTypes := make(map[string]bool, len(typeKeys))
+ for _, key := range typeKeys {
+ wantTypes[key] = enabled
+ }
+ body, err := json.Marshal(map[string]criterionData{
+ "criterion": {Name: "Public notes", Types: wantTypes},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ recorder := perform("/api/storage/setCriterion", string(body))
+ if responseCode(t, recorder) != 0 {
+ t.Fatalf("set criterion types failed: %s", recorder.Body.String())
+ }
+ criteria = getCriteria()
+ if len(criteria) != 1 || !reflect.DeepEqual(criteria[0].Types, wantTypes) {
+ t.Fatalf("criterion type keys or values changed after persistence: got %#v, want %#v", criteria, wantTypes)
+ }
+ }
+
removeRecorder := perform("/api/storage/removeCriterion", `{"name":"Public notes"}`)
if responseCode(t, removeRecorder) != 0 {
t.Fatalf("remove criterion failed: %s", removeRecorder.Body.String())
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 1f5db23dee..5b9d1c2da1 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -486,3 +486,5 @@ var PutFile = define[PutFileRequest, Null]("putFile", "/api/file/putFile", FormB
var GetFile = define[FilePathRequest, BinaryContent]("getFile", "/api/file/getFile", JSONBody,
ResponseOptions{Output: BinaryOutput, ErrorStatus: 202, AdditionalCodes: []int{-3, 403, 404, 409, 500, 503}}, "POST")
+
+var QuerySQL = define[SQLQueryRequest, SQLRows]("SQL", "/api/query/sql", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, NonNullable: true}, "POST")
diff --git a/kernel/apicontract/criterion.go b/kernel/apicontract/criterion.go
index 2856303381..500d3e1fcc 100644
--- a/kernel/apicontract/criterion.go
+++ b/kernel/apicontract/criterion.go
@@ -36,6 +36,8 @@ type CriterionTypes struct {
IFrameBlock bool `json:"iframeBlock" api:"optional,nullable"`
WidgetBlock bool `json:"widgetBlock" api:"optional,nullable"`
Callout bool `json:"callout" api:"optional,nullable"`
+ Tabs bool `json:"tabs" api:"optional,nullable"`
+ TabItem bool `json:"tabItem" api:"optional,nullable"`
}
type CriterionReplaceTypes struct {
diff --git a/kernel/apicontract/legacy_routes.json b/kernel/apicontract/legacy_routes.json
index 38e1345b8b..597b13dc8f 100644
--- a/kernel/apicontract/legacy_routes.json
+++ b/kernel/apicontract/legacy_routes.json
@@ -254,7 +254,6 @@
{"method":"POST","path":"/api/plugin/listLoadedPlugins","handler":"listLoadedPlugins"},
{"method":"POST","path":"/api/plugin/rpc","handler":"pluginJsonRpcHttp"},
{"method":"POST","path":"/api/plugin/rpc/:name","handler":"pluginJsonRpcHttp"},
- {"method":"POST","path":"/api/query/sql","handler":"SQL"},
{"method":"POST","path":"/api/ref/getBacklink2","handler":"getBacklink2"},
{"method":"POST","path":"/api/ref/getBacklinkDoc","handler":"getBacklinkDoc"},
{"method":"POST","path":"/api/ref/getBackmentionDoc","handler":"getBackmentionDoc"},
diff --git a/kernel/apicontract/query.go b/kernel/apicontract/query.go
new file mode 100644
index 0000000000..87b8b6b50b
--- /dev/null
+++ b/kernel/apicontract/query.go
@@ -0,0 +1,43 @@
+package apicontract
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+)
+
+type SQLQueryRequest struct {
+ Stmt string `json:"stmt" api:"trim"`
+ Mode string `json:"mode" api:"optional,nullable"`
+}
+
+// SQLValue 保留数据库标量的 JSON 表示,包括整数精度和二进制值的 Base64 文本。
+type SQLValue struct{ raw json.RawMessage }
+
+func (v SQLValue) MarshalJSON() ([]byte, error) {
+ if len(v.raw) == 0 {
+ return []byte("null"), nil
+ }
+ return v.raw, nil
+}
+
+func (v *SQLValue) UnmarshalJSON(data []byte) error {
+ data = bytes.TrimSpace(data)
+ if !json.Valid(data) || data[0] == '{' || data[0] == '[' {
+ return fmt.Errorf("SQL value must be a JSON scalar")
+ }
+ v.raw = append(v.raw[:0], data...)
+ return nil
+}
+
+type SQLRows []map[string]SQLValue
+
+type SQLQueryLimit struct {
+ Limit int `json:"limit"`
+ Truncated bool `json:"truncated"`
+}
+
+// SuccessSQL 将限额信息保留在信封顶层,查询结果仍位于 data。
+func SuccessSQL(rows SQLRows, limit int, truncated bool) Response[SQLRows] {
+ return Response[SQLRows]{data: rows, queryLimit: &SQLQueryLimit{Limit: limit, Truncated: truncated}}
+}
diff --git a/kernel/apicontract/query_test.go b/kernel/apicontract/query_test.go
new file mode 100644
index 0000000000..749c4b7b69
--- /dev/null
+++ b/kernel/apicontract/query_test.go
@@ -0,0 +1,33 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestSQLResponseScalarsAndMetadata(t *testing.T) {
+ var rows SQLRows
+ if err := json.Unmarshal([]byte(`[{"integer":9223372036854775807,"binary":"AP8=","null":null,"boolean":true,"real":1.25}]`), &rows); err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(SuccessSQL(rows, 2, false))
+ if err != nil || !strings.Contains(string(data), `9223372036854775807`) || !strings.Contains(string(data), `"truncated":false`) {
+ t.Fatalf("SQL scalar precision or metadata changed: %s, %v", data, err)
+ }
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = bundle.ValidateResponse("POST", "/api/query/sql", data); err != nil {
+ t.Fatal(err)
+ }
+ if err = bundle.ValidateResponse("POST", "/api/query/sql", []byte(`{"code":0,"msg":"","data":[]}`)); err == nil {
+ t.Fatal("query success requires limit metadata")
+ }
+ for _, invalid := range []string{`[{"value":[]}]`, `[{"value":{}}]`} {
+ if err := json.Unmarshal([]byte(invalid), &rows); err == nil {
+ t.Fatal("SQL scalar accepted a composite value")
+ }
+ }
+}
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index 7c2396eab5..b7b44f58a1 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -58,10 +58,11 @@ func (Null) MarshalJSON() ([]byte, error) { return []byte("null"), nil }
// Response 的载荷仅能通过有类型的成功构造函数或明确的错误构造函数设置。
type Response[Data any] struct {
- code int
- msg string
- data any
- binary *BinaryContent
+ code int
+ msg string
+ data any
+ binary *BinaryContent
+ queryLimit *SQLQueryLimit
}
func Success[Data any](data Data) Response[Data] { return Response[Data]{data: data} }
@@ -89,5 +90,6 @@ func (r Response[Data]) MarshalJSON() ([]byte, error) {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
- }{r.code, r.msg, r.data})
+ *SQLQueryLimit
+ }{r.code, r.msg, r.data, r.queryLimit})
}
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index 919ef386c3..bc2a79e6e2 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -75,6 +75,9 @@ func nonnullable(schema *Schema) *Schema {
}
func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {
+ if t == reflect.TypeFor[SQLValue]() {
+ return &Schema{AnyOf: []*Schema{{Type: "null"}, {Type: "string"}, {Type: "number"}, {Type: "boolean"}}}, nil
+ }
if t == reflect.TypeFor[BinaryContent]() {
if input {
return nil, fmt.Errorf("binary content can only appear in responses")
@@ -352,6 +355,11 @@ func BuildBundle() (*Bundle, error) {
data = nonnullable(data)
}
success := object(map[string]*Schema{"code": {Type: "integer", Enum: []any{0}}, "msg": {Type: "string"}, "data": data}, "code", "msg", "data")
+ if definition.Data == reflect.TypeFor[SQLRows]() {
+ success.Properties["limit"] = &Schema{Type: "integer"}
+ success.Properties["truncated"] = &Schema{Type: "boolean"}
+ success.Required = append(success.Required, "limit", "truncated")
+ }
if definition.Output == BinaryOutput {
success = data
// fetch 按媒体类型将文件读作文本或 JSON,JSON 文件本身没有信封约束。
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 58c747609c..c6d854ab8b 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -2665,9 +2665,15 @@
"superBlock": {
"type": "boolean"
},
+ "tabItem": {
+ "type": "boolean"
+ },
"table": {
"type": "boolean"
},
+ "tabs": {
+ "type": "boolean"
+ },
"videoBlock": {
"type": "boolean"
},
@@ -2691,7 +2697,9 @@
"mathBlock",
"paragraph",
"superBlock",
+ "tabItem",
"table",
+ "tabs",
"videoBlock",
"widgetBlock"
],
@@ -2850,6 +2858,16 @@
}
]
},
+ "tabItem": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"table": {
"anyOf": [
{
@@ -2860,6 +2878,16 @@
}
]
},
+ "tabs": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"videoBlock": {
"anyOf": [
{
@@ -6268,6 +6296,28 @@
],
"additionalProperties": false
},
+ "SQLQueryRequestInput": {
+ "type": "object",
+ "properties": {
+ "mode": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "stmt": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "stmt"
+ ],
+ "additionalProperties": false
+ },
"SearchBlock": {
"type": "object",
"properties": {
@@ -19786,6 +19836,116 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/query/sql",
+ "handler": "SQL",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/SQLQueryRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "type": "array",
+ "items": {
+ "anyOf": [
+ {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "type": "null"
+ },
+ {
+ "type": "string"
+ },
+ {
+ "type": "number"
+ },
+ {
+ "type": "boolean"
+ }
+ ]
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "limit": {
+ "type": "integer"
+ },
+ "msg": {
+ "type": "string"
+ },
+ "truncated": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data",
+ "limit",
+ "truncated"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1,
+ 1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/repo/checkSnapshot",
diff --git a/kernel/cli/cmd/search.go b/kernel/cli/cmd/search.go
index ae2c59d7fb..09d9468f55 100644
--- a/kernel/cli/cmd/search.go
+++ b/kernel/cli/cmd/search.go
@@ -214,7 +214,7 @@ func init() {
searchCmd.Flags().StringArray("ext", nil, "asset file extension filter, repeatable, e.g. --ext pdf --ext docx (asset mode only)")
searchCmd.Flags().StringArrayP("notebook", "n", nil, "notebook ID filter (repeatable)")
searchCmd.Flags().StringArray("path", nil, "path prefix filter (repeatable)")
- searchCmd.Flags().StringArrayP("type", "t", nil, "block type filter, repeatable (document heading paragraph list listItem codeBlock mathBlock table blockquote superBlock htmlBlock embedBlock databaseBlock audioBlock videoBlock iframeBlock widgetBlock callout)")
+ searchCmd.Flags().StringArrayP("type", "t", nil, "block type filter, repeatable (document heading paragraph list listItem codeBlock mathBlock table blockquote superBlock htmlBlock embedBlock databaseBlock audioBlock videoBlock iframeBlock widgetBlock callout tabs tabItem)")
searchCmd.Flags().StringArray("subtype", nil, "block subtype filter, repeatable (h1-h6, list:o, list:u, list:t, listItem:o, listItem:u, listItem:t)")
searchCmd.Flags().IntP("method", "m", 0, "search method: 0=keyword 1=query-syntax 2=sql 3=regex 4=semantic (asset mode ignores 4=semantic; uses 0-3 with same meanings)")
searchCmd.Flags().IntP("order-by", "o", 0, "order — blocks: 0=type 1=created-asc 2=created-desc 3=updated-asc 4=updated-desc 5=content 6=relevance-asc 7=relevance-desc; asset: 0=relevance-desc 1=relevance-asc 2=updated-asc 3=updated-desc")
diff --git a/kernel/model/storage.go b/kernel/model/storage.go
index 4335f3feda..0ab6f2660c 100644
--- a/kernel/model/storage.go
+++ b/kernel/model/storage.go
@@ -158,6 +158,8 @@ type CriterionTypes struct {
IFrameBlock bool `json:"iframeBlock"`
WidgetBlock bool `json:"widgetBlock"`
Callout bool `json:"callout"`
+ Tabs bool `json:"tabs"`
+ TabItem bool `json:"tabItem"`
}
type CriterionReplaceTypes struct {