Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Transactions with Primary Key's not supported? #108

Open
liveFreeOrCode opened this issue Aug 8, 2024 · 0 comments
Open

Bug: Transactions with Primary Key's not supported? #108

liveFreeOrCode opened this issue Aug 8, 2024 · 0 comments

Comments

@liveFreeOrCode
Copy link

I would expect both test cases to work, but they do not. I assume somewhere there is a copy of the record in the primary key index that isn't getting rolled back?

package transactions

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"testing"

	"github.com/jmoiron/sqlx"
	_ "github.com/proullon/ramsql/driver"
)

func TestTx(t *testing.T) {
	tests := map[string]struct {
		driverName     string
		dataSourceName string
		withPrimaryKey bool
	}{
		"ramsql with pk":    {driverName: "ramsql", dataSourceName: "testdbwithpk", withPrimaryKey: true},
		"ramsql without pk": {driverName: "ramsql", dataSourceName: "testdbwithoutpk", withPrimaryKey: false},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			ctx := context.Background()

			db, err := sqlx.Open(test.driverName, test.dataSourceName)
			if err != nil {
				log.Fatal(err)
			}
			defer db.Close()

			pkStr := ""
			if test.withPrimaryKey {
				pkStr = "PRIMARY KEY"
			}

			db.MustExec(fmt.Sprintf("CREATE TABLE foos (id BIGINT %s, value TEXT)", pkStr))

			type Foo struct {
				ID    int64  `db:"id"`
				Value string `db:"value"`
			}

			var foo Foo

			if err = db.Get(&foo, "SELECT id, value FROM foos WHERE id = $1", 1); err != sql.ErrNoRows {
				t.Fatal("expected no rows")
			}

			tx, err := db.BeginTxx(ctx, &sql.TxOptions{})
			if err != nil {
				t.Fatal("unexpected tx error")
			}

			_, err = tx.NamedExecContext(ctx, "INSERT INTO foos (id, value) VALUES (:id, :value)", Foo{ID: 1, Value: "test"})
			if err != nil {
				t.Fatal("unexpected insert error")
			}

			if err = tx.Rollback(); err != nil {
				t.Fatal("unexpected rollback error")
			}

			if err = db.Get(&foo, "SELECT id, value FROM foos WHERE id = $1", 1); err != sql.ErrNoRows {
				t.Fail()
			}
		})
	}

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant