Database module

This commit is contained in:
Anton Kamalov
2025-01-03 19:28:07 +00:00
parent 387fcae36b
commit e5633c9f12
5 changed files with 112 additions and 1 deletions

85
database/database.go Normal file
View File

@@ -0,0 +1,85 @@
package database
import (
"fmt"
"log"
"os"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
yaml "gopkg.in/yaml.v2"
)
type Conf struct {
User string `yaml:"user"`
DBname string `yaml:"dbname"`
SSLMode string `yaml:"sslmode"`
Password string `yaml:"password"`
Host string `yaml:"hostname"`
}
func LoadConfig(path string) (*Conf, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var config Conf
err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func CheckError(err error) bool {
if err != nil {
log.Fatalln(err)
return false
}
return true
}
func Test_connection() {
config, err := LoadConfig("config/config.yaml")
if err != nil {
log.Fatalln("Failed to load config:", err)
}
dsn := fmt.Sprintf("user=%s dbname=%s sslmode=%s password=%s host=%s",
config.User, config.DBname, config.SSLMode, config.Password, config.Host)
db, err := sqlx.Connect("postgres", dsn)
if err != nil {
log.Fatalln(err)
}
defer db.Close()
// Test the connection to the database
if err := db.Ping(); err != nil {
log.Fatal(err)
} else {
log.Println("Successfully Connected")
}
}
func Insert_Data(query string) bool {
config, err := LoadConfig("config/config.yaml")
if err != nil {
log.Fatalln("Failed to load config:", err)
return false
}
dsn := fmt.Sprintf("user=%s dbname=%s sslmode=%s password=%s host=%s",
config.User, config.DBname, config.SSLMode, config.Password, config.Host)
db, err := sqlx.Open("postgres", dsn)
if !CheckError(err) {
return false
}
defer db.Close()
_, e := db.Exec(query)
return CheckError(e)
}