Merge 'Initialize LIMIT after after ORDER BY / GROUP BY initialization' from Jussi Saurio

Closes #3853
Currently LIMIT 0 jumps to "after the main loop", and it is done before
ORDER BY and GROUP BY cursor have had a chance to be initialized, which
causes a panic.
Simplest fix for now is to delay the LIMIT initialization.

Reviewed-by: Preston Thorpe <preston@turso.tech>

Closes #3854
This commit is contained in:
Jussi Saurio
2025-10-29 10:17:05 +02:00
committed by GitHub
2 changed files with 20 additions and 5 deletions

View File

@@ -272,8 +272,6 @@ pub fn emit_query<'a>(
let after_main_loop_label = program.allocate_label();
t_ctx.label_main_loop_end = Some(after_main_loop_label);
init_limit(program, t_ctx, &plan.limit, &plan.offset)?;
if !plan.values.is_empty() {
let reg_result_cols_start = emit_values(program, plan, t_ctx)?;
program.preassign_label_to_next_insn(after_main_loop_label);
@@ -356,6 +354,9 @@ pub fn emit_query<'a>(
if let Distinctness::Distinct { ctx } = &mut plan.distinctness {
*ctx = distinct_ctx
}
init_limit(program, t_ctx, &plan.limit, &plan.offset)?;
init_loop(
program,
t_ctx,
@@ -2079,7 +2080,7 @@ fn init_limit(
_ => {
let r = limit_ctx.reg_limit;
_ = translate_expr(program, None, expr, r, &t_ctx.resolver);
_ = translate_expr(program, None, expr, r, &t_ctx.resolver)?;
program.emit_insn(Insn::MustBeInt { reg: r });
}
}
@@ -2109,7 +2110,7 @@ fn init_limit(
}
}
_ => {
_ = translate_expr(program, None, expr, offset_reg, &t_ctx.resolver);
_ = translate_expr(program, None, expr, offset_reg, &t_ctx.resolver)?;
}
}
program.add_comment(program.offset(), "OFFSET counter");

View File

@@ -1098,4 +1098,18 @@ do_execsql_test_on_specific_db {:memory:} unambiguous-self-join {
2|3
3|1
3|2
3|3}
3|3}
# Regression test for https://github.com/tursodatabase/turso/issues/3853
do_execsql_test_on_specific_db {:memory:} order-by-limit-0 {
CREATE TABLE t(a);
INSERT INTO t VALUES (1), (2), (3);
SELECT * FROM t ORDER BY a LIMIT 0;
} {}
# Regression test for https://github.com/tursodatabase/turso/issues/3853
do_execsql_test_on_specific_db {:memory:} group-by-limit-0 {
CREATE TABLE t(a);
INSERT INTO t VALUES (1), (2), (3);
SELECT a, COUNT(*) FROM t GROUP BY a LIMIT 0;
} {}