From 3294b780513a24b43ec6ad5839e75bc3021c9edf Mon Sep 17 00:00:00 2001 From: Jussi Saurio Date: Tue, 28 Oct 2025 13:08:05 +0200 Subject: [PATCH] Initialize LIMIT after after ORDER BY / GROUP BY initialization 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. --- core/translate/emitter.rs | 9 +++++---- testing/select.test | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/core/translate/emitter.rs b/core/translate/emitter.rs index db84007f0..237f037b3 100644 --- a/core/translate/emitter.rs +++ b/core/translate/emitter.rs @@ -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, @@ -2073,7 +2074,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 }); } } @@ -2103,7 +2104,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"); diff --git a/testing/select.test b/testing/select.test index 1267f131d..daa3e220b 100755 --- a/testing/select.test +++ b/testing/select.test @@ -1098,4 +1098,18 @@ do_execsql_test_on_specific_db {:memory:} unambiguous-self-join { 2|3 3|1 3|2 -3|3} \ No newline at end of file +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; +} {} \ No newline at end of file