101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
package database
|
|
|
|
import (
|
|
"court/models"
|
|
"court/utils"
|
|
"database/sql"
|
|
"fmt"
|
|
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
type DB struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
func (self DB) CreateRandUrl(url string) (error, string) {
|
|
uuid := utils.GenerateUUID()
|
|
_, err := self.db.Exec("INSERT INTO court (id, url) VALUES ($1, $2)", uuid, url)
|
|
if err != nil {
|
|
return err, ""
|
|
}
|
|
return nil, uuid
|
|
}
|
|
|
|
func (self DB) CreateChosenUrl(id, url string) (error, string) {
|
|
_, err := self.db.Exec("INSERT INTO court (id, url) VALUES ($1, $2)", id, url)
|
|
if err != nil {
|
|
return err, ""
|
|
}
|
|
return nil, id
|
|
}
|
|
|
|
func (self DB) Close() {
|
|
self.db.Close()
|
|
}
|
|
|
|
func (self DB) GetAllUrls() (error, *[]models.Court) {
|
|
var res models.Court
|
|
var courts []models.Court
|
|
rows, err := self.db.Query("SELECT * FROM court")
|
|
defer rows.Close()
|
|
if err != nil {
|
|
return err, nil
|
|
}
|
|
for rows.Next() {
|
|
err = rows.Scan(&res.ID, &res.URL)
|
|
if err != nil {
|
|
return err, nil
|
|
}
|
|
courts = append(courts, res)
|
|
}
|
|
return nil, &courts
|
|
}
|
|
|
|
func (self DB) GetUrlByID(id string) (error, string) {
|
|
var reponse string
|
|
err := self.db.QueryRow("SELECT url FROM court WHERE id=$1", id).Scan(&reponse)
|
|
if err != nil {
|
|
if err == sql.ErrNoRows {
|
|
return nil, ""
|
|
}
|
|
return err, ""
|
|
}
|
|
return nil, reponse
|
|
}
|
|
|
|
func (self DB) DeleteByID(id string) (error, int) {
|
|
// Check if id exist in table
|
|
err, url := self.GetUrlByID(id)
|
|
if err != nil {
|
|
return err, 500
|
|
}
|
|
if url == "" {
|
|
return nil, 404
|
|
}
|
|
|
|
_, err = self.db.Exec("DELETE FROM court WHERE id=$1", id)
|
|
if err != nil {
|
|
return err, 500
|
|
}
|
|
return nil, 200
|
|
|
|
}
|
|
|
|
func ConnectDB() (error, *DB) {
|
|
dbuser := utils.Getenv("DB_USER", "postgres")
|
|
dbname := utils.Getenv("DB_NAME", "court")
|
|
dbhost := utils.Getenv("DB_HOST", "localhost")
|
|
dbpassword := utils.Getenv("DB_PASSWORD", "bonjour")
|
|
dbport := utils.Getenv("DB_PORT", "5432")
|
|
connStr := fmt.Sprintf("host=%s user=%s password=%s port=%s dbname=%s sslmode=disable", dbhost, dbuser, dbpassword, dbport, dbname)
|
|
db, err := sql.Open("postgres", connStr)
|
|
if err != nil {
|
|
return err, nil
|
|
}
|
|
err = db.Ping()
|
|
if err != nil {
|
|
return err, nil
|
|
}
|
|
return nil, &DB{db}
|
|
}
|