forked from picatic/norm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
96 lines (79 loc) · 2.3 KB
/
connection.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package norm
import (
"database/sql"
"errors"
"github.com/gocraft/dbr"
)
// Connection initialized with a database
type Connection interface {
// dbr.Connection
NewSession(log dbr.EventReceiver) Session
Database() string
ValidatorCache() ValidatorCache
}
type connection struct {
*dbr.Connection
database string
validatorCache ValidatorCache
}
// NewConnection return a Connection as configured
func NewConnection(db *sql.DB, database string, log dbr.EventReceiver) Connection {
return &connection{Connection: dbr.NewConnection(db, log), database: database, validatorCache: make(ValidatorCache, 0)}
}
// Database returns name of database
func (c connection) Database() string {
return c.database
}
// ValidatorCache returns ValidatorCache
func (c connection) ValidatorCache() ValidatorCache {
return c.validatorCache
}
// NewSession Create a new Session with the Connection
func (c connection) NewSession(log dbr.EventReceiver) Session {
return &session{Session: c.Connection.NewSession(log), connection: &c}
}
// Session return a Session to work with
type Session interface {
// dbr.Session functions
Begin() (Tx, error)
DeleteFrom(from string) *dbr.DeleteBuilder
InsertInto(into string) *dbr.InsertBuilder
Select(cols ...string) *dbr.SelectBuilder
SelectBySql(sql string, args ...interface{}) *dbr.SelectBuilder
Update(table string) *dbr.UpdateBuilder
UpdateBySql(sql string, args ...interface{}) *dbr.UpdateBuilder
Connection() Connection
}
type session struct {
*dbr.Session
connection Connection
}
// Connection returns the connection used to create the session
func (s session) Connection() Connection {
return s.connection
}
// Begin returns a norm Tx which has wrapped a dbr.Tx
// A real database connection has been aquired and is held by the enclosed sql.Tx instance
func (s session) Begin() (Tx, error) {
dbrTx, err := s.Session.Begin()
return &tx{dbrTx, s.Connection()}, err
}
// Tx embeds dbr.Tx and norm Session
type Tx interface {
Session
Commit() error
Rollback() error
RollbackUnlessCommitted()
}
// tx implements Tx interface
type tx struct {
*dbr.Tx
connection Connection
}
// Connection returns norm Connection
func (t tx) Connection() Connection {
return t.connection
}
func (t tx) Begin() (Tx, error) {
return nil, errors.New("Support for nested transactions not implemented")
}