Grandchild foreign key - go

I'm creating a rest application in Go, and am using GORM for my orm. So far I successfully have everything implemented however I'm now wanting to add some further details to my model in order to make the front end application easier.
This will be adding "grandchildren" foreign keys (Can't think of a better thing to call it). I can't see anything in the documentation about this but effectivly what i'm wanting is the following:
type Map struct{
Id int `gorm:"primaryKey"`
Buildings []Building `gorm:"references:Id"`
}
type Building struct{
Id int `gorm:"primaryKey"`
MapId int
Floors []Floor `gorm:"references:Id"`
}
type Floor struct{
Id int `gorm:"primaryKey"`
BuildingId int
MapId int
}
To clarify, I'm unsure how to get the map ID into the database for the Floor struct and from reading documentation I can't seem to find a way of doing this, if anyone can link to some documentation or an example that would be great, please note: I don't want to hold an instance of the map within the floor just the ID.

Answer for people finding this in the future:
After posting on GORM git page (https://github.com/go-gorm/gorm/issues/3788) i was directed towards hooks: https://gorm.io/docs/hooks.html#Hooks
My code to solve this is to use a before create for each sub level wgere u then set the approriate values iterativly over the list of sub structs like so:
func (building *Building) BeforeCreate(tx *gorm.DB) (err error){
for i := 0; i < len(building.Floors); i++ {
building.Floors[i].MapId = building.MapId
}
return
}

Related

Defining a generics constraint on type fields [duplicate]

I am trying to define a generic function in Go that accepts values that have certain fields, for example, ID int. I have tried several approaches but none seems to work. Here is an example of what I have tried.
package main
import (
"fmt"
)
func Print[T IDer](s T) {
fmt.Print(s.ID)
}
func main() {
Print(Person{3, "Test"})
}
type IDer interface {
~struct{ ID int }
}
type Person struct {
ID int
Name string
}
type Store struct {
ID int
Domain string
}
And here is the playground link: https://gotipplay.golang.org/p/2I4RsUCwagF
In the example above, I want to guarantee every value passed to the Print function has a property ID int, which is also accessible in the function. Is there any way I can achieve this is Go without defining a method in an interface (e.g., GetID() int)?
Is there any way I can achieve this is Go without defining a method in an interface (e.g., GetID() int)?
No, you have to define the method in an interface.
The generics implementation in Go 1.18 doesn't have support for structural types, even though the original type parameters proposal suggests it would. For accessing common fields in a union instead see also this explanation.
Although, I think it's worth it to point out a misconception that can easily arise from your example: the meaning of the approximation ~T (tilde-type) means "the set of types whose underlying type is T.
Now, when you write:
~struct{ ID int }
this means types whose underlying type is exactly struct{ ID int }. No matter what, this does not include structs that have the field ID int and something else. E.g. the underlying type of type Foo struct { ID int; Name string } is struct { ID int; Name string }, and not struct{ ID int }, so that wouldn't satisfy the constraint anyway.
The current time param implementation doesn't have syntax to specify partial struct types. I recall a proposal to add field terms in interface constraints (along with type terms and methods), something on the line:
type IDer interface {
ID int
}
which would enable what you are trying to do without breaking the meaning of the tilde ~. But this won't be included in Go 1.18.

Is there a way we can ensure passed values have certain fields using generics?

I am trying to define a generic function in Go that accepts values that have certain fields, for example, ID int. I have tried several approaches but none seems to work. Here is an example of what I have tried.
package main
import (
"fmt"
)
func Print[T IDer](s T) {
fmt.Print(s.ID)
}
func main() {
Print(Person{3, "Test"})
}
type IDer interface {
~struct{ ID int }
}
type Person struct {
ID int
Name string
}
type Store struct {
ID int
Domain string
}
And here is the playground link: https://gotipplay.golang.org/p/2I4RsUCwagF
In the example above, I want to guarantee every value passed to the Print function has a property ID int, which is also accessible in the function. Is there any way I can achieve this is Go without defining a method in an interface (e.g., GetID() int)?
Is there any way I can achieve this is Go without defining a method in an interface (e.g., GetID() int)?
No, you have to define the method in an interface.
The generics implementation in Go 1.18 doesn't have support for structural types, even though the original type parameters proposal suggests it would. For accessing common fields in a union instead see also this explanation.
Although, I think it's worth it to point out a misconception that can easily arise from your example: the meaning of the approximation ~T (tilde-type) means "the set of types whose underlying type is T.
Now, when you write:
~struct{ ID int }
this means types whose underlying type is exactly struct{ ID int }. No matter what, this does not include structs that have the field ID int and something else. E.g. the underlying type of type Foo struct { ID int; Name string } is struct { ID int; Name string }, and not struct{ ID int }, so that wouldn't satisfy the constraint anyway.
The current time param implementation doesn't have syntax to specify partial struct types. I recall a proposal to add field terms in interface constraints (along with type terms and methods), something on the line:
type IDer interface {
ID int
}
which would enable what you are trying to do without breaking the meaning of the tilde ~. But this won't be included in Go 1.18.

Reflection to get field tag

In Go is there a good way to use reflection to get a field tag by just wrapping a field in a function from the reflect library?
I am basically trying to create a thin data access object that allows be to get the column name in the db without hard coding it all over the place.
Below is the struct with db column names as tags.
// Table Structures
type CusipTableRow struct {
Id int64 `db:"id"`
Cusip string `db:"cusip"`
Symbol string `db:"symbol"`
Active int8 `db:"active"`
Added_Time int32 `db:"added_timestamp"`
Description string `db:"description"`
Exchange string `db:"exchange"`
AssetType string `db:"asset_type"`
}
I am seeking a suggestion other than downloading another library on how to use reflection to essentially make a call like this to return a string with the tag value.
var row CusipTableRow
row.GetColumnName(row.Id) //Return column name based on tag.
I was considering possibly trying to use a map[address] fieldTag, but did not have luck getting that to work perhaps due to not fully having a grasp of the unsafe package. If that approach would have worked I was thinking a call like this could have worked:
row.GetColumnName(&row.Id) //Return column name based on tag.
You can get field tag given the address of the struct and the address of the field. Unsafe shenanigans are not required.
func GetColumnName(pstruct interface{}, pfield interface{}) string {
v := reflect.ValueOf(pstruct).Elem()
for i := 0; i < v.NumField(); i++ {
if v.Field(i).Addr().Interface() == pfield {
return v.Type().Field(i).Tag.Get("db")
}
}
panic("field not in struct")
}
Example use:
var v CusipTableRow
fmt.Println(GetColumnName(&v, &v.Added_Time)) // prints added_timestamp
Run it on the Go Playground.

Golang's GORM not adding associations to "has many" relationship

I just started using GORM and tried to build a "has many relationship". I'm trying to add an association to Previous.Holdings (I think I followed the docs correctly) but when I try to do a select * from previous I don't see anything showing up in the database. Any idea on what I'm missing.
import (
orm "github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Previous struct {
orm.Model
Holdings []Holding `gorm:"foreignkey:ID"`
}
type Holding struct {
ID uint `gorm:"primary_key"`
Symbol string
PurchaseDate time.Time
SellDate time.Time
}
func main() {
t1, _ := time.Parse("2006-01-02", "2017-06-16")
h := Holding{
Symbol: "abc",
PurchaseDate: t1,
}
db.Model(&Previous{}).Association("Holdings").Append(h)
}
First of all you should create your previous table. You can make that by making migrations. You probably should make that migrations after db connection initialization. e.g.
db.AutoMigrate(&Previous{})
So when u using db.Model(&Previous{}) you not saving any entity and if u wanna make asscociation with Holdings entity you need as first step to Save or Find existing Previous record by doing e.g.
previous := &Previous{}
db.Save(previous)
After that you can append your holding record to Model like you do in your code but changing referenced Previous. So it will look like this
h := Holding{
Symbol: "abc",
PurchaseDate: t1,
}
db.Model(previous).Association("Holdings").Append(h)
I don't know if its for testing but when you modeling entities you can make referenced id whithout specifing foreign key also you are using your Holding ID as ForeignKey so ID of Previous will be your ID of Holding.
For me your model declaration should look like this (PreviousID will be automaticaly signed as foreign key for Previous)
type Previous struct {
orm.Model
Holdings []Holding
}
type Holding struct {
ID uint `gorm:"primary_key"`
PreviousID uint
Symbol string
PurchaseDate time.Time
SellDate time.Time
}

How to implement a linked list

I'm trying to implement a sorted linked list in Go. And I'm having a hard time coming up with a generic way to make the linked list work with any type that can by compared with itself. Since its a sorted list, I want the 'go compiler' to ensure that the values being inserted into the linked list can be compared.
For example,
import "linkedlist"
type Person struct {
name string
}
func main() {
l := linkedlist.New()
p := Person{"Jay"}
l.insert(p)
}
In the above example, how do I make the compiler ensure that the value 'p' which has type 'Person' can be compared with another value which also has type 'Person'. I want the compiler to catch the error in those situations where the value being inserted is not an appropriate value.
I can do something like this,
import "linkedlist"
type Element interface {
func IsGreater(v Element{}) bool
}
type Person struct {
name string
age int
}
func (p *Person) IsGreater(p1 interface{}) bool {
if ok, v := p1.(Person); ok && p.age > v.age {
return true
}
return false
}
And then, within the "insert" function of the linked list I can use the IsGreater function to decide where to place the Element in the linked list.
My question is...
Is there a better way to do this? Something that is a lot better than the solution above.
I've already gone through sort.Sort and seen how its done in that package. The way its done there is to create a new type for a slice of the type and then make that new type fulfill the sort interface by implementing Len, Less and Swap.
I can probably do the same thing here in my case as well. But having to create a new slice type and then implement a few functions to satisfy an interface, when I'll only be dealing with 2 values of the same type at a time.. seems a bit overkill to me.
Because Golang do not support generics, So all of containers should use interface{} and type assert, I think no better solution for your requirement.
Library functions for this already exist:
http://golang.org/pkg/container/list/
http://golang.org/pkg/container/ring/
You can compare the lists with reflect.DeepEqual.
If you want to implement a linked list that uses type checking, make an embedded struct for the list type MyLinkedList struct { *list.List} and one for the items in the list type Element struct{ *List.Element }. You can then implement all the methods of list.List and over-ride as necessary with your type checks.

Resources