79 lines
1.6 KiB
Go
79 lines
1.6 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log"
|
|
|
|
_ "github.com/lib/pq"
|
|
)
|
|
|
|
const (
|
|
host = "202.46.28.160"
|
|
port = 45432
|
|
user = "5803024005"
|
|
password = "pw5803024005"
|
|
dbname = "tgs01_5803024005"
|
|
)
|
|
|
|
var DB *sql.DB
|
|
|
|
func InitDB() {
|
|
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
|
|
|
|
var err error
|
|
DB, err = sql.Open("postgres", psqlconn)
|
|
if err != nil {
|
|
log.Fatal("Failed to open database connection:", err)
|
|
}
|
|
|
|
// Test the connection
|
|
err = DB.Ping()
|
|
if err != nil {
|
|
log.Fatal("Failed to ping database:", err)
|
|
}
|
|
|
|
log.Println("Database connection established successfully")
|
|
|
|
// Create tables if they don't exist
|
|
createTables()
|
|
}
|
|
|
|
func createTables() {
|
|
// Create Groups table
|
|
createGroupsTable := `
|
|
CREATE TABLE IF NOT EXISTS "Groups" (
|
|
"GroupID" SERIAL PRIMARY KEY,
|
|
"GroupName" VARCHAR(255) NOT NULL
|
|
);`
|
|
|
|
_, err := DB.Exec(createGroupsTable)
|
|
if err != nil {
|
|
log.Fatal("Failed to create Groups table:", err)
|
|
}
|
|
|
|
// Create Tasks table
|
|
createTasksTable := `
|
|
CREATE TABLE IF NOT EXISTS "Tasks" (
|
|
"TaskID" SERIAL PRIMARY KEY,
|
|
"TaskName" VARCHAR(255) NOT NULL,
|
|
"TaskDescription" TEXT,
|
|
"GroupID" INTEGER REFERENCES "Groups"("GroupID") ON DELETE CASCADE,
|
|
"IsDone" BOOLEAN DEFAULT FALSE,
|
|
"CreatedAt" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
);`
|
|
|
|
_, err = DB.Exec(createTasksTable)
|
|
if err != nil {
|
|
log.Fatal("Failed to create Tasks table:", err)
|
|
}
|
|
|
|
log.Println("Database tables created/verified successfully")
|
|
}
|
|
|
|
func CheckError(err error) {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|