forked from LunaNode/lobster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
96 lines (79 loc) · 1.71 KB
/
database.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 lobster
import _ "github.com/go-sql-driver/mysql"
import "database/sql"
import "log"
type Database struct {
db *sql.DB
}
func GetDatabaseString() string {
s := cfg.Database.Username + ":" + cfg.Database.Password + "@"
if cfg.Database.Host != "localhost" {
s += cfg.Database.Host
}
s += "/" + cfg.Database.Name + "?charset=utf8&parseTime=true"
return s
}
func MakeDatabase() *Database {
this := new(Database)
db, err := sql.Open("mysql", GetDatabaseString())
checkErr(err)
this.db = db
return this
}
func (this *Database) Query(q string, args ...interface{}) Rows {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
rows, err := this.db.Query(q, args...)
checkErr(err)
return Rows{rows}
}
func (this *Database) QueryRow(q string, args ...interface{}) Row {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
row := this.db.QueryRow(q, args...)
return Row{row}
}
func (this *Database) Exec(q string, args ...interface{}) Result {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
result, err := this.db.Exec(q, args...)
checkErr(err)
return Result{result}
}
type Rows struct {
rows *sql.Rows
}
func (r Rows) Close() {
err := r.rows.Close()
checkErr(err)
}
func (r Rows) Next() bool {
return r.rows.Next()
}
func (r Rows) Scan(dest ...interface{}) {
err := r.rows.Scan(dest...)
checkErr(err)
}
type Row struct {
row *sql.Row
}
func (r Row) Scan(dest ...interface{}) {
err := r.row.Scan(dest...)
checkErr(err)
}
type Result struct {
result sql.Result
}
func (r Result) LastInsertId() int {
id, err := r.result.LastInsertId()
checkErr(err)
return int(id)
}
func (r Result) RowsAffected() int {
count, err := r.result.RowsAffected()
checkErr(err)
return int(count)
}