1use super::types::*;
4use crate::api_request::{ApiRequest, JoinType, QualifiedIdentifier, Range, SelectItem};
5use crate::error::{Error, Result};
6use crate::schema_cache::{Relationship, SchemaCache, Table};
7use serde::{Deserialize, Serialize};
8
9#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct ReadPlan {
12 pub select: Vec<CoercibleSelectField>,
14 pub from: QualifiedIdentifier,
16 pub from_alias: Option<String>,
18 pub where_clauses: Vec<CoercibleLogicTree>,
20 pub order: Vec<CoercibleOrderTerm>,
22 pub range: Range,
24 pub rel_name: String,
26 pub rel_to_parent: Option<Relationship>,
28 pub rel_join_conds: Vec<JoinCondition>,
30 pub rel_join_type: Option<JoinType>,
32 pub rel_select: Vec<RelSelectField>,
34 pub depth: u32,
36}
37
38impl ReadPlan {
39 pub fn from_request(
41 request: &ApiRequest,
42 table: &Table,
43 schema_cache: &SchemaCache,
44 ) -> Result<Self> {
45 let qi = table.qualified_identifier();
46
47 let mut select = build_select_fields(&request.query_params.select, table)?;
49
50 for field in select.iter_mut() {
55 if field.field.transform.is_some() || field.aggregate.is_some() {
56 continue;
57 }
58 let Some(column) = table.get_column(&field.field.name) else {
59 continue;
60 };
61 if let Some(function) =
62 schema_cache.representation(column.representation_type(), "json")
63 {
64 field.field.transform = Some(function.to_string());
65 }
66 }
67
68 if request.preferences.timezone.is_some() {
74 for field in select.iter_mut() {
75 if field.cast.is_none()
76 && field.aggregate.is_none()
77 && field.field.json_path.is_empty()
78 && matches!(
79 field.field.ir_type.as_str(),
80 "timestamptz"
81 | "timetz"
82 | "timestamp with time zone"
83 | "time with time zone"
84 )
85 {
86 field.field.transform = Some("to_jsonb".to_string());
87 }
88 }
89 }
90
91 let mut where_clauses = build_where_clauses(request, table)?;
93 for clause in where_clauses.iter_mut() {
94 attach_representation_tree(clause, table, schema_cache);
95 }
96
97 let order = build_order_terms(request, table)?;
99
100 let rel_select = build_relation_selects(&request.query_params.select, table, schema_cache)?;
102
103 Ok(Self {
104 select,
105 from: qi,
106 from_alias: None,
107 where_clauses,
108 order,
109 range: resolve_top_level_range(request),
110 rel_name: table.name.clone(),
111 rel_to_parent: None,
112 rel_join_conds: vec![],
113 rel_join_type: None,
114 rel_select,
115 depth: 0,
116 })
117 }
118
119 pub fn for_mutation(
121 request: &ApiRequest,
122 table: &Table,
123 schema_cache: &SchemaCache,
124 ) -> Result<Self> {
125 let mut plan = Self::from_request(request, table, schema_cache)?;
126
127 plan.from = QualifiedIdentifier::unqualified(crate::query::MUTATION_RESULT);
132 plan.from_alias = None;
133 plan.where_clauses.clear();
134
135 for field in plan.select.iter_mut() {
138 if let Some(computed) = field.field.computed.as_mut() {
139 computed.relation = crate::query::MUTATION_RESULT.to_string();
140 }
141 }
142
143 Ok(plan)
144 }
145
146 pub fn has_where(&self) -> bool {
148 !self.where_clauses.is_empty()
149 }
150
151 pub fn has_order(&self) -> bool {
153 !self.order.is_empty()
154 }
155
156 pub fn has_pagination(&self) -> bool {
158 self.range.limit.is_some() || self.range.offset > 0
159 }
160}
161
162fn build_select_fields(items: &[SelectItem], table: &Table) -> Result<Vec<CoercibleSelectField>> {
164 if items.is_empty() {
165 return Ok(table
167 .columns
168 .iter()
169 .map(|(name, col)| CoercibleSelectField::simple(name, &col.data_type))
170 .collect());
171 }
172
173 let mut fields = Vec::new();
174
175 for item in items {
176 match item {
177 SelectItem::Field { field, .. } if field.name == "*" => {
179 fields.extend(
180 table
181 .columns
182 .iter()
183 .map(|(name, col)| CoercibleSelectField::simple(name, &col.data_type)),
184 );
185 }
186 SelectItem::Field {
187 field,
188 aggregate,
189 aggregate_cast,
190 cast,
191 alias,
192 } => {
193 let legacy_count = aggregate.is_none()
199 && field.name == "count"
200 && field.json_path.is_empty()
201 && table.get_column("count").is_none();
202
203 let computed = match table.get_column(&field.name) {
208 Some(_) => None,
209 None => table
213 .get_computed_column(&field.name)
214 .filter(|c| !c.takes_arguments),
215 };
216
217 let pg_type = if field.name.is_empty() || legacy_count {
218 String::new()
219 } else if let Some(computed) = computed {
220 computed.data_type.clone()
221 } else {
222 table
223 .get_column(&field.name)
224 .ok_or_else(|| {
225 Error::ColumnNotFound(format!("{}.{}", table.name, field.name))
226 })?
227 .data_type
228 .clone()
229 };
230
231 let (field, aggregate) = if legacy_count {
232 (
233 &crate::api_request::Field::simple(""),
234 &Some(crate::api_request::AggregateFunction::Count),
235 )
236 } else {
237 (field, aggregate)
238 };
239
240 let mut resolved = CoercibleField::from_field(field, &pg_type);
241 resolved.computed = computed.map(|computed| crate::plan::ComputedRef {
242 function: computed.function.clone(),
243 relation: table.name.clone(),
244 row_type: table.qualified_identifier(),
245 });
246
247 fields.push(CoercibleSelectField {
248 field: resolved,
249 aggregate: aggregate.clone(),
250 aggregate_cast: aggregate_cast.clone(),
251 cast: cast.clone(),
252 alias: alias.clone(),
253 });
254 }
255 SelectItem::Relation { .. } | SelectItem::SpreadRelation { .. } => {}
257 }
258 }
259
260 Ok(fields)
261}
262
263pub fn resolve_top_level_range(request: &ApiRequest) -> Range {
271 let mut range = request.top_level_range.clone();
272
273 if let Some(from_params) = request.query_params.ranges.get("") {
274 if from_params.limit.is_some() {
275 range.limit = from_params.limit;
276 }
277 if from_params.offset_explicit {
278 range.offset = from_params.offset;
279 }
280 }
281
282 range.offset = range.offset.max(0);
286
287 if let Some(max_rows) = request.max_rows {
288 range.limit = Some(match range.limit {
289 Some(requested) => requested.min(max_rows),
290 None => max_rows,
291 });
292 }
293
294 range
295}
296
297fn build_where_clauses(request: &ApiRequest, table: &Table) -> Result<Vec<CoercibleLogicTree>> {
299 let type_resolver = |name: &str| -> String {
303 table
304 .get_column(name)
305 .map(|c| c.nominal_type.clone())
306 .unwrap_or_else(|| "text".to_string())
307 };
308
309 let embedded: std::collections::HashSet<&str> = request
314 .query_params
315 .select
316 .iter()
317 .filter_map(|item| match item {
318 SelectItem::Relation {
319 relation, alias, ..
320 } => Some(alias.as_deref().unwrap_or(relation)),
321 SelectItem::SpreadRelation { relation, .. } => Some(relation.as_str()),
322 SelectItem::Field { .. } => None,
323 })
324 .filter(|name| table.get_column(name).is_none())
325 .collect();
326
327 let mut clauses = Vec::new();
328
329 for filter in &request.query_params.filters_root {
331 if embedded.contains(filter.field.name.as_str()) {
332 continue;
333 }
334 let pg_type = type_resolver(&filter.field.name);
335 clauses.push(CoercibleLogicTree::Stmt(CoercibleFilter::from_filter(
336 filter, &pg_type,
337 )));
338 }
339
340 let embeds = crate::api_request::embedded_names(&request.query_params.select);
346 for (path, tree) in &request.query_params.logic {
347 if path.is_empty() && !tree.names_only(&embeds) {
348 clauses.push(CoercibleLogicTree::from_logic_tree(tree, type_resolver));
349 }
350 }
351
352 for clause in clauses.iter_mut() {
353 attach_computed_tree(clause, table);
354 }
355
356 Ok(clauses)
357}
358
359fn attach_representation(field: &mut CoercibleField, table: &Table, schema_cache: &SchemaCache) {
366 let Some(column) = table.get_column(&field.name) else {
367 return;
368 };
369 if let Some(function) = schema_cache.representation("text", column.representation_type()) {
370 field.transform = Some(function.to_string());
371 }
372}
373
374fn attach_representation_tree(
376 tree: &mut CoercibleLogicTree,
377 table: &Table,
378 schema_cache: &SchemaCache,
379) {
380 match tree {
381 CoercibleLogicTree::Expr { children, .. } => {
382 for child in children {
383 attach_representation_tree(child, table, schema_cache);
384 }
385 }
386 CoercibleLogicTree::Stmt(filter) => {
387 attach_representation(&mut filter.field, table, schema_cache)
388 }
389 CoercibleLogicTree::NullEmbed { .. } => {}
390 }
391}
392
393fn attach_computed(field: &mut CoercibleField, table: &Table) {
400 if table.get_column(&field.name).is_some() {
401 return;
402 }
403 if let Some(computed) = table
404 .get_computed_column(&field.name)
405 .filter(|c| !c.takes_arguments)
406 {
407 field.ir_type = computed.data_type.clone();
408 field.base_type = computed.data_type.clone();
409 field.computed = Some(crate::plan::ComputedRef {
410 function: computed.function.clone(),
411 relation: table.name.clone(),
412 row_type: table.qualified_identifier(),
413 });
414 }
415}
416
417fn attach_computed_tree(tree: &mut CoercibleLogicTree, table: &Table) {
419 match tree {
420 CoercibleLogicTree::Expr { children, .. } => {
421 for child in children {
422 attach_computed_tree(child, table);
423 }
424 }
425 CoercibleLogicTree::Stmt(filter) => attach_computed(&mut filter.field, table),
426 CoercibleLogicTree::NullEmbed { .. } => {}
427 }
428}
429
430fn build_order_terms(request: &ApiRequest, table: &Table) -> Result<Vec<CoercibleOrderTerm>> {
432 let mut terms = Vec::new();
433
434 for (path, order_terms) in &request.query_params.order {
435 if path.is_empty() {
436 for term in order_terms {
437 let field_name = match term {
438 crate::api_request::OrderTerm::Field { field, .. } => &field.name,
439 crate::api_request::OrderTerm::Relation { field, .. } => &field.name,
440 };
441
442 let pg_type = table
443 .get_column(field_name)
444 .map(|c| c.data_type.as_str())
445 .unwrap_or("text");
446
447 let mut resolved = CoercibleOrderTerm::from_order_term(term, pg_type);
448 attach_computed(&mut resolved.field, table);
449 terms.push(resolved);
450 }
451 }
452 }
453
454 Ok(terms)
455}
456
457fn build_relation_selects(
459 items: &[SelectItem],
460 table: &Table,
461 schema_cache: &SchemaCache,
462) -> Result<Vec<RelSelectField>> {
463 let mut rel_selects = Vec::new();
464
465 for item in items {
466 match item {
467 SelectItem::Relation {
468 relation,
469 alias,
470 hint,
471 join_type,
472 select: _,
473 } => {
474 let _rel = schema_cache
476 .find_relationship(
477 &table.qualified_identifier(),
478 relation,
479 hint.as_deref(),
480 &table.schema,
481 )?
482 .ok_or_else(|| {
483 schema_cache.relationship_not_found(
484 &table.qualified_identifier(),
485 relation,
486 hint.as_deref(),
487 &table.schema,
488 )
489 })?;
490
491 rel_selects.push(RelSelectField {
492 name: relation.clone(),
493 agg_alias: alias
494 .clone()
495 .unwrap_or_else(|| format!("pgrst_{}", relation)),
496 join_type: join_type.clone().unwrap_or_default(),
497 is_spread: false,
498 });
499 }
500 SelectItem::SpreadRelation {
501 relation,
502 hint,
503 join_type,
504 select: _,
505 } => {
506 let _rel = schema_cache
507 .find_relationship(
508 &table.qualified_identifier(),
509 relation,
510 hint.as_deref(),
511 &table.schema,
512 )?
513 .ok_or_else(|| {
514 schema_cache.relationship_not_found(
515 &table.qualified_identifier(),
516 relation,
517 hint.as_deref(),
518 &table.schema,
519 )
520 })?;
521
522 rel_selects.push(RelSelectField {
523 name: relation.clone(),
524 agg_alias: format!("pgrst_spread_{}", relation),
525 join_type: join_type.clone().unwrap_or_default(),
526 is_spread: true,
527 });
528 }
529 _ => {}
530 }
531 }
532
533 Ok(rel_selects)
534}
535
536#[derive(Clone, Debug)]
538pub struct ReadPlanTree {
539 pub root: ReadPlan,
541 pub children: Vec<ReadPlanTree>,
543}
544
545impl ReadPlanTree {
546 pub fn empty() -> Self {
548 Self {
549 root: ReadPlan {
550 select: vec![],
551 from: QualifiedIdentifier::unqualified(""),
552 from_alias: None,
553 where_clauses: vec![],
554 order: vec![],
555 range: Range::default(),
556 rel_name: String::new(),
557 rel_to_parent: None,
558 rel_join_conds: vec![],
559 rel_join_type: None,
560 rel_select: vec![],
561 depth: 0,
562 },
563 children: vec![],
564 }
565 }
566
567 pub fn leaf(plan: ReadPlan) -> Self {
569 Self {
570 root: plan,
571 children: vec![],
572 }
573 }
574
575 pub fn add_child(&mut self, child: ReadPlanTree) {
577 self.children.push(child);
578 }
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584
585 #[test]
586 fn test_read_plan_tree_empty() {
587 let tree = ReadPlanTree::empty();
588 assert!(tree.root.select.is_empty());
589 assert!(tree.children.is_empty());
590 }
591}