Add a minimal gorm example that takes a go struct, creates a postgres table, and writes the struct to the table.

This commit is contained in:
Michael Hohn
2024-06-03 14:03:26 -07:00
committed by =Michael Hohn
parent e850a36943
commit 71838d3320
6 changed files with 113 additions and 3 deletions

32
cmd/postgres/pgmin.go Normal file
View File

@@ -0,0 +1,32 @@
package main
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"mrvacommander/pkg/common"
)
// TODO migrate this to test/
// TODO add a reader test
// Minimal gorm example that takes a go struct, creates a postgres table,
// and writes the struct to the table.
func main() {
// Set up the database connection string
dsn := "host=postgres user=exampleuser dbname=exampledb sslmode=disable password=examplepass"
// Open the database connection
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema: create the 'owner_repo' table from the struct
err = db.AutoMigrate(&common.OwnerRepo{})
if err != nil {
panic("failed to migrate database")
}
// Create an entry in the database
db.Create(&common.OwnerRepo{Owner: "foo", Repo: "foo/bar"})
}