diff --git a/result.go b/result.go index 82dc0f9b6..b292fb9a8 100644 --- a/result.go +++ b/result.go @@ -36,10 +36,16 @@ type mysqlResult struct { } func (res *mysqlResult) LastInsertId() (int64, error) { + if len(res.insertIds) == 0 { + return 0, nil + } return res.insertIds[len(res.insertIds)-1], nil } func (res *mysqlResult) RowsAffected() (int64, error) { + if len(res.affectedRows) == 0 { + return 0, nil + } return res.affectedRows[len(res.affectedRows)-1], nil } diff --git a/result_test.go b/result_test.go new file mode 100644 index 000000000..c38dc6cc4 --- /dev/null +++ b/result_test.go @@ -0,0 +1,22 @@ +// Go MySQL Driver - A MySQL-Driver for Go's database/sql package +// +// Copyright 2026 The Go-MySQL-Driver Authors. All rights reserved. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this file, +// You can obtain one at http://mozilla.org/MPL/2.0/. + +package mysql + +import "testing" + +// Regression for #1733: indexing into an empty result slice used to panic. +func TestEmptyResult(t *testing.T) { + r := &mysqlResult{} + if id, err := r.LastInsertId(); err != nil || id != 0 { + t.Errorf("LastInsertId() = (%d, %v), want (0, nil)", id, err) + } + if rows, err := r.RowsAffected(); err != nil || rows != 0 { + t.Errorf("RowsAffected() = (%d, %v), want (0, nil)", rows, err) + } +}