1use serde_json::{json, Map, Value};
4
5use crate::bson::id_key;
6use crate::computes::{collect_field_deps, merge_depends_into_ast, InjectInfo};
7use crate::permission::{can_read_schema, is_relation_readable, merge_owner_condition, Context};
8use crate::pipeline::{
9 build_pipeline, build_projection, flatten_object_fields, is_nullish, param, parse_gql, Ast,
10 RelAst, REL_PRED_PREFIX,
11};
12use crate::rbac::{ensure_read, merge_row_condition};
13use crate::schema::{Registry, Schema};
14use crate::types::{is_truthy, validate_pipeline_stages};
15
16use super::cmd::{cmd_aggregate, cmd_find, num_value, to_number};
17use super::{ensure_context, ERR_PERMISSION, MAX_PAGE_SIZE, PHASE1_IDS};
18
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Page {
21 pub page: f64,
22 pub page_size: f64,
23}
24
25impl Page {
26 pub fn to_value(&self) -> Value {
27 json!({
28 "page": num_value(self.page),
29 "pageSize": num_value(self.page_size),
30 })
31 }
32
33 pub fn has_more(&self, total: f64) -> bool {
35 (self.page + 1.0) * self.page_size < total
36 }
37}
38
39pub fn resolve_page(ast: &Ast, params: &Map<String, Value>) -> Page {
41 let (page, page_size) = if params.contains_key("page") || params.contains_key("pageSize") {
42 let page = match params.get("page").filter(|v| !v.is_null()) {
43 Some(v) => to_number(Some(v)).max(0.0).floor(),
44 None => 0.0,
45 };
46 let page_size = match params.get("pageSize").filter(|v| !v.is_null()) {
47 Some(v) => to_number(Some(v)),
48 None => 50.0,
49 };
50 (page, page_size)
51 } else {
52 let skip_val = param(params, ast.params.get("skip"));
53 let limit_val = param(params, ast.params.get("limit"));
54 let page = if !is_nullish(skip_val) && is_truthy(limit_val.unwrap_or(&Value::Null)) {
55 (to_number(skip_val) / to_number(limit_val)).floor()
56 } else {
57 0.0
58 };
59 let page_size = if is_nullish(limit_val) {
60 50.0
61 } else {
62 to_number(limit_val)
63 };
64 (page, page_size)
65 };
66
67 Page {
68 page,
69 page_size: if page_size < MAX_PAGE_SIZE {
70 page_size
71 } else {
72 MAX_PAGE_SIZE
73 },
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq)]
79pub enum Mode {
80 Find,
82 TwoPhase,
84 Aggregate,
86}
87
88impl Mode {
89 pub fn as_str(self) -> &'static str {
90 match self {
91 Mode::Find => "find",
92 Mode::TwoPhase => "two_phase",
93 Mode::Aggregate => "aggregate",
94 }
95 }
96}
97
98#[derive(Debug, Clone)]
99pub struct QueryPlan {
100 pub collection: String,
101 pub mode: Mode,
102 pub commands: Vec<Value>,
103 pub postprocess: Option<Value>,
105 pub sort: Option<Value>,
107}
108
109impl QueryPlan {
110 pub fn to_value(&self) -> Value {
111 json!({
112 "collection": self.collection,
113 "mode": self.mode.as_str(),
114 "commands": self.commands,
115 "postprocess": self.postprocess.clone().unwrap_or(Value::Null),
116 "sort": self.sort.clone().unwrap_or(Value::Null),
117 })
118 }
119}
120
121fn postprocess_value(ast: &Ast, inject: &InjectInfo) -> Value {
122 json!({
123 "ast": ast.to_value(),
124 "inject": if inject.is_empty() { Value::Null } else { inject.to_value() },
125 })
126}
127
128pub fn plan_query(
130 gql: &str,
131 params: &Map<String, Value>,
132 registry: &Registry,
133 ctx: Option<&Context>,
134) -> Result<QueryPlan, String> {
135 let mut params = params.clone();
136 plan_query_mut(gql, &mut params, registry, ctx)
137}
138
139pub fn plan_query_mut(
141 gql: &str,
142 params: &mut Map<String, Value>,
143 registry: &Registry,
144 ctx: Option<&Context>,
145) -> Result<QueryPlan, String> {
146 let ast = parse_gql(gql)?;
147 plan_query_ast_mut(ast, params, registry, ctx)
148}
149
150pub fn plan_query_one(
156 gql: &str,
157 params: &Map<String, Value>,
158 registry: &Registry,
159 ctx: Option<&Context>,
160) -> Result<QueryPlan, String> {
161 let mut params = params.clone();
162 let mut ast = parse_gql(gql)?;
163 if !ast.params.contains_key("limit") {
164 ast.params
165 .insert("limit".to_string(), "@__core_one_limit__".to_string());
166 params.insert("__core_one_limit__".to_string(), json!(1));
167 }
168 plan_query_ast_mut(ast, &mut params, registry, ctx)
169}
170
171pub fn plan_query_ast_mut(
177 mut ast: Ast,
178 params: &mut Map<String, Value>,
179 registry: &Registry,
180 ctx: Option<&Context>,
181) -> Result<QueryPlan, String> {
182 ensure_context(registry, ctx)?;
183 let schema = registry.get(&ast.model)?;
184
185 if ctx.is_some() && !can_read_schema(registry.role_rules(), schema, ctx) {
186 return Err(ERR_PERMISSION.to_string());
187 }
188 ensure_read(registry, schema, ctx)?;
190
191 if ctx.is_some() {
194 if let Some(r) = ast.params.get("condition").cloned() {
195 let key = r.get(1..).unwrap_or("").to_string();
196 let owner_merged = merge_owner_condition(
197 registry.role_rules(),
198 schema,
199 ctx,
200 params.get(&key).cloned(),
201 );
202 match merge_row_condition(registry, schema, ctx, "read", owner_merged) {
203 Some(v) => {
204 params.insert(key, v);
205 }
206 None => {
207 params.remove(&key);
208 }
209 }
210 } else {
211 let static_owner = merge_owner_condition(registry.role_rules(), schema, ctx, None);
215 if let Some(owner) = merge_row_condition(registry, schema, ctx, "read", static_owner)
216 .filter(|v| v.as_object().map(|o| !o.is_empty()).unwrap_or(false))
217 {
218 ast.params
219 .insert("condition".to_string(), "@__core_owner__".to_string());
220 params.insert("__core_owner__".to_string(), owner);
221 }
222 }
223 }
224
225 let mut inject = merge_depends_into_ast(&mut ast.relations, schema)?;
226 inject.fields = collect_field_deps(&mut ast.fields, schema);
229
230 let mut post_ast = ast.clone();
232 flatten_object_fields(&mut post_ast, schema);
233
234 build_plan(ast, &post_ast, &inject, params, registry, ctx)
235}
236
237pub fn check_readable_relations(
244 relations: &[(String, RelAst)],
245 schema: &Schema,
246 registry: &Registry,
247 ctx: Option<&Context>,
248) -> Result<(), String> {
249 if ctx.is_none() {
250 return Ok(());
251 }
252 for (rel_name, rel_ast) in relations {
253 let Some(rel_def) = schema.relations.get(rel_name) else {
254 continue;
255 };
256 if rel_def.model.is_empty() {
258 continue;
259 }
260 if !is_relation_readable(registry.role_rules(), schema, ctx, rel_name) {
261 return Err(ERR_PERMISSION.to_string());
262 }
263 let rel_schema = registry.get(&rel_def.model)?;
264 if !can_read_schema(registry.role_rules(), rel_schema, ctx) {
265 return Err(ERR_PERMISSION.to_string());
266 }
267 ensure_read(registry, rel_schema, ctx)?;
269 check_readable_relations(&rel_ast.relations, rel_schema, registry, ctx)?;
270 }
271 Ok(())
272}
273
274pub fn build_plan(
280 mut fetch_ast: Ast,
281 post_ast: &Ast,
282 inject: &InjectInfo,
283 params: &Map<String, Value>,
284 registry: &Registry,
285 ctx: Option<&Context>,
286) -> Result<QueryPlan, String> {
287 ensure_context(registry, ctx)?;
288 let schema = registry.get(&fetch_ast.model)?;
289
290 check_readable_relations(&fetch_ast.relations, schema, registry, ctx)?;
293
294 let pipeline = build_pipeline(&mut fetch_ast, params, registry, ctx)?;
295 let stages: Vec<Value> = pipeline.as_array().cloned().unwrap_or_default();
296
297 let has_vector = stages.iter().any(|s| s.get("$vectorSearch").is_some());
300 if fetch_ast.fields.iter().any(|f| f == "_score") && !has_vector {
301 return Err("字段 _score 仅在向量检索($near)查询中可用".to_string());
302 }
303
304 let grouped = stages.iter().any(|s| s.get("$group").is_some());
308
309 let projection = if grouped {
310 None
311 } else {
312 build_projection(&fetch_ast, schema, ctx, registry)
313 };
314
315 let collection = schema.collection.clone();
316 let post = || {
317 if grouped {
318 None
319 } else {
320 Some(postprocess_value(post_ast, inject))
321 }
322 };
323
324 let vector_first = stages
327 .first()
328 .map(|s| s.get("$vectorSearch").is_some())
329 .unwrap_or(false);
330 if vector_first && stages.len() == 1 {
331 return Err(
332 "向量检索计划缺少后置阶段:$vectorSearch 必须与 $addFields._score 成对出现".into(),
333 );
334 }
335
336 if stages.len() == 1 {
338 if let Some(filter) = stages[0].get("$match") {
339 return Ok(QueryPlan {
340 collection: collection.clone(),
341 mode: Mode::Find,
342 commands: vec![cmd_find(schema, filter, projection.as_ref())],
343 postprocess: post(),
344 sort: None,
345 });
346 }
347 }
348
349 let first_lookup = stages.iter().position(|s| {
353 s.get("$lookup")
354 .map(|lo| {
355 !lo.get("as")
356 .and_then(|v| v.as_str())
357 .map(|a| a.starts_with(REL_PRED_PREFIX))
358 .unwrap_or(false)
359 })
360 .unwrap_or(false)
361 });
362 let has_skip_limit = stages
363 .iter()
364 .any(|s| s.get("$skip").is_some() || s.get("$limit").is_some());
365 let sort_stage = stages.iter().find(|s| s.get("$sort").is_some()).cloned();
366
367 if let Some(idx) = first_lookup {
368 if !grouped && has_skip_limit && !sorts_by_relation(sort_stage.as_ref()) {
369 let mut id_pipeline: Vec<Value> = stages[..idx].to_vec();
370 for key in ["$sort", "$skip", "$limit"] {
371 if let Some(st) = stages.iter().find(|s| s.get(key).is_some()) {
372 id_pipeline.push(st.clone());
373 }
374 }
375 id_pipeline.push(json!({ "$project": { "_id": 1 } }));
376
377 let mut full: Vec<Value> = stages[idx..]
378 .iter()
379 .filter(|s| {
380 !(s.get("$sort").is_some()
381 || s.get("$skip").is_some()
382 || s.get("$limit").is_some())
383 })
384 .cloned()
385 .collect();
386 full.insert(0, json!({ "$match": { "_id": { "$in": PHASE1_IDS } } }));
387 if let Some(p) = projection.as_ref() {
388 full.push(json!({ "$project": p }));
389 }
390
391 return Ok(QueryPlan {
392 collection: collection.clone(),
393 mode: Mode::TwoPhase,
394 commands: vec![
395 cmd_aggregate(schema, &id_pipeline),
396 cmd_aggregate(schema, &full),
397 ],
398 postprocess: post(),
399 sort: sort_stage,
400 });
401 }
402 }
403
404 let mut final_stages = stages;
406 if let Some(p) = projection.as_ref() {
407 final_stages.push(json!({ "$project": p }));
408 }
409 validate_pipeline_stages(&final_stages)?;
411
412 Ok(QueryPlan {
413 collection,
414 mode: Mode::Aggregate,
415 commands: vec![cmd_aggregate(schema, &final_stages)],
416 postprocess: post(),
417 sort: None,
418 })
419}
420
421pub fn sorts_by_relation(sort_stage: Option<&Value>) -> bool {
423 sort_stage
424 .and_then(|s| s.get("$sort"))
425 .and_then(|s| s.as_object())
426 .map(|o| o.keys().any(|k| k.contains('.')))
427 .unwrap_or(false)
428}
429
430pub fn restore_sort_order(items: &mut [Value], ids: &[Value], sort_stage: Option<&Value>) {
432 if sort_stage.is_none() || ids.len() <= 1 {
433 return;
434 }
435 let mut index: std::collections::HashMap<_, usize> =
438 std::collections::HashMap::with_capacity(ids.len());
439 for (i, id) in ids.iter().enumerate() {
440 index.entry(id_key(id)).or_insert(i);
441 }
442 let keyed: Vec<(usize, Value)> = items
443 .iter()
444 .map(|it| {
445 let k = id_key(it.get("_id").unwrap_or(&Value::Null));
446 let pos = index.get(&k).copied().unwrap_or(ids.len());
447 (pos, it.clone())
448 })
449 .collect();
450 let mut sorted = keyed;
451 sorted.sort_by_key(|(pos, _)| *pos);
452 for (slot, (_, v)) in items.iter_mut().zip(sorted) {
453 *slot = v;
454 }
455}