Esempio n. 1
0
func TestRunServer(t *testing.T) {
	db, stop := testserver.NewDBForTest(t)
	defer stop()

	_, err := db.Exec("SELECT 1")
	if err != nil {
		t.Fatal(err)
	}
}
Esempio n. 2
0
func initTestDB(t *testing.T) (*sql.DB, func()) {
	db, stop := testserver.NewDBForTest(t)

	if err := initSchema(db); err != nil {
		stop()
		t.Fatal(err)
	}

	return db, stop
}
Esempio n. 3
0
// TestExecuteTx verifies transaction retry using the classic
// example of write skew in bank account balance transfers.
func TestExecuteTx(t *testing.T) {
	db, stop := testserver.NewDBForTest(t)
	defer stop()

	initStmt := `
CREATE DATABASE d;
CREATE TABLE d.t (acct INT PRIMARY KEY, balance INT);
INSERT INTO d.t (acct, balance) VALUES (1, 100), (2, 100);
`
	if _, err := db.Exec(initStmt); err != nil {
		t.Fatal(err)
	}

	type queryI interface {
		Query(string, ...interface{}) (*sql.Rows, error)
	}

	getBalances := func(q queryI) (bal1, bal2 int, err error) {
		var rows *sql.Rows
		rows, err = q.Query(`SELECT balance FROM d.t WHERE acct IN (1, 2);`)
		if err != nil {
			return
		}
		defer rows.Close()
		balances := []*int{&bal1, &bal2}
		i := 0
		for ; rows.Next(); i += 1 {
			if err = rows.Scan(balances[i]); err != nil {
				return
			}
		}
		if i != 2 {
			err = fmt.Errorf("expected two balances; got %d", i)
			return
		}
		return
	}

	runTxn := func(wg *sync.WaitGroup, iter *int) <-chan error {
		errCh := make(chan error, 1)
		go func() {
			*iter = 0
			errCh <- ExecuteTx(db, func(tx *sql.Tx) error {
				*iter++
				bal1, bal2, err := getBalances(tx)
				if err != nil {
					return err
				}
				// If this is the first iteration, wait for the other tx to also read.
				if *iter == 1 {
					wg.Done()
					wg.Wait()
				}
				// Now, subtract from one account and give to the other.
				if bal1 > bal2 {
					if _, err := tx.Exec(`
UPDATE d.t SET balance=balance-100 WHERE acct=1;
UPDATE d.t SET balance=balance+100 WHERE acct=2;
`); err != nil {
						return err
					}
				} else {
					if _, err := tx.Exec(`
UPDATE d.t SET balance=balance+100 WHERE acct=1;
UPDATE d.t SET balance=balance-100 WHERE acct=2;
`); err != nil {
						return err
					}
				}
				return nil
			})
		}()
		return errCh
	}

	var wg sync.WaitGroup
	wg.Add(2)
	var iters1, iters2 int
	txn1Err := runTxn(&wg, &iters1)
	txn2Err := runTxn(&wg, &iters2)
	if err := <-txn1Err; err != nil {
		t.Errorf("expected success in txn1; got %s", err)
	}
	if err := <-txn2Err; err != nil {
		t.Errorf("expected success in txn2; got %s", err)
	}
	if iters1+iters2 <= 2 {
		t.Errorf("expected at least one retry between the competing transactions; "+
			"got txn1=%d, txn2=%d", iters1, iters2)
	}
	bal1, bal2, err := getBalances(db)
	if err != nil || bal1 != 100 || bal2 != 100 {
		t.Errorf("expected balances to be restored without error; "+
			"got acct1=%d, acct2=%d: %s", bal1, bal2, err)
	}
}