Skip to content

[Bug]: Prepared statements don't error on division by zero in strict mode #23438

Closed

Description

@XuPeng-SH

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Branch Name

main,3.0-dev

Commit ID

latest

Actual Behavior

When using prepared statements (JDBC with useServerPrepStmts=true), INSERT/UPDATE with division by zero returns NULL instead of raising an error, even with STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO in sql_mode.

SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO';
INSERT INTO t VALUES (1, 10/0);
-- Actual: Query OK (inserts NULL)

Expected Behavior

INSERT/UPDATE with division by zero should raise error when both STRICT_TRANS_TABLES and ERROR_FOR_DIVISION_BY_ZERO are enabled.

SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO';
INSERT INTO t VALUES (1, 10/0);
-- Expected: ERROR 1365 (HY000): division by zero

Direct SQL execution works correctly; only prepared statements are affected.

Steps to Reproduce

  1. Connect using JDBC with useServerPrepStmts=true
  2. Execute:
CREATE TABLE t (id INT, val INT);
SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO';
INSERT INTO t VALUES (1, 10/0);
SELECT * FROM t;
  1. INSERT succeeds with NULL instead of error

Root Cause

In PREPARE/EXECUTE phases, stmtType is "Prepare"/"Execute" not "Insert". checkDivisionByZeroBehavior() checks for "Insert"/"Update" stmtType, so it never triggers for prepared statements.

Affected Code

  • pkg/sql/plan/function/baseTemplate.go: checkDivisionByZeroBehavior()
  • pkg/frontend/mysql_cmd_executor.go: COM_STMT_PREPARE/EXECUTE handling

Proposed Solution

Track actual statement type (INSERT/UPDATE) separately from outer type (PREPARE/EXECUTE).

Additional information

  • Direct SQL works correctly; only prepared statements affected
  • mo-tester uses useServerPrepStmts=true, so BVT tests are affected

Activity

  1. added this to the MO-202601 milestone on Jan 4, 2026
  2. self-assigned this
    on Jan 4, 2026
  3. added
    kind/bug
    kind/compatibility
    severity/s0
    on Jan 4, 2026
  4. added theissue type on Jan 4, 2026
  5. modified the milestones: MO-202601, MO-202603 on Feb 3, 2026
  6. daviszhen commented on May 12, 2026

    @daviszhen
    Contributor

    在最新的main 51df6a5 , 用 go和java的测试程序都未复现出来.

    // Copyright 2021 Matrix Origin
    //
    // Licensed under the Apache License, Version 2.0 (the "License");
    // you may not use this file except in compliance with the License.
    // You may obtain a copy of the License at
    //
    //      http://www.apache.org/licenses/LICENSE-2.0
    //
    // Unless required by applicable law or agreed to in writing, software
    // distributed under the License is distributed on an "AS IS" BASIS,
    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    // See the License for the specific language governing permissions and
    // limitations under the License.
    
    package compile_test
    
    import (
    	"context"
    	"database/sql"
    	"errors"
    	"fmt"
    	"os"
    	"strings"
    	"testing"
    	"time"
    
    	mysqlDriver "github.com/go-sql-driver/mysql"
    )
    
    const mysqlErrDivisionByZero uint16 = 1365
    
    func TestPreparedStmtDivisionByZeroInStrictDML(t *testing.T) {
    	dsn := os.Getenv("MO_TEST_MYSQL_DSN")
    	if dsn == "" {
    		dsn = "dump:111@tcp(127.0.0.1:6001)/?timeout=5s&readTimeout=10s&writeTimeout=10s&interpolateParams=false"
    	}
    
    	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    	defer cancel()
    
    	db, err := sql.Open("mysql", dsn)
    	if err != nil {
    		t.Fatalf("open mysql connection: %v", err)
    	}
    	defer db.Close()
    	db.SetMaxOpenConns(1)
    	db.SetMaxIdleConns(1)
    
    	if err = db.PingContext(ctx); err != nil {
    		t.Skipf("skip prepared statement division-by-zero test; MatrixOne is not available via MO_TEST_MYSQL_DSN or 127.0.0.1:6001: %v", err)
    	}
    
    	dbName := fmt.Sprintf("test_prepare_div_zero_%d", time.Now().UnixNano())
    	execSQL(t, ctx, db, "drop database if exists "+dbName)
    	execSQL(t, ctx, db, "create database "+dbName)
    	t.Cleanup(func() {
    		cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)
    		defer cleanupCancel()
    		_, _ = db.ExecContext(cleanupCtx, "drop database if exists "+dbName)
    	})
    
    	execSQL(t, ctx, db, "use "+dbName)
    	execSQL(t, ctx, db, "create table t (id int primary key, val int)")
    	execSQL(t, ctx, db, "set sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO'")
    
    	insertStmt, err := db.PrepareContext(ctx, "insert into t values (1, 10 / 0)")
    	if err != nil {
    		t.Fatalf("prepare insert: %v", err)
    	}
    	defer insertStmt.Close()
    	_, err = insertStmt.ExecContext(ctx)
    	assertDivisionByZeroError(t, err)
    	assertTableRows(t, ctx, db, 0)
    
    	execSQL(t, ctx, db, "insert into t values (1, 10)")
    	updateStmt, err := db.PrepareContext(ctx, "update t set val = 10 / 0 where id = 1")
    	if err != nil {
    		t.Fatalf("prepare update: %v", err)
    	}
    	defer updateStmt.Close()
    	_, err = updateStmt.ExecContext(ctx)
    	assertDivisionByZeroError(t, err)
    	assertVal(t, ctx, db, 10)
    }
    
    func execSQL(t *testing.T, ctx context.Context, db *sql.DB, sqlText string) {
    	t.Helper()
    	if _, err := db.ExecContext(ctx, sqlText); err != nil {
    		t.Fatalf("execute %q: %v", sqlText, err)
    	}
    }
    
    func assertDivisionByZeroError(t *testing.T, err error) {
    	t.Helper()
    	if err == nil {
    		t.Fatalf("expected division by zero error")
    	}
    	var mysqlErr *mysqlDriver.MySQLError
    	if errors.As(err, &mysqlErr) {
    		if mysqlErr.Number != mysqlErrDivisionByZero {
    			t.Fatalf("expected mysql error %d, got %d: %v", mysqlErrDivisionByZero, mysqlErr.Number, err)
    		}
    		return
    	}
    	if !strings.Contains(strings.ToLower(err.Error()), "division by zero") &&
    		!strings.Contains(strings.ToLower(err.Error()), "division by 0") {
    		t.Fatalf("expected division by zero error, got: %v", err)
    	}
    }
    
    func assertTableRows(t *testing.T, ctx context.Context, db *sql.DB, expected int) {
    	t.Helper()
    	var rows int
    	if err := db.QueryRowContext(ctx, "select count(*) from t").Scan(&rows); err != nil {
    		t.Fatalf("count rows: %v", err)
    	}
    	if rows != expected {
    		t.Fatalf("expected %d rows, got %d", expected, rows)
    	}
    }
    
    func assertVal(t *testing.T, ctx context.Context, db *sql.DB, expected int) {
    	t.Helper()
    	var val int
    	if err := db.QueryRowContext(ctx, "select val from t where id = 1").Scan(&val); err != nil {
    		t.Fatalf("query val: %v", err)
    	}
    	if val != expected {
    		t.Fatalf("expected val %d, got %d", expected, val)
    	}
    }
  7. daviszhen commented on May 12, 2026

    @daviszhen
    Contributor

    java 测试程序.

    23438.tar.gz

  8. daviszhen commented on May 12, 2026

    @daviszhen
    Contributor

    分析有2点可能性.
    1, proc.Base.DivByZeroErrorMode 的值有缓存性质. 如果同一个请求有多个语句时, 前一个语句的DivByZeroErrorMode 会继承成给下一个条语句. 这个需要修改.
    2, 10/0, 被常量折叠. 代码了已经做了处理, 这种情况不折叠. 无需再修改.

  9. added a commit that references this issue on May 14, 2026
  10. ghost closed this as completedon May 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/bugkind/compatibilityseverity/s0

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions