forked from rokybulrayhan/go_bun_core_practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
73 lines (57 loc) · 1.8 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
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
toml "github.com/pelletier/go-toml"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/extra/bundebug"
)
func dbconn(dbconfig *toml.Tree) *bun.DB {
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v search_path=%v sslmode=disable", dbconfig.Get("dbhost").(string), dbconfig.Get("dbuser").(string), dbconfig.Get("dbpass").(string), dbconfig.Get("dbname").(string), dbconfig.Get("schema").(string))
sqldb, err := sql.Open("postgres", dsn)
// db := bun.NewDB(sqldb, sqlitedialect.New())
//sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn)))
db := bun.NewDB(sqldb, pgdialect.New())
ctx := context.Background()
var status []Status
count, err := db.NewSelect().Model(&status).Limit(20).ScanAndCount(ctx)
if err != nil {
panic(err)
}
fmt.Println(status, count)
if err != nil {
log.Fatal(err.Error())
}
if err = db.Ping(); err != nil {
log.Fatal(err)
} else {
fmt.Println("DB Connected...")
}
/*var user User1
db.NewCreateTable().
Model(user)
*/
db.SetMaxOpenConns(SetMaxOpenConns)
db.AddQueryHook(bundebug.NewQueryHook(
bundebug.WithVerbose(true)))
return db
}
//gorm
/*func dbconn(dbconfig *toml.Tree) *gorm.DB {
dsn := fmt.Sprintf("host=%v user=%v password=%v dbname=%v search_path=%v sslmode=disable", dbconfig.Get("dbhost").(string), dbconfig.Get("dbuser").(string), dbconfig.Get("dbpass").(string), dbconfig.Get("dbname").(string), dbconfig.Get("schema").(string))
//db, err := sql.Open("postgres", dsn)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("could not connect to the database")
} else {
fmt.Println("DB Connected...")
}
db.AutoMigrate(&User1{})
return db
}
*/
/*end postgresql connection*/