Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(databases): stop row queries ordered by position or alias from panicking (#8940)

Eric Hayesdfd31e2788a7
diff --git a/crates/database_sql/src/fold/test.rs b/crates/database_sql/src/fold/test.rs
index 404ba6038b..d5e074e2cf 100644
--- a/crates/database_sql/src/fold/test.rs
+++ b/crates/database_sql/src/fold/test.rs
@@ -544,3 +544,23 @@ fn bins_do_not_answer_a_row_shaped_plan() {
Err(RunError::NotAnsweredByBins)
);
}
+
+#[test]
+fn row_queries_order_by_position_and_alias() {
+ let expected = vec![
+ vec![Some(Cell::Text("Acme".into()))],
+ vec![Some(Cell::Text("Initech".into()))],
+ vec![Some(Cell::Text("Globex".into()))],
+ vec![Some(Cell::Text("hooli".into()))],
+ ];
+ for sql in [
+ "SELECT name, amount FROM crm.deals ORDER BY 2 DESC",
+ "SELECT name, amount AS total FROM crm.deals ORDER BY total DESC",
+ ] {
+ let names: Vec<_> = fold_rows(&catalog(), &plan(sql), deals())
+ .into_iter()
+ .map(|row| vec![row[0].clone()])
+ .collect();
+ assert_eq!(names, expected, "{sql}");
+ }
+}
diff --git a/crates/database_sql/src/resolve.rs b/crates/database_sql/src/resolve.rs
index a931915da4..f0459f5f29 100644
--- a/crates/database_sql/src/resolve.rs
+++ b/crates/database_sql/src/resolve.rs
@@ -266,8 +266,9 @@ pub struct Order {
pub enum OrderKey {
/// A column key, selected or not.
Column(Uuid),
- /// A 0-based index into the select list; positional keys and aggregates
- /// both resolve to this.
+ /// A 0-based index into the select list of a grouped or aggregate query;
+ /// its positional, alias, and aggregate keys resolve to this. A row
+ /// query's positions and aliases resolve to the column they select.
Item(usize),
}
diff --git a/crates/database_sql/src/resolve/select.rs b/crates/database_sql/src/resolve/select.rs
index fe7e6608a8..d095c72432 100644
--- a/crates/database_sql/src/resolve/select.rs
+++ b/crates/database_sql/src/resolve/select.rs
@@ -247,6 +247,19 @@ fn resolve_order(
None => order_column(scope, items, group_by, name)?,
},
};
+ // A row query's select list holds only columns, and its rows are sorted
+ // by column key, so a position or alias names the column it selects.
+ let rows = group_by.is_none()
+ && items
+ .iter()
+ .all(|item| matches!(item, SelectItem::Column(_)));
+ let key = match (key, rows) {
+ (OrderKey::Item(index), true) => match items[index] {
+ SelectItem::Column(column) => OrderKey::Column(column),
+ SelectItem::Aggregate { .. } => OrderKey::Item(index),
+ },
+ (key, _) => key,
+ };
Ok(Order {
key,
direction: order.direction,