diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 36127e9..09dbe0a 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -41,7 +41,7 @@ body: label: 期望的解决方案 description: 描述你期望的功能行为,如有具体的 API 设计或交互方式请一并说明 validations: - required: true + required: false - type: textarea id: alternatives diff --git a/Cargo.lock b/Cargo.lock index bd33abf..539303b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1307,7 +1307,7 @@ dependencies = [ [[package]] name = "qb_api" -version = "1.0.0" +version = "1.1.0" dependencies = [ "anyhow", "argon2", diff --git a/Cargo.toml b/Cargo.toml index 1c3d747..f038703 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "qb_api" -version = "1.0.0" +version = "1.1.0" edition = "2021" [dependencies] diff --git a/docs/API.md b/docs/API.md index 14a1afe..9a7eea4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -140,7 +140,7 @@ | `GET /auth/me` | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `PATCH /auth/me/password` | — | ✅ | ✅ | ✅ | — | ✅ | | `POST /auth/logout` | — | ✅ | ✅ | ✅ | ✅ | ✅ | -| `GET` questions/papers/tags | — | ✅ | ✅ | ✅ | ✅ | ✅ | +| `GET /questions`, `POST /questions/search`, `GET` questions/papers/tags | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `POST` bundles | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `POST /questions`(上传) | — | — | ✅ | ✅ | ✅ | ✅ | | `PATCH /questions/:id`(更新) | — | — | ⚠️¹ | ⚠️³ | ✅ | ✅ | @@ -474,6 +474,62 @@ Bot 账号不会自动生成;管理员创建或轮换 bot 账号时,接口 **Query 参数**:`paper_id`, `category`, `tag`, `author`, `reviewer`(支持逗号分隔多值,匹配任一), `assigned_reviewer_id`, `score_min`, `score_max`, `difficulty_tag`, `difficulty_min`, `difficulty_max`, `q`, `created_after`, `created_before`, `updated_after`, `updated_before`, `limit` (1-100, 默认 20), `offset` (默认 0)。 +- `tag` 仍用于简单单标签精确匹配 +- 复杂标签组合查询请使用 `POST /questions/search` + +**成功响应** `200`:分页包裹,`items` 为 `QuestionSummary[]`。 + +--- + +#### `POST /questions/search` + +按 JSON 逻辑树进行高级题目搜索。认证:`viewer` 及以上。 + +- **Content-Type**:`application/json` +- **说明**:除 `tag_filter` 外,其余字段与 `GET /questions` 的过滤字段一致;返回格式也一致 + +**请求体示例**: + +```json +{ + "category": "T", + "q": "pendulum", + "limit": 20, + "offset": 0, + "tag_filter": { + "type": "or", + "children": [ + { "type": "tag", "tag": "mechanics" }, + { + "type": "and", + "children": [ + { "type": "tag", "tag": "contest" }, + { + "type": "not", + "child": { "type": "tag", "tag": "deprecated" } + } + ] + } + ] + } +} +``` + +**`tag_filter` 节点结构**: + +| `type` | 其他字段 | 说明 | +|---|---|---| +| `"tag"` | `tag: string` | 精确匹配单个标签 | +| `"and"` | `children: TagFilter[]` | 子条件全部满足 | +| `"or"` | `children: TagFilter[]` | 子条件任一满足 | +| `"not"` | `child: TagFilter` | 子条件不满足 | + +**校验规则**: + +- `tag_filter.tag` 会先 trim,不能为空 +- `and` / `or` 的 `children` 不能为空数组 +- 后端只接受固定 JSON 结构并把所有 tag 值作为 SQL 绑定参数处理,不接受原始 SQL / 表达式字符串 + **成功响应** `200`:分页包裹,`items` 为 `QuestionSummary[]`。 --- diff --git a/migrations/0004_question_tags_tag_question_id_idx.sql b/migrations/0004_question_tags_tag_question_id_idx.sql new file mode 100644 index 0000000..6c86e39 --- /dev/null +++ b/migrations/0004_question_tags_tag_question_id_idx.sql @@ -0,0 +1,2 @@ +CREATE INDEX IF NOT EXISTS idx_question_tags_tag_question_id + ON question_tags(tag, question_id); diff --git a/scripts/tests/config.py b/scripts/tests/config.py index c978286..b43c859 100644 --- a/scripts/tests/config.py +++ b/scripts/tests/config.py @@ -41,6 +41,15 @@ def _cfg(key: str, default: str) -> str: return os.environ.get(key, _dotenv.get(key, default)) +def _cfg_any(keys: tuple[str, ...], default: str) -> str: + """Resolve config from the first present key across env and .env.""" + for key in keys: + value = os.environ.get(key, _dotenv.get(key)) + if value is not None: + return value + return default + + POSTGRES_USER = _cfg("POSTGRES_USER", "postgres") POSTGRES_PASSWORD = _cfg("POSTGRES_PASSWORD", "postgres") POSTGRES_DB = _cfg("POSTGRES_DB", "qb") @@ -49,5 +58,5 @@ def _cfg(key: str, default: str) -> str: CONTAINER_NAME = _cfg("CONTAINER_NAME", "qb-postgres-e2e") POSTGRES_IMAGE = _cfg("POSTGRES_IMAGE", f"postgres:{POSTGRES_MAJOR}") POSTGRES_PORT = _cfg("POSTGRES_PORT", "55433") -API_PORT = _cfg("QB_BIND_PORT", "8080") +API_PORT = _cfg_any(("QB_BIND_PORT", "API_PORT"), "18080") DB_URL = f"postgres://{POSTGRES_USER}:{POSTGRES_PASSWORD}@127.0.0.1:{POSTGRES_PORT}/{POSTGRES_DB}" diff --git a/scripts/tests/test_1_questions.py b/scripts/tests/test_1_questions.py index 06ba570..059eade 100644 --- a/scripts/tests/test_1_questions.py +++ b/scripts/tests/test_1_questions.py @@ -35,6 +35,22 @@ def assert_question_query( ) +def assert_question_search( + api: ApiClient, payload: dict, expected_ids: list[str], +) -> None: + _, body, _ = api.post_json("/questions/search", payload) + actual = question_ids_from_body(body) + if expected_ids: + missing = set(expected_ids) - set(actual) + assert not missing, ( + f"search {payload}: missing {sorted(missing)} from {sorted(actual)}" + ) + else: + assert actual == [], ( + f"search {payload}: expected empty, got {sorted(actual)}" + ) + + def _apply_question_patch(api: ApiClient, question_id: str, patch: dict) -> None: """Apply per-field PATCH / POST calls to match the spec['patch'] dict. @@ -388,6 +404,120 @@ def test_filter_questions(api, state): api.get("/questions?updated_before=abc", expect=400) +def test_search_questions(api, state): + """POST /questions/search supports boolean tag logic and shared filters.""" + qs = state.q_by_slug + + assert_question_search( + api, + { + "tag_filter": { + "type": "or", + "children": [ + {"type": "tag", "tag": "mechanics"}, + {"type": "tag", "tag": "optics"}, + ], + }, + "limit": 100, + "offset": 0, + }, + [qs["mechanics"], qs["optics"]], + ) + + assert_question_search( + api, + { + "tag_filter": { + "type": "and", + "children": [ + {"type": "tag", "tag": "mechanics"}, + { + "type": "not", + "child": {"type": "tag", "tag": "optics"}, + }, + ], + }, + }, + [qs["mechanics"]], + ) + + assert_question_search( + api, + { + "tag": "mechanics", + "tag_filter": { + "type": "or", + "children": [ + {"type": "tag", "tag": "mechanics"}, + {"type": "tag", "tag": "optics"}, + ], + }, + }, + [qs["mechanics"]], + ) + + assert_question_search( + api, + { + "q": "热学", + "tag_filter": {"type": "tag", "tag": "thermal"}, + "difficulty_tag": "human", + "difficulty_min": 5, + "difficulty_max": 5, + }, + [qs["thermal"]], + ) + + assert_question_search( + api, + { + "category": "E", + "tag_filter": { + "type": "or", + "children": [ + {"type": "tag", "tag": "mechanics"}, + {"type": "tag", "tag": "optics"}, + ], + }, + }, + [qs["optics"]], + ) + + +def test_search_questions_validation(api): + api.post_json( + "/questions/search", + {"tag_filter": {"type": "tag", "tag": " "}}, + expect=400, + ) + api.post_json( + "/questions/search", + {"tag_filter": {"type": "and", "children": []}}, + expect=400, + ) + api.post_json( + "/questions/search", + {"difficulty_min": 5}, + expect=400, + ) + api.post_json( + "/questions/search", + {"q": "ok", "extra": 1}, + expect=400, + ) + api.post_json( + "/questions/search", + { + "tag_filter": { + "type": "tag", + "tag": "mechanics", + "extra": 1, + }, + }, + expect=400, + ) + + def test_filter_questions_by_author(api, state): """Filter questions by author (exact match on questions.author field). diff --git a/src/api/admin/models.rs b/src/api/admin/models.rs index 936849b..904a4c4 100644 --- a/src/api/admin/models.rs +++ b/src/api/admin/models.rs @@ -128,6 +128,7 @@ impl AdminQuestionsParams { paper_id: self.paper_id.clone(), category: self.category.clone(), tag: self.tag.clone(), + tag_filter: None, author: self.author.clone(), reviewer: self.reviewer.clone(), assigned_reviewer_id: self.assigned_reviewer_id.clone(), diff --git a/src/api/auth/API.md b/src/api/auth/API.md index 2c35f3a..e564c62 100644 --- a/src/api/auth/API.md +++ b/src/api/auth/API.md @@ -26,7 +26,7 @@ | `GET /auth/me` | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `PATCH /auth/me/password` | — | ✅ | ✅ | ✅ | — | ✅ | | `POST /auth/logout` | — | ✅ | ✅ | ✅ | ✅ | ✅ | -| `GET` questions/papers/tags | — | ✅ | ✅ | ✅ | ✅ | ✅ | +| `GET /questions`, `POST /questions/search`, `GET` questions/papers/tags | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `POST` bundles | — | ✅ | ✅ | ✅ | ✅ | ✅ | | `POST /questions`(上传) | — | — | ✅ | ✅ | ✅ | ✅ | | `PATCH /questions/:id`(更新) | — | — | ⚠️¹ | ⚠️³ | ✅ | ✅ | diff --git a/src/api/mod.rs b/src/api/mod.rs index 98026a6..7743b64 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -68,6 +68,10 @@ pub fn router(state: AppState, cors_origins: &[String]) -> Router { "/questions/tags", axum::routing::get(questions::handlers::list_question_tags), ) + .route( + "/questions/search", + axum::routing::post(questions::handlers::search_questions), + ) .route( "/questions/difficulty-tags", axum::routing::get(questions::handlers::list_difficulty_tags), diff --git a/src/api/questions/API.md b/src/api/questions/API.md index 473a471..63428d4 100644 --- a/src/api/questions/API.md +++ b/src/api/questions/API.md @@ -92,6 +92,62 @@ **Query 参数**:`paper_id`, `category`, `tag`, `author`, `reviewer`(支持逗号分隔多值,匹配任一), `assigned_reviewer_id`, `score_min`, `score_max`, `difficulty_tag`, `difficulty_min`, `difficulty_max`, `q`, `created_after`, `created_before`, `updated_after`, `updated_before`, `limit` (1-100, 默认 20), `offset` (默认 0)。 +- `tag` 仍用于简单单标签精确匹配 +- 复杂标签组合查询请使用 `POST /questions/search` + +**成功响应** `200`:分页包裹,`items` 为 `QuestionSummary[]`。 + +--- + +### `POST /questions/search` + +按 JSON 逻辑树进行高级题目搜索。认证:`viewer` 及以上。 + +- **Content-Type**:`application/json` +- **说明**:除 `tag_filter` 外,其余字段与 `GET /questions` 的过滤字段一致;返回格式也一致 + +**请求体示例**: + +```json +{ + "category": "T", + "q": "pendulum", + "limit": 20, + "offset": 0, + "tag_filter": { + "type": "or", + "children": [ + { "type": "tag", "tag": "mechanics" }, + { + "type": "and", + "children": [ + { "type": "tag", "tag": "contest" }, + { + "type": "not", + "child": { "type": "tag", "tag": "deprecated" } + } + ] + } + ] + } +} +``` + +**`tag_filter` 节点结构**: + +| `type` | 其他字段 | 说明 | +|---|---|---| +| `"tag"` | `tag: string` | 精确匹配单个标签 | +| `"and"` | `children: TagFilter[]` | 子条件全部满足 | +| `"or"` | `children: TagFilter[]` | 子条件任一满足 | +| `"not"` | `child: TagFilter` | 子条件不满足 | + +**校验规则**: + +- `tag_filter.tag` 会先 trim,不能为空 +- `and` / `or` 的 `children` 不能为空数组 +- 后端只接受固定 JSON 结构并把所有 tag 值作为 SQL 绑定参数处理,不接受原始 SQL / 表达式字符串 + **成功响应** `200`:分页包裹,`items` 为 `QuestionSummary[]`。 --- diff --git a/src/api/questions/handlers.rs b/src/api/questions/handlers.rs index ae2549e..415abe9 100644 --- a/src/api/questions/handlers.rs +++ b/src/api/questions/handlers.rs @@ -1,5 +1,6 @@ use anyhow::Context; use axum::{ + body::Bytes, extract::{Multipart, Path as AxumPath, Query, State}, response::Response, Extension, Json, @@ -13,10 +14,10 @@ use super::{ models::{ CreateDifficultyRequest, CreateQuestionRequest, QuestionBundleRequest, QuestionDeleteResponse, QuestionDetail, QuestionDifficultyTagsResponse, - QuestionFileReplaceResponse, QuestionImportResponse, QuestionSummary, QuestionTagsResponse, - QuestionsParams, UpdateAuthorRequest, UpdateCategoryRequest, UpdateDescriptionRequest, - UpdateDifficultyRequest, UpdateReviewerNamesRequest, UpdateStatusRequest, - UpdateTagsRequest, + QuestionFileReplaceResponse, QuestionImportResponse, QuestionSearchRequest, + QuestionSummary, QuestionTagsResponse, QuestionsParams, UpdateAuthorRequest, + UpdateCategoryRequest, UpdateDescriptionRequest, UpdateDifficultyRequest, + UpdateReviewerNamesRequest, UpdateStatusRequest, UpdateTagsRequest, }, queries::{ execute_questions_query, list_active_difficulty_tags, list_active_question_tags, @@ -41,6 +42,25 @@ use crate::api::{ pub(crate) async fn list_questions( Query(params): Query, State(state): State, +) -> ApiResult> { + execute_question_search(&state, params).await +} + +pub(crate) async fn search_questions( + State(state): State, + body: Bytes, +) -> ApiResult> { + let request: QuestionSearchRequest = serde_json::from_slice(&body) + .map_err(|err| ApiError::bad_request(format!("invalid JSON body: {err}")))?; + let params = request + .normalize() + .map_err(|err| ApiError::bad_request(err.to_string()))?; + execute_question_search(&state, params).await +} + +async fn execute_question_search( + state: &AppState, + params: QuestionsParams, ) -> ApiResult> { validate_question_filters(¶ms).map_err(|e| ApiError::bad_request(e.to_string()))?; let mut plan = params.build_query(); diff --git a/src/api/questions/models.rs b/src/api/questions/models.rs index 4b11db9..c2d90ba 100644 --- a/src/api/questions/models.rs +++ b/src/api/questions/models.rs @@ -102,11 +102,45 @@ pub(crate) struct QuestionDifficultyTagsResponse { pub(crate) difficulty_tags: Vec, } +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub(crate) enum QuestionTagFilter { + Tag { tag: String }, + And { children: Vec }, + Or { children: Vec }, + Not { child: Box }, +} + #[derive(Debug, Deserialize)] pub(crate) struct QuestionsParams { pub(crate) paper_id: Option, pub(crate) category: Option, pub(crate) tag: Option, + pub(crate) tag_filter: Option, + pub(crate) author: Option, + pub(crate) reviewer: Option, + pub(crate) assigned_reviewer_id: Option, + pub(crate) score_min: Option, + pub(crate) score_max: Option, + pub(crate) difficulty_tag: Option, + pub(crate) difficulty_min: Option, + pub(crate) difficulty_max: Option, + pub(crate) created_after: Option, + pub(crate) created_before: Option, + pub(crate) updated_after: Option, + pub(crate) updated_before: Option, + pub(crate) q: Option, + pub(crate) limit: Option, + pub(crate) offset: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct QuestionSearchRequest { + pub(crate) paper_id: Option, + pub(crate) category: Option, + pub(crate) tag: Option, + pub(crate) tag_filter: Option, pub(crate) author: Option, pub(crate) reviewer: Option, pub(crate) assigned_reviewer_id: Option, @@ -347,6 +381,75 @@ impl QuestionBundleRequest { } } +impl QuestionTagFilter { + pub(crate) fn normalize(self) -> Result { + let mut node_count = 0; + self.normalize_inner(1, &mut node_count) + } + + fn normalize_inner(self, depth: usize, node_count: &mut usize) -> Result { + const MAX_TAG_FILTER_DEPTH: usize = 16; + const MAX_TAG_FILTER_NODES: usize = 128; + + if depth > MAX_TAG_FILTER_DEPTH { + bail!("tag_filter nesting must not exceed {MAX_TAG_FILTER_DEPTH} levels"); + } + + *node_count += 1; + if *node_count > MAX_TAG_FILTER_NODES { + bail!("tag_filter must not contain more than {MAX_TAG_FILTER_NODES} nodes"); + } + + match self { + Self::Tag { tag } => { + let tag = tag.trim().to_string(); + if tag.is_empty() { + bail!("tag_filter tag must not be empty"); + } + Ok(Self::Tag { tag }) + } + Self::And { children } => Ok(Self::And { + children: normalize_tag_filter_children("and", children, depth, node_count)?, + }), + Self::Or { children } => Ok(Self::Or { + children: normalize_tag_filter_children("or", children, depth, node_count)?, + }), + Self::Not { child } => Ok(Self::Not { + child: Box::new(child.normalize_inner(depth + 1, node_count)?), + }), + } + } +} + +impl QuestionSearchRequest { + pub(crate) fn normalize(self) -> Result { + Ok(QuestionsParams { + paper_id: self.paper_id, + category: self.category, + tag: self.tag, + tag_filter: self + .tag_filter + .map(QuestionTagFilter::normalize) + .transpose()?, + author: self.author, + reviewer: self.reviewer, + assigned_reviewer_id: self.assigned_reviewer_id, + score_min: self.score_min, + score_max: self.score_max, + difficulty_tag: self.difficulty_tag, + difficulty_min: self.difficulty_min, + difficulty_max: self.difficulty_max, + created_after: self.created_after, + created_before: self.created_before, + updated_after: self.updated_after, + updated_before: self.updated_before, + q: self.q, + limit: self.limit, + offset: self.offset, + }) + } +} + fn normalize_category(value: &str) -> Result { let normalized = value.trim().to_string(); validate_question_category(&normalized)?; @@ -380,6 +483,22 @@ fn normalize_tags(values: Vec) -> Result> { Ok(normalized) } +fn normalize_tag_filter_children( + operator: &str, + children: Vec, + depth: usize, + node_count: &mut usize, +) -> Result> { + if children.is_empty() { + bail!("tag_filter {operator} must contain at least one child"); + } + + children + .into_iter() + .map(|child| child.normalize_inner(depth + 1, node_count)) + .collect() +} + fn normalize_bundle_ids(field_name: &str, ids: Vec) -> Result> { if ids.is_empty() { return Err(anyhow!("{field_name} must not be empty")); @@ -407,6 +526,18 @@ fn normalize_bundle_ids(field_name: &str, ids: Vec) -> Result QuestionTagFilter { + let mut filter = QuestionTagFilter::Tag { + tag: "mechanics".into(), + }; + for _ in 0..levels { + filter = QuestionTagFilter::Not { + child: Box::new(filter), + }; + } + filter + } + #[test] fn create_request_normalizes_with_defaults() { let request = CreateQuestionRequest { @@ -548,4 +679,60 @@ mod tests { }; assert!(req.normalize().is_err()); } + + #[test] + fn question_tag_filter_normalizes_nested_tags() { + let normalized = QuestionTagFilter::Not { + child: Box::new(QuestionTagFilter::And { + children: vec![QuestionTagFilter::Tag { + tag: " mechanics ".into(), + }], + }), + } + .normalize() + .expect("tag filter should normalize"); + + assert_eq!( + normalized, + QuestionTagFilter::Not { + child: Box::new(QuestionTagFilter::And { + children: vec![QuestionTagFilter::Tag { + tag: "mechanics".into(), + }], + }), + } + ); + } + + #[test] + fn question_tag_filter_rejects_excessive_depth() { + let result = nested_not_filter(16).normalize(); + assert!(result.is_err()); + } + + #[test] + fn question_tag_filter_rejects_excessive_nodes() { + let result = QuestionTagFilter::And { + children: (0..128) + .map(|idx| QuestionTagFilter::Tag { + tag: format!("tag-{idx}"), + }) + .collect(), + } + .normalize(); + assert!(result.is_err()); + } + + #[test] + fn question_tag_filter_accepts_maximum_node_count() { + let result = QuestionTagFilter::And { + children: (0..127) + .map(|idx| QuestionTagFilter::Tag { + tag: format!("tag-{idx}"), + }) + .collect(), + } + .normalize(); + assert!(result.is_ok()); + } } diff --git a/src/api/questions/queries.rs b/src/api/questions/queries.rs index 1395539..d7fe2c3 100644 --- a/src/api/questions/queries.rs +++ b/src/api/questions/queries.rs @@ -8,7 +8,7 @@ use sqlx::{postgres::PgRow, query, PgPool, Postgres, QueryBuilder, Row}; use super::models::{ validate_question_category, DifficultyEditor, QuestionAssetRef, QuestionDetail, QuestionDifficulty, QuestionDifficultyValue, QuestionPaperRef, QuestionSourceRef, - QuestionSummary, QuestionsParams, + QuestionSummary, QuestionTagFilter, QuestionsParams, }; use crate::api::shared::{ pagination::{normalize_limit, normalize_offset}, @@ -67,6 +67,10 @@ impl QuestionsParams { .push_bind(tag) .push(")"); } + if let Some(tag_filter) = &self.tag_filter { + builder.push(" AND "); + push_question_tag_filter(&mut builder, tag_filter); + } if let Some(reviewer) = &self.reviewer { let names: Vec<&str> = reviewer .split(',') @@ -191,6 +195,9 @@ pub(crate) fn validate_question_filters(params: &QuestionsParams) -> Result<()> return Err(anyhow!("difficulty_tag must not be empty")); } } + if let Some(tag_filter) = ¶ms.tag_filter { + let _ = tag_filter.clone().normalize()?; + } if (params.difficulty_min.is_some() || params.difficulty_max.is_some()) && params.difficulty_tag.is_none() { @@ -241,6 +248,45 @@ pub(crate) fn validate_question_filters(params: &QuestionsParams) -> Result<()> Ok(()) } +fn push_question_tag_filter<'a>( + builder: &mut QueryBuilder<'a, Postgres>, + tag_filter: &'a QuestionTagFilter, +) { + match tag_filter { + QuestionTagFilter::Tag { tag } => { + builder + .push("EXISTS (SELECT 1 FROM question_tags qt WHERE qt.question_id = q.question_id AND qt.tag = ") + .push_bind(tag) + .push(")"); + } + QuestionTagFilter::And { children } => { + builder.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + builder.push(" AND "); + } + push_question_tag_filter(builder, child); + } + builder.push(')'); + } + QuestionTagFilter::Or { children } => { + builder.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + builder.push(" OR "); + } + push_question_tag_filter(builder, child); + } + builder.push(')'); + } + QuestionTagFilter::Not { child } => { + builder.push("NOT ("); + push_question_tag_filter(builder, child); + builder.push(')'); + } + } +} + pub(crate) async fn execute_questions_query( pool: &PgPool, plan: &mut QuestionsQueryPlan<'_>, diff --git a/src/api/tests.rs b/src/api/tests.rs index 7b62cb5..91fbed8 100644 --- a/src/api/tests.rs +++ b/src/api/tests.rs @@ -3,9 +3,10 @@ mod tests { use crate::api::{ papers::models::PapersParams, questions::models::{ - CreateDifficultyRequest, CreateQuestionRequest, QuestionsParams, UpdateAuthorRequest, - UpdateCategoryRequest, UpdateDescriptionRequest, UpdateDifficultyRequest, - UpdateReviewerNamesRequest, UpdateStatusRequest, UpdateTagsRequest, + CreateDifficultyRequest, CreateQuestionRequest, QuestionSearchRequest, + QuestionTagFilter, QuestionsParams, UpdateAuthorRequest, UpdateCategoryRequest, + UpdateDescriptionRequest, UpdateDifficultyRequest, UpdateReviewerNamesRequest, + UpdateStatusRequest, UpdateTagsRequest, }, }; @@ -19,6 +20,7 @@ mod tests { paper_id: Some("550e8400-e29b-41d4-a716-446655440000".into()), category: Some("none".into()), tag: Some("mechanics".into()), + tag_filter: None, author: None, reviewer: None, assigned_reviewer_id: None, @@ -59,6 +61,7 @@ mod tests { paper_id: None, category: None, tag: None, + tag_filter: None, author: None, reviewer: Some("Alice".into()), assigned_reviewer_id: None, @@ -87,6 +90,7 @@ mod tests { paper_id: None, category: None, tag: None, + tag_filter: None, author: None, reviewer: Some("Alice,Bob".into()), assigned_reviewer_id: None, @@ -109,6 +113,182 @@ mod tests { assert!(sql.contains("q.reviewers &&")); } + #[test] + fn question_query_builds_boolean_tag_filter_sql() { + let params = QuestionsParams { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::And { + children: vec![ + QuestionTagFilter::Tag { + tag: "mechanics".into(), + }, + QuestionTagFilter::Or { + children: vec![ + QuestionTagFilter::Tag { + tag: "contest".into(), + }, + QuestionTagFilter::Not { + child: Box::new(QuestionTagFilter::Tag { + tag: "deprecated".into(), + }), + }, + ], + }, + ], + }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + + let plan = params.build_query(); + let sql = plan.builder.sql().to_owned(); + assert!(sql.contains(" AND (EXISTS (SELECT 1 FROM question_tags qt")); + assert!(sql.contains(" OR NOT (EXISTS (SELECT 1 FROM question_tags qt")); + assert_eq!(sql.matches("FROM question_tags qt").count(), 3); + } + + #[test] + fn question_query_combines_simple_tag_and_tag_filter() { + let params = QuestionsParams { + paper_id: None, + category: None, + tag: Some("core".into()), + tag_filter: Some(QuestionTagFilter::Tag { + tag: "mechanics".into(), + }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + + let plan = params.build_query(); + let sql = plan.builder.sql().to_owned(); + assert_eq!(sql.matches("FROM question_tags qt").count(), 2); + assert!(sql.contains(" AND EXISTS (SELECT 1 FROM question_tags qt")); + } + + #[test] + fn question_search_request_normalizes_tag_filter() { + let request = QuestionSearchRequest { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::And { + children: vec![QuestionTagFilter::Tag { + tag: " mechanics ".into(), + }], + }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + + let normalized = request + .normalize() + .expect("search request should normalize"); + assert_eq!( + normalized.tag_filter, + Some(QuestionTagFilter::And { + children: vec![QuestionTagFilter::Tag { + tag: "mechanics".into(), + }], + }) + ); + } + + #[test] + fn question_search_request_rejects_empty_tag_filter_tag() { + let request = QuestionSearchRequest { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::Tag { tag: " ".into() }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + + assert!(request.normalize().is_err()); + } + + #[test] + fn question_search_request_rejects_empty_and_children() { + let request = QuestionSearchRequest { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::And { children: vec![] }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + + assert!(request.normalize().is_err()); + } + // ----------------------------------------------------------------------- // Paper query plan tests // ----------------------------------------------------------------------- @@ -494,6 +674,20 @@ mod tests { assert!(result.is_err()); } + #[test] + fn question_search_json_rejects_unknown_fields() { + let result: Result = + serde_json::from_str(r#"{"q":"ok","extra":1}"#); + assert!(result.is_err()); + } + + #[test] + fn question_search_json_rejects_unknown_tag_filter_fields() { + let result: Result = + serde_json::from_str(r#"{"tag_filter":{"type":"tag","tag":"mechanics","extra":1}}"#); + assert!(result.is_err()); + } + // ----------------------------------------------------------------------- // JSON deserialization: valid payloads // ----------------------------------------------------------------------- @@ -527,6 +721,32 @@ mod tests { assert_eq!(req.notes.as_deref(), Some("test")); } + #[test] + fn question_search_json_parses_nested_tag_filter() { + let req: QuestionSearchRequest = serde_json::from_str( + r#"{ + "q":"pendulum", + "tag_filter":{ + "type":"or", + "children":[ + {"type":"tag","tag":"mechanics"}, + { + "type":"not", + "child":{"type":"tag","tag":"deprecated"} + } + ] + } + }"#, + ) + .unwrap(); + + assert_eq!(req.q.as_deref(), Some("pendulum")); + assert!(matches!( + req.tag_filter, + Some(QuestionTagFilter::Or { children }) if children.len() == 2 + )); + } + // ----------------------------------------------------------------------- // Role permission helpers // ----------------------------------------------------------------------- @@ -582,6 +802,7 @@ mod tests { paper_id: None, category: Some("X".into()), tag: None, + tag_filter: None, author: None, reviewer: None, assigned_reviewer_id: None, @@ -608,6 +829,7 @@ mod tests { paper_id: None, category: None, tag: None, + tag_filter: None, author: None, reviewer: None, assigned_reviewer_id: None, @@ -634,6 +856,7 @@ mod tests { paper_id: None, category: Some("T".into()), tag: Some("optics".into()), + tag_filter: None, author: None, reviewer: None, assigned_reviewer_id: None, @@ -660,6 +883,7 @@ mod tests { paper_id: None, category: None, tag: None, + tag_filter: None, author: None, reviewer: None, assigned_reviewer_id: None, @@ -679,6 +903,64 @@ mod tests { assert!(validate_question_filters(¶ms).is_err()); } + #[test] + fn question_filter_rejects_invalid_tag_filter() { + use crate::api::questions::queries::validate_question_filters; + let params = QuestionsParams { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::Or { children: vec![] }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + assert!(validate_question_filters(¶ms).is_err()); + } + + #[test] + fn question_filter_accepts_valid_tag_filter() { + use crate::api::questions::queries::validate_question_filters; + let params = QuestionsParams { + paper_id: None, + category: None, + tag: None, + tag_filter: Some(QuestionTagFilter::Not { + child: Box::new(QuestionTagFilter::Tag { + tag: "mechanics".into(), + }), + }), + author: None, + reviewer: None, + assigned_reviewer_id: None, + score_min: None, + score_max: None, + difficulty_tag: None, + difficulty_min: None, + difficulty_max: None, + created_after: None, + created_before: None, + updated_after: None, + updated_before: None, + q: None, + limit: None, + offset: None, + }; + assert!(validate_question_filters(¶ms).is_ok()); + } + // ----------------------------------------------------------------------- // Paper filter validation: positive & negative // -----------------------------------------------------------------------