go-sqlite3/driver/transaction.go

61 lines
1.3 KiB
Go
Raw Normal View History

2018-06-19 18:53:53 +03:00
// Copyright (C) 2018 The Go-SQLite3 Authors.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// +build cgo
package sqlite3
/*
#ifndef USE_LIBSQLITE3
#include <sqlite3-binding.h>
#else
#include <sqlite3.h>
#endif
*/
import "C"
import (
"context"
"database/sql/driver"
)
var (
_ driver.Tx = (*SQLiteTx)(nil)
)
// SQLiteTx implemen sql.Tx.
type SQLiteTx struct {
c *SQLiteConn
}
// Begin transaction.
func (c *SQLiteConn) Begin() (driver.Tx, error) {
return c.begin(context.Background())
}
func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
if _, err := c.exec(ctx, c.txlock, nil); err != nil {
return nil, err
}
return &SQLiteTx{c}, nil
}
// Commit transaction.
func (tx *SQLiteTx) Commit() error {
_, err := tx.c.exec(context.Background(), "COMMIT", nil)
if err != nil && err.(Error).Code == C.SQLITE_BUSY {
// sqlite3 will leave the transaction open in this scenario.
// However, database/sql considers the transaction complete once we
// return from Commit() - we must clean up to honour its semantics.
tx.c.exec(context.Background(), "ROLLBACK", nil)
}
return err
}
// Rollback transaction.
func (tx *SQLiteTx) Rollback() error {
_, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
return err
}