diff options
author | Santo Cariotti <santo@dcariotti.me> | 2025-04-08 14:37:33 +0200 |
---|---|---|
committer | Santo Cariotti <santo@dcariotti.me> | 2025-04-08 14:39:13 +0200 |
commit | 1f0d9ec8452f15c27cd33c4e3874454c35993743 (patch) | |
tree | c453a31ae5eb823aaf48868eea9fc4daf65f108b /internal/api/database | |
parent | c5b10e28b358308d8349b940af09f64368172f2e (diff) |
Use internal/pkg structure
Diffstat (limited to 'internal/api/database')
-rw-r--r-- | internal/api/database/database.go | 32 | ||||
-rw-r--r-- | internal/api/database/models.go | 24 |
2 files changed, 56 insertions, 0 deletions
diff --git a/internal/api/database/database.go b/internal/api/database/database.go new file mode 100644 index 0000000..4470c58 --- /dev/null +++ b/internal/api/database/database.go @@ -0,0 +1,32 @@ +package database + +import ( + "gorm.io/driver/postgres" + "gorm.io/gorm" + + "errors" +) + +// Global variable but private +var db *gorm.DB = nil + +// Init the database from a DSN string which must be a valid PostgreSQL dsn. +// Also, auto migrate all the models. +func InitDb(dsn string) (*gorm.DB, error) { + var err error + db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) + + if err == nil { + db.AutoMigrate(&User{}, &Game{}) + } + + return db, err +} + +// Return the instance or error if the config is not laoded yet +func GetDb() (*gorm.DB, error) { + if db == nil { + return nil, errors.New("You must call `InitDb()` first.") + } + return db, nil +} diff --git a/internal/api/database/models.go b/internal/api/database/models.go new file mode 100644 index 0000000..a6e76c5 --- /dev/null +++ b/internal/api/database/models.go @@ -0,0 +1,24 @@ +package database + +import "time" + +type User struct { + ID int `json:"id"` + Username string `json:"username"` + Password string `json:"password"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type Game struct { + ID int `json:"id"` + Player1ID int `json:"-"` + Player1 User `gorm:"foreignKey:Player1ID" json:"player1"` + Player2ID *int `json:"-"` + Player2 *User `gorm:"foreignKey:Player2ID;null" json:"player2"` + Name string `json:"name"` + IP1 string `json:"ip1"` + IP2 string `json:"ip2"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} |