forked from lunny/godbc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
66 lines (58 loc) · 1.31 KB
/
tx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package odbc
import (
"database/sql/driver"
"errors"
"github.com/lunny/godbc/api"
)
type Tx struct {
c *Conn
}
func (c *Conn) setAutoCommitAttr(a uintptr) error {
ret := api.SQLSetConnectAttr(c.h, api.SQL_ATTR_AUTOCOMMIT,
api.SQLPOINTER(a), api.SQL_IS_UINTEGER)
if IsError(ret) {
return NewError("SQLSetConnectAttr", c.h)
}
return nil
}
func (c *Conn) Begin() (driver.Tx, error) {
if c.tx != nil {
return nil, errors.New("already in a transaction")
}
c.tx = &Tx{c: c}
err := c.setAutoCommitAttr(api.SQL_AUTOCOMMIT_OFF)
if err != nil {
return nil, err
}
return c.tx, nil
}
func (c *Conn) endTx(commit bool) error {
if c.tx == nil {
return errors.New("not in a transaction")
}
c.tx = nil
var howToEnd api.SQLSMALLINT
if commit {
howToEnd = api.SQL_COMMIT
} else {
howToEnd = api.SQL_ROLLBACK
}
ret := api.SQLEndTran(api.SQL_HANDLE_DBC, api.SQLHANDLE(c.h), howToEnd)
if IsError(ret) {
return NewError("SQLEndTran", c.h)
}
err := c.setAutoCommitAttr(api.SQL_AUTOCOMMIT_ON)
if err != nil {
return err
}
return nil
}
func (tx *Tx) Commit() error {
return tx.c.endTx(true)
}
func (tx *Tx) Rollback() error {
return tx.c.endTx(false)
}