-
Notifications
You must be signed in to change notification settings - Fork 0
/
orm.go
110 lines (100 loc) · 2.33 KB
/
orm.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package orm
import(
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
var (
db *sql.DB
)
func Conn(_db *sql.DB){
db = _db
}
func Close(){
db.Close()
}
func Delete(namespace string, query Query) (count int64, err error) {
return ExecUpdate(namespace, SQL_DELETE_KEY, query)
}
func Update(namespace string, query Query) (count int64, err error) {
return ExecUpdate(namespace, SQL_UPDATE_KEY, query)
}
/**
* save query to database, execute insert into table command
*/
func ExecUpdate(namespace, sqlKey string, query Query) (count int64, err error) {
stmt := MustStmt(namespace, sqlKey, query)
pstmt, err := db.Prepare(stmt.Sql)
if err!= nil {
return
}
result, err := pstmt.Exec(stmt.Params...)
if err!= nil {
return
}
return result.RowsAffected()
}
func Save(namespace string, query Query) (id int64, err error) {
return ExecSave(namespace, SQL_INSERT_KEY, query)
}
/**
* save query to database, execute insert into table command
*/
func ExecSave(namespace, sqlKey string, query Query) (id int64, err error) {
stmt := MustStmt(namespace, sqlKey, query)
pstmt, err := db.Prepare(stmt.Sql)
if err!= nil {
return
}
result, err := pstmt.Exec(stmt.Params...)
if err!= nil {
return
}
return result.LastInsertId()
}
func List(namespace string, query Query) (entities []interface{}, err error) {
return ExecList(namespace, SQL_SELECT_KEY, query)
}
/**
* list entities from database
*/
func ExecList(namespace, sqlKey string, query Query) (entities []interface{}, err error) {
stmt := MustStmt(namespace, sqlKey, query)
pstmt, err := db.Prepare(stmt.Sql)
if err!= nil {
return
}
rows, err := pstmt.Query(stmt.Params...)
if err!= nil {
return
}
defer rows.Close()
entities = make([]interface{}, 0)
for rows.Next() {
entity, err := stmt.Scan(rows)
if err != nil {
return nil, err
}
entities = append(entities, entity)
}
err = rows.Err()
return
}
func Get(namespace string, query Query) (entity interface{}, err error) {
return ExecGet(namespace, SQL_GET_KEY, query)
}
/**
* get one entity from database
*/
func ExecGet(namespace, sqlKey string, query Query) (entity interface{}, err error) {
stmt := MustStmt(namespace, sqlKey, query)
pstmt, err := db.Prepare(stmt.Sql)
if err!= nil {
return
}
row := pstmt.QueryRow(stmt.Params...)
entity, err = stmt.Scan(row)
if err != nil {
return nil, err
}
return
}