ADD: added database connection for players data handling and started login funtion with database
This commit is contained in:
@@ -5,28 +5,66 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"volleyball/internal/player"
|
||||
|
||||
_ "github.com/lib/pq" // Import the PostgreSQL driver
|
||||
)
|
||||
|
||||
const playerTable = `
|
||||
CREATE TABLE IF NOT EXISTS players (
|
||||
const teamTable = `
|
||||
CREATE TABLE IF NOT EXISTS teams (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
age INT NOT NULL,
|
||||
birthday DATE NOT NULL
|
||||
player1_id uuid NOT NULL,
|
||||
player2_id uuid NOT NULL,
|
||||
formation_date DATE NOT NULL DEFAULT CURRENT_DATE,
|
||||
FOREIGN KEY (player1_id) REFERENCES players(id),
|
||||
FOREIGN KEY (player2_id) REFERENCES players(id)
|
||||
);
|
||||
`
|
||||
|
||||
func InitTables(db *sql.DB) {
|
||||
var tableNames = []string{
|
||||
"players",
|
||||
"teams",
|
||||
}
|
||||
|
||||
func CheckIfTablesExist(db *sql.DB) (bool, error) {
|
||||
for _, tableName := range tableNames {
|
||||
exists, err := tableExists(db, tableName)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error checking if table %s exists: %w", tableName, err)
|
||||
}
|
||||
if !exists {
|
||||
return false, nil // At least one table does not exist
|
||||
}
|
||||
}
|
||||
return true, nil // All tables exist
|
||||
}
|
||||
|
||||
func tableExists(db *sql.DB, tableName string) (bool, error) {
|
||||
query := `
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_name = $1
|
||||
);
|
||||
`
|
||||
var exists bool
|
||||
err := db.QueryRow(query, tableName).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func InitTables(d *sql.DB) error {
|
||||
tables := []string{
|
||||
playerTable,
|
||||
player.PlayerTable,
|
||||
player.RoleTable,
|
||||
teamTable,
|
||||
}
|
||||
|
||||
for _, table := range tables {
|
||||
if _, err := db.Exec(table); err != nil {
|
||||
if _, err := d.Exec(table); err != nil {
|
||||
log.Fatalf("Error creating table: %v", err)
|
||||
return fmt.Errorf("error creating table: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("Tables initialized successfully.")
|
||||
log.Println("Tables initialized successfully.")
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user