basic frontend (#3)
All checks were successful
continuous-integration/drone/push Build is passing

Co-authored-by: aovantsev <aovantsev@avito.ru>
Reviewed-on: #3
This commit is contained in:
2025-10-03 16:25:14 +00:00
parent 78122bc996
commit ebf4bdeede
52 changed files with 21272 additions and 26 deletions

92
database.go Normal file
View File

@@ -0,0 +1,92 @@
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq"
)
var db *sql.DB
// InitDB initializes the database connection (legacy function)
func InitDB() error {
// Get database URL from environment variable
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
// Default for local development
dbURL = "postgres://postgres:password@localhost:5432/counter_db?sslmode=disable"
}
return initDBWithURL(dbURL)
}
// InitDBWithConfig initializes the database connection with configuration
func InitDBWithConfig(config *Config) error {
return initDBWithURL(config.DatabaseURL)
}
// initDBWithURL initializes the database connection with a specific URL
func initDBWithURL(dbURL string) error {
var err error
db, err = sql.Open("postgres", dbURL)
if err != nil {
return fmt.Errorf("failed to open database: %w", err)
}
// Test the connection
if err = db.Ping(); err != nil {
return fmt.Errorf("failed to ping database: %w", err)
}
log.Println("✅ Database connection established successfully")
return nil
}
// CreateTables creates the necessary database tables
func CreateTables() error {
queries := []string{
`CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`,
`CREATE TABLE IF NOT EXISTS counters (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`,
`CREATE TABLE IF NOT EXISTS counter_entries (
id SERIAL PRIMARY KEY,
counter_id INTEGER REFERENCES counters(id) ON DELETE CASCADE,
value INTEGER NOT NULL,
date DATE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`,
`CREATE INDEX IF NOT EXISTS idx_counters_user_id ON counters(user_id)`,
`CREATE INDEX IF NOT EXISTS idx_counter_entries_counter_id ON counter_entries(counter_id)`,
`CREATE INDEX IF NOT EXISTS idx_counter_entries_date ON counter_entries(date)`,
}
for _, query := range queries {
if _, err := db.Exec(query); err != nil {
return fmt.Errorf("failed to execute query: %w", err)
}
}
log.Println("✅ Database tables created successfully")
return nil
}
// GetDB returns the database connection
func GetDB() *sql.DB {
return db
}