use reddb_server::{RedDBError, RedDBOptions, RedDBRuntime};
use reddb_types::Value;
fn runtime_with_rows() -> RedDBRuntime {
let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
for sql in [
"CREATE TABLE compat_l (row_no INT, join_code INT)",
"INSERT INTO compat_l (row_no, join_code) VALUES (2,8),(1,7),(3,NULL),(4,7)",
"CREATE TABLE compat_r (r_no INT, join_code INT)",
"INSERT INTO compat_r (r_no, join_code) VALUES (10,7),(20,7),(30,9),(40,NULL)",
] {
runtime.execute_query(sql).expect(sql);
}
runtime
}
#[test]
fn is_distinct_from_returns_a_boolean_for_nulls_and_values() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query(
"SELECT NULL IS DISTINCT FROM NULL AS both_null,
2 IS DISTINCT FROM NULL AS right_null,
NULL IS DISTINCT FROM 2 AS left_null,
2 IS DISTINCT FROM 2.0 AS equal,
9007199254740992::bigint IS DISTINCT FROM 9007199254740993::bigint AS unequal,
2 = 2 IS DISTINCT FROM TRUE AS left_comparison,
FALSE IS DISTINCT FROM 2 = 2 AS right_comparison",
)
.expect("scalar distinctness comparisons");
let [record] = result.result.records.as_slice() else {
panic!("expected one scalar row");
};
for name in ["right_null", "left_null", "unequal", "right_comparison"] {
assert_eq!(record.get(name), Some(&Value::Boolean(true)), "{name}");
}
for name in ["both_null", "equal", "left_comparison"] {
assert_eq!(record.get(name), Some(&Value::Boolean(false)), "{name}");
}
}
#[test]
fn is_distinct_from_filters_nulls_in_prepared_and_grouped_queries() {
let runtime = runtime_with_rows();
let prepared = runtime
.execute_query_with_params(
"SELECT row_no FROM compat_l WHERE (join_code IS DISTINCT FROM $1) ORDER BY row_no",
&[Value::Null],
)
.expect("parameterized distinctness comparison");
let row_numbers: Vec<_> = prepared
.result
.records
.iter()
.map(|row| row.get("row_no").cloned())
.collect();
assert_eq!(
row_numbers,
[1, 2, 4].map(|row_no| Some(Value::Integer(row_no)))
);
let aggregated = runtime
.execute_query(
"SELECT join_code AS code,
COUNT(*) FILTER (WHERE join_code IS DISTINCT FROM NULL) AS present
FROM compat_l GROUP BY join_code
HAVING (COUNT(*) IS DISTINCT FROM 2)
ORDER BY code",
)
.expect("distinctness in aggregate predicates");
let [with_code, no_code] = aggregated.result.records.as_slice() else {
panic!("expected two groups with one row each");
};
assert_eq!(with_code.get("code"), Some(&Value::Integer(8)));
assert_eq!(with_code.get("present"), Some(&Value::Integer(1)));
assert_eq!(no_code.get("code"), Some(&Value::Null));
assert_eq!(no_code.get("present"), Some(&Value::Integer(0)));
}
#[test]
fn is_not_distinct_from_returns_a_boolean_for_nulls_and_values() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query(
"SELECT NULL IS NOT DISTINCT FROM NULL AS both_null,
2 IS NOT DISTINCT FROM NULL AS right_null,
NULL IS NOT DISTINCT FROM 2 AS left_null,
2 IS NOT DISTINCT FROM 2.0 AS equal,
9007199254740992::bigint IS NOT DISTINCT FROM 9007199254740993::bigint AS unequal,
2 = 2 IS NOT DISTINCT FROM TRUE AS left_comparison,
FALSE IS NOT DISTINCT FROM 2 = 3 AS right_comparison",
)
.expect("scalar null-safe comparisons");
let [record] = result.result.records.as_slice() else {
panic!("expected one scalar row");
};
for name in ["both_null", "equal", "left_comparison", "right_comparison"] {
assert_eq!(record.get(name), Some(&Value::Boolean(true)), "{name}");
}
for name in ["right_null", "left_null", "unequal"] {
assert_eq!(record.get(name), Some(&Value::Boolean(false)), "{name}");
}
}
#[test]
fn is_not_distinct_from_filters_before_limit_and_binds_parameters() {
let runtime = runtime_with_rows();
for result in [
runtime.execute_query(
"SELECT row_no FROM compat_l
WHERE join_code IS NOT DISTINCT FROM NULL LIMIT 1",
),
runtime.execute_query_with_params(
"SELECT row_no FROM compat_l WHERE join_code IS NOT DISTINCT FROM $1",
&[Value::Null],
),
runtime.execute_query(
"SELECT row_no FROM compat_l
WHERE row_no = 3 IS NOT DISTINCT FROM TRUE",
),
] {
let result = result.expect("null-safe WHERE comparison");
let [row] = result.result.records.as_slice() else {
panic!("expected only the NULL join key");
};
assert_eq!(row.get("row_no"), Some(&Value::Integer(3)));
}
}
#[test]
fn is_not_distinct_from_works_with_filtered_and_correlated_aggregates() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query(
"SELECT l.join_code AS code,
COUNT(*) FILTER (WHERE l.join_code IS NOT DISTINCT FROM NULL) AS missing
FROM compat_l l GROUP BY l.join_code
HAVING EXISTS (SELECT 1 FROM compat_r r
WHERE r.join_code IS NOT DISTINCT FROM l.join_code)
ORDER BY code",
)
.expect("null-safe correlated predicate");
let [with_code, no_code] = result.result.records.as_slice() else {
panic!("expected the non-null and NULL matches");
};
assert_eq!(with_code.get("code"), Some(&Value::Integer(7)));
assert_eq!(with_code.get("missing"), Some(&Value::Integer(0)));
assert_eq!(no_code.get("code"), Some(&Value::Null));
assert_eq!(no_code.get("missing"), Some(&Value::Integer(1)));
let result = runtime
.execute_query(
"SELECT COUNT(*) AS total FROM compat_l l CROSS JOIN compat_r r
WHERE l.join_code IS NOT DISTINCT FROM r.join_code",
)
.expect("null-safe comparison on joined rows");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(5))
);
}
#[test]
fn having_exists_binds_outer_aggregates_and_group_keys() {
let runtime = runtime_with_rows();
for sql in [
"CREATE TABLE exists_targets (total INT, match_code INT)",
"INSERT INTO exists_targets (total, match_code) VALUES (5,7),(5,7),(2,8),(3,99),(NULL,NULL)",
] {
runtime.execute_query(sql).expect(sql);
}
let sql = "SELECT l.join_code AS code, SUM(DISTINCT row_no) FILTER (WHERE row_no > 10) AS total
FROM compat_l l GROUP BY code
HAVING EXISTS (SELECT 1 / 0 FROM exists_targets r
WHERE r.total = SUM(DISTINCT l.row_no) AND r.match_code = l.join_code)
ORDER BY code";
let result = runtime.execute_query(sql).expect("correlated aggregate");
let [first, second] = result.result.records.as_slice() else {
panic!("expected only the two matching groups");
};
assert_eq!(first.get("code"), Some(&Value::Integer(7)));
assert_eq!(second.get("code"), Some(&Value::Integer(8)));
assert_eq!(first.get("total"), Some(&Value::Null));
assert_eq!(second.get("total"), Some(&Value::Null));
let result = runtime
.execute_query_with_params(
"SELECT join_code AS code FROM compat_l l GROUP BY join_code
HAVING EXISTS (SELECT 1 FROM exists_targets r
WHERE r.match_code = l.join_code AND r.total = $1)",
&[Value::Integer(2)],
)
.expect("prepared inner predicate");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("code"),
Some(&Value::Integer(8))
);
let result = runtime
.execute_query(
"SELECT COUNT(*) AS total FROM compat_l
HAVING EXISTS (SELECT 1 FROM exists_targets r
WHERE r.total = SUM(DISTINCT compat_l.join_code) - 10)",
)
.expect("single implicit group without GROUP BY");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(4))
);
let result = runtime
.execute_query(
"SELECT l.join_code AS code FROM compat_l l GROUP BY l.join_code
HAVING EXISTS (SELECT 1 FROM exists_targets r WHERE r.match_code = l.join_code OFFSET 1)
AND NOT EXISTS (SELECT 1 FROM exists_targets r WHERE r.match_code = l.join_code LIMIT 0)",
)
.expect("pagination and qualified group key");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("code"),
Some(&Value::Integer(7))
);
}
#[test]
fn having_exists_rejects_inner_aggregates_and_ungrouped_columns() {
let runtime = runtime_with_rows();
assert!(runtime
.execute_query("SELECT row_no FROM compat_l WHERE EXISTS (SELECT 1 FROM compat_r)")
.is_err());
for (predicate, message) in [
(
"SUM(DISTINCT l.row_no + r.r_no) = r.r_no",
"aggregate functions are not allowed in WHERE",
),
(
"SUM(r.r_no) > 0",
"aggregate functions are not allowed in WHERE",
),
("l.row_no = r.r_no", "subquery uses ungrouped column row_no"),
] {
let sql = format!(
"SELECT COUNT(*) FROM compat_l l GROUP BY join_code
HAVING EXISTS (SELECT 1 FROM compat_r r WHERE {predicate})"
);
let error = runtime.execute_query(&sql).expect_err(&sql).to_string();
assert!(error.contains(message), "{error}");
}
}
#[test]
fn having_exists_checks_inner_row_policies_and_cache_dependencies() {
let runtime = runtime_with_rows();
runtime
.execute_query("SET CONFIG runtime.result_cache.enabled = true")
.unwrap();
runtime
.execute_query("CREATE POLICY visible ON compat_r FOR SELECT USING (r_no = 30)")
.unwrap();
runtime
.execute_query("ALTER TABLE compat_r ENABLE ROW LEVEL SECURITY")
.unwrap();
let sql = "SELECT l.join_code AS code FROM compat_l l GROUP BY l.join_code
HAVING EXISTS (SELECT 1 FROM compat_r r WHERE r.join_code = l.join_code)";
assert!(runtime
.execute_query(sql)
.unwrap()
.result
.records
.is_empty());
runtime
.execute_query("INSERT INTO compat_r (r_no, join_code) VALUES (30,8)")
.unwrap();
let result = runtime.execute_query(sql).unwrap();
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("code"),
Some(&Value::Integer(8))
);
}
#[test]
fn text_cast_regex_filters_distinct_aggregate_inputs() {
let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
for sql in [
"CREATE TABLE regex_values (bucket INT, n INT, pattern TEXT)",
"INSERT INTO regex_values (bucket, n, pattern) VALUES (1,123,'^123$'),(1,123,'never'),(1,9123,'123'),(1,8,'8'),(2,NULL,'.'),(2,42,'^9'),(3,-123,'^-')",
] {
runtime.execute_query(sql).expect(sql);
}
let result = runtime
.execute_query("SELECT bucket, SUM(DISTINCT n) FILTER (WHERE n::text ~ '123') AS total, COUNT(*) FILTER (WHERE n::text ~ pattern) AS matched FROM regex_values GROUP BY bucket ORDER BY bucket")
.expect("regex in independent aggregate filters");
let [first, second, third] = result.result.records.as_slice() else {
panic!("expected three groups");
};
assert_eq!(first.get("total"), Some(&Value::Integer(9246)));
assert_eq!(first.get("matched"), Some(&Value::Integer(3)));
assert_eq!(second.get("total"), Some(&Value::Null));
assert_eq!(second.get("matched"), Some(&Value::Integer(0)));
assert_eq!(third.get("total"), Some(&Value::Integer(-123)));
assert_eq!(third.get("matched"), Some(&Value::Integer(1)));
let result = runtime
.execute_query(
"SELECT COUNT(*) AS matched FROM regex_values WHERE n::text ~ '^12' AND bucket = 1",
)
.expect("regex in a WHERE predicate");
assert_eq!(
result.result.records[0].get("matched"),
Some(&Value::Integer(2))
);
let result = runtime
.execute_query("SELECT 'Alpha' ~ '(?i)^a' AS matched")
.expect("quoted regex flags remain in SQL mode");
assert_eq!(
result.result.records[0].get("matched"),
Some(&Value::Boolean(true))
);
let error = runtime
.execute_query("SELECT COUNT(*) FILTER (WHERE n::text ~ '[') FROM regex_values")
.expect_err("malformed regex must fail");
assert!(
error.to_string().contains("invalid regular expression"),
"{error}"
);
}
#[test]
fn text_cast_regex_in_a_join_filter_uses_qualified_columns() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT SUM(DISTINCT r.r_no) FILTER (WHERE r.r_no::text ~ '^1') AS total FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code")
.expect("regex filter on a joined aggregate");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(10))
);
}
#[test]
fn sum_distinct_filters_before_deduplication_and_sums_exactly() {
let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
for sql in [
"CREATE TABLE distinct_values (bucket INT, n BIGINT, divisor INT, keep BOOLEAN)",
"INSERT INTO distinct_values (bucket, n, divisor, keep) VALUES (1,9007199254740993,2,TRUE),(1,9007199254740993,2,TRUE),(1,9007199254740994,1,TRUE),(1,NULL,NULL,TRUE),(1,100,0,FALSE),(2,1,0,NULL)",
] {
runtime.execute_query(sql).expect(sql);
}
let result = runtime
.execute_query("SELECT bucket, SUM(DISTINCT n) FILTER (WHERE keep) AS exact, SUM(DISTINCT n) FILTER (WHERE NOT keep) AS rejected, SUM(DISTINCT 6 / divisor + 1) FILTER (WHERE keep) AS quotients FROM distinct_values GROUP BY bucket ORDER BY bucket")
.expect("sum separate sets of admitted values");
let [first, second] = result.result.records.as_slice() else {
panic!("expected two groups");
};
assert_eq!(
first.get("exact"),
Some(&Value::Integer(18_014_398_509_481_987))
);
assert_eq!(first.get("rejected"), Some(&Value::Integer(100)));
assert_eq!(first.get("quotients"), Some(&Value::Integer(11)));
assert_eq!(second.get("exact"), Some(&Value::Null));
assert_eq!(second.get("quotients"), Some(&Value::Null));
let result = runtime
.execute_query("SELECT bucket, SUM(DISTINCT divisor) FILTER (WHERE keep) AS total FROM distinct_values GROUP BY bucket HAVING SUM(DISTINCT divisor) FILTER (WHERE keep) > 0 ORDER BY SUM(DISTINCT n) FILTER (WHERE keep)")
.expect("use filtered sums in HAVING and ORDER BY");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(3))
);
}
#[test]
fn sum_distinct_over_a_join_counts_repeated_values_once() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT SUM(DISTINCT r.r_no) FILTER (WHERE l.row_no > 0) AS unique_right, SUM(r.r_no) AS all_right, SUM(DISTINCT l.row_no) AS unique_left FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
.expect("aggregate distinct join values");
let record = &result.result.records[0];
assert_eq!(record.get("unique_right"), Some(&Value::Integer(30)));
assert_eq!(record.get("all_right"), Some(&Value::Integer(60)));
assert_eq!(record.get("unique_left"), Some(&Value::Integer(5)));
}
#[test]
fn aggregate_filters_skip_rows_before_argument_evaluation() {
let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
for sql in [
"CREATE TABLE filtered_rows (bucket INT, divisor INT, keep BOOLEAN)",
"INSERT INTO filtered_rows (bucket, divisor, keep) VALUES (1,2,TRUE),(1,0,FALSE),(1,NULL,TRUE),(2,0,NULL)",
] {
runtime.execute_query(sql).expect(sql);
}
let result = runtime
.execute_query("SELECT bucket, COUNT(*) AS total, COUNT(*) FILTER (WHERE keep) AS kept, COUNT(divisor) FILTER (WHERE keep) AS non_null, SUM(6 / divisor) FILTER (WHERE keep) AS quotient, SUM(divisor) FILTER (WHERE NOT keep) AS rejected_sum, ARRAY_AGG(divisor) FILTER (WHERE keep AND divisor IS NULL) AS null_items FROM filtered_rows GROUP BY bucket ORDER BY bucket")
.expect("apply independent aggregate filters");
let [first, second] = result.result.records.as_slice() else {
panic!("expected both groups");
};
assert_eq!(first.get("total"), Some(&Value::Integer(3)));
assert_eq!(first.get("kept"), Some(&Value::Integer(2)));
assert_eq!(first.get("non_null"), Some(&Value::Integer(1)));
assert_eq!(first.get("quotient"), Some(&Value::Integer(3)));
assert_eq!(first.get("rejected_sum"), Some(&Value::Integer(0)));
assert_eq!(
first.get("null_items"),
Some(&Value::Array(vec![Value::Null]))
);
assert_eq!(second.get("total"), Some(&Value::Integer(1)));
assert_eq!(second.get("kept"), Some(&Value::Integer(0)));
assert_eq!(second.get("quotient"), Some(&Value::Null));
assert_eq!(second.get("null_items"), Some(&Value::Null));
let result = runtime
.execute_query("SELECT bucket, COUNT(*) AS total FROM filtered_rows GROUP BY bucket HAVING COUNT(*) FILTER (WHERE keep) > 0 ORDER BY SUM(divisor) FILTER (WHERE keep)")
.expect("use filtered aggregates in HAVING and ORDER BY");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("bucket"),
Some(&Value::Integer(1))
);
let result = runtime
.execute_query("SELECT COUNT(DISTINCT divisor) FILTER (WHERE keep) AS total FROM filtered_rows WHERE FALSE")
.expect("return count zero for empty input");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(0))
);
}
#[test]
fn join_aggregate_filters_use_both_sides_and_preserve_null_extended_rows() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT COUNT(*) AS total, COUNT(*) FILTER (WHERE r.r_no IS NULL) AS unmatched, COUNT(r.r_no) FILTER (WHERE l.row_no > 1) AS non_null, SUM(l.row_no + r.r_no) FILTER (WHERE r.r_no = 10) AS total_low, AVG(r.r_no) FILTER (WHERE l.row_no = 1) AS average FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code")
.expect("aggregate filtered outer join");
let record = &result.result.records[0];
assert_eq!(record.get("total"), Some(&Value::Integer(6)));
assert_eq!(record.get("unmatched"), Some(&Value::Integer(2)));
assert_eq!(record.get("non_null"), Some(&Value::Integer(2)));
assert_eq!(record.get("total_low"), Some(&Value::Integer(25)));
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("15.0000000000000000".into()))
);
let result = runtime
.execute_query("SELECT l.row_no AS id, COUNT(*) AS total FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no HAVING SUM(r.r_no) FILTER (WHERE r.r_no > 15) > 0 ORDER BY id")
.expect("use a hidden filtered aggregate on an outer join");
let [first, second] = result.result.records.as_slice() else {
panic!("expected two groups");
};
assert_eq!(first.get("id"), Some(&Value::Integer(1)));
assert_eq!(second.get("id"), Some(&Value::Integer(4)));
}
#[test]
fn count_star_aggregates_filtered_join_rows_before_pagination() {
let runtime = runtime_with_rows();
for (suffix, expected) in [
("", Some(4)),
(" WHERE l.row_no < 0", Some(0)),
(" LIMIT 1", Some(4)),
(" LIMIT 0", None),
(" OFFSET 1", None),
] {
let result = runtime
.execute_query(&format!(
"SELECT COUNT(*) AS total FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code{suffix}"
))
.expect("count join");
assert_eq!(
result.result.records.len(),
usize::from(expected.is_some()),
"{suffix}"
);
if let Some(expected) = expected {
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(expected))
);
}
}
}
#[test]
fn sum_and_avg_aggregate_join_matches_before_pagination() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT SUM(l.row_no) AS total, AVG(r.r_no) AS average, COUNT(*) AS pairs FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no > 1 LIMIT 1")
.expect("aggregate joined rows");
assert_eq!(result.result.records.len(), 1);
let record = &result.result.records[0];
assert_eq!(record.get("total"), Some(&Value::Integer(8)));
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("15.0000000000000000".into()))
);
assert_eq!(record.get("pairs"), Some(&Value::Integer(2)));
for predicate in ["l.row_no < 0", "l.row_no = 2"] {
let result = runtime
.execute_query(&format!(
"SELECT SUM(r.r_no) AS total, AVG(r.r_no) AS average FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code WHERE {predicate}"
))
.expect("aggregate join with no non-null inputs");
assert_eq!(result.result.records.len(), 1);
assert_eq!(result.result.records[0].get("total"), Some(&Value::Null));
assert_eq!(result.result.records[0].get("average"), Some(&Value::Null));
}
}
#[test]
fn outer_join_aggregates_keep_same_named_columns_on_their_own_side() {
let runtime = runtime_with_rows();
for sql in [
"CREATE TABLE compat_amt_l (id INT, amount INT)",
"INSERT INTO compat_amt_l (id, amount) VALUES (1,8),(2,17),(3,4)",
"CREATE TABLE compat_amt_r (id INT, amount INT)",
"INSERT INTO compat_amt_r (id, amount) VALUES (1,3),(1,6),(2,NULL),(4,31)",
] {
runtime.execute_query(sql).expect(sql);
}
let result = runtime
.execute_query("SELECT SUM(l.amount) AS lhs, SUM(r.amount) AS rhs, AVG(r.amount) AS average FROM compat_amt_l l FULL OUTER JOIN compat_amt_r r ON l.id = r.id")
.expect("aggregate each side of the full outer join");
assert_eq!(result.result.records.len(), 1);
let record = &result.result.records[0];
assert_eq!(record.get("lhs"), Some(&Value::Integer(37)));
assert_eq!(record.get("rhs"), Some(&Value::Integer(40)));
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("13.3333333333333333".into()))
);
let result = runtime
.execute_query("SELECT SUM(l.amount) AS lhs FROM compat_amt_l l LEFT JOIN compat_amt_r r ON l.id = r.id WHERE r.amount IS NULL")
.expect("filter null-extended and explicitly null inputs");
assert_eq!(
result.result.records[0].get("lhs"),
Some(&Value::Integer(21))
);
let result = runtime
.execute_query("SELECT SUM(l.amount + r.amount) AS total FROM compat_amt_l l LEFT JOIN compat_amt_r r ON l.id = r.id")
.expect("arithmetic uses the input scope and preserves NULL");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(25))
);
}
#[test]
fn aggregate_join_arguments_evaluate_arithmetic_before_accumulating() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT SUM(l.row_no + r.r_no) AS total, AVG(r.r_no - l.row_no) AS average, SUM(5 / 2) AS integer_division, SUM(5.0 / 2) AS float_division FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
.expect("numeric expressions over both inputs");
let record = &result.result.records[0];
assert_eq!(record.get("total"), Some(&Value::Integer(70)));
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("12.5000000000000000".into()))
);
assert_eq!(record.get("integer_division"), Some(&Value::Integer(8)));
assert_eq!(record.get("float_division"), Some(&Value::Integer(10)));
}
#[test]
fn integer_division_preserves_precision_in_aggregates_and_updates() {
let runtime = RedDBRuntime::with_options(RedDBOptions::in_memory()).expect("runtime");
for sql in [
"CREATE TABLE quotients (n BIGINT, d INTEGER)",
"INSERT INTO quotients (n, d) VALUES (9007199254740995,2),(5,2),(NULL,2)",
] {
runtime.execute_query(sql).expect(sql);
}
let result = runtime
.execute_query("SELECT SUM(n / d) AS total FROM quotients")
.expect("aggregate the quotients");
assert_eq!(
result.result.records[0].get("total"),
Some(&Value::Integer(4_503_599_627_370_499))
);
runtime
.execute_query("UPDATE quotients SET n = n / d WHERE n / d = 4503599627370497")
.expect("update the matching row");
let result = runtime
.execute_query("SELECT n FROM quotients WHERE n > 100")
.expect("read the updated quotient");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("n"),
Some(&Value::BigInt(4_503_599_627_370_497))
);
}
#[test]
fn sum_join_integers_preserves_values_beyond_float_and_signed_integer_ranges() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT AVG(9007199254740993) AS large_avg, SUM(9007199254740993) AS total, SUM(9223372036854775807) AS wide, SUM(9007199254740993 + 0) AS integer_total, SUM(9007199254740993 + 0.0) AS float_total FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code")
.expect("integer SUM remains exact even when sharing an AVG input");
let record = &result.result.records[0];
assert_eq!(
record.get("large_avg"),
Some(&Value::DecimalText("9007199254740993.0000".into()))
);
assert_eq!(
record.get("total"),
Some(&Value::Integer(36_028_797_018_963_972))
);
assert_eq!(
record.get("wide"),
Some(&Value::DecimalText("36893488147419103228".into()))
);
assert_eq!(
record.get("integer_total"),
Some(&Value::Integer(36_028_797_018_963_972))
);
assert_eq!(
record.get("float_total"),
Some(&Value::Integer(36_028_797_018_963_968))
);
}
#[test]
fn group_by_join_aggregates_orders_and_paginates_groups() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT r.r_no AS bucket, SUM(l.row_no + r.r_no) AS total, AVG(l.row_no) AS average, COUNT(*) AS pairs FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no > 0 GROUP BY r_no ORDER BY total DESC, 1 DESC LIMIT 1 OFFSET 1")
.expect("grouping, then ordering and pagination");
assert_eq!(result.result.records.len(), 1);
let record = &result.result.records[0];
assert_eq!(record.get("bucket"), Some(&Value::Integer(10)));
assert_eq!(record.get("total"), Some(&Value::Integer(25)));
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("2.5000000000000000".into()))
);
assert_eq!(record.get("pairs"), Some(&Value::Integer(2)));
assert!(runtime
.execute_query("SELECT l.row_no, COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no")
.expect_err("invalid ungrouped projection")
.to_string()
.contains("must appear in GROUP BY"));
}
#[test]
fn having_on_join_filters_with_hidden_aggregates_before_pagination() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(l.row_no + r.r_no) > 25 AND COUNT(*) = 2 ORDER BY bucket LIMIT 1")
.expect("HAVING uses aggregates outside SELECT");
assert_eq!(result.result.columns, vec!["bucket"]);
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("bucket"),
Some(&Value::Integer(20))
);
assert_eq!(result.result.records[0].column_names().len(), 1);
let result = runtime
.execute_query("SELECT r.r_no AS bucket FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(r.r_no) >= 20 ORDER BY bucket NULLS FIRST LIMIT 1 OFFSET 1")
.expect("exclude unknown HAVING before OFFSET");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("bucket"),
Some(&Value::Integer(20))
);
}
#[test]
fn avg_join_integers_keeps_fractional_precision_after_cancellation() {
let runtime = runtime_with_rows();
runtime
.execute_query("CREATE TABLE compat_avg (row_no INT, amount BIGINT)")
.expect("table");
runtime.execute_query("INSERT INTO compat_avg (row_no, amount) VALUES (1,9007199254740993),(1,-9007199254740992),(1,0),(1,NULL)").expect("amounts");
let result = runtime
.execute_query("SELECT AVG(a.amount) AS average, AVG(-a.amount) AS negative, AVG(l.row_no + 0.5) AS float_avg FROM compat_avg a JOIN compat_l l ON l.row_no = a.row_no")
.expect("average exact inputs before rounding");
let record = &result.result.records[0];
assert_eq!(
record.get("average"),
Some(&Value::DecimalText("0.33333333333333333333".into()))
);
assert_eq!(
record.get("negative"),
Some(&Value::DecimalText("-0.33333333333333333333".into()))
);
assert_eq!(record.get("float_avg"), Some(&Value::Float(1.5)));
}
#[test]
fn avg_join_integers_remains_numeric_in_having_and_order_by() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT r.r_no AS bucket, AVG(l.row_no + r.r_no) AS average FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING AVG(l.row_no + r.r_no) BETWEEN 12.49 AND 22.51 AND AVG(9007199254740993) > 9007199254740992 ORDER BY average DESC")
.expect("decimal averages compare numerically");
let records = &result.result.records;
assert_eq!(records.len(), 2);
assert_eq!(records[0].get("bucket"), Some(&Value::Integer(20)));
assert_eq!(records[1].get("bucket"), Some(&Value::Integer(10)));
let result = runtime
.execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING AVG(l.row_no + r.r_no) + 1.0 > 20.0")
.expect("AVG values still work with arithmetic in HAVING");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("bucket"),
Some(&Value::Integer(20))
);
}
#[test]
fn having_on_join_checks_group_columns_nulls_and_wide_integer_sums() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING r_no IS NULL AND SUM(r.r_no) IS NULL")
.expect("HAVING can inspect a hidden group key and NULL aggregate");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("pairs"),
Some(&Value::Integer(2))
);
let result = runtime
.execute_query("SELECT r.r_no AS bucket FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING SUM(9223372036854775807) > 9223372036854775807")
.expect("HAVING preserves exact comparison of sums above i64");
assert_eq!(result.result.records.len(), 2);
let error = runtime
.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no HAVING l.row_no > 1")
.expect_err("HAVING must reject ungrouped input columns");
assert!(error.to_string().contains("must appear in GROUP BY"));
}
#[test]
fn group_by_outer_join_combines_null_keys_and_omits_empty_groups() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no, l.join_code ORDER BY r.r_no DESC NULLS FIRST, l.join_code DESC NULLS LAST")
.expect("sort by unprojected keys, including NULL");
let actual: Vec<_> = result
.result
.records
.iter()
.map(|row| row.get("pairs").cloned())
.collect();
assert_eq!(
actual,
vec![
Some(Value::Integer(1)),
Some(Value::Integer(1)),
Some(Value::Integer(2)),
Some(Value::Integer(2)),
]
);
let result = runtime
.execute_query("SELECT r.r_no AS bucket, COUNT(*) AS pairs FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no ORDER BY bucket DESC NULLS FIRST")
.expect("all missing right keys form a single NULL group");
let records = &result.result.records;
assert_eq!(records.len(), 3);
assert_eq!(records[0].get("bucket"), Some(&Value::Null));
assert_eq!(records[0].get("pairs"), Some(&Value::Integer(2)));
assert_eq!(records[1].get("bucket"), Some(&Value::Integer(20)));
assert_eq!(records[2].get("bucket"), Some(&Value::Integer(10)));
let result = runtime
.execute_query("SELECT r.r_no AS bucket FROM compat_l l LEFT JOIN compat_r r ON l.join_code = r.join_code WHERE l.row_no < 0 GROUP BY r.r_no")
.expect("empty grouped input");
assert!(result.result.records.is_empty());
runtime
.execute_query("SET CONFIG stream.executor.max_materialized_rows = 1")
.expect("set group limit");
let error = runtime
.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no")
.expect_err("second group exceeds the materialization limit");
assert!(matches!(
error,
RedDBError::MaterializationLimitExceeded {
executor: "aggregation",
limit: 1,
current: 2,
}
));
}
#[test]
fn group_by_join_authorizes_unprojected_group_columns() {
use reddb_server::auth::{
policies::Policy, store::PrincipalRef, AuthConfig, AuthStore, Role, UserId,
};
use reddb_server::runtime::mvcc::{clear_current_auth_identity, set_current_auth_identity};
use std::sync::Arc;
let runtime = runtime_with_rows();
let store = Arc::new(AuthStore::new(AuthConfig::default()));
store
.create_user("reader", "p", Role::Write)
.expect("reader");
let policy = Policy::from_json_str(r#"{
"id":"join-group-columns","version":1,"statements":[
{"effect":"allow","actions":["select"],"resources":["database:*","table:compat_l","table:compat_r"]},
{"effect":"deny","actions":["select"],"resources":["column:compat_r.r_no"]}
]
}"#).expect("policy");
store.put_policy(policy).expect("store policy");
store
.attach_policy(
PrincipalRef::User(UserId::platform("reader")),
"join-group-columns",
)
.expect("attach policy");
runtime.set_auth_store(store);
set_current_auth_identity("reader".to_string(), Role::Write);
let allowed = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no");
let denied = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY r.r_no");
let denied_having = runtime.execute_query("SELECT COUNT(*) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code GROUP BY l.row_no HAVING SUM(r.r_no) > 0");
let denied_filter = runtime.execute_query("SELECT SUM(l.row_no) FILTER (WHERE r.r_no > 0) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code");
let denied_table_filter =
runtime.execute_query("SELECT SUM(join_code) FILTER (WHERE r_no > 0) FROM compat_r");
let denied_distinct = runtime.execute_query("SELECT SUM(DISTINCT r.r_no + 1) FILTER (WHERE FALSE) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code");
let denied_table_distinct =
runtime.execute_query("SELECT SUM(DISTINCT r_no + 1) FILTER (WHERE FALSE) FROM compat_r");
let denied_exists_inner = runtime.execute_query(
"SELECT COUNT(*) FROM compat_l l GROUP BY join_code
HAVING EXISTS (SELECT 1 FROM compat_r r WHERE r.r_no = l.join_code)",
);
let denied_exists_outer = runtime.execute_query(
"SELECT COUNT(*) FROM compat_r r GROUP BY join_code
HAVING EXISTS (SELECT 1 FROM compat_l l WHERE SUM(r.r_no) = l.join_code)",
);
clear_current_auth_identity();
assert_eq!(allowed.expect("allowed grouping").result.records.len(), 2);
let error = denied.expect_err("protected grouping column").to_string();
assert!(
error.contains("cannot select column `compat_r.r_no`"),
"{error}"
);
for denied in [
denied_filter,
denied_table_filter,
denied_distinct,
denied_table_distinct,
denied_exists_inner,
denied_exists_outer,
] {
let error = denied
.expect_err("protected aggregate filter column")
.to_string();
assert!(error.contains("compat_r.r_no"), "{error}");
}
let error = denied_having
.expect_err("protected aggregate argument in HAVING")
.to_string();
assert!(
error.contains("cannot select column `compat_r.r_no`"),
"{error}"
);
}
#[test]
fn join_order_uses_select_aliases_before_pagination() {
let runtime = runtime_with_rows();
for order in ["left_id DESC, right_id DESC", "1 DESC, 2 DESC"] {
let result = runtime
.execute_query(&format!(
"SELECT l.row_no AS left_id, r.r_no AS right_id FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code ORDER BY {order} LIMIT 2"
))
.expect("ordered join");
let records = &result.result.records;
assert_eq!(records.len(), 2);
assert_eq!(records[0].get("left_id"), Some(&Value::Integer(4)));
assert_eq!(records[0].get("right_id"), Some(&Value::Integer(20)));
assert_eq!(records[1].get("left_id"), Some(&Value::Integer(4)));
assert_eq!(records[1].get("right_id"), Some(&Value::Integer(10)));
}
}
#[test]
fn distinct_order_by_ordinal_respects_projection_and_limit() {
let runtime = runtime_with_rows();
let result = runtime
.execute_query("SELECT DISTINCT join_code AS code FROM compat_l ORDER BY 1 LIMIT 2")
.expect("ordered distinct");
let records = &result.result.records;
assert_eq!(records.len(), 2);
assert_eq!(records[0].get("code"), Some(&Value::Integer(7)));
assert_eq!(records[1].get("code"), Some(&Value::Integer(8)));
let result = runtime
.execute_query(
"SELECT DISTINCT join_code AS code FROM compat_l ORDER BY 1 LIMIT 1 OFFSET 1",
)
.expect("offset excludes distinct rows");
assert_eq!(result.result.records.len(), 1);
assert_eq!(
result.result.records[0].get("code"),
Some(&Value::Integer(8))
);
for position in [-1, 0, 2] {
let error = runtime
.execute_query(&format!(
"SELECT DISTINCT join_code FROM compat_l ORDER BY {position}"
))
.expect_err("position outside the SELECT list");
assert!(error.to_string().contains("is not in the select list"));
}
}
#[test]
fn unknown_sql_projection_function_fails_even_without_input_rows() {
let runtime = runtime_with_rows();
for sql in [
"SELECT compat_unregistered_90321(row_no) AS result FROM compat_l WHERE row_no = 1",
"SELECT compat_unregistered_90321(row_no) AS result FROM compat_l WHERE row_no < 0",
"SELECT compat_unregistered_90321(1) AS result",
"SELECT COALESCE(compat_unregistered_90321(row_no), 0) FROM compat_l",
"SELECT compat_unregistered_90321(l.row_no) FROM compat_l l JOIN compat_r r ON l.join_code = r.join_code",
] {
let error = runtime.execute_query(sql).expect_err(sql);
assert!(error.to_string().contains("compat_unregistered_90321"));
}
let result = runtime
.execute_query("SELECT LOWER(NULL) AS result FROM compat_l LIMIT 1")
.expect("known function may return NULL");
assert_eq!(result.result.records[0].get("result"), Some(&Value::Null));
let result = runtime
.execute_query("SELECT ROW_NUMBER() OVER (ORDER BY row_no) AS result FROM compat_l")
.expect("window projections use their own evaluator");
assert_eq!(result.result.records.len(), 4);
}