iver-wharf / wharf-api

Wharf backend written in Go
MIT License
1 stars 0 forks source link

Fix database model associations #146

Open applejag opened 2 years ago

applejag commented 2 years ago

We have a lot of misconfigured associations in our pkg/model/database package.

When doing just a simple test implementation of Sqlite foreign key constraints (#145), I noticed that our invalid database model relations are really obstructing this. Maybe it will mess up our Postgres integration as well?

Actual

For example, the Project type should have many builds, but instead the Build model is set up to with a "has-one" relation to Project. I.e. an inverted model dependency

type Project struct {
    TimeMetadata
    ProjectID       uint      `gorm:"primaryKey"`
    // ...
}

type Build struct {
    TimeMetadata
    BuildID             uint                `gorm:"primaryKey"`
    ProjectID           uint                `gorm:"not null;index:build_idx_project_id"`
    Project             *Project            `gorm:"foreignKey:ProjectID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
    // ...
}

Expected

The Project model should have a "has-many" relation to the Build model, like so:

 type Project struct {
    TimeMetadata
    ProjectID     uint    `gorm:"primaryKey"`
+   Builds        []Build `gorm:"foreignKey:ProjectID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
    // ...
 }

 type Build struct {
    TimeMetadata
    BuildID             uint                `gorm:"primaryKey"`
    ProjectID           uint                `gorm:"not null;index:build_idx_project_id"`
-   Project             *Project            `gorm:"foreignKey:ProjectID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
    // ...
 }

Docs: https://gorm.io/docs/has_many.html