diff --git a/doc/design/web-net-capabilities.md b/doc/design/web-net-capabilities.md index c03b8b6..90115ae 100644 --- a/doc/design/web-net-capabilities.md +++ b/doc/design/web-net-capabilities.md @@ -133,10 +133,10 @@ | B3 | **结果集型裸查询**(exec 返回 rows) | count / join / group / 子查询完全不可用 | `plugins/web` | P1 ✅ | | B4 | **分页**(db 层 `limit`+`offset`;页面层上一页/下一页) | 列表页只能限量 | `plugins/web` + `ext/web` | P1 ✅(db 层;页面 UI 属 D4) | | B5 | **查询表达力**:OR / IN / BETWEEN / IS NULL / LIKE 转义 / 括号组合 | where 只能 AND | `plugins/web` | P1 ✅ | -| B6 | **迁移机制**(schema 版本表 + 迁移脚本) | 无法演进表结构 | `plugins/web` + `ext/web` | P2 | +| B6 | **迁移机制**(schema 版本表 + 迁移脚本) | ✅ **已实现(W6)**:`db.migrate` + `_marqdo_migrations`(SQLite) | `plugins/web` + `ext/web` | P2 ✅ | | B7 | **索引 / 唯一 / 外键声明**(init 表增强) | 完整性、查询性能 | `plugins/web` | P2 | | B8 | **聚合辅助**:count / group 便捷 API | 统计面板、标签计数 | `plugins/web` | P2 ✅(`db.count`) | -| B9 | **全文搜索**(SQLite FTS5) | 站内搜索刚需 | `plugins/web`(FTS5 现成) | P2 | +| B9 | **全文搜索**(SQLite FTS5) | ✅ **已实现(W6)**:`db.fts` + `db.search`(bm25) | `plugins/web`(FTS5 现成) | P2 ✅ | | B10 | **时间戳 / 审计字段自动维护** | 博客发布日期、更新时间 | `plugins/web` | P3 | ### 3.3 类 C:安全硬化(能上线的前提) @@ -180,7 +180,7 @@ | **W3** | 安全硬化 | 密码哈希 + CSRF + 会话持久化 + CSPRNG session id + cookie 增强 + 登录限速/锁定 | C1–C7 | | **W4** | 内容站点标配 | SEO 元数据 + sitemap/robots + RSS + Markdown 渲染 + 分页导航 UI + 标签/分类 | D1–D6 | | **W5** | 上传与媒体 | multipart 文件上传接收 + 落盘 + 下载 + 图片库 | A5 D9 ✅ **A5 done**(D9 相册 UI 后续) | -| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 D7 D8 + WS 增强 | +| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;D7/D8 用表+where;WS 广播后续 | ### 4.2 边界判定要点(严格遵守既有约束) diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md index 7d48b8e..2202727 100644 --- a/doc/roadmap/ext-web.md +++ b/doc/roadmap/ext-web.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **W0–W5 + 安全硬化 + 内容标配 W4c 已落地** | +| 状态 | **W0–W6(迁移/FTS)+ 安全硬化 + 内容标配 W4c 已落地** | | 日期 | 2026-08-28 | | **锁定设计** | [design/ext-web.md](../design/ext-web.md) | | 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [ext-llm.md](../design/ext-llm.md) | @@ -31,8 +31,9 @@ | **W4** | Postgres;Redis / S3 驱动(见 [ext-web-drivers.md](../design/ext-web-drivers.md)) | **done** | | **W4c** | 内容标配:SEO / Markdown / RSS / 分页 UI(见 [web-net-capabilities.md](../design/web-net-capabilities.md)) | **done** | | **W5** | 上传与媒体:multipart 接收 + 落盘 + 下载(见 [web-net-capabilities.md](../design/web-net-capabilities.md) A5) | **done** | +| **W6** | 迁移 + FTS5 搜索;草稿/评论用既有 where/表(WS 广播后续) | **done**(核心) | -验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`ext_cli_add_web`。 +验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`ext_cli_add_web`。 --- diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 2ea5d94..545495f 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -242,6 +242,35 @@ Count rows matching a `where` filter (same syntax as `select`). Returns a number *r = > web_db_count url=`url` table=`table` where=`where` txn=`txn`* **r[^count]** +## migrate + + `steps` + +Apply versioned SQL migrations. `steps` is a `|version|sql|` / `|版本|SQL|` table. Applied versions are recorded in `_marqdo_migrations`. Re-running is a no-op for already-applied versions. SQLite only. + +*url = self[^url]* +**> web_db_migrate url=`url` steps=`steps`** + +## fts + + `table` + + `columns` + + `name`=None + +Create an FTS5 index on `table` for the listed content columns (CSV string or list). Default FTS name is `{table}_fts`. Keeps the index in sync via triggers. Requires integer `id` PK. SQLite only. + +*url = self[^url]* +**> web_db_fts_create url=`url` table=`table` columns=`columns` name=`name`** + +## search + + `table` + + `q` + + `limit`=20 + + `name`=None + +Full-text search (`MATCH`) against the FTS5 index from `fts`. Returns `{ rows, count }` with a `rank` column (bm25). SQLite only. + +*url = self[^url]* +**> web_db_search url=`url` table=`table` q=`q` limit=`limit` name=`name`** + ## 事务 Begin a transaction: borrows the pooled connection exclusively and returns a diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index 571cd0c..df4a23f 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -229,6 +229,35 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c *r = > web_db_count url=`url` table=`表` where=`条件` txn=`事务`* **r[^count]** +## 迁移 + + `步骤` + +按版本执行 SQL 迁移。`步骤` 为 `|版本|SQL|` 表;已应用版本记入 `_marqdo_migrations`。重复执行对已应用版本是空操作。仅 SQLite。 + +*url = self[^url]* +**> web_db_migrate url=`url` steps=`步骤`** + +## 全文 + + `表` + + `列` + + `名`=None + +为 `表` 的内容列创建 FTS5 索引(CSV 或列表)。默认索引名 `{表}_fts`,用触发器保持同步。需要整数 `id` 主键。仅 SQLite。 + +*url = self[^url]* +**> web_db_fts_create url=`url` table=`表` columns=`列` name=`名`** + +## 搜索 + + `表` + + `关键词` + + `上限`=20 + + `名`=None + +对 `全文` 建立的索引做 `MATCH` 检索。返回 `{ rows, count }`,含 `rank`(bm25)。仅 SQLite。 + +*url = self[^url]* +**> web_db_search url=`url` table=`表` q=`关键词` limit=`上限` name=`名`** + ## 事务 开启一个事务:从连接池独占借用连接,返回 `事务` 句柄。在事务内写入,然后 `提交` 或 `回滚`。所有语句在同一连接上执行,整批写入是原子的。 diff --git a/plugins/web/src/db.rs b/plugins/web/src/db.rs index f49ce29..26b6b37 100644 --- a/plugins/web/src/db.rs +++ b/plugins/web/src/db.rs @@ -832,3 +832,284 @@ pub fn table_info(url: &str, table: &str) -> Result, String> { .map_err(|e| e.to_string())?; Ok(rows) } + +/// Apply versioned SQL steps. Table `_marqdo_migrations` tracks applied versions. +/// +/// `steps` is a list of `{version|版本, sql|SQL}` (GFM columnar tables ok via `as_rows`). +pub fn migrate(url: &str, steps: &Value) -> Result { + if crate::db_pg::is_postgres(url) { + return Err( + "db.migrate is SQLite-only in this wave (use postgres migration tooling)".into(), + ); + } + let rows = crate::table::as_rows(steps); + let arr = rows.as_array().ok_or("migrate steps must be a list")?; + let mut parsed: Vec<(i64, String)> = Vec::new(); + for row in arr { + let obj = row.as_object().ok_or("migrate step must be a map")?; + let ver = obj + .get("version") + .or_else(|| obj.get("版本")) + .or_else(|| obj.get("ver")) + .ok_or("migrate step missing `version`/`版本`")?; + let version = match ver { + Value::Number(n) => n + .as_i64() + .ok_or_else(|| "migrate version must be an integer".to_string())?, + Value::String(s) => s + .trim() + .parse::() + .map_err(|_| format!("bad migrate version `{s}`"))?, + _ => return Err("migrate version must be an integer".into()), + }; + if version <= 0 { + return Err(format!("migrate version must be positive, got {version}")); + } + let sql = obj + .get("sql") + .or_else(|| obj.get("SQL")) + .or_else(|| obj.get("Sql")) + .map(cell_str) + .unwrap_or_default(); + if sql.trim().is_empty() { + return Err(format!("migrate version {version} has empty SQL")); + } + parsed.push((version, sql)); + } + parsed.sort_by_key(|(v, _)| *v); + for w in parsed.windows(2) { + if w[0].0 == w[1].0 { + return Err(format!("duplicate migrate version {}", w[0].0)); + } + } + + let conn = pooled(url)?; + let c = conn.lock().unwrap_or_else(|e| e.into_inner()); + c.execute_batch( + "CREATE TABLE IF NOT EXISTS \"_marqdo_migrations\" ( + version INTEGER PRIMARY KEY, + applied_at TEXT NOT NULL + )", + ) + .map_err(|e| e.to_string())?; + let current: i64 = c + .query_row( + "SELECT COALESCE(MAX(version), 0) FROM \"_marqdo_migrations\"", + [], + |r| r.get(0), + ) + .unwrap_or(0); + let mut applied = Vec::new(); + for (version, sql) in parsed { + if version <= current { + continue; + } + c.execute_batch("BEGIN IMMEDIATE") + .map_err(|e| e.to_string())?; + match c.execute_batch(&sql) { + Ok(()) => { + if let Err(e) = c.execute( + "INSERT INTO \"_marqdo_migrations\" (version, applied_at) VALUES (?1, datetime('now'))", + rusqlite::params![version], + ) { + let _ = c.execute_batch("ROLLBACK"); + return Err(e.to_string()); + } + c.execute_batch("COMMIT").map_err(|e| e.to_string())?; + applied.push(version); + } + Err(e) => { + let _ = c.execute_batch("ROLLBACK"); + return Err(format!("migrate version {version} failed: {e}")); + } + } + } + let to = applied.last().copied().unwrap_or(current); + Ok(json!({ + "ok": true, + "from": current, + "to": to, + "applied": applied, + })) +} + +fn parse_column_list(columns: &Value) -> Result, String> { + match columns { + Value::String(s) => { + let cols: Vec = s + .split(',') + .map(|p| p.trim().to_string()) + .filter(|p| !p.is_empty()) + .collect(); + if cols.is_empty() { + return Err("fts columns is empty".into()); + } + for c in &cols { + let _ = ident(c)?; + } + Ok(cols) + } + Value::Array(a) => { + let mut cols = Vec::new(); + for v in a { + let name = cell_str(v); + let _ = ident(&name)?; + cols.push(name); + } + if cols.is_empty() { + return Err("fts columns is empty".into()); + } + Ok(cols) + } + Value::Object(_) => { + let rows = crate::table::as_rows(columns); + if let Some(arr) = rows.as_array() { + let mut cols = Vec::new(); + for row in arr { + if let Some(obj) = row.as_object() { + let name = obj + .get("name") + .or_else(|| obj.get("字段")) + .or_else(|| obj.get("column")) + .or_else(|| obj.values().next()) + .map(cell_str) + .unwrap_or_default(); + if !name.is_empty() { + let _ = ident(&name)?; + cols.push(name); + } + } else { + let name = cell_str(row); + if !name.is_empty() { + let _ = ident(&name)?; + cols.push(name); + } + } + } + if cols.is_empty() { + return Err("fts columns is empty".into()); + } + return Ok(cols); + } + Err("fts columns must be a list or CSV string".into()) + } + _ => Err("fts columns must be a list or CSV string".into()), + } +} + +/// Create an FTS5 virtual table synced to `table` via content= + triggers. +pub fn fts_create( + url: &str, + table: &str, + columns: &Value, + name: Option<&str>, +) -> Result { + if crate::db_pg::is_postgres(url) { + return Err("db.fts is SQLite-only in this wave".into()); + } + let table = ident(table)?; + let cols = parse_column_list(columns)?; + let fts = match name { + Some(n) if !n.trim().is_empty() => ident(n.trim())?.to_string(), + _ => format!("{table}_fts"), + }; + let col_sql = cols + .iter() + .map(|c| format!("\"{c}\"")) + .collect::>() + .join(", "); + let conn = pooled(url)?; + let c = conn.lock().unwrap_or_else(|e| e.into_inner()); + + let create = format!( + "CREATE VIRTUAL TABLE IF NOT EXISTS \"{fts}\" USING fts5({col_sql}, content=\"{table}\", content_rowid=\"id\")" + ); + c.execute_batch(&create).map_err(|e| e.to_string())?; + + let ai = format!("{fts}_ai"); + let ad = format!("{fts}_ad"); + let au = format!("{fts}_au"); + c.execute_batch(&format!( + "DROP TRIGGER IF EXISTS \"{ai}\"; + DROP TRIGGER IF EXISTS \"{ad}\"; + DROP TRIGGER IF EXISTS \"{au}\";" + )) + .map_err(|e| e.to_string())?; + + let new_cols = cols + .iter() + .map(|c| format!("new.\"{c}\"")) + .collect::>() + .join(", "); + let old_cols = cols + .iter() + .map(|c| format!("old.\"{c}\"")) + .collect::>() + .join(", "); + + c.execute_batch(&format!( + "CREATE TRIGGER \"{ai}\" AFTER INSERT ON \"{table}\" BEGIN + INSERT INTO \"{fts}\"(rowid, {col_sql}) VALUES (new.id, {new_cols}); + END; + CREATE TRIGGER \"{ad}\" AFTER DELETE ON \"{table}\" BEGIN + INSERT INTO \"{fts}\"(\"{fts}\", rowid, {col_sql}) VALUES('delete', old.id, {old_cols}); + END; + CREATE TRIGGER \"{au}\" AFTER UPDATE ON \"{table}\" BEGIN + INSERT INTO \"{fts}\"(\"{fts}\", rowid, {col_sql}) VALUES('delete', old.id, {old_cols}); + INSERT INTO \"{fts}\"(rowid, {col_sql}) VALUES (new.id, {new_cols}); + END;" + )) + .map_err(|e| e.to_string())?; + + c.execute( + &format!("INSERT INTO \"{fts}\"(\"{fts}\") VALUES('rebuild')"), + [], + ) + .map_err(|e| e.to_string())?; + + Ok(json!({ + "ok": true, + "table": table, + "fts": fts, + "columns": cols, + })) +} + +/// Full-text search against an FTS5 table created by `fts_create`. +pub fn search( + url: &str, + table: &str, + q: &str, + limit: i64, + name: Option<&str>, +) -> Result { + if crate::db_pg::is_postgres(url) { + return Err("db.search is SQLite-only in this wave".into()); + } + let table = ident(table)?; + let fts = match name { + Some(n) if !n.trim().is_empty() => ident(n.trim())?.to_string(), + _ => format!("{table}_fts"), + }; + let q = q.trim(); + if q.is_empty() { + return Ok(json!({ "rows": [], "count": 0 })); + } + let limit = if limit <= 0 { 20 } else { limit.min(500) }; + let sql = format!( + "SELECT t.*, bm25(\"{fts}\") AS rank + FROM \"{fts}\" + JOIN \"{table}\" t ON t.id = \"{fts}\".rowid + WHERE \"{fts}\" MATCH ?1 + ORDER BY rank + LIMIT ?2" + ); + let conn = pooled(url)?; + let c = conn.lock().unwrap_or_else(|e| e.into_inner()); + let vals = vec![ + rusqlite::types::Value::Text(q.to_string()), + rusqlite::types::Value::Integer(limit), + ]; + let rows = query_rows(&c, &sql, &vals)?; + Ok(json!({ "rows": rows, "count": rows.len() })) +} diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index ecf127c..e34f9ec 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -727,6 +727,39 @@ web_ffi!(web_db_count, |args: &Value| { db::count(&url, &table, where_v, txn) }); +web_ffi!(web_db_migrate, |args: &Value| { + let url = db_url_of(args)?; + let steps = args + .get("steps") + .ok_or_else(|| "missing `steps`".to_string())?; + db::migrate(&url, steps) +}); + +web_ffi!(web_db_fts_create, |args: &Value| { + let url = db_url_of(args)?; + let table = arg_str(args, "table")?.to_string(); + let columns = args + .get("columns") + .ok_or_else(|| "missing `columns`".to_string())?; + let name = arg_str_opt(args, "name"); + db::fts_create(&url, &table, columns, name) +}); + +web_ffi!(web_db_search, |args: &Value| { + let url = db_url_of(args)?; + let table = arg_str(args, "table")?.to_string(); + let q = arg_str(args, "q") + .or_else(|_| arg_str(args, "query")) + .or_else(|_| arg_str(args, "关键词"))? + .to_string(); + let limit = args + .get("limit") + .and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64))) + .unwrap_or(20); + let name = arg_str_opt(args, "name"); + db::search(&url, &table, &q, limit, name) +}); + web_ffi!(web_db_begin, |args: &Value| { let url = db_url_of(args)?; db::begin(&url) @@ -1575,6 +1608,17 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int "url,table,where,txn", web_db_count as PluginFn, ), + ("web_db_migrate", "url,steps", web_db_migrate as PluginFn), + ( + "web_db_fts_create", + "url,table,columns,name", + web_db_fts_create as PluginFn, + ), + ( + "web_db_search", + "url,table,q,limit,name", + web_db_search as PluginFn, + ), ("web_db_begin", "url", web_db_begin as PluginFn), ("web_db_commit", "txn", web_db_commit as PluginFn), ("web_db_rollback", "txn", web_db_rollback as PluginFn), diff --git a/tests/ext/web-db-w6-smoke.mq.md b/tests/ext/web-db-w6-smoke.mq.md new file mode 100644 index 0000000..66bd9a1 --- /dev/null +++ b/tests/ext/web-db-w6-smoke.mq.md @@ -0,0 +1,83 @@ +--- +title: web db W6 smoke — migrate / FTS5 / published filter +import web:ext/web/web.mq.md +--- + +# main + +*store = > web.db url="sqlite:web-fixtures/data/w6-smoke.db"* + +`steps` = + +| 版本 | SQL | +|------|-----| +| 1 | CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT, status TEXT NOT NULL DEFAULT 'draft') | +| 2 | CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY AUTOINCREMENT, post_id INTEGER NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending') | + +*m1 = > `store`.migrate steps=`steps`* +*a1 = m1[^applied]* +*n1 = > len value=`a1`* +1. `n1` == 2 + > print text=migrate-ok +2. * + > print text=migrate-fail + +*m2 = > `store`.migrate steps=`steps`* +*a2 = m2[^applied]* +*n2 = > len value=`a2`* +1. `n2` == 0 + > print text=migrate-idempotent-ok +2. * + > print text=migrate-idempotent-fail + +`rows` = + +| title | body | status | +|-------|------|--------| +| Alpha note | hello world search | published | +| Beta draft | secret draft body | draft | +| Gamma published | another hello | published | + +> `store`.insert table=posts rows=`rows` + +`pub` = + +| 字段 | 操作 | 值 | +|------|------|-----| +| status | = | published | + +*pc = > `store`.count table="posts" where=`pub`* +1. `pc` == 2 + > print text=published-filter-ok +2. * + > print text=published-filter-fail + +`comments` = + +| post_id | body | status | +|---------|------|--------| +| 1 | nice post | approved | +| 1 | spam | pending | + +> `store`.insert table=comments rows=`comments` +*cc = > `store`.count table="comments"* +1. `cc` == 2 + > print text=comments-ok +2. * + > print text=comments-fail + +> `store`.fts table="posts" columns="title,body" +*hit = > `store`.search table="posts" q="hello" limit=10* +*hn = hit[^count]* +1. `hn` >= 1 + > print text=fts-ok +2. * + > print text=fts-fail + +*rows2 = hit[^rows]* +*first = rows2[^1]* +*ft = first[^title]* +1. `ft` + > print text=fts-row-ok +2. * + > print text=fts-row-fail diff --git a/tests/gold.rs b/tests/gold.rs index 58387be..525d773 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1937,6 +1937,32 @@ fn ext_web_upload_live() { let _ = child.wait(); } +#[test] +fn ext_web_db_w6_smoke() { + // W6: versioned migrate, FTS5 search, published filter + comments table. + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_web"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build web plugin"); + assert!(status.success(), "failed to build marqdo_plugin_web"); + + let db = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/ext/web-fixtures/data/w6-smoke.db"); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{}", db.display(), suffix)); + } + assert_out( + "tests/ext/web-db-w6-smoke.mq.md", + "migrate-ok +migrate-idempotent-ok +published-filter-ok +comments-ok +fts-ok +fts-row-ok", + ); +} + #[test] fn ext_web_db_w2_smoke() { // W2 data layer: transactions, connection pooling, pagination, query