moduforge-search 0.6.4

moduforge 搜索服务 - SQLite 后端
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
use crate::model::IndexDoc;
use anyhow::Result;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::TransactionBehavior;
use std::path::PathBuf;

/// SQLite 后端索引增量变更
#[derive(Debug, Clone)]
pub enum IndexMutation {
    Add(IndexDoc),
    Upsert(IndexDoc),
    DeleteById(String),
    DeleteManyById(Vec<String>),
}

/// 查询条件
#[derive(Debug, Clone, Default)]
pub struct SearchQuery {
    /// 全文查询(走 FTS5)
    pub text: Option<String>,
    /// 节点类型精确匹配
    pub node_type: Option<String>,
    /// 父节点精确匹配
    pub parent_id: Option<String>,
    /// 路径前缀匹配(如 "/root/section")
    pub path_prefix: Option<String>,
    /// 标记类型(简单查询:只检查是否包含某类型 mark)
    pub marks: Vec<String>,
    /// 带属性的精确 mark 查询(mark_type, attr_key, attr_value)
    /// 例如:("link", "href", "https://example.com")
    pub mark_attrs: Vec<(String, String, String)>,
    /// JSON 属性匹配(支持复杂查询)
    pub attrs: Vec<(String, String)>,
    /// 返回条数限制
    pub limit: usize,
    /// 偏移量
    pub offset: usize,
    /// 排序字段
    pub sort_by: Option<String>,
    /// 排序方向 true=升序,false=降序
    pub sort_asc: bool,
    /// 树形查询:返回子树所有节点
    pub include_descendants: bool,
    /// 范围查询
    pub range_field: Option<String>,
    pub range_min: Option<i64>,
    pub range_max: Option<i64>,
}

/// SQLite 后端实现
pub struct SqliteBackend {
    pool: Pool<SqliteConnectionManager>,
    index_dir: PathBuf,
    /// 临时目录对象(如果使用临时目录)
    /// 保存此对象以确保临时目录在 Backend 生命周期内不被删除
    _temp_dir: Option<tempfile::TempDir>,
}

impl SqliteBackend {
    /// 在指定目录创建或打开数据库
    pub fn new_in_dir(dir: &std::path::Path) -> Result<Self> {
        std::fs::create_dir_all(dir)?;
        let db_path = dir.join("index.db");

        // 创建连接池管理器
        let manager = SqliteConnectionManager::file(&db_path);
        let pool = Pool::new(manager)?;

        // 初始化表结构
        pool.get()?.execute_batch(
            "-- 开启 WAL 模式(高并发)
             PRAGMA journal_mode=WAL;
             PRAGMA synchronous=NORMAL;
             PRAGMA cache_size=-64000;  -- 64MB cache
             PRAGMA temp_store=MEMORY;

             -- 创建主表
             CREATE TABLE IF NOT EXISTS nodes (
                 id TEXT PRIMARY KEY,
                 node_type TEXT NOT NULL,
                 parent_id TEXT,
                 path TEXT NOT NULL,
                 marks TEXT,
                 marks_json TEXT,
                 attrs TEXT,
                 attrs_json TEXT,
                 text TEXT,
                 order_i64 INTEGER,
                 created_at_i64 INTEGER,
                 updated_at_i64 INTEGER
             );

             -- 创建索引
             CREATE INDEX IF NOT EXISTS idx_node_type ON nodes(node_type);
             CREATE INDEX IF NOT EXISTS idx_parent_id ON nodes(parent_id);
             CREATE INDEX IF NOT EXISTS idx_path ON nodes(path);
             CREATE INDEX IF NOT EXISTS idx_created_at ON nodes(created_at_i64);
             CREATE INDEX IF NOT EXISTS idx_updated_at ON nodes(updated_at_i64);
             CREATE INDEX IF NOT EXISTS idx_order ON nodes(order_i64);

             -- 创建 FTS5 全文索引表
             CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
                 id UNINDEXED,
                 text,
                 content='nodes',
                 content_rowid='rowid'
             );

             -- 创建触发器:自动同步 FTS5
             CREATE TRIGGER IF NOT EXISTS nodes_ai AFTER INSERT ON nodes BEGIN
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_ad AFTER DELETE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_au AFTER UPDATE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;"
        )?;

        Ok(Self {
            pool,
            index_dir: dir.to_path_buf(),
            _temp_dir: None,  // 持久化目录,不使用临时目录
        })
    }

    /// 使用系统临时目录
    pub fn new_in_system_temp() -> Result<Self> {
        let temp_dir = tempfile::Builder::new()
            .prefix("mf_index_")
            .tempdir()?;

        let db_path = temp_dir.path().join("index.db");

        // 创建连接池管理器
        let manager = SqliteConnectionManager::file(&db_path);
        let pool = Pool::new(manager)?;

        // 初始化表结构
        pool.get()?.execute_batch(
            "-- 开启 WAL 模式(高并发)
             PRAGMA journal_mode=WAL;
             PRAGMA synchronous=NORMAL;
             PRAGMA cache_size=-64000;  -- 64MB cache
             PRAGMA temp_store=MEMORY;

             -- 创建主表
             CREATE TABLE IF NOT EXISTS nodes (
                 id TEXT PRIMARY KEY,
                 node_type TEXT NOT NULL,
                 parent_id TEXT,
                 path TEXT NOT NULL,
                 marks TEXT,
                 marks_json TEXT,
                 attrs TEXT,
                 attrs_json TEXT,
                 text TEXT,
                 order_i64 INTEGER,
                 created_at_i64 INTEGER,
                 updated_at_i64 INTEGER
             );

             -- 创建索引
             CREATE INDEX IF NOT EXISTS idx_node_type ON nodes(node_type);
             CREATE INDEX IF NOT EXISTS idx_parent_id ON nodes(parent_id);
             CREATE INDEX IF NOT EXISTS idx_path ON nodes(path);
             CREATE INDEX IF NOT EXISTS idx_created_at ON nodes(created_at_i64);
             CREATE INDEX IF NOT EXISTS idx_updated_at ON nodes(updated_at_i64);
             CREATE INDEX IF NOT EXISTS idx_order ON nodes(order_i64);

             -- 创建 FTS5 全文索引表
             CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
                 id UNINDEXED,
                 text,
                 content='nodes',
                 content_rowid='rowid'
             );

             -- 创建触发器:自动同步 FTS5
             CREATE TRIGGER IF NOT EXISTS nodes_ai AFTER INSERT ON nodes BEGIN
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_ad AFTER DELETE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_au AFTER UPDATE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;"
        )?;

        Ok(Self {
            pool,
            index_dir: temp_dir.path().to_path_buf(),
            _temp_dir: Some(temp_dir),  // 保存临时目录对象,确保生命周期内不被删除
        })
    }

    /// 在指定临时根目录下创建
    pub fn new_in_temp_root(temp_root: &std::path::Path) -> Result<Self> {
        let temp_dir = tempfile::Builder::new()
            .prefix("mf_index_")
            .tempdir_in(temp_root)?;

        let db_path = temp_dir.path().join("index.db");

        // 创建连接池管理器
        let manager = SqliteConnectionManager::file(&db_path);
        let pool = Pool::new(manager)?;

        // 初始化表结构
        pool.get()?.execute_batch(
            "-- 开启 WAL 模式(高并发)
             PRAGMA journal_mode=WAL;
             PRAGMA synchronous=NORMAL;
             PRAGMA cache_size=-64000;  -- 64MB cache
             PRAGMA temp_store=MEMORY;

             -- 创建主表
             CREATE TABLE IF NOT EXISTS nodes (
                 id TEXT PRIMARY KEY,
                 node_type TEXT NOT NULL,
                 parent_id TEXT,
                 path TEXT NOT NULL,
                 marks TEXT,
                 marks_json TEXT,
                 attrs TEXT,
                 attrs_json TEXT,
                 text TEXT,
                 order_i64 INTEGER,
                 created_at_i64 INTEGER,
                 updated_at_i64 INTEGER
             );

             -- 创建索引
             CREATE INDEX IF NOT EXISTS idx_node_type ON nodes(node_type);
             CREATE INDEX IF NOT EXISTS idx_parent_id ON nodes(parent_id);
             CREATE INDEX IF NOT EXISTS idx_path ON nodes(path);
             CREATE INDEX IF NOT EXISTS idx_created_at ON nodes(created_at_i64);
             CREATE INDEX IF NOT EXISTS idx_updated_at ON nodes(updated_at_i64);
             CREATE INDEX IF NOT EXISTS idx_order ON nodes(order_i64);

             -- 创建 FTS5 全文索引表
             CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
                 id UNINDEXED,
                 text,
                 content='nodes',
                 content_rowid='rowid'
             );

             -- 创建触发器:自动同步 FTS5
             CREATE TRIGGER IF NOT EXISTS nodes_ai AFTER INSERT ON nodes BEGIN
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_ad AFTER DELETE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
             END;

             CREATE TRIGGER IF NOT EXISTS nodes_au AFTER UPDATE ON nodes BEGIN
                 INSERT INTO nodes_fts(nodes_fts, rowid, id, text)
                 VALUES('delete', old.rowid, old.id, old.text);
                 INSERT INTO nodes_fts(rowid, id, text)
                 VALUES (new.rowid, new.id, new.text);
             END;"
        )?;

        Ok(Self {
            pool,
            index_dir: temp_dir.path().to_path_buf(),
            _temp_dir: Some(temp_dir),  // 保存临时目录对象,确保生命周期内不被删除
        })
    }

    /// 获取索引目录
    pub fn index_dir(&self) -> &std::path::Path {
        &self.index_dir
    }

    /// 应用增量变更
    pub async fn apply(&self, mutations: Vec<IndexMutation>) -> Result<()> {
        let mut conn = self.pool.get()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;

        for mutation in mutations {
            match mutation {
                IndexMutation::Add(doc) | IndexMutation::Upsert(doc) => {
                    self.upsert_doc(&tx, &doc)?;
                }
                IndexMutation::DeleteById(id) => {
                    tx.execute("DELETE FROM nodes WHERE id = ?", [&id])?;
                }
                IndexMutation::DeleteManyById(ids) => {
                    for id in ids {
                        tx.execute("DELETE FROM nodes WHERE id = ?", [&id])?;
                    }
                }
            }
        }

        tx.commit()?;
        Ok(())
    }

    /// 插入或更新文档
    fn upsert_doc(
        &self,
        tx: &rusqlite::Transaction,
        doc: &IndexDoc,
    ) -> Result<()> {
        let marks_types_json = serde_json::to_string(&doc.marks)?;
        let attrs_flat_json = serde_json::to_string(&doc.attrs_flat)?;
        let path_str = format!("/{}", doc.path.join("/"));

        tx.execute(
            "INSERT OR REPLACE INTO nodes
             (id, node_type, parent_id, path, marks, marks_json, attrs, attrs_json, text,
              order_i64, created_at_i64, updated_at_i64)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
            rusqlite::params![
                &doc.node_id,
                &doc.node_type,
                &doc.parent_id,
                &path_str,
                &marks_types_json,
                &doc.marks_json,
                &attrs_flat_json,
                &doc.attrs_json,
                &doc.text,
                doc.order_i64,
                doc.created_at_i64,
                doc.updated_at_i64,
            ],
        )?;

        Ok(())
    }

    /// 重建全部索引
    pub async fn rebuild_all(&self, docs: Vec<IndexDoc>) -> Result<()> {
        let mut conn = self.pool.get()?;
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;

        // 清空表
        tx.execute("DELETE FROM nodes", [])?;

        // 批量插入
        for doc in docs {
            self.upsert_doc(&tx, &doc)?;
        }

        tx.commit()?;
        Ok(())
    }

    /// 搜索节点 ID
    pub async fn search_ids(&self, query: SearchQuery) -> Result<Vec<String>> {
        let conn = self.pool.get()?;

        // 树形查询
        if query.include_descendants && query.parent_id.is_some() {
            return self.search_tree(&conn, &query);
        }

        // 全文搜索
        if query.text.is_some() {
            return self.search_fulltext(&conn, &query);
        }

        // 结构化查询
        self.search_structured(&conn, &query)
    }

    /// 搜索并返回完整文档
    pub async fn search_docs(&self, query: SearchQuery) -> Result<Vec<IndexDoc>> {
        let ids = self.search_ids(query).await?;
        self.get_docs_by_ids(&ids).await
    }

    /// 根据 ID 列表获取完整文档
    pub async fn get_docs_by_ids(&self, ids: &[String]) -> Result<Vec<IndexDoc>> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }

        let conn = self.pool.get()?;

        // 构建 IN 查询
        let placeholders = ids.iter().map(|_| "?").collect::<Vec<_>>().join(",");
        let sql = format!(
            "SELECT id, node_type, parent_id, path, marks, marks_json, attrs, attrs_json, text,
                    order_i64, created_at_i64, updated_at_i64
             FROM nodes WHERE id IN ({})",
            placeholders
        );

        let mut stmt = conn.prepare(&sql)?;
        let params: Vec<&dyn rusqlite::ToSql> = ids.iter()
            .map(|id| id as &dyn rusqlite::ToSql)
            .collect();

        let docs = stmt.query_map(&params[..], |row| {
            // 解析 marks JSON
            let marks_json: String = row.get(5)?;
            let marks_objects: Vec<mf_model::mark::Mark> = serde_json::from_str(&marks_json)
                .unwrap_or_default();
            let marks: Vec<String> = marks_objects.iter()
                .map(|m| m.r#type.clone())
                .collect();

            // 解析 attrs JSON
            let attrs_json: String = row.get(7)?;
            let attrs_map: imbl::HashMap<String, serde_json::Value> = serde_json::from_str(&attrs_json)
                .unwrap_or_default();
            let attrs_flat: Vec<(String, String)> = attrs_map.iter()
                .map(|(k, v)| {
                    let value_str = match v {
                        serde_json::Value::Null => "null".to_string(),
                        serde_json::Value::Bool(b) => b.to_string(),
                        serde_json::Value::Number(n) => n.to_string(),
                        serde_json::Value::String(s) => s.clone(),
                        _ => serde_json::to_string(v).unwrap_or_default(),
                    };
                    (k.clone(), value_str)
                })
                .collect();

            // 解析 path
            let path_str: String = row.get(3)?;
            let path: Vec<String> = path_str
                .trim_start_matches('/')
                .split('/')
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect();

            Ok(IndexDoc {
                node_id: row.get(0)?,
                node_type: row.get(1)?,
                parent_id: row.get(2)?,
                path,
                marks,
                marks_json: row.get(5)?,
                attrs_flat,
                attrs_json: row.get(7)?,
                text: row.get(8)?,
                order_i64: row.get(9)?,
                created_at_i64: row.get(10)?,
                updated_at_i64: row.get(11)?,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;

        Ok(docs)
    }

    /// 树形递归查询
    fn search_tree(
        &self,
        conn: &rusqlite::Connection,
        query: &SearchQuery,
    ) -> Result<Vec<String>> {
        let parent_id = query.parent_id.as_ref().unwrap();

        let mut sql = String::from(
            "WITH RECURSIVE tree(id, level) AS (
                SELECT id, 0 as level FROM nodes WHERE id = ?1
                UNION ALL
                SELECT n.id, t.level + 1
                FROM nodes n
                JOIN tree t ON n.parent_id = t.id
                WHERE t.level < 100
            )
            SELECT id FROM tree WHERE 1=1"
        );

        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(parent_id.clone())];

        // 添加过滤条件
        if let Some(node_type) = &query.node_type {
            sql.push_str(" AND id IN (SELECT id FROM nodes WHERE node_type = ?)");
            params.push(Box::new(node_type.clone()));
        }

        // 排序和分页
        if let Some(sort_by) = &query.sort_by {
            let direction = if query.sort_asc { "ASC" } else { "DESC" };
            sql.push_str(&format!(
                " ORDER BY (SELECT {} FROM nodes WHERE nodes.id = tree.id) {}",
                sort_by, direction
            ));
        }

        let limit = if query.limit == 0 { 1000 } else { query.limit };
        sql.push_str(&format!(" LIMIT {} OFFSET {}", limit, query.offset));

        let mut stmt = conn.prepare(&sql)?;
        let params_ref: Vec<&dyn rusqlite::ToSql> = params
            .iter()
            .map(|p| p.as_ref() as &dyn rusqlite::ToSql)
            .collect();

        let ids: Vec<String> = stmt
            .query_map(&params_ref[..], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ids)
    }

    /// 全文搜索
    fn search_fulltext(
        &self,
        conn: &rusqlite::Connection,
        query: &SearchQuery,
    ) -> Result<Vec<String>> {
        let text = query.text.as_ref().unwrap();

        let mut sql = String::from(
            "SELECT nodes.id FROM nodes_fts
             JOIN nodes ON nodes_fts.id = nodes.id
             WHERE nodes_fts.text MATCH ?1"
        );

        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![Box::new(text.clone())];
        let mut param_index = 2;

        // 添加过滤条件
        if let Some(node_type) = &query.node_type {
            sql.push_str(&format!(" AND nodes.node_type = ?{}", param_index));
            params.push(Box::new(node_type.clone()));
            param_index += 1;
        }

        if let Some(parent_id) = &query.parent_id {
            sql.push_str(&format!(" AND nodes.parent_id = ?{}", param_index));
            params.push(Box::new(parent_id.clone()));
            param_index += 1;
        }

        // 标记过滤
        for mark in &query.marks {
            sql.push_str(&format!(" AND nodes.marks LIKE ?{}", param_index));
            params.push(Box::new(format!("%\"{}\"%%", mark)));
            param_index += 1;
        }

        // 排序
        if let Some(sort_by) = &query.sort_by {
            let direction = if query.sort_asc { "ASC" } else { "DESC" };
            sql.push_str(&format!(" ORDER BY nodes.{} {}", sort_by, direction));
        } else {
            sql.push_str(" ORDER BY rank"); // FTS5 相关性排序
        }

        let limit = if query.limit == 0 { 50 } else { query.limit };
        sql.push_str(&format!(" LIMIT {} OFFSET {}", limit, query.offset));

        let mut stmt = conn.prepare(&sql)?;
        let params_ref: Vec<&dyn rusqlite::ToSql> = params
            .iter()
            .map(|p| p.as_ref() as &dyn rusqlite::ToSql)
            .collect();

        let ids: Vec<String> = stmt
            .query_map(&params_ref[..], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ids)
    }

    /// 结构化查询
    fn search_structured(
        &self,
        conn: &rusqlite::Connection,
        query: &SearchQuery,
    ) -> Result<Vec<String>> {
        let mut sql = String::from("SELECT id FROM nodes WHERE 1=1");
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = vec![];
        let mut param_index = 1;

        // 节点类型
        if let Some(node_type) = &query.node_type {
            sql.push_str(&format!(" AND node_type = ?{}", param_index));
            params.push(Box::new(node_type.clone()));
            param_index += 1;
        }

        // 父节点
        if let Some(parent_id) = &query.parent_id {
            sql.push_str(&format!(" AND parent_id = ?{}", param_index));
            params.push(Box::new(parent_id.clone()));
            param_index += 1;
        }

        // 路径前缀
        if let Some(path_prefix) = &query.path_prefix {
            sql.push_str(&format!(" AND path LIKE ?{}", param_index));
            params.push(Box::new(format!("{}%", path_prefix)));
            param_index += 1;
        }

        // 标记过滤(简单:只检查类型)
        for mark in &query.marks {
            sql.push_str(&format!(" AND marks LIKE ?{}", param_index));
            params.push(Box::new(format!("%\"{}\"%%", mark)));
            param_index += 1;
        }

        // 带属性的精确 mark 查询(使用 marks_json)
        for (mark_type, attr_key, attr_value) in &query.mark_attrs {
            // 使用 json_each 查询 marks_json 数组中符合条件的 mark
            sql.push_str(&format!(
                " AND EXISTS (
                    SELECT 1 FROM json_each(marks_json)
                    WHERE json_extract(value, '$.type') = ?{}
                    AND json_extract(value, '$.attrs.{}') = ?{}
                )",
                param_index, attr_key, param_index + 1
            ));
            params.push(Box::new(mark_type.clone()));
            params.push(Box::new(attr_value.clone()));
            param_index += 2;
        }

        // 属性过滤(简单:使用 attrs 字段)
        for (key, value) in &query.attrs {
            sql.push_str(&format!(
                " AND json_extract(attrs, '$.{}') = ?{}",
                key, param_index
            ));
            params.push(Box::new(value.clone()));
            param_index += 1;
        }

        // 范围查询
        if let Some(field) = &query.range_field {
            if let Some(min) = query.range_min {
                sql.push_str(&format!(" AND {} >= ?{}", field, param_index));
                params.push(Box::new(min));
                param_index += 1;
            }
            if let Some(max) = query.range_max {
                sql.push_str(&format!(" AND {} <= ?{}", field, param_index));
                params.push(Box::new(max));
            }
        }

        // 排序
        if let Some(sort_by) = &query.sort_by {
            let direction = if query.sort_asc { "ASC" } else { "DESC" };
            sql.push_str(&format!(" ORDER BY {} {}", sort_by, direction));
        }

        // 分页
        let limit = if query.limit == 0 { 50 } else { query.limit };
        sql.push_str(&format!(" LIMIT {} OFFSET {}", limit, query.offset));

        let mut stmt = conn.prepare(&sql)?;
        let params_ref: Vec<&dyn rusqlite::ToSql> = params
            .iter()
            .map(|p| p.as_ref() as &dyn rusqlite::ToSql)
            .collect();

        let ids: Vec<String> = stmt
            .query_map(&params_ref[..], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?;

        Ok(ids)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_basic_operations() {
        let backend = SqliteBackend::new_in_system_temp().unwrap();

        // 插入文档
        let doc = IndexDoc {
            node_id: "test1".to_string(),
            node_type: "paragraph".to_string(),
            parent_id: Some("root".to_string()),
            path: vec!["root".to_string(), "test1".to_string()],
            marks: vec!["bold".to_string()],
            marks_json: r#"[{"type":"bold","attrs":{}}]"#.to_string(),
            attrs_flat: vec![("status".to_string(), "published".to_string())],
            attrs_json: r#"{"status":"published"}"#.to_string(),
            text: Some("测试文本".to_string()),
            order_i64: Some(1),
            created_at_i64: Some(1000),
            updated_at_i64: Some(2000),
        };

        backend.apply(vec![IndexMutation::Add(doc)]).await.unwrap();

        // 查询
        let results = backend
            .search_ids(SearchQuery {
                node_type: Some("paragraph".to_string()),
                limit: 10,
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0], "test1");
    }

    #[tokio::test]
    async fn test_tree_query() {
        let backend = SqliteBackend::new_in_system_temp().unwrap();

        // 插入树形结构
        let docs = vec![
            IndexDoc {
                node_id: "root".to_string(),
                node_type: "doc".to_string(),
                parent_id: None,
                path: vec!["root".to_string()],
                marks: vec![],
                marks_json: "[]".to_string(),
                attrs_flat: vec![],
                attrs_json: "{}".to_string(),
                text: None,
                order_i64: None,
                created_at_i64: None,
                updated_at_i64: None,
            },
            IndexDoc {
                node_id: "child1".to_string(),
                node_type: "section".to_string(),
                parent_id: Some("root".to_string()),
                path: vec!["root".to_string(), "child1".to_string()],
                marks: vec![],
                marks_json: "[]".to_string(),
                attrs_flat: vec![],
                attrs_json: "{}".to_string(),
                text: None,
                order_i64: None,
                created_at_i64: None,
                updated_at_i64: None,
            },
            IndexDoc {
                node_id: "child2".to_string(),
                node_type: "paragraph".to_string(),
                parent_id: Some("child1".to_string()),
                path: vec!["root".to_string(), "child1".to_string(), "child2".to_string()],
                marks: vec![],
                marks_json: "[]".to_string(),
                attrs_flat: vec![],
                attrs_json: "{}".to_string(),
                text: None,
                order_i64: None,
                created_at_i64: None,
                updated_at_i64: None,
            },
        ];

        backend.rebuild_all(docs).await.unwrap();

        // 查询子树
        let results = backend
            .search_ids(SearchQuery {
                parent_id: Some("root".to_string()),
                include_descendants: true,
                limit: 100,
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(results.len(), 3); // root + 2 children
    }

    #[tokio::test]
    async fn test_search_docs() {
        let backend = SqliteBackend::new_in_system_temp().unwrap();

        // 插入测试文档
        let docs = vec![
            IndexDoc {
                node_id: "doc1".to_string(),
                node_type: "paragraph".to_string(),
                parent_id: Some("root".to_string()),
                path: vec!["root".to_string(), "doc1".to_string()],
                marks: vec!["bold".to_string()],
                marks_json: r#"[{"type":"bold","attrs":{}}]"#.to_string(),
                attrs_flat: vec![("status".to_string(), "published".to_string())],
                attrs_json: r#"{"status":"published"}"#.to_string(),
                text: Some("第一篇文档".to_string()),
                order_i64: Some(1),
                created_at_i64: Some(1000),
                updated_at_i64: Some(1500),
            },
            IndexDoc {
                node_id: "doc2".to_string(),
                node_type: "paragraph".to_string(),
                parent_id: Some("root".to_string()),
                path: vec!["root".to_string(), "doc2".to_string()],
                marks: vec!["italic".to_string()],
                marks_json: r#"[{"type":"italic","attrs":{}}]"#.to_string(),
                attrs_flat: vec![("status".to_string(), "draft".to_string())],
                attrs_json: r#"{"status":"draft"}"#.to_string(),
                text: Some("第二篇文档".to_string()),
                order_i64: Some(2),
                created_at_i64: Some(2000),
                updated_at_i64: Some(2500),
            },
        ];

        backend.rebuild_all(docs).await.unwrap();

        // 测试:搜索并返回完整文档
        let results = backend
            .search_docs(SearchQuery {
                node_type: Some("paragraph".to_string()),
                limit: 10,
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(results.len(), 2);

        // 验证第一个文档的完整性
        let doc1 = results.iter().find(|d| d.node_id == "doc1").unwrap();
        assert_eq!(doc1.node_type, "paragraph");
        assert_eq!(doc1.text, Some("第一篇文档".to_string()));
        assert_eq!(doc1.marks, vec!["bold".to_string()]);
        assert_eq!(doc1.attrs_flat, vec![("status".to_string(), "published".to_string())]);
        assert_eq!(doc1.order_i64, Some(1));

        // 验证第二个文档
        let doc2 = results.iter().find(|d| d.node_id == "doc2").unwrap();
        assert_eq!(doc2.text, Some("第二篇文档".to_string()));
        assert_eq!(doc2.marks, vec!["italic".to_string()]);
    }

    #[tokio::test]
    async fn test_get_docs_by_ids() {
        let backend = SqliteBackend::new_in_system_temp().unwrap();

        // 插入文档
        let doc = IndexDoc {
            node_id: "test123".to_string(),
            node_type: "heading".to_string(),
            parent_id: None,
            path: vec!["test123".to_string()],
            marks: vec![],
            marks_json: "[]".to_string(),
            attrs_flat: vec![("level".to_string(), "1".to_string())],
            attrs_json: r#"{"level":"1"}"#.to_string(),
            text: Some("标题文本".to_string()),
            order_i64: None,
            created_at_i64: None,
            updated_at_i64: None,
        };

        backend.apply(vec![IndexMutation::Add(doc)]).await.unwrap();

        // 通过 ID 获取文档
        let docs = backend.get_docs_by_ids(&["test123".to_string()]).await.unwrap();

        assert_eq!(docs.len(), 1);
        assert_eq!(docs[0].node_id, "test123");
        assert_eq!(docs[0].node_type, "heading");
        assert_eq!(docs[0].text, Some("标题文本".to_string()));

        // 测试空列表
        let empty = backend.get_docs_by_ids(&[]).await.unwrap();
        assert_eq!(empty.len(), 0);

        // 测试不存在的 ID
        let not_found = backend.get_docs_by_ids(&["nonexistent".to_string()]).await.unwrap();
        assert_eq!(not_found.len(), 0);
    }
}