..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 | package database
import (
"log/slog"
"pagoda/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var Database *gorm.DB
func Initialise() {
var err error
Database, err = gorm.Open(postgres.Open(config.DSN), &gorm.Config{})
if err != nil {
slog.Error("Failed to connect to database")
panic(err)
}
slog.Info("Connected to database")
if config.ClearAndResetDatabaseOnStart {
if err := clearAndResetDatabase(); err != nil {
slog.Error("Failed to clear and reset database")
panic(err)
}
}
if err := migrateSchema(); err != nil {
slog.Error("Failed to migrate schema")
panic(err)
}
slog.Info("Database initialised successfully")
}
func clearAndResetDatabase() error {
// Drop all tables
err := Database.Exec("DROP SCHEMA public CASCADE").Error
if err != nil {
slog.Error("Error dropping schema", "error", err)
return err
}
// Recreate public schema
err = Database.Exec("CREATE SCHEMA public").Error
if err != nil {
slog.Error("Error recreating schema", "error", err)
return err
}
slog.Info("All data cleared and database reset successfully.")
return nil
}
func migrateSchema() error {
err := Database.AutoMigrate(&User{}, &Session{})
if err != nil {
slog.Error("Error migrating schema", "error", err)
return err
}
slog.Info("Schema migrated successfully")
return nil
}
|
|