1use std::fmt::{self, Write};
16
17#[cfg(test)]
18use rudb_common::LogicalType;
19use rudb_common::Value;
20
21use crate::expr::Expr;
22use crate::node::Node;
23use crate::plan::Plan;
24use crate::{ExprRef, NodeRef, Slice};
25
26pub(crate) const RESERVED: [&str; 3] = ["CAST", "TRY_CAST", "CASE"];
30
31impl fmt::Display for Plan {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write_node(self, f, self.root(), 0)
34 }
35}
36
37impl Plan {
38 #[must_use]
45 pub fn operator(&self, node: NodeRef) -> String {
46 let mut out = String::new();
47 let held = self.node(node);
48 let _ = out.write_str(held.keyword());
50 let _ = write_arguments(self, &mut out, held);
51 out
52 }
53}
54
55fn write_node<W: Write>(plan: &Plan, out: &mut W, node: NodeRef, depth: usize) -> fmt::Result {
56 for _ in 0..depth {
57 out.write_str(" ")?;
58 }
59 let held = plan.node(node);
60 out.write_str(held.keyword())?;
61 write_arguments(plan, out, held)?;
62 out.write_char('\n')?;
63 for child in held.children().into_iter().flatten() {
64 write_node(plan, out, child, depth + 1)?;
65 }
66 Ok(())
67}
68
69fn write_arguments<W: Write>(plan: &Plan, out: &mut W, node: &Node) -> fmt::Result {
70 match *node {
71 Node::Dummy | Node::CrossProduct { .. } => Ok(()),
72 Node::Get { catalog, schema, table, alias, index, columns } => {
73 out.write_char(' ')?;
74 write_identifier(out, plan.string(catalog))?;
75 out.write_char('.')?;
76 write_identifier(out, plan.string(schema))?;
77 out.write_char('.')?;
78 write_identifier(out, plan.string(table))?;
79 out.write_str(" AS ")?;
80 write_identifier(out, plan.string(alias))?;
81 write!(out, " #{index} ")?;
82 write_schema(plan, out, columns)
83 }
84 Node::Values { index, columns, rows } => {
85 write!(out, " #{index} ")?;
86 write_schema(plan, out, columns)?;
87 out.write_str(" rows=[")?;
88 for (position, row) in plan.row_list(rows).iter().enumerate() {
89 if position > 0 {
90 out.write_str(", ")?;
91 }
92 write_expr_list(plan, out, *row)?;
93 }
94 out.write_char(']')
95 }
96 Node::TableFunction { index, function, args, options, settings, columns } => {
97 out.write_char(' ')?;
98 write_identifier(out, plan.string(function))?;
99 out.write_str(" args=")?;
100 write_expr_list(plan, out, args)?;
101 if options.len > 0 {
104 out.write_str(" options=[")?;
105 for (at, (&name, &value)) in
106 plan.name_list(options).iter().zip(plan.expr_list(settings)).enumerate()
107 {
108 if at > 0 {
109 out.write_str(", ")?;
110 }
111 write_identifier(out, plan.string(name))?;
112 out.write_char('=')?;
113 write_expr(plan, out, value)?;
114 }
115 out.write_char(']')?;
116 }
117 write!(out, " #{index} ")?;
118 write_schema(plan, out, columns)
119 }
120 Node::Filter { predicate, .. } => {
121 out.write_char(' ')?;
122 write_expr(plan, out, predicate)
123 }
124 Node::Project { index, exprs, names, .. } => {
125 write!(out, " #{index} [")?;
126 for (position, &expr) in plan.expr_list(exprs).iter().enumerate() {
127 if position > 0 {
128 out.write_str(", ")?;
129 }
130 write_expr(plan, out, expr)?;
131 out.write_str(" AS ")?;
132 write_identifier(out, plan.string(plan.name_list(names)[position]))?;
133 }
134 out.write_char(']')
135 }
136 Node::Aggregate { index, groups, aggregates, .. } => {
137 write!(out, " #{index} groups=")?;
138 write_expr_list(plan, out, groups)?;
139 out.write_str(" aggregates=")?;
140 write_expr_list(plan, out, aggregates)
141 }
142 Node::Sort { keys, .. } => write_sort_keys(plan, out, keys),
143 Node::Limit { count, offset, .. } => {
144 match count {
145 Some(count) => write!(out, " {count}")?,
146 None => out.write_str(" ALL")?,
147 }
148 write!(out, " offset {offset}")
149 }
150 Node::TopN { keys, count, offset, .. } => {
151 write!(out, " {count} offset {offset}")?;
152 write_sort_keys(plan, out, keys)
153 }
154 Node::Distinct { on, .. } => {
155 out.write_str(" on=")?;
156 write_expr_list(plan, out, on)
157 }
158 Node::Join { kind, conditions, .. } => {
159 write!(out, " {} on=", kind.keyword())?;
160 write_expr_list(plan, out, conditions)
161 }
162 Node::SetOp { kind, all, index, .. } => {
163 let quantifier = if all { "ALL" } else { "DISTINCT" };
164 write!(out, " {} {quantifier} #{index}", kind.keyword())
165 }
166 }
167}
168
169fn write_schema<W: Write>(plan: &Plan, out: &mut W, columns: Slice) -> fmt::Result {
171 out.write_char('[')?;
172 for (position, field) in plan.field_list(columns).iter().enumerate() {
173 if position > 0 {
174 out.write_str(", ")?;
175 }
176 write_identifier(out, &field.name)?;
177 write!(out, "::{}", field.ty)?;
178 }
179 out.write_char(']')
180}
181
182fn write_sort_keys<W: Write>(plan: &Plan, out: &mut W, keys: Slice) -> fmt::Result {
184 out.write_str(" [")?;
185 for (position, key) in plan.sort_key_list(keys).iter().enumerate() {
186 if position > 0 {
187 out.write_str(", ")?;
188 }
189 write_expr(plan, out, key.expr)?;
190 out.write_str(if key.descending { " DESC" } else { " ASC" })?;
191 out.write_str(if key.nulls_first { " NULLS FIRST" } else { " NULLS LAST" })?;
192 }
193 out.write_char(']')
194}
195
196fn write_expr_list<W: Write>(plan: &Plan, out: &mut W, list: Slice) -> fmt::Result {
197 out.write_char('[')?;
198 for (position, &expr) in plan.expr_list(list).iter().enumerate() {
199 if position > 0 {
200 out.write_str(", ")?;
201 }
202 write_expr(plan, out, expr)?;
203 }
204 out.write_char(']')
205}
206
207fn write_expr<W: Write>(plan: &Plan, out: &mut W, expr: ExprRef) -> fmt::Result {
208 write_form(plan, out, expr)?;
209 write!(out, "::{}", plan.expr_type(expr))
210}
211
212fn write_form<W: Write>(plan: &Plan, out: &mut W, expr: ExprRef) -> fmt::Result {
213 match *plan.expr(expr) {
214 Expr::Column(binding) => write!(out, "#{}.{}", binding.table, binding.column),
215 Expr::Constant(value) => write_value(out, plan.value(value)),
216 Expr::Cast { input, try_cast } => {
217 out.write_str(if try_cast { "TRY_CAST(" } else { "CAST(" })?;
218 write_expr(plan, out, input)?;
219 out.write_char(')')
220 }
221 Expr::Compare { op, left, right } => {
222 out.write_char('(')?;
223 write_expr(plan, out, left)?;
224 write!(out, " {} ", op.symbol())?;
225 write_expr(plan, out, right)?;
226 out.write_char(')')
227 }
228 Expr::Conjunction { op, children } => {
229 out.write_char('(')?;
230 for (position, &child) in plan.expr_list(children).iter().enumerate() {
231 if position > 0 {
232 write!(out, " {} ", op.keyword())?;
233 }
234 write_expr(plan, out, child)?;
235 }
236 out.write_char(')')
237 }
238 Expr::Function { name, args } => {
239 write_function_name(out, plan.string(name))?;
240 out.write_char('(')?;
241 write_arguments_of(plan, out, args)?;
242 out.write_char(')')
243 }
244 Expr::Aggregate { name, args, distinct, filter } => {
245 write_function_name(out, plan.string(name))?;
246 out.write_char('(')?;
247 if distinct {
248 out.write_str("DISTINCT ")?;
249 }
250 write_arguments_of(plan, out, args)?;
251 if let Some(filter) = filter {
252 if !plan.expr_list(args).is_empty() {
255 out.write_char(' ')?;
256 }
257 out.write_str("FILTER ")?;
258 write_expr(plan, out, filter)?;
259 }
260 out.write_char(')')
261 }
262 Expr::Case { arms, otherwise } => {
263 out.write_str("CASE")?;
264 for arm in plan.arm_list(arms) {
265 out.write_str(" WHEN ")?;
266 write_expr(plan, out, arm.when)?;
267 out.write_str(" THEN ")?;
268 write_expr(plan, out, arm.then)?;
269 }
270 if let Some(otherwise) = otherwise {
271 out.write_str(" ELSE ")?;
272 write_expr(plan, out, otherwise)?;
273 }
274 out.write_str(" END")
275 }
276 }
277}
278
279fn write_arguments_of<W: Write>(plan: &Plan, out: &mut W, args: Slice) -> fmt::Result {
280 for (position, &arg) in plan.expr_list(args).iter().enumerate() {
281 if position > 0 {
282 out.write_str(", ")?;
283 }
284 write_expr(plan, out, arg)?;
285 }
286 Ok(())
287}
288
289fn write_value<W: Write>(out: &mut W, value: &Value) -> fmt::Result {
298 match value {
299 Value::Null => out.write_str("NULL"),
300 Value::Boolean(held) => out.write_str(if *held { "TRUE" } else { "FALSE" }),
301 Value::TinyInt(held) => write!(out, "{held}"),
302 Value::SmallInt(held) => write!(out, "{held}"),
303 Value::Integer(held) => write!(out, "{held}"),
304 Value::BigInt(held) => write!(out, "{held}"),
305 Value::HugeInt(held) => write!(out, "{held}"),
306 Value::UTinyInt(held) => write!(out, "{held}"),
307 Value::USmallInt(held) => write!(out, "{held}"),
308 Value::UInteger(held) => write!(out, "{held}"),
309 Value::UBigInt(held) => write!(out, "{held}"),
310 Value::UHugeInt(held) => write!(out, "{held}"),
311 Value::Float(held) => write!(out, "{held:?}"),
315 Value::Double(held) => write!(out, "{held:?}"),
316 Value::Decimal { unscaled, scale, .. } => out.write_str(&decimal_text(*unscaled, *scale)),
317 Value::Varchar(held) => write_string(out, held),
318 Value::Blob(held) => {
319 out.write_str("X'")?;
320 for byte in held {
321 write!(out, "{byte:02x}")?;
322 }
323 out.write_char('\'')
324 }
325 Value::Date(held) => write!(out, "{held}"),
326 Value::Time(held) | Value::Timestamp(held) => write!(out, "{held}"),
327 Value::Interval { months, days, micros } => write!(out, "{{{months}, {days}, {micros}}}"),
328 Value::List { values, .. } => {
329 out.write_char('{')?;
330 for (position, element) in values.iter().enumerate() {
331 if position > 0 {
332 out.write_str(", ")?;
333 }
334 write_value(out, element)?;
335 }
336 out.write_char('}')
337 }
338 Value::Struct(fields) => {
341 out.write_char('{')?;
342 for (position, (_, held)) in fields.iter().enumerate() {
343 if position > 0 {
344 out.write_str(", ")?;
345 }
346 write_value(out, held)?;
347 }
348 out.write_char('}')
349 }
350 other => write!(out, "<no textual form for {other:?}>"),
355 }
356}
357
358pub(crate) fn decimal_text(unscaled: i128, scale: u8) -> String {
364 if scale == 0 {
365 return unscaled.to_string();
366 }
367 let scale = usize::from(scale);
368 let digits = unscaled.unsigned_abs().to_string();
369 let padded = if digits.len() <= scale {
372 format!("{}{digits}", "0".repeat(scale + 1 - digits.len()))
373 } else {
374 digits
375 };
376 let point = padded.len() - scale;
377 let sign = if unscaled < 0 { "-" } else { "" };
378 format!("{sign}{}.{}", &padded[..point], &padded[point..])
379}
380
381fn write_string<W: Write>(out: &mut W, text: &str) -> fmt::Result {
387 out.write_char('\'')?;
388 for character in text.chars() {
389 match character {
390 '\'' => out.write_str("''")?,
391 '\\' => out.write_str("\\\\")?,
392 control if control.is_control() => write!(out, "\\x{:02x}", control as u32)?,
393 other => out.write_char(other)?,
394 }
395 }
396 out.write_char('\'')
397}
398
399pub(crate) fn is_plain_identifier(name: &str) -> bool {
401 !name.is_empty()
402 && name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
403 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
404}
405
406fn write_identifier<W: Write>(out: &mut W, name: &str) -> fmt::Result {
408 if is_plain_identifier(name) {
409 return out.write_str(name);
410 }
411 out.write_char('"')?;
412 for character in name.chars() {
413 if character == '"' {
414 out.write_str("\"\"")?;
415 } else {
416 out.write_char(character)?;
417 }
418 }
419 out.write_char('"')
420}
421
422fn write_function_name<W: Write>(out: &mut W, name: &str) -> fmt::Result {
424 if RESERVED.iter().any(|reserved| name.eq_ignore_ascii_case(reserved)) {
425 return write!(out, "\"{name}\"");
426 }
427 write_identifier(out, name)
428}
429
430#[cfg(test)]
437pub(crate) fn prints_readably(ty: &LogicalType) -> bool {
438 let text = ty.to_string();
439 crate::parse::type_extent(&text, 0) == text.len()
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 #[test]
447 fn a_decimal_gets_its_point_from_its_scale() {
448 assert_eq!(decimal_text(1234, 2), "12.34");
449 assert_eq!(decimal_text(1234, 0), "1234");
450 assert_eq!(decimal_text(5, 3), "0.005");
451 assert_eq!(decimal_text(-5, 3), "-0.005");
452 assert_eq!(decimal_text(-1234, 2), "-12.34");
453 assert_eq!(decimal_text(0, 2), "0.00");
454 }
455
456 #[test]
457 fn the_widest_decimal_still_prints() {
458 let widest = 10i128.pow(37) - 1;
459 assert_eq!(decimal_text(widest, 0).len(), 37);
460 assert_eq!(decimal_text(widest, 37).len(), 39);
461 }
462
463 #[test]
464 fn a_name_that_needs_quoting_gets_it() {
465 let quoted = |name: &str| {
466 let mut out = String::new();
467 write_identifier(&mut out, name).unwrap();
468 out
469 };
470 assert_eq!(quoted("SearchPhrase"), "SearchPhrase");
471 assert_eq!(quoted("_hidden9"), "_hidden9");
472 assert_eq!(quoted("a b"), "\"a b\"");
473 assert_eq!(quoted("9lives"), "\"9lives\"", "a name cannot start with a digit");
474 assert_eq!(quoted(""), "\"\"");
475 assert_eq!(quoted("say \"hi\""), "\"say \"\"hi\"\"\"");
476 }
477
478 #[test]
479 fn a_function_named_after_a_reserved_word_is_quoted() {
480 for name in ["cast", "CAST", "Try_Cast", "case"] {
481 let mut out = String::new();
482 write_function_name(&mut out, name).unwrap();
483 assert!(out.starts_with('"'), "{name} would be read back as syntax");
484 }
485 let mut out = String::new();
486 write_function_name(&mut out, "casting").unwrap();
487 assert_eq!(out, "casting", "only the reserved words themselves are reserved");
488 }
489
490 #[test]
491 fn a_string_never_contains_a_newline_when_it_is_written() {
492 let mut out = String::new();
493 write_string(&mut out, "one\ntwo\ttab'quote\\slash").unwrap();
494 assert!(!out.contains('\n'), "a value would split an operator across two lines");
495 assert_eq!(out, "'one\\x0atwo\\x09tab''quote\\\\slash'");
496 }
497
498 #[test]
502 fn a_float_prints_the_text_that_reads_back_as_the_same_bits() {
503 for held in [0.1f32, f32::MIN, f32::MAX, f32::EPSILON, -0.0, 1e-40] {
504 let mut out = String::new();
505 write_value(&mut out, &Value::Float(held)).unwrap();
506 let back: f32 = out.parse().expect("a float we printed parses");
507 assert_eq!(back.to_bits(), held.to_bits(), "{out} is not the same float");
508 }
509 for held in [0.1f64, f64::MIN, f64::MAX, f64::EPSILON, -0.0, 1e-308] {
510 let mut out = String::new();
511 write_value(&mut out, &Value::Double(held)).unwrap();
512 let back: f64 = out.parse().expect("a double we printed parses");
513 assert_eq!(back.to_bits(), held.to_bits(), "{out} is not the same double");
514 }
515 }
516
517 #[test]
518 fn a_plan_that_is_only_a_dummy_prints_one_line() {
519 assert_eq!(Plan::new().to_string(), "Dummy\n");
520 }
521
522 #[test]
528 fn every_type_prints_as_something_the_reader_can_find_the_end_of() {
529 let scalars = [
530 LogicalType::Null,
531 LogicalType::Boolean,
532 LogicalType::TinyInt,
533 LogicalType::SmallInt,
534 LogicalType::Integer,
535 LogicalType::BigInt,
536 LogicalType::HugeInt,
537 LogicalType::UTinyInt,
538 LogicalType::USmallInt,
539 LogicalType::UInteger,
540 LogicalType::UBigInt,
541 LogicalType::UHugeInt,
542 LogicalType::Float,
543 LogicalType::Double,
544 LogicalType::Varchar,
545 LogicalType::Blob,
546 LogicalType::Bit,
547 LogicalType::Uuid,
548 LogicalType::Date,
549 LogicalType::Time,
550 LogicalType::TimeTz,
551 LogicalType::Timestamp,
552 LogicalType::TimestampS,
553 LogicalType::TimestampMs,
554 LogicalType::TimestampNs,
555 LogicalType::TimestampTz,
556 LogicalType::Interval,
557 ];
558 let mut all: Vec<LogicalType> = scalars.to_vec();
559 all.push(LogicalType::decimal(18, 3).expect("18 and 3 is a decimal"));
560 all.push(LogicalType::decimal(38, 0).expect("the widest decimal"));
561 for scalar in &scalars {
562 all.push(LogicalType::list(scalar.clone()));
563 all.push(LogicalType::array(scalar.clone(), 4));
564 all.push(LogicalType::map(LogicalType::Varchar, scalar.clone()));
565 all.push(LogicalType::Struct(vec![
566 rudb_common::Field::new("a", scalar.clone()),
567 rudb_common::Field::new("b b", LogicalType::Varchar),
568 ]));
569 all.push(LogicalType::Union(vec![rudb_common::Field::new("u", scalar.clone())]));
570 }
571 all.push(LogicalType::list(LogicalType::list(LogicalType::Integer)));
572 all.push(LogicalType::list(LogicalType::map(
573 LogicalType::Varchar,
574 LogicalType::TimestampTz,
575 )));
576
577 for ty in all {
578 let text = ty.to_string();
579 assert!(prints_readably(&ty), "the reader cannot find the end of {text}");
580 let back = LogicalType::parse(&text)
581 .unwrap_or_else(|error| panic!("{text} does not parse: {error}"));
582 assert_eq!(back, ty, "{text} does not read back as itself");
583 }
584 }
585}