Skip to content

Instantly share code, notes, and snippets.

@udondan
Last active April 25, 2024 17:50
Show Gist options
  • Save udondan/97b3c9178848012e50b61aec45d429f3 to your computer and use it in GitHub Desktop.
Save udondan/97b3c9178848012e50b61aec45d429f3 to your computer and use it in GitHub Desktop.
Example: golang gorm postgres uuid relation
[2018-08-15 16:35:42] [7.58ms] CREATE TABLE "parents" ("id" uuid DEFAULT uuid_generate_v4(),"name" text , PRIMARY KEY ("id"))
[0 rows affected or returned ]
[2018-08-15 16:35:42] [7.22ms] CREATE TABLE "children" ("id" uuid DEFAULT uuid_generate_v4(),"parent_id" uuid REFERENCES parents(id),"name" text , PRIMARY KEY ("id"))
[0 rows affected or returned ]
[2018-08-15 16:35:42] [2.54ms] INSERT INTO "parents" ("name") VALUES ('I am the parent') RETURNING "parents"."id"
[1 rows affected or returned ]
[2018-08-15 16:35:42] [4.31ms] SELECT "id" FROM "parents" WHERE (id = 'fd763ae6-b0e1-4808-bac6-73119eca075b')
[1 rows affected or returned ]
[2018-08-15 16:35:42] [5.19ms] INSERT INTO "children" ("parent_id","name") VALUES ('fd763ae6-b0e1-4808-bac6-73119eca075b','I am the child') RETURNING "children"."id"
[1 rows affected or returned ]
[2018-08-15 16:35:42] [1.78ms] SELECT "id" FROM "children" WHERE (id = '8c1424a8-62db-4b71-a136-8825a7d2f44f')
[1 rows affected or returned ]
{8c1424a8-62db-4b71-a136-8825a7d2f44f fd763ae6-b0e1-4808-bac6-73119eca075b {fd763ae6-b0e1-4808-bac6-73119eca075b I am the parent} I am the child}
[2018-08-15 16:35:42] [1.67ms] SELECT * FROM "children" WHERE (id = '8c1424a8-62db-4b71-a136-8825a7d2f44f')
[1 rows affected or returned ]
[2018-08-15 16:35:42] [1.80ms] SELECT * FROM "parents" WHERE ("id" IN ('fd763ae6-b0e1-4808-bac6-73119eca075b'))
[1 rows affected or returned ]
(main.Child) {
ID: (uuid.UUID) (len=16 cap=16) 8c1424a8-62db-4b71-a136-8825a7d2f44f,
ParentID: (uuid.UUID) (len=16 cap=16) fd763ae6-b0e1-4808-bac6-73119eca075b,
Parent: (main.Parent) {
ID: (uuid.UUID) (len=16 cap=16) fd763ae6-b0e1-4808-bac6-73119eca075b,
Name: (string) (len=15) "I am the parent"
},
Name: (string) (len=14) "I am the child"
}

Example: golang gorm postgres uuid relation

I was trying forever to get autoloading relationships working with postgres 9.4 and gorm and primary keys of type uuid.

Many tutorials and examples, even those on the official docs were just not workiong or missing important details.

The program in this gist creates the table structure and inserts a nested record. A parent and a child object is created by simply creating the child, which holds the relation to a parent. The child element then is queried by ID. The returned object holds the nested parent object.

Used package versions:

package main
import (
"fmt"
"os"
"github.com/davecgh/go-spew/spew"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/satori/go.uuid"
)
type Parent struct { // table name: parents
ID uuid.UUID `gorm:"primary_key;type:uuid;default:uuid_generate_v4()"`
Name string
}
type Child struct { // table name: children
ID uuid.UUID `gorm:"primary_key;type:uuid;default:uuid_generate_v4()"`
ParentID uuid.UUID `gorm:"type:uuid REFERENCES parents(id)"`
Parent Parent `gorm:"ForeignKey:ParentID;AssociationForeignKey:ID`
Name string
}
func main() {
dbString := "postgres://user:password@localhost/schema?sslmode=disable"
db, err := gorm.Open("postgres", dbString)
if err != nil {
fmt.Fprintf(os.Stderr, "db connection failed: %s", err.Error())
os.Exit(1)
}
db.LogMode(true)
defer db.Close()
//dropTables(db)
createTables(db)
newID := createNewRecord(db)
showRecord(db, newID)
}
func dropTables(db *gorm.DB) {
db.DropTable(&Child{})
db.DropTable(&Parent{})
}
func createTables(db *gorm.DB) {
db.CreateTable(&Parent{})
db.CreateTable(&Child{})
}
func createNewRecord(db *gorm.DB) uuid.UUID {
testObject := Child{
Name: "I am the child",
Parent: Parent{
Name: "I am the parent",
},
}
db.Create(&testObject)
return testObject.ID,
}
func showRecord(db *gorm.DB, key interface{}) {
var child Child
db.Set("gorm:auto_preload", true).Find(&child, "id = ?", key)
spew.Dump(child)
}
@meghashyamc
Copy link

Thanks! This was helpful.

@eduolalo
Copy link

Tks bro, just a question: Using your example, should I implement the "BeforeCreate" hook?

I've got confused by this post I Think the author used some old version (the post almost 3 year old)

@udondan
Copy link
Author

udondan commented Nov 27, 2021

Well this gist is even older. 😅 Honestly, I haven't worked with gorm (actually not even go) in the past 2 years. I have no clue what I was writing about up there 😅

@isperk
Copy link

isperk commented Jan 22, 2022

Thanks a lot!
I saw that a " is missing on line 21.

@gipsh
Copy link

gipsh commented Feb 11, 2022

to enable uuid support you need to run this query first

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

@ENsu
Copy link

ENsu commented Feb 20, 2022

@gipsh Thank you so much! Save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment