Skip to content

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

:art: Expose default row limit and truncation in SQL API responses https://github.com/siyuan-note/siyuan/issues/19337

Danielf97b7be20b0f
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 499c060c62..d34f75a39c 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -1271,6 +1271,9 @@
```
* `stmt`: SQL文
+
+外側の `LIMIT` を明示しない場合、返される結果は既定で `search.limit` 行(設定の検索結果件数)までです。ページ分割には `LIMIT` と `OFFSET` を明示し、`ORDER BY hpath, id` のように順序が安定して一意に決まる並べ替えを使用してください。外側の `LIMIT` を明示すると既定の制限を上書きでき、`search.limit` より大きい値も指定できます。
+
* 戻り値
```json
@@ -1279,10 +1282,14 @@
"msg": "",
"data": [
{ "col": "val" }
- ]
+ ],
+ "limit": 0,
+ "truncated": false
}
```
+成功時の `data` は配列のままです。`limit` は今回のクエリに適用されたサーバーの既定の上限を表し、SQL に外側の `LIMIT` が明示されている場合は `0` になります。明示された句の値を表すものではありません。`truncated` は、サーバーの既定の制限によって少なくとも1行が返されなかった場合にのみ `true` になります。結果が上限と同じ件数でも、省略された行がなければ `false` です。上記の例では `LIMIT 7` が明示されているため、`limit` は `0`、`truncated` は `false` です。エラー応答にはこの2つのフィールドは含まれません。
+
注:データセキュリティを確保するため、パブリッシュモードでの本インターフェースへのアクセスは禁止されています。
### トランザクションをフラッシュ
diff --git a/docs/API.md b/docs/API.md
index 27808379f4..91484d136a 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1275,6 +1275,9 @@ Move documents by `id`:
```
* `stmt`: SQL statement
+
+Without an explicit outer `LIMIT`, results default to at most `search.limit` rows (the configured search result limit). Use explicit `LIMIT` and `OFFSET` clauses to paginate, with a stable, unique ordering such as `ORDER BY hpath, id`. An explicit outer `LIMIT` overrides the default, including values larger than `search.limit`.
+
* Return value
```json
@@ -1283,10 +1286,14 @@ Move documents by `id`:
"msg": "",
"data": [
{ "col": "val" }
- ]
+ ],
+ "limit": 0,
+ "truncated": false
}
```
+On success, `data` remains an array. `limit` is the server default limit applied to this query, or `0` when the SQL supplies an explicit outer `LIMIT`; it is not the value of that explicit clause. `truncated` is `true` only when the server default limit omitted at least one result row. Exactly reaching the limit does not imply truncation. For the example above, `LIMIT 7` is explicit, so `limit` is `0` and `truncated` is `false`. These fields are omitted on errors.
+
Note: To ensure data security, access to this interface is prohibited in Publish Mode.
### Flush transaction
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index 6d1bfd9eee..f3a61d01fc 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -1271,6 +1271,9 @@
```
* `stmt`:SQL 脚本
+
+未显式指定外层 `LIMIT` 时,默认最多返回 `search.limit` 行,即设置中的搜索结果条数。请使用显式的 `LIMIT` 和 `OFFSET` 分页,并采用稳定且唯一的排序,例如 `ORDER BY hpath, id`。显式外层 `LIMIT` 会覆盖默认限制,可以大于 `search.limit`。
+
* 返回值
```json
@@ -1279,10 +1282,14 @@
"msg": "",
"data": [
{ "列": "值" }
- ]
+ ],
+ "limit": 0,
+ "truncated": false
}
```
-
+
+成功时,`data` 仍为数组。`limit` 表示本次查询应用的服务端默认上限;SQL 显式指定外层 `LIMIT` 时为 `0`,不表示该子句指定的数值。仅当服务端默认限制导致至少一行结果未返回时,`truncated` 才为 `true`;结果恰好达到上限不算截断。上例显式指定了 `LIMIT 7`,因此 `limit` 为 `0`,`truncated` 为 `false`。错误响应不包含这两个字段。
+
注意:为保证数据安全,发布模式下禁止访问该接口。
### 提交事务
diff --git a/kernel/api/sql.go b/kernel/api/sql.go
index f59a5b09b8..98f657baae 100644
--- a/kernel/api/sql.go
+++ b/kernel/api/sql.go
@@ -37,7 +37,13 @@ func flushTransaction(c *gin.Context) {
func SQL(c *gin.Context) {
ret := gulu.Ret.NewResult()
- defer c.JSON(http.StatusOK, ret)
+ 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 {
@@ -81,7 +87,7 @@ func SQL(c *gin.Context) {
return
}
- result, err := sql.Query(stmt, model.Conf.Search.Limit)
+ result, info, err := sql.QueryWithLimitInfo(stmt, model.Conf.Search.Limit)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -89,4 +95,5 @@ func SQL(c *gin.Context) {
}
ret.Data = result
+ limitInfo = &info
}
diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.go
index 3f54f74cb2..bddd93759f 100644
--- a/kernel/sql/block_query.go
+++ b/kernel/sql/block_query.go
@@ -432,6 +432,13 @@ func QueryNoLimitArgs(stmt string, args ...any) (ret []map[string]any, err error
}
func Query(stmt string, limit int) (ret []map[string]any, err error) {
+ return queryWithLimitInfo(stmt, limit, nil)
+}
+
+func queryWithLimitInfo(stmt string, limit int, info *QueryLimitInfo) (ret []map[string]any, err error) {
+ if info != nil && containsMultipleStatements(stmt) {
+ return queryRawStmtWithLimitInfo(stmt, limit, info)
+ }
originalStmt := stmt
fallbackStmt := originalStmt
// Kernel API `/api/query/sql` support `||` operator https://github.com/siyuan-note/siyuan/issues/9662
@@ -444,12 +451,15 @@ func Query(stmt string, limit int) (ret []map[string]any, err error) {
// 这个解析器无法处理 || 连接字符串操作符
parsedStmt, err2 := sqlparser.Parse(stmt)
if nil != err2 {
- return queryRawStmt(stmt, limit)
+ return queryRawStmtWithLimitInfo(stmt, limit, info)
}
switch parsedStmt.(type) {
case *sqlparser.Select:
slct := parsedStmt.(*sqlparser.Select)
+ if info != nil && slct.Limit != nil && slct.Limit.Rowcount != nil {
+ info.Limit = 0
+ }
if nil == slct.Limit || nil == slct.Limit.Rowcount {
fallbackStmt += " LIMIT " + strconv.Itoa(limit)
}
@@ -459,6 +469,9 @@ func Query(stmt string, limit int) (ret []map[string]any, err error) {
case *sqlparser.Union:
// Kernel API `/api/query/sql` support `UNION` statement https://github.com/siyuan-note/siyuan/issues/8226
union := parsedStmt.(*sqlparser.Union)
+ if info != nil && union.Limit != nil && union.Limit.Rowcount != nil {
+ info.Limit = 0
+ }
if nil == union.Limit || nil == union.Limit.Rowcount {
fallbackStmt += " LIMIT " + strconv.Itoa(limit)
}
@@ -466,26 +479,29 @@ func Query(stmt string, limit int) (ret []map[string]any, err error) {
union.Limit = limitClause
stmt = sqlparser.String(union)
default:
- return queryRawStmt(stmt, limit)
+ return queryRawStmtWithLimitInfo(stmt, limit, info)
}
} else {
- return queryRawStmt(stmt, limit)
+ return queryRawStmtWithLimitInfo(stmt, limit, info)
}
} else {
switch parsedStmt2.(type) {
case *sqlparser2.SelectStatement:
slct := parsedStmt2.(*sqlparser2.SelectStatement)
+ if info != nil && slct.LimitExpr != nil {
+ info.Limit = 0
+ }
if nil == slct.LimitExpr {
fallbackStmt += " LIMIT " + strconv.Itoa(limit)
slct.LimitExpr = &sqlparser2.NumberLit{Value: strconv.Itoa(limit)}
serialized, ok := stringifySelectStatement(slct)
if !ok {
- return queryRawStmt(originalStmt, limit)
+ return queryRawStmtWithLimitInfo(originalStmt, limit, info)
}
stmt = serialized
}
default:
- return queryRawStmt(stmt, limit)
+ return queryRawStmtWithLimitInfo(stmt, limit, info)
}
}
@@ -524,7 +540,11 @@ func Query(stmt string, limit int) (ret []map[string]any, err error) {
m[colName] = *val
}
ret = append(ret, m)
+ if info != nil && info.Limit > 0 && len(ret) >= limit {
+ break
+ }
}
+ err = rows.Err()
return
}
@@ -595,6 +615,10 @@ func getLimitClause(parsedStmt sqlparser.Statement, limit int) (ret *sqlparser.L
}
func queryRawStmt(stmt string, limit int) (ret []map[string]any, err error) {
+ return queryRawStmtWithLimitInfo(stmt, limit, nil)
+}
+
+func queryRawStmtWithLimitInfo(stmt string, limit int, info *QueryLimitInfo) (ret []map[string]any, err error) {
rows, err := query(stmt)
if err != nil {
if strings.Contains(err.Error(), "syntax error") {
@@ -610,6 +634,12 @@ func queryRawStmt(stmt string, limit int) (ret []map[string]any, err error) {
}
noLimit := !containsLimitClause(stmt)
+ if info != nil {
+ noLimit = !containsOuterLimitClause(stmt)
+ if !noLimit {
+ info.Limit = 0
+ }
+ }
var count int
for rows.Next() {
columns := make([]any, len(cols))
@@ -630,10 +660,11 @@ func queryRawStmt(stmt string, limit int) (ret []map[string]any, err error) {
ret = append(ret, m)
count++
- if noLimit && limit < count {
+ if noLimit && (limit < count || (info != nil && limit == count)) {
break
}
}
+ err = rows.Err()
return
}
diff --git a/kernel/sql/query_limit.go b/kernel/sql/query_limit.go
new file mode 100644
index 0000000000..b0a67cc00f
--- /dev/null
+++ b/kernel/sql/query_limit.go
@@ -0,0 +1,109 @@
+package sql
+
+import (
+ "errors"
+ "math"
+ "strings"
+)
+
+// QueryLimitInfo 描述服务端默认限制;Limit 为零表示使用 SQL 自身的限制。
+type QueryLimitInfo struct {
+ Limit int `json:"limit"`
+ Truncated bool `json:"truncated"`
+}
+
+// QueryWithLimitInfo 在同一次查询中多读取一行,判断默认限制是否截断了结果。
+func QueryWithLimitInfo(stmt string, limit int) (rows []map[string]any, info QueryLimitInfo, err error) {
+ if limit < 1 || limit == math.MaxInt {
+ return nil, info, errors.New("invalid default SQL limit")
+ }
+ info.Limit = limit
+ rows, err = queryWithLimitInfo(stmt, limit+1, &info)
+ if err != nil {
+ return nil, QueryLimitInfo{}, err
+ }
+ if info.Limit > 0 && len(rows) > limit {
+ info.Truncated = true
+ rows = rows[:limit]
+ }
+ if rows == nil {
+ rows = []map[string]any{}
+ }
+ return
+}
+
+// containsOuterLimitClause 检查最后一条非空语句的外层 LIMIT,跳过引号、注释和括号内的内容。
+// 多语句查询由 SQLite 执行,返回结果对应最后一条语句。
+func containsOuterLimitClause(stmt string) bool {
+ depth, found, nextStatement := 0, false, false
+ for i := 0; i < len(stmt); {
+ ch := stmt[i]
+ if ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '\f' {
+ i++
+ continue
+ }
+ if i+1 < len(stmt) && stmt[i:i+2] == "--" {
+ i += 2
+ for i < len(stmt) && stmt[i] != '\n' {
+ i++
+ }
+ continue
+ }
+ if i+1 < len(stmt) && stmt[i:i+2] == "/*" {
+ end := strings.Index(stmt[i+2:], "*/")
+ if end < 0 {
+ break
+ }
+ i += end + 4
+ continue
+ }
+ if ch == ';' && depth == 0 {
+ nextStatement = true
+ i++
+ continue
+ }
+ if nextStatement {
+ found, nextStatement = false, false
+ }
+ if ch == '\'' || ch == '"' || ch == '`' || ch == '[' {
+ end := ch
+ if ch == '[' {
+ end = ']'
+ }
+ i++
+ for i < len(stmt) {
+ if stmt[i] == end {
+ i++
+ if ch != '[' && i < len(stmt) && stmt[i] == end {
+ i++
+ continue
+ }
+ break
+ }
+ i++
+ }
+ continue
+ }
+ if ch == '(' {
+ depth++
+ } else if ch == ')' {
+ depth--
+ }
+ if isSQLLimitWordByte(ch) {
+ start := i
+ for i < len(stmt) && isSQLLimitWordByte(stmt[i]) {
+ i++
+ }
+ if depth == 0 && strings.EqualFold(stmt[start:i], "limit") {
+ found = true
+ }
+ continue
+ }
+ i++
+ }
+ return found
+}
+
+func isSQLLimitWordByte(ch byte) bool {
+ return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_' || ch == '$' || ch >= 0x80
+}
diff --git a/kernel/sql/query_limit_test.go b/kernel/sql/query_limit_test.go
new file mode 100644
index 0000000000..18524dde10
--- /dev/null
+++ b/kernel/sql/query_limit_test.go
@@ -0,0 +1,102 @@
+package sql
+
+import (
+ gosql "database/sql"
+ "testing"
+)
+
+func TestQueryWithLimitInfo(t *testing.T) {
+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")
+ if err != nil {
+ t.Fatal(err)
+ }
+ testDB.SetMaxOpenConns(1)
+ defer testDB.Close()
+ previousDB := db
+ db = testDB
+ defer func() { db = previousDB }()
+ if _, err = testDB.Exec("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1), (2), (3), (4), (5)"); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name, stmt string
+ count, limit int
+ truncated bool
+ }{
+ {"empty", "SELECT n FROM items WHERE n < 0", 0, 3, false},
+ {"below", "SELECT n FROM items WHERE n < 3", 2, 3, false},
+ {"equal", "SELECT n FROM items WHERE n <= 3", 3, 3, false},
+ {"above", "SELECT n FROM items ORDER BY n", 3, 3, true},
+ {"explicit below", "SELECT n FROM items LIMIT 2", 2, 0, false},
+ {"explicit equal", "SELECT n FROM items LIMIT 3", 3, 0, false},
+ {"explicit above", "SELECT n FROM items LIMIT 4", 4, 0, false},
+ {"explicit zero", "SELECT n FROM items LIMIT 0", 0, 0, false},
+ {"explicit unlimited", "SELECT n FROM items LIMIT -1", 5, 0, false},
+ {"offset", "SELECT n FROM items ORDER BY n LIMIT 3 OFFSET 3", 2, 0, false},
+ {"aggregate", "SELECT count(*) FROM items", 1, 3, false},
+ {"union", "SELECT n FROM items UNION SELECT 6", 3, 3, true},
+ {"union explicit", "SELECT n FROM items UNION SELECT 6 LIMIT 5", 5, 0, false},
+ {"nested", "SELECT n FROM (SELECT n FROM items LIMIT 4)", 3, 3, true},
+ {"cte", "WITH x AS (SELECT n FROM items LIMIT 4) SELECT * FROM x", 3, 3, true},
+ {"fallback", "SELECT n || ' limit ' FROM items UNION SELECT 'x'", 3, 3, true},
+ {"fallback below", "SELECT n || '' FROM items WHERE n < 2 UNION SELECT 'x'", 2, 3, false},
+ {"fallback equal", "SELECT n || '' FROM items WHERE n < 3 UNION SELECT 'x'", 3, 3, false},
+ {"fallback explicit", "SELECT n || '' FROM items UNION SELECT 'x' LIMIT\n4", 4, 0, false},
+ {"fallback nested", "SELECT n || '' FROM (SELECT n FROM items LIMIT 4) UNION SELECT 'x'", 3, 3, true},
+ {"fallback comment", "SELECT n || '' FROM items UNION SELECT 'x' /* LIMIT 1 */", 3, 3, true},
+ {"multiple", "SELECT n FROM items LIMIT 1; SELECT n FROM items", 3, 3, true},
+ {"multiple explicit", "SELECT n FROM items; SELECT n FROM items LIMIT 4", 4, 0, false},
+ {"multiple write", "SELECT 1; INSERT INTO items VALUES (6) RETURNING n", 1, 3, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rows, info, queryErr := QueryWithLimitInfo(tc.stmt, 3)
+ if queryErr != nil {
+ t.Fatal(queryErr)
+ }
+ if rows == nil || len(rows) != tc.count || info.Limit != tc.limit || info.Truncated != tc.truncated {
+ t.Fatalf("rows=%v info=%+v, want count=%d limit=%d truncated=%v", rows, info, tc.count, tc.limit, tc.truncated)
+ }
+ })
+ }
+ var count int
+ if err = testDB.QueryRow("SELECT count(*) FROM items WHERE n = 6").Scan(&count); err != nil || count != 1 {
+ t.Fatalf("write executed more than once: count=%d err=%v", count, err)
+ }
+ if _, _, err = QueryWithLimitInfo("SELECT * FROM missing_table", 3); err == nil {
+ t.Fatal("expected query error")
+ }
+ if _, _, err = QueryWithLimitInfo("SELECT abs(-9223372036854775808)", 3); err == nil {
+ t.Fatal("expected row iteration error")
+ }
+ if _, _, err = QueryWithLimitInfo("SELECT abs(-9223372036854775808) || '' UNION SELECT 'x'", 3); err == nil {
+ t.Fatal("expected raw row iteration error")
+ }
+ rows, _, err := QueryWithLimitInfo("SELECT n FROM items ORDER BY n LIMIT 2 OFFSET 3", 3)
+ if err != nil || len(rows) != 2 || rows[0]["n"] != int64(4) || rows[1]["n"] != int64(5) {
+ t.Fatalf("unexpected page: rows=%v err=%v", rows, err)
+ }
+}
+
+func TestContainsOuterLimitClause(t *testing.T) {
+ for _, stmt := range []string{
+ "SELECT * FROM t LIMIT\n3; -- trailing",
+ "SELECT * FROM t LiMiT/* comment */3",
+ "SELECT 1; SELECT * FROM t LIMIT 3;; /* trailing */",
+ } {
+ if !containsOuterLimitClause(stmt) {
+ t.Errorf("missing outer limit: %s", stmt)
+ }
+ }
+ for _, stmt := range []string{
+ "SELECT ' limit ', 'it''s limit ', \"limit\", `limit`, [limit] FROM t",
+ "SELECT * FROM (SELECT * FROM t LIMIT 3)",
+ "SELECT * FROM t -- LIMIT 3",
+ "SELECT * FROM t /* LIMIT 3 */",
+ "SELECT * FROM t LIMIT 3; SELECT * FROM t",
+ "SELECT [a' limit ] FROM t",
+ } {
+ if containsOuterLimitClause(stmt) {
+ t.Errorf("unexpected outer limit: %s", stmt)
+ }
+ }
+}