Changed the structure of the whole application, should be no changes to functionality.
This commit is contained in:
61
pkg/db/dbHelper.go
Normal file
61
pkg/db/dbHelper.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
"os"
|
||||
)
|
||||
|
||||
var pool *pgxpool.Pool
|
||||
|
||||
func InitDB(host string, port int, user string, password string, dbname string) {
|
||||
|
||||
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
|
||||
"password=%s dbname=%s sslmode=disable",
|
||||
host, port, user, password, dbname)
|
||||
|
||||
fmt.Println(psqlInfo)
|
||||
|
||||
var err error
|
||||
pool, err = pgxpool.Connect(context.Background(), psqlInfo)
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var success string
|
||||
err = pool.QueryRow(context.Background(), "select 'Successfully connected!'").Scan(&success)
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(success)
|
||||
}
|
||||
|
||||
func CloseDb() {
|
||||
pool.Close()
|
||||
}
|
||||
|
||||
func Testf() {
|
||||
rows, dbErr := pool.Query(context.Background(), "select game_name from game")
|
||||
if dbErr != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", dbErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
for rows.Next() {
|
||||
var gameName string
|
||||
dbErr = rows.Scan(&gameName)
|
||||
if dbErr != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", dbErr)
|
||||
}
|
||||
_, _ = fmt.Fprintf(os.Stderr, "%v\n", gameName)
|
||||
}
|
||||
}
|
||||
|
||||
func resetGameIdSeq() {
|
||||
_, err := pool.Query(context.Background(), "SELECT setval('game_id_seq', (SELECT MAX(id) FROM game)+1);")
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "Exec failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user