Golang: sqlx StructScan mapping db column to struct - go

i have my model struct like the below :
type Detail struct {
Product
Stocks
}
type Product struct {
Name string `db:"name"`
Id int `db:"id"`
}
type Stocks {
Name string `db:"name"`
Price float `db:"price"`
Type string `db:"type"`
}
i would have a query to join the above tables like the below :
query, args, err := sqlx.In("select p.name , s.price from Product p,Stocks s where p.name=s.name and type IN (?)",typecodes)
query = s.Cmd.Db.Rebind(query)
var rows *sqlx.Rows
rows, err = s.Cmd.Db.Queryx(query, args...)
for rows.Next() {
var p model.Detail
err = rows.StructScan(&p)
}
Would like to know when i do rows.StructScan(&p) will the Product structure Name field be populated or will there be any ambuigity found for the same since Stocks also have a Name field ?
Currently i am not getting any result for the above.But when i comment the Name field in the Stocks struct, i am getting the data.
Let me know what i am missing here.

For ambiguous fields you're best annotating them with a prefix of their struct name, e.g. product_name, stock_name, then alias them appropriately in your SQL statement.
I.e.
type Detail struct {
Product
Stocks
}
type Product struct {
Name string `db:"product_name"`
Id int `db:"id"`
}
type Stocks {
Name string `db:"stock_name"`
Price float `db:"price"`
Type string `db:"type"`
}
And in your SQL:
SELECT p.name AS product_name, s.name AS stock_name, ... FROM Product p, Stocks s WHERE ...

Related

GORM select certain column with preload

Let's say I have these struct that represent my models
type QuestionHeader struct {
QuestionHeaderId int `gorm:"primaryKey;column:question_id" json:"question_id"`
LevelId int `gorm:"column:level_id" json:"level_id"`
SubjectId int `gorm:"column:subject_id" json:"subject_id"`
QuestionBody []QuestionBody
QuestionSolution []QuestionSolution
OtherColumn1A string
OtherColumn2A string
}
type QuestionBody struct {
QuestionBody int `gorm:"primaryKey;column:question_id" json:"question_id"`
Value string `gorm:"column:value" json:"value"`
Type string `gorm:"column:type" json:"type"`
OtherColumn1B string
OtherColumn2B string
}
type QuestionSolution struct {
QuestionSolutionId int `gorm:"primaryKey;column:question_id" json:"question_id"`
Value string `gorm:"column:value" json:"value"`
Type string `gorm:"column:type" json:"type"`
OtherColumn1C string
OtherColumn2c string
}
Then I want to do a query with preload like this
qs.db().
Preload("QuestionHeader.QuestionBody", func(db *gorm.DB) *gorm.DB {
return db.Where("question_body.status = ?", 1)
// I only want to select certain column here
}).
Preload("QuestionHeader.QuestionSolution", func(db *gorm.DB) *gorm.DB {
return db.Where("question_solution.status = ?", 1)
// I only want to select certain column here
}).
Where("level_id = ?", 2).
Find(&questionHeaders) // I only want to select certain column here
But the catch with that code is, I will select all the columns based on my model property
What if I want to select only a certain column with preload?
For example, I want to select only type for QuestionBody
I know that you can create another struct for your select statement as described in the docs, but are there any other ways? I don't want to create a struct for every select statement
In Laravel Eloquent, you can do something like this
There are few issue that i would like to point out
You don't have the many2many association defined in QuestionHeader for QuestionBody or QuestionSolution
In query you are using status column but I don't seem them defined in QuestionBody or QuestionSolution
Rename QuestionBody id column to QuestionBodyId in QuestionBody
As per the points changes would be as below:
type QuestionHeader struct {
QuestionHeaderId int `gorm:"primaryKey;column:question_id" json:"question_id"`
LevelId int `gorm:"column:level_id" json:"level_id"`
SubjectId int `gorm:"column:subject_id" json:"subject_id"`
QuestionBody []QuestionBody `gorm:"many2many:question_header_question_bodies;"`
QuestionSolution []QuestionSolution `gorm:"many2many:question_header_question_solutions;"`
OtherColumn1A string
OtherColumn2A string
}
type QuestionBody struct {
QuestionBodyId int `gorm:"primaryKey;column:question_id" json:"question_id"`
Value string `gorm:"column:value" json:"value"`
Type string `gorm:"column:type" json:"type"`
Status uint8 `gorm:"column:status;default:0" json:"status"`
OtherColumn1B string
OtherColumn2B string
}
type QuestionSolution struct {
QuestionSolutionId int `gorm:"primaryKey;column:question_id" json:"question_id"`
Value string `gorm:"column:value" json:"value"`
Type string `gorm:"column:type" json:"type"`
Status uint8 `gorm:"column:status;default:0" json:"status"`
OtherColumn1C string
OtherColumn2c string
}
var questionHeaders QuestionHeader
db.
Preload("QuestionBody", func(db *gorm.DB) *gorm.DB {
return db.Where("Status = ?", 1).Select("QuestionBodyId", "Value")
}).
Preload("QuestionSolution", func(db *gorm.DB) *gorm.DB {
return db.Where("Status = ?", 1).Select("QuestionSolutionId", "Value")
}).
Where("level_id = ?", 2).
Select("SubjectId").
Find(&questionHeaders)
}
In Preload Select we would have to include the unique primary key for gorm to uniquely identify the associated slice of structs

One-to-many association

I'm having troubles with one-to-many associations in GORM.
I have those two structures and I'd like to get one patient's full history. Here is my sample code:
type Patient struct {
gorm.Model
Prenom string `json:"prenom" gorm:"column:patient_prenom"`
Nom string `json:"nom" gorm:"column:patient_nom"`
Genre string `json:"genre" gorm:"column:patient_genre"`
Naissance string `json:"naissance" gorm:"column:patient_naissance"`
Historique []Historique `gorm:"ForeignKey:Fk_patient_id"`
}
type Historique struct {
Fk_patient_id string
Date_consultation string
Fk_maladie_id uint
Fk_compte_medecin_id uint
Patient Patient
}
func GetPatientWithDiseases(id uint) (*Patient, error) {
patient := &Patient{}
//The line right there works so i can retrieve without the history
//err := GetDB().Find(patient, id).Error
db := GetDB().Preload("tt_historique").Find(patient)
err := db.Error
if err != nil {
return nil, err
}
return patient, nil
}
Where "Historique" uses the foreign key of the patient (Fk_patient_id), and the Historique []Historique is the list of every Historique that should end up in the Patient struct after the query.
However I get this error can't preload field tt_historique for models.Patient. I've tried multiple syntaxes that I've found on Internet in the gorm specifications in the struct but nothing worked. I've only been developing using GO for 3 days and GORM is my first ORM, so maybe I'm missing something really obvious.
Based on the presumption that tt_historique is your table name, there are a couple of things you need to take care of here.
By convention, go-gorm uses pluralized snake case struct names as database tables when constructing a SQL query. In your case, to preload the Historique []Historique field, it would look for the historiques table.
To override this, you need to implement the Tabler interface:
type Patient struct {
gorm.Model
Prenom string `json:"prenom" gorm:"column:patient_prenom"`
Nom string `json:"nom" gorm:"column:patient_nom"`
Genre string `json:"genre" gorm:"column:patient_genre"`
Naissance string `json:"naissance" gorm:"column:patient_naissance"`
Historique []Historique `gorm:"foreignKey:Fk_patient_id"`
}
type Historique struct {
Fk_patient_id string
Date_consultation string
Fk_maladie_id uint
Fk_compte_medecin_id uint
Patient Patient
}
func (Historique) TableName() string {
return "tt_historique"
}
Then, your query would look like this:
db := GetDB().Preload("Historique").Find(patient)

"doesn't have relation" from go-pg

I am trying to pull data for CountyEntity that related with CityEntity:
type CityEntity struct {
tableName struct{} `pg:"city,alias:ci,discard_unknown_columns"`
Id string `pg:"id"`
Name string `pg:"name"`
}
type CountyEntity struct {
tableName struct{} `pg:"county,alias:co,discard_unknown_columns"`
Id int64 `pg:"id"`
Name string `pg:"name"`
DefaultTargetXDockId int64 `pg:"defaulttargetxdockid"`
MapsPreference string `pg:"mapspreference"`
EmptyDistrictAllowed bool `pg:"empty_district_allowed"`
CityId int64 `pg:"cityid"`
City *CityEntity `pg:"fk:cityid"`
}
My query is:
db, _ := repository.pgRepository.CreateDBConnection(.....)
var counties []model.CountyEntity
err := db.Model(&counties).
Join("inner join test.city ci on ci.id = co.cityid").
Relation("City").
Where("co.cityid = ?", cityId).
Select()
return counties, err
it throws that:
model=CountyEntity does not have relation="City"
But actually, I have the relation between city and county table on the database.
Db Relation Image
I tried different ways to solve but I couldn't solve it. Does anybody have an idea about what is the root cause of it and what is the possible solutions?
Pretty old and I'm sure you've figured it out by now, but for anyone else that stumbles across this your model should look like this
type CountyEntity struct {
tableName struct{} `pg:"county,alias:co,discard_unknown_columns"`
Id int64 `pg:"id"`
Name string `pg:"name"`
DefaultTargetXDockId int64 `pg:"defaulttargetxdockid"`
MapsPreference string `pg:"mapspreference"`
EmptyDistrictAllowed bool `pg:"empty_district_allowed"`
CityId int64 `pg:"cityid"`
City *CityEntity `pg:"rel:has-one,fk:cityid"`
}
Notice the "rel:has-one" added to the city column. You can find more information about all of these here: https://pg.uptrace.dev/models/

Gorm WHERE clause not working on Preload data

This query here below works, where the where clause works becuase it's using values from ResourceUsage struct, but I would love to be able to do something like this, where the where clause is using value from the ResourceMetadata struct.
db.Preload("ResourceMetadata").Where("resource_type = ?", resourceType).Where("timestamp BETWEEN ? AND ?", start, end).Limit(10).Find(&resourceUsage)
But it throws exception:
2019-12-03 11:06:12] Error 1054: Unknown column 'resource_type' in 'where clause'
Code:
// ResourceUsage describes the storage model for resource-usage
type ResourceUsage struct {
ID int64 `json:"-"`
DetailsID int64 `json:"details_id"`
ResourceMetadata *ResourceMetadata `gorm:"foreignkey:DetailsID;association_foreignkey:ID"`
MeasuredType string `json:"measured_type"`
Quantity float64 `json:"quantity"`
Timestamp int64 `json:"timestamp"`
}
// ResourceMetadata describes the storage model for resource-usage
type ResourceMetadata struct {
ID int64 `json:"-"`
ResourceUUID string `json:"resource_uuid"`
ResourceName string `json:"resource_name"`
ResourceDisplayName string `json:"resource_display_name"`
ResourceType string `json:"resource_type"`
}
db.Preload("ResourceMetadata").Where("timestamp BETWEEN ? AND ?", start, end).Limit(10).Find(&resourceUsage)
Can you use a JOIN?
resourceUsages := []ResourceUsage{}
if err := db.Joins("JOIN resource_metadata ON resource_metadata.id=details_id").
Where("resource_metadata.resource_type = ? AND timestamp BETWEEN ? AND ?", resourceType, start, end).
Preload("ResourceMetadata").Limit(10).
Find(&resourceUsages).Error; err != nil {
// ... handle error ...
}

JOIN using sqlx causes 'missing destination name'

I have this query that works fine on mysql and return the intended result, but sqlx has difficulty to handle it:
var jokes []model.Joke
err := shared.Dbmap.Select(&jokes, "SELECT * FROM joke INNER JOIN jokevote ON joke.id=jokevote.joke_id AND jokevote.vote=? AND joke.user_id=?", 1, userId)
if err != nil {
log.Println(err)
}
At runtime, I get no result but this error message in terminal:
missing destination name joke_id
I don't have this issue when querying a single table.
So I'm wondering what is wrong here and how to fix it?
UPDATE: Here are the structs:
type Joke struct {
ID int `db:"id" json:"id"`
UserID int `db:"user_id" json:"user_id"`
Title string `db:"title" json:"title"`
Content string `db:"content" json:"content"`
...
}
type JokeVote struct {
ID int `db:"id" json:"id"`
JokeID int `db:"joke_id" json:"joke_id"`
UserID int `db:"user_id" json:"user_id"`
Vote int `db:"vote" json:"vote"`
}
When you execute "SELECT * FROM joke INNER JOIN jokevote" you will get columns from both joke and jokevote tables.
Try to query "SELECT joke.* FROM joke INNER JOIN jokevote" to get only columns from joke table.

Resources