-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
59 lines (49 loc) · 1.15 KB
/
db.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
package opao
import (
"database/sql"
"errors"
"reflect"
"github.com/OblivionOcean/opao/support"
"github.com/OblivionOcean/opao/support/mysql"
"github.com/OblivionOcean/opao/support/pg"
"github.com/OblivionOcean/opao/support/sqlite"
)
const (
EmptyQ = ""
)
type Database struct {
Conn *sql.DB
sqlDriverName string
support.ORM
}
func NewDatabase(sqlDriverName, linkInfo string) (*Database, error) {
conn, err := sql.Open(sqlDriverName, linkInfo)
if err != nil {
return nil, err
}
db := &Database{Conn: conn}
db.sqlDriverName = sqlDriverName
db.ORM = support.ORM{}
var driver func(*sql.DB, any, reflect.Type, string, []support.Elem, error) support.ObjectORM
switch db.sqlDriverName {
case "mysql":
driver = mysql.NewMySQL
case "postgres", "pg", "pgsql":
driver = pg.NewPg
case "sqlite3", "sqlite":
driver = sqlite.NewSqlite
default:
return nil, errors.New("driver not supported")
}
db.ORM.Init(db.Conn, driver)
return db, nil
}
func (db *Database) Close() error {
if db.Conn == nil {
return errors.New("database is not initialized")
}
return db.Conn.Close()
}
func (db *Database) GetConn() *sql.DB {
return db.Conn
}