forked from geektutu/7days-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geeorm.go
44 lines (38 loc) · 966 Bytes
/
geeorm.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
package geeorm
import (
"database/sql"
"geeorm/log"
"geeorm/session"
)
// Engine is the main struct of geeorm, manages all db sessions and transactions.
type Engine struct {
db *sql.DB
}
// NewEngine create a instance of Engine
// connect database and ping it to test whether it's alive
func NewEngine(driver, source string) (e *Engine, err error) {
db, err := sql.Open(driver, source)
if err != nil {
log.Error(err)
return
}
// Send a ping to make sure the database connection is alive.
if err = db.Ping(); err != nil {
log.Error(err)
return
}
e = &Engine{db: db}
log.Info("Connect database success")
return
}
// Close database connection
func (engine *Engine) Close() {
if err := engine.db.Close(); err != nil {
log.Error("Failed to close database")
}
log.Info("Close database success")
}
// NewSession creates a new session for next operations
func (engine *Engine) NewSession() *session.Session {
return session.New(engine.db)
}