Skip to content

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

@liveFreeOrCode

Description

@liveFreeOrCode

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()
			}
		})
	}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions