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_pipeline_projection, build_projection, flatten_object_fields, is_nullish,
10 param, parse_gql, Ast, 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 has_pipeline(ast: &Ast, params: &Map<String, Value>) -> bool {
134 ast.params
135 .get("pipeline")
136 .map(|r| !is_nullish(param(params, Some(r))))
137 .unwrap_or(false)
138}
139
140pub fn plan_query(
142 gql: &str,
143 params: &Map<String, Value>,
144 registry: &Registry,
145 ctx: Option<&Context>,
146) -> Result<QueryPlan, String> {
147 let mut params = params.clone();
148 plan_query_mut(gql, &mut params, registry, ctx)
149}
150
151pub fn plan_query_mut(
153 gql: &str,
154 params: &mut Map<String, Value>,
155 registry: &Registry,
156 ctx: Option<&Context>,
157) -> Result<QueryPlan, String> {
158 let ast = parse_gql(gql)?;
159 plan_query_ast_mut(ast, params, registry, ctx)
160}
161
162pub fn plan_query_one(
169 gql: &str,
170 params: &Map<String, Value>,
171 registry: &Registry,
172 ctx: Option<&Context>,
173) -> Result<QueryPlan, String> {
174 let mut params = params.clone();
175 let mut ast = parse_gql(gql)?;
176 if !ast.params.contains_key("limit") && !has_pipeline(&ast, ¶ms) {
177 ast.params
178 .insert("limit".to_string(), "@__core_one_limit__".to_string());
179 params.insert("__core_one_limit__".to_string(), json!(1));
180 }
181 plan_query_ast_mut(ast, &mut params, registry, ctx)
182}
183
184pub fn plan_query_ast_mut(
190 mut ast: Ast,
191 params: &mut Map<String, Value>,
192 registry: &Registry,
193 ctx: Option<&Context>,
194) -> Result<QueryPlan, String> {
195 ensure_context(registry, ctx)?;
196 let schema = registry.get(&ast.model)?;
197
198 if ctx.is_some() && !can_read_schema(schema, ctx) {
199 return Err(ERR_PERMISSION.to_string());
200 }
201 ensure_read(registry, schema, ctx)?;
203
204 if ctx.is_some() {
207 if let Some(r) = ast.params.get("condition").cloned() {
208 let key = r.get(1..).unwrap_or("").to_string();
209 let owner_merged = merge_owner_condition(schema, ctx, params.get(&key).cloned());
210 match merge_row_condition(registry, schema, ctx, "read", owner_merged) {
211 Some(v) => {
212 params.insert(key, v);
213 }
214 None => {
215 params.remove(&key);
216 }
217 }
218 } else {
219 let static_owner = merge_owner_condition(schema, ctx, None);
223 if let Some(owner) =
224 merge_row_condition(registry, schema, ctx, "read", static_owner)
225 .filter(|v| v.as_object().map(|o| !o.is_empty()).unwrap_or(false))
226 {
227 ast.params
228 .insert("condition".to_string(), "@__core_owner__".to_string());
229 params.insert("__core_owner__".to_string(), owner);
230 }
231 }
232 }
233
234 let has_pipeline = has_pipeline(&ast, params);
235
236 let mut inject = if has_pipeline {
237 InjectInfo::default()
238 } else {
239 merge_depends_into_ast(&mut ast.relations, schema)?
240 };
241 if !has_pipeline {
244 inject.fields = collect_field_deps(&mut ast.fields, schema);
245 }
246
247 let mut post_ast = ast.clone();
250 if !has_pipeline {
251 flatten_object_fields(&mut post_ast, schema);
252 }
253
254 build_plan(ast, &post_ast, &inject, params, registry, ctx)
255}
256
257pub fn check_readable_relations(
264 relations: &[(String, RelAst)],
265 schema: &Schema,
266 registry: &Registry,
267 ctx: Option<&Context>,
268) -> Result<(), String> {
269 if ctx.is_none() {
270 return Ok(());
271 }
272 for (rel_name, rel_ast) in relations {
273 let Some(rel_def) = schema.relations.get(rel_name) else {
274 continue;
275 };
276 if rel_def.model.is_empty() {
278 continue;
279 }
280 if !is_relation_readable(schema, ctx, rel_name) {
281 return Err(ERR_PERMISSION.to_string());
282 }
283 let rel_schema = registry.get(&rel_def.model)?;
284 if !can_read_schema(rel_schema, ctx) {
285 return Err(ERR_PERMISSION.to_string());
286 }
287 ensure_read(registry, rel_schema, ctx)?;
289 check_readable_relations(&rel_ast.relations, rel_schema, registry, ctx)?;
290 }
291 Ok(())
292}
293
294pub fn build_plan(
300 mut fetch_ast: Ast,
301 post_ast: &Ast,
302 inject: &InjectInfo,
303 params: &Map<String, Value>,
304 registry: &Registry,
305 ctx: Option<&Context>,
306) -> Result<QueryPlan, String> {
307 ensure_context(registry, ctx)?;
308 let schema = registry.get(&fetch_ast.model)?;
309
310 check_readable_relations(&fetch_ast.relations, schema, registry, ctx)?;
313
314 let has_pipeline = has_pipeline(&fetch_ast, params);
318
319 let pipeline = build_pipeline(&mut fetch_ast, params, registry, ctx)?;
320 let stages: Vec<Value> = pipeline.as_array().cloned().unwrap_or_default();
321
322 let grouped = stages.iter().any(|s| s.get("$group").is_some());
326
327 let projection = if has_pipeline {
328 build_pipeline_projection(&fetch_ast, schema)
329 } else if grouped {
330 None
331 } else {
332 build_projection(&fetch_ast, schema, ctx, registry.rbac())
333 };
334
335 let collection = schema.collection.clone();
336 let post = || {
337 if has_pipeline || grouped {
338 None
339 } else {
340 Some(postprocess_value(post_ast, inject))
341 }
342 };
343
344 if !has_pipeline && stages.len() == 1 {
346 if let Some(filter) = stages[0].get("$match") {
347 return Ok(QueryPlan {
348 collection: collection.clone(),
349 mode: Mode::Find,
350 commands: vec![cmd_find(schema, filter, projection.as_ref())],
351 postprocess: post(),
352 sort: None,
353 });
354 }
355 }
356
357 let first_lookup = stages.iter().position(|s| {
361 s.get("$lookup")
362 .map(|lo| {
363 !lo.get("as")
364 .and_then(|v| v.as_str())
365 .map(|a| a.starts_with(REL_PRED_PREFIX))
366 .unwrap_or(false)
367 })
368 .unwrap_or(false)
369 });
370 let has_skip_limit = !has_pipeline
372 && stages
373 .iter()
374 .any(|s| s.get("$skip").is_some() || s.get("$limit").is_some());
375 let sort_stage = stages.iter().find(|s| s.get("$sort").is_some()).cloned();
376
377 if let Some(idx) = first_lookup {
378 if !grouped && has_skip_limit && !sorts_by_relation(sort_stage.as_ref()) {
379 let mut id_pipeline: Vec<Value> = stages[..idx].to_vec();
380 for key in ["$sort", "$skip", "$limit"] {
381 if let Some(st) = stages.iter().find(|s| s.get(key).is_some()) {
382 id_pipeline.push(st.clone());
383 }
384 }
385 id_pipeline.push(json!({ "$project": { "_id": 1 } }));
386
387 let mut full: Vec<Value> = stages[idx..]
388 .iter()
389 .filter(|s| {
390 !(s.get("$sort").is_some()
391 || s.get("$skip").is_some()
392 || s.get("$limit").is_some())
393 })
394 .cloned()
395 .collect();
396 full.insert(0, json!({ "$match": { "_id": { "$in": PHASE1_IDS } } }));
397 if let Some(p) = projection.as_ref() {
398 full.push(json!({ "$project": p }));
399 }
400
401 return Ok(QueryPlan {
402 collection: collection.clone(),
403 mode: Mode::TwoPhase,
404 commands: vec![
405 cmd_aggregate(schema, &id_pipeline),
406 cmd_aggregate(schema, &full),
407 ],
408 postprocess: post(),
409 sort: sort_stage,
410 });
411 }
412 }
413
414 let mut final_stages = stages;
416 if let Some(p) = projection.as_ref() {
417 final_stages.push(json!({ "$project": p }));
418 }
419 validate_pipeline_stages(&final_stages)?;
422
423 Ok(QueryPlan {
424 collection,
425 mode: Mode::Aggregate,
426 commands: vec![cmd_aggregate(schema, &final_stages)],
427 postprocess: post(),
428 sort: None,
429 })
430}
431
432pub fn sorts_by_relation(sort_stage: Option<&Value>) -> bool {
434 sort_stage
435 .and_then(|s| s.get("$sort"))
436 .and_then(|s| s.as_object())
437 .map(|o| o.keys().any(|k| k.contains('.')))
438 .unwrap_or(false)
439}
440
441pub fn restore_sort_order(items: &mut [Value], ids: &[Value], sort_stage: Option<&Value>) {
443 if sort_stage.is_none() || ids.len() <= 1 {
444 return;
445 }
446 let mut index: std::collections::HashMap<_, usize> =
449 std::collections::HashMap::with_capacity(ids.len());
450 for (i, id) in ids.iter().enumerate() {
451 index.entry(id_key(id)).or_insert(i);
452 }
453 let keyed: Vec<(usize, Value)> = items
454 .iter()
455 .map(|it| {
456 let k = id_key(it.get("_id").unwrap_or(&Value::Null));
457 let pos = index.get(&k).copied().unwrap_or(ids.len());
458 (pos, it.clone())
459 })
460 .collect();
461 let mut sorted = keyed;
462 sorted.sort_by_key(|(pos, _)| *pos);
463 for (slot, (_, v)) in items.iter_mut().zip(sorted) {
464 *slot = v;
465 }
466}