Gorm many-to-many relationship duplicates values - go

I am trying to set up a many to many relationship in my demo API, between a Job, and a list of skills []Skill.
Job Struct
type Job struct {
ID string `sql:"type:uuid;primary_key;"`
Title string `json:"title,omitempty"`
Skills []*skill.Skill `json:"skills,omitempty"gorm:"many2many:job_skill;"`
CreatedAt time.Time
UpdatedAt time.Time
}
Skill Struct
type Skill struct {
gorm.Model
Name string `json:"name,omitempty"`
}
I then use gorm.DB.AutoMigrate() to generate the join table automatically.
When I send a POST request to my API, the data is created correctly the first time around, and the join table populates as you'd expect.
Example POST data
{
"title": "Senior Python Engineer",
"skills": [{"name": "javascript"}, {"name": "python"}]
}
But then when I send a PATCH request to add a new skill, it duplicates the skill in the skills table and then creates a new record in the join table for the skills that already exist.
Example PATCH data
{
"title": "Lead Engineer",
"skills": [{"name": "javascript"}, {"name": "python"}, {"name": "management"}]
}
Doing a get request for the data will show the following:
{
"title": "Lead Engineer",
"skills": [{"name": "javascript"}, {"name": "python"}, {"name": "javascript"}, {"name": "python"}, {"name": "management"}]
}
I have also tried setting gorm:"unique" on the skill struck Name but when adding a new Skill it fails as it says the other two already exist, which is good but then won't add the new one.
I am assuming I can only send back new values? Not the entire list?
Some of my Go code for clarity
func GetJobs(w http.ResponseWriter, r *http.Request) {
j := &[]Job{}
o := database.DB.Preload("Skills").Find(&j)
render.JSON(w, r, o)
}
func UpdateJob(w http.ResponseWriter, r *http.Request) {
j := &Job{}
err := json.NewDecoder(r.Body).Decode(j)
if err != nil {
return
}
o := database.DB.Model(&j).Where("id = ?", j.ID).Update(&j)
render.JSON(w, r, o)
}

These are two things with gorm associations that I feel aren't adequately conveyed in its documentation which continue to confuse developers.
1) It uses IDs to identify the associated entities
When you Update that list of skills, if they have no IDs in them to gorm they are just new entities to be added. This leads to your duplicated values. Even if you have a unique field, if that field isn't the entity's primary key, then gorm will try to create a new record and result in a constraint violation instead.
There are a few ways of dealing with this:
Making sure the API user must supply an ID for the related entities
Pulling out of the DB the entity IDs via some other surrogate key that the user does provide, and populating those in your to-save entity. In your case that could be name since it's unique.
Making that surrogate key your primary key (making name the gorm:"primaryKey" of your Skill struct).
2) When Updating, it won't delete existing associations that don't appear in the association slice
When you call Save/Update gorm doesn't delete entities in the far side of collection associations. This is a safety feature to avoid accidentally deleting data on a simple Save/Update. You have to be explicit about wanting that behaviour.
To deal with that you can use Association mode to replace the collection as part of your update: db.Model(&job).Association('Skills').Replace(&job.Skills).

To elaborate on Eziquel's answer and show what worked for me.
I updated my Skill struct to use the Name as the primary key
type Skill struct {
Name string `json:"name,omitempty" gorm:"primary_key"`
}
I then read some documentation saing to just use gorm.DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&j) Not sure what it does, but without it, the associations were duplicating or not updating.
func UpdateJob(w http.ResponseWriter, r *http.Request) {
j := &Job{}
err := json.NewDecoder(r.Body).Decode(j)
if err != nil {
return
}
database.DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&j)
database.DB.Model(&j).Association("Skills").Replace(&j.Skills)
render.JSON(w, r, &j)
}
I dont know what database.DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&j) does but I saw Jihnzu say to use it in the docs, no further explanation. Using that in combination with the .Association("Skills").Replace(&j.Skills) ensure there are no duplicates and that the association updates.
If there was more than one you would do:
database.DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&j)
database.DB.Model(&j).Association("Skills").Replace(&j.Skills)
database.DB.Model(&j).Association("Locations").Replace(&j.Locations)

Related

Foreign Key Constraint in gorm

I want to create a Booking-Class relationship, where every Booking can be assigned only one Class.
type Class struct {
Id int `json:"id"`
Name string `json:"name"`
}
type Booking struct {
Id int `json:"id"`
User string `json:"user"`
Members int `json:"members"`
ClassId int `json:"classid"`
}
I understand that it is similar to gorm's "belongs-to" relationship explained here https://gorm.io/docs/belongs_to.html but I was wondering if it's possible to achieve "foreign key constraint" without defining the field of type Class inside the Booking model (only ClassId int). To make sure that non-existent ClassId-s are used I defined functions:
func Find(slice []int, val int) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
func GetClassKeys(d *gorm.DB) []int {
var keys []int
rows, _ := d.Raw(`SELECT id
FROM classes`).Rows()
defer rows.Close()
for rows.Next() {
var key int
rows.Scan(&key)
keys = append(keys, key)
}
return keys
}
And perform this check before creating/updating a booking:
if !Find(GetClassKeys(db), booking.ClassId) {
log.Println("Wrong class id value")
return
}
But this doesn't handle the case of removed class id (which regular databases do automatically). I was wondering is there a way to achieve a normal database foreign key functionality with gorm by simply referencing the primary key of Class in a User model? Thanks in advance
I don't think the Migrator tool will help you because it assumes you're going to use the default Gorm patterns for defining relationships, and you've explicitly decided NOT to use these.
The only remaining option is to manage the constraint yourself, either through an SQL script or easier, some custom queries you run alongside your AutoMigrate call:
import "gorm.io/gorm/clause"
// somewhere you must be calling
db.AutoMigrate(&Class{}, &Booking{})
// then you'd have:
constraint := "fk_booking_classid"
var count int64
err := db.Raw(
"SELECT count(*) FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ?",
db.Migrator().CurrentDatabase(),
"bookings",
constraint,
).Scan(&count).Error
// handle error
if (count == 0) {
err := db.Exec(
"ALTER TABLE bookings ADD CONSTRAINT ? FOREIGN KEY class_id REFERENCES classes(id)",
clause.Table{Name: constraint},
).Error
// handle error
}
Of course, this negates the advantage of having an automated migration (which means when things change like the field name, the constraint will be updated without changes to the migration code).
I'd be looking at why you don't want to define the foreign key as gorm expects, as this smells of you trying to use the database model directly as your JSON API Request/Response model, and that usually doesn't lead to a good end :)

Multi value list foreign key sql gorm

type Users struct {
ID int64
Email string
Permissions string
}
type UserPermissions struct {
ID int64
Description json.RawMessage
}
The user json should be like this:
{
"status": 200,
"data": {
"id": 1,
"email": "hello#hello.com",
"permisions": [{
"id":"1",
"description":"Create permission"
},
{
"id":"3",
"description":"Edit permission"
}]
}
}
I have the following string in the Permissions of my User:
';1;3;5;7;' every number is the id related to the UserPermissions struct/table
How can I match the string with the user permission table using gorm?.
I'm using mysql
An answer to your question (if you are using PostgreSQL as your DB).
If you want to query for the Permissions that a given User record has, given its ID
perms := []Permission{}
err := db.Joins("JOIN users u ON id::string IN STRING_TO_ARRAY(TRIM(';' FROM u.permissions), ';')").
Where("u.id = ?", userID).
Find(&perms).
Error
if err != nil {
log.Fatal(err) // or something like that
}
As you can see, we are doing a funky join with functions that clean and split the permission field into individual string IDs. This is clunky, brittle and super slow and convoluted, and stems from the faulty relational design that you started with.
EDIT: Nevermind, for MySQL the equivalent solution is very much more complicated, so I suggest you instead use the advice below.
A better way
If you have control over the database design, the better way to do this would be
by not storing an array of IDs as a string, never a good thing in database design, but instead using a foreign key on the many side of the HasMany relationship*.
This would look like this as go structs:
type User struct {
ID int64 `json:"id"`
Email string `json:"email"`
Permissions []UserPermission `json:"permissions"`
}
type UserPermissions struct {
ID int64 `json:"id"`
UserID int64 `json:"-"`
Description json.RawMessage `json:"description"`
}
// now you can use gorm to query the permissions that are related to a user
user := User{}
err := db.Preload("Permissions").First(&user, userID).Error
if err != nil {
log.Fatal(err)
}
// now you can access user.Permissions[i].Description for example.
// or marshal to json
out, err := json.Marshal(user)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
*: I am assuming that the relationship between User and UserPermission is One-to-many. This may very well not be the case, and a Many-to-many relationship actually makes sense (One user can have many permissions, one permission can belong to many users). If this is the case, the concepts are the same and you should be able to modify this solution following the Gorm guide on many to many relationships.

How to update with a many-to-many relationship

I'm facing a difficulty with the go orm gorm:
I have a structure like this:
type Data struct {
gorm.Model
UserID int `json:"user_id,omitempty"`
AnswerID int `json:"answer_id,omitempty"`
Entities []Entity `gorm:"many2many:data_entities;"`
}
type Entity struct {
gorm.Model
Name string
}
And now, either if I do:
db.Model(&data).Where(Data{AnswerID: data.AnswerID}).Assign(&data).FirstOrCreate(&data)
Or
db.Model(&data).Where(Data{AnswerID: d.AnswerID}).Update(&data)
My many-to-many fields aren't updated but created... Leading to duplications if already exists.
If I try to play with the Related() function, it simply stop updating the foreign field.
Is there a way to update or create properly every tables linked?
I do it like this:
To update your data just pass a struct with only the fields you wanna update:
db.Model(&data).Updates(Data{UserID: 2, AnswerID: 2})
and to add new entities:
db.Model(&data).Association("Entities").Append([]*Entity{&Entity{Name: "mynewentity"}})
The way I handled it is using a custom join table and just inserting or deleting the rows manually.
type DataEntity struct {
DataID string `gorm:"primaryKey"`
EntityID string `gorm:"primaryKey"`
CreatedAt time.Time
DeletedAt gorm.DeletedAt
}
set up the join table
err := db.AutoMigrate(&Data{}, &Entity{}, &DataEntity{})
err = db.SetupJoinTable(&Data{}, "Entities", &DataEntity{})
Then for deleting entities:
db.Unscoped().Model(&Data).Association("Entities").Clear()
To add entities:
dataEntities := []DataEntity{DataEntity{DataID:dataid,EntityID:eid}}
dbConnection.Create(&dataEntites)
Slightly cumbersome but it's the only solution I've found so far.
So far the only I found is this one:
db.Table("entities").
Where(
"id in (?)",
db.Table("data_entities").
Select("entity_id").
Where(
"data_id = ?",
data.ID,
).
QueryExpr(),
).
Where("entity_name = ?", *entityName).
Update(&data.Entity)
But I found 2 problems here:
1) Impossible to do a deeper subrequest:
Select("entity_id").
Where(
"data_id = ?",
data.ID,
)...
Won't work if instead of data.ID I want to go deeper with an other sub-request.
2) in case of multiple many-2-many I assume I would need to duplicate the query.
I was able to resolve according to the documentation using the Association.Replace
http://gorm.io/docs/associations.html#Replace-Associations
db.Debug().First(&data)
data.Name = "New Name"
db.Save(&data).Association("Entities").Replace([]Entity{{Name: "mynewentity"}})

GORM Golang how to optimize this code

I use GORM in my project and I want to create something like DB admin page.
To load records I send GET with params:
category: "name", // database table name
On server I have the next code:
func LoadItems(db *gorm.DB, category string) interface{} {
var items interface{}
loadItems := func(i interface{}) {
err := db.Find(i).Error
if err != nil {
panic(err)
}
items = i
}
switch category {
case "groups":
var records []*models.Groups
loadItems(&records)
case "departments":
var records []*models.Departments
loadItems(&records)
case .....
........
}
return items
}
Is it possible to replace switch because I have 10 tables and after record editing I send new data to server, where I re forced to use switch in other function to save it.
I'm not familiar with gorm, but:
Maybe store "department" (as key) and a variable of the corresponding model type in a map, and then referencing via key to the model. If not already, the models then have to implement a common interface in order to be able to store them in one map.
Though, if that would be a better solution I'm not sure. Maybe a bit easier to maintain, because new model types only have to be added to the map, and you don't have to adjust switches on multiple places in your code.
Another obvious way would be, outsourcing the switch to a function, returning a variable of a common interface type and using that on different places in your code. That would definitely not be faster, but easier to maintain.

how do you access the values in a couchbase view?

I have a widget.json file which is loaded into a document in couchbase:
{
"type": "widget",
"name": "clicker",
"description": "clicks!"
}
I also have a couchbase design document, couchbase.ddoc, for a bucket. It is registered with the name "views":
{
"_id": "_design/accesscheck",
"language": "javascript",
"views": {
"all_widgets": {
"map": "function(doc, meta) { if(doc.type == 'widget') { emit(meta.id, doc.name); } }"
}
}
}
and some golang code, using the couchbase golang API, to fetch it:
opts := map[string]interface{}{
"stale": false
}
data, _ := bucket.View("views", "all_widgets", opts)
and at this point i still have A Few Questions:
what is the best way to determine what i can do with the "data" variable? I suspect it's a list of integer-indexed rows, each of which contains a key/value map where the value can be of different types. I see plenty of trivial examples for map[string]interface{}, but this seems to have an additional level of indirection. Easily understandable in C, IMHO, but the interface{}{} is puzzling to me.
probably an extension of the above answer, but how can i effectively search using the design document? I would rather have the Couchbase server doing the sifting.
some of the Get() examples pass in a struct type i.e.
type User struct {
Name string `json:"name"`
Id string `json:"id"`
}
err = bucket.Get("1", &user)
if err != nil {
log.Fatalf("Failed to get data from the cluster (%s)\n", err)
}
fmt.Printf("Got back a user with a name of (%s) and id (%s)\n", user.Name, user.Id)
Is it possible to do something like this with a View()?
does somebody know of a good way to flexibly hook the View mechanism into a net/http REST handler? Just hoping..
I didn't find these questions covered in the golang client API examples or documentation. I probably missed something. If someone has links please let me know.
Thanks for any help!
Customize View Result In Go
If you are using github.com/couchbaselabs/go-couchbase, you can use bucket.ViewCustom to solve your problem. It accepts a item which view result parsed to.
The bucket.View is just calling bucket.ViewCustom with predefined struct and returns it.
An executed view result is a json object like below;
{
"total_rows": 123,
"rows": [
{
"id": "id of document",
"key": {key you emitted},
"value": {value you emitted},
"doc": {the document}
},
...
]
}
As we are know this structure, we can set struct type manually to bucket.ViewCustom.
In your case, you can write custom view struct for "all_widgets" like this;
type AllWidgetsView struct {
Total int `json:"total_rows"`
Rows []struct {
ID string `json:"id"` // document id
Key string `json:"string"` // key you emitted, the 'meta.id'
Value string `json:"value"` // value you emitted, the 'doc.name'
} `json:"rows"`
}
And use bucket.ViewCustom to retrieve the value.
var result AllWidgetsView
opts := map[string]interface{}{}
viewErr := bucket.ViewCustom("views", "all_widgets", opts, &result)
if viewErr != nil {
// handle error
}
If this pattern of code appears frequently, you can refactor it.
Effective searching
For the question 2, it's not related to golang but Couchbase itself.
View has some feature that bucket has not. View results are sorted by key so you can specify startkey option to where the result start. You can use this attribute and make view for searching. See Querying views for more information.
But you need more detailed search like full-text search, you should use ElasticSearch plugin or N1QL to do it.
(note the N1QL is preview and not officially released yet)

Resources