Skip to main content

mz_testdrive/action/duckdb/
query.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::sync::Arc;
11
12use anyhow::{Context, anyhow};
13use duckdb::types::ValueRef;
14use mz_ore::retry::Retry;
15
16use crate::action::duckdb::get_or_create_connection;
17use crate::action::{ControlFlow, State};
18use crate::parser::BuiltinCommand;
19
20pub async fn run_query(
21    mut cmd: BuiltinCommand,
22    state: &mut State,
23) -> Result<ControlFlow, anyhow::Error> {
24    let name = cmd.args.string("name")?;
25    let sort_rows = cmd.args.opt_bool("sort-rows")?.unwrap_or(false);
26    cmd.args.done()?;
27
28    // First line is the query, remaining lines are expected output
29    let mut lines = cmd.input.into_iter();
30    let query = lines
31        .next()
32        .ok_or_else(|| anyhow!("duckdb-query requires a query as the first input line"))?;
33    let mut expected_rows: Vec<String> = lines.collect();
34    if sort_rows {
35        expected_rows.sort();
36    }
37
38    let conn = get_or_create_connection(state, name).await?;
39    println!(">> {}", query);
40
41    let in_ci = mz_ore::env::is_var_truthy("CI");
42    // Reading from an external system (e.g. an Iceberg table backed by a sink
43    // with a non-zero COMMIT INTERVAL) is eventually consistent, so retry until
44    // the result matches the expectation or the timeout elapses, mirroring the
45    // behavior of testdrive's `>` SQL queries. Query-execution errors (e.g. the
46    // table not yet existing after a restart) are retried too.
47    let (previous_notice, result) = Retry::default()
48        .initial_backoff(state.initial_backoff)
49        .factor(state.backoff_factor)
50        .max_duration(state.timeout)
51        .max_tries(state.max_tries)
52        .retry_async_with_state(String::new(), |retry_state, mut previous_notice| {
53            let conn = Arc::clone(&conn);
54            let query = query.clone();
55            let expected_rows = &expected_rows;
56            async move {
57                let res = mz_ore::task::spawn_blocking(
58                    || "duckdb_query".to_string(),
59                    move || {
60                        let conn = conn.lock().map_err(|e| anyhow!("lock poisoned: {}", e))?;
61                        let mut stmt =
62                            conn.prepare(&query).context("preparing DuckDB query")?;
63                        let mut rows = stmt.query([]).context("executing DuckDB query")?;
64
65                        let mut result = Vec::new();
66                        while let Some(row) = rows.next()? {
67                            // Get column count from the row's statement
68                            let column_count = row.as_ref().column_count();
69                            let mut row_values = Vec::with_capacity(column_count);
70                            for i in 0..column_count {
71                                let val = row.get_ref(i)?;
72                                let formatted = format_value(&val);
73                                row_values.push(formatted);
74                            }
75                            result.push(row_values.join(" "));
76                        }
77                        Ok::<_, anyhow::Error>(result)
78                    },
79                )
80                .await;
81
82                let err = match res {
83                    Err(e) => e,
84                    Ok(mut actual_rows) => {
85                        if sort_rows {
86                            actual_rows.sort();
87                        }
88                        if actual_rows == *expected_rows {
89                            return (previous_notice, Ok(()));
90                        }
91                        anyhow!(
92                            "DuckDB query result mismatch\nexpected ({} rows):\n{}\n\nactual ({} rows):\n{}",
93                            expected_rows.len(),
94                            expected_rows.join("\n"),
95                            actual_rows.len(),
96                            actual_rows.join("\n")
97                        )
98                    }
99                };
100
101                if let Some(backoff) = retry_state.next_backoff
102                    && !backoff.is_zero()
103                    && (retry_state.i == 0 || !in_ci)
104                {
105                    let notice = format!(
106                        "{err}\nrows didn't match; sleeping to see if the result catches up 🕑"
107                    );
108                    if notice != previous_notice {
109                        clear_retry_notice(&previous_notice);
110                        println!("{notice} {backoff:.0?}");
111                        previous_notice = notice;
112                    }
113                }
114                (previous_notice, Err(err))
115            }
116        })
117        .await;
118    if !in_ci {
119        clear_retry_notice(&previous_notice);
120    }
121    result?;
122
123    Ok(ControlFlow::Continue)
124}
125
126fn clear_retry_notice(notice: &str) {
127    for _ in notice.lines() {
128        print!("\x1B[1A\x1B[2K");
129    }
130}
131
132fn format_value(val: &ValueRef) -> String {
133    match val {
134        ValueRef::Null => "<null>".to_string(),
135        ValueRef::Boolean(b) => b.to_string(),
136        ValueRef::TinyInt(i) => i.to_string(),
137        ValueRef::SmallInt(i) => i.to_string(),
138        ValueRef::Int(i) => i.to_string(),
139        ValueRef::BigInt(i) => i.to_string(),
140        ValueRef::HugeInt(i) => i.to_string(),
141        ValueRef::UTinyInt(i) => i.to_string(),
142        ValueRef::USmallInt(i) => i.to_string(),
143        ValueRef::UInt(i) => i.to_string(),
144        ValueRef::UBigInt(i) => i.to_string(),
145        ValueRef::UHugeInt(i) => i.to_string(),
146        ValueRef::Decimal(d) => d.to_string(),
147        ValueRef::Float(f) => f.to_string(),
148        ValueRef::Double(f) => f.to_string(),
149        ValueRef::Text(bytes) => String::from_utf8_lossy(bytes).to_string(),
150        ValueRef::Blob(bytes) | ValueRef::Geometry(bytes) => format!("{:?}", bytes),
151        _ => format!("{:?}", val),
152    }
153}