|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Use of this software is governed by the CockroachDB Software License |
| 4 | +// included in the /LICENSE file. |
| 5 | + |
| 6 | +package logical |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/cockroachdb/cockroach/pkg/base" |
| 13 | + "github.com/cockroachdb/cockroach/pkg/kv" |
| 14 | + "github.com/cockroachdb/cockroach/pkg/sql" |
| 15 | + "github.com/cockroachdb/cockroach/pkg/sql/sessiondata" |
| 16 | + "github.com/cockroachdb/cockroach/pkg/testutils/serverutils" |
| 17 | + "github.com/cockroachdb/cockroach/pkg/testutils/sqlutils" |
| 18 | + "github.com/cockroachdb/cockroach/pkg/util/leaktest" |
| 19 | + "github.com/cockroachdb/cockroach/pkg/util/log" |
| 20 | + "github.com/cockroachdb/errors" |
| 21 | + "github.com/stretchr/testify/require" |
| 22 | +) |
| 23 | + |
| 24 | +func TestWithSavepoint(t *testing.T) { |
| 25 | + defer leaktest.AfterTest(t)() |
| 26 | + defer log.Scope(t).Close(t) |
| 27 | + |
| 28 | + srv, rawDB, _ := serverutils.StartServer(t, base.TestServerArgs{}) |
| 29 | + defer srv.Stopper().Stop(context.Background()) |
| 30 | + |
| 31 | + ctx := context.Background() |
| 32 | + sqlDB := sqlutils.MakeSQLRunner(rawDB) |
| 33 | + sqlDB.Exec(t, "CREATE TABLE test (id STRING PRIMARY KEY, value STRING)") |
| 34 | + |
| 35 | + require.NoError(t, srv.DB().Txn(ctx, func(ctx context.Context, txn *kv.Txn) error { |
| 36 | + err := withSavepoint(ctx, txn, func() error { |
| 37 | + _, err := srv.InternalExecutor().(*sql.InternalExecutor).ExecEx( |
| 38 | + ctx, |
| 39 | + "test-insert", |
| 40 | + txn, |
| 41 | + sessiondata.NodeUserSessionDataOverride, |
| 42 | + "INSERT INTO defaultdb.test VALUES ('ok', 'is-persisted')", |
| 43 | + ) |
| 44 | + return err |
| 45 | + }) |
| 46 | + require.NoError(t, err) |
| 47 | + |
| 48 | + err = withSavepoint(ctx, txn, func() error { |
| 49 | + _, err := srv.InternalExecutor().(*sql.InternalExecutor).ExecEx( |
| 50 | + ctx, |
| 51 | + "test-insert", |
| 52 | + txn, |
| 53 | + sessiondata.NodeUserSessionDataOverride, |
| 54 | + "INSERT INTO defaultdb.test VALUES ('fails', 'is-rolled-back')", |
| 55 | + ) |
| 56 | + require.NoError(t, err) |
| 57 | + // NOTE: the query above is okay, which means it wrote things to KV, |
| 58 | + // but we're going to return an error which rolls back the |
| 59 | + // savepoint. |
| 60 | + return errors.New("something to rollback") |
| 61 | + }) |
| 62 | + require.ErrorContains(t, err, "something to rollback") |
| 63 | + |
| 64 | + return nil |
| 65 | + })) |
| 66 | + |
| 67 | + sqlDB.CheckQueryResults(t, "SELECT id, value FROM test", [][]string{ |
| 68 | + {"ok", "is-persisted"}, |
| 69 | + }) |
| 70 | +} |
0 commit comments