MySQL Query returning empty result - mysql

I have a simple SELECT statement which calls all of the columns in my coupon table by who_added.
code:
func CouponByUserID(c *gin.Context) {
fmt.Println("CouponByUserID()")
lCoupon := []model.Coupon{}
whoAdded := c.PostForm("whoAdded")
fmt.Println("whoAdded: " + whoAdded)
var sqlSel = ""
sqlSel = sqlSel + " SELECT * FROM coupon WHERE who_added = ? "
fmt.Println("sqlSel")
fmt.Println(sqlSel)
_, err := dbmap.Select(&lCoupon, sqlSel, whoAdded)
if err == nil || lCoupon != nil {
fmt.Println("got result")
fmt.Println(lCoupon)
c.Header("Content-Type", "application/json")
c.JSON(http.StatusOK, lCoupon)
} else {
fmt.Println("coupon not found")
c.JSON(404, gin.H{"error": "coupon not found"})
}
}
Coupon Model:
type Coupon struct {
CouponID int64 `db:"coupon_id, primarykey, autoincrement"`
CouponName string `db:"coupon_name,omitempty"`
CouponCode string `db:"coupon_code,omitempty"`
Description string `db:"description,omitempty"`
Status string `db:"status,omitempty"`
CampaignStart int64 `db:"campaign_start,omitempty"`
CampaignEnd int64 `db:"campaign_end,omitempty"`
SourceType string `db:"source_type,omitempty"`
Preview string `db:"preview,omitempty"`
CouponFormat string `db:"coupon_format,omitempty"`
PreviewType string `db:"preview_format,omitempty"`
Display string `db:"display,omitempty"`
DisplayType string `db:"display_format,omitempty"`
Width float64 `db:"width,omitempty"`
Height float64 `db:"height,omitempty"`
WhoAdded int `db:"who_added,omitempty"`
WhenAdded int `db:"when_added,omitempty"`
WhoUpdated int `db:"who_updated,omitempty"`
WhenUpdated int `db:"when_updated,omitempty"`
TermsAndCondition string `db:"terms_and_condition,omitempty"`
CouponLocation string `db:"coupon_location,omitempty"`
BusID string `db:"bus_id,omitempty"`
ImgCoupon string `db:"img_coupon,omitempty"`
}
Result:
As you can see here it's empty even if my table has data.
Problem: Data on my table is not showing in the result.
I tried to query the same statement on MySQL workbench and it's work just fine.
Where did I go wrong?

Related

How to save a record in a controller to two different tables in go

People, I am trying to save an employee in the employee table, it already saves and everything is fine, the problem is when I try to save the schedule that is related to another table where schedule_id is the foreign of the employee table and is related to the id of the time table, this is the code:
Controlador
func Save(writer http.ResponseWriter, request *http.Request) {
employe := models.Employe{}
db := common.GetConnection()
error := json.NewDecoder(request.Body).Decode(&employe)
if error != nil {
log.Fatal(error)
common.SendError(writer, http.StatusBadRequest)
return
}
randomBytes := make([]byte, 2)
_, err := rand.Read(randomBytes)
if err != nil {
log.Fatal(error)
common.SendError(writer, http.StatusBadRequest)
return
}
employe.PinEmploye = hex.EncodeToString(randomBytes)
horary := models.Employe{Arrival: employe.Arrival, Departure: employe.Departure}
error = db.Save(&horary).Error
if error != nil {
log.Fatal(error)
common.SendError(writer, http.StatusInternalServerError)
return
}
employe.ScheduleId = horary.ID
error = db.Save(&employe).Error
if error != nil {
log.Fatal(error)
common.SendError(writer, http.StatusInternalServerError)
return
}
json, _ := json.Marshal(employe)
common.SendResponse(writer, http.StatusCreated, json)
fmt.Println(employe)
}
structs
type Employe struct {
ID int `json:"id" gorm:"primary_key;auto_increment"`
PinEmploye string `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
FirstName string `json:"first_name" `
LastName string `json:"last_name"`
Company string `json:"company"`
Position string `json:"position"`
ScheduleId int `json:"schedule_id"`
// Arrival time.Time `json:"arrival"`
// Departure time.Time `json:"departure"`
CreatedAt time.Time `json:"fechacreacion"`
}
Horary:
type Horary struct {
ID int `json:"id" gorm:"primary_key;auto_increment"`
Arrival time.Time `json:"arrival"`
Departure time.Time `json:"departure"`
}
I tried to do it with entities but I still don't know very well about the subject
type Employe struct {
ID int `json:"id" gorm:"primary_key;auto_increment"`
PinEmploye string `json:"pinEmploye" gorm:"FOREIGNKEY:PinEmploye" `
FirstName string `json:"first_name" `
LastName string `json:"last_name"`
Company string `json:"company"`
Position string `json:"position"`
ScheduleId int `json:"schedule_id"`
CreatedAt time.Time `json:"fechacreacion"`
}
I have tried with entity model but still can't do it, I tried to do it with chatGPT but still can't

Multiple One to Many Relations in GORM

I have a struct definition in GO like this
package models
//StoryStatus indicates the current state of the story
type StoryStatus string
const (
//Progress indicates a story is currenty being written
Progress StoryStatus = "progress"
//Completed indicates a story was completed
Completed StoryStatus = "completed"
)
//Story holds detials of story
type Story struct {
ID int
Title string `gorm:"type:varchar(100);unique_index"`
Status StoryStatus `sql:"type ENUM('progress', 'completed');default:'progress'"`
Paragraphs []Paragraph `gorm:"ForeignKey:StoryID"`
}
//Paragraph is linked to a story
//A story can have around configurable paragraph
type Paragraph struct {
ID int
StoryID int
Sentences []Sentence `gorm:"ForeignKey:ParagraphID"`
}
//Sentence are linked to paragraph
//A paragraph can have around configurable paragraphs
type Sentence struct {
ID uint
Value string
Status bool
ParagraphID uint
}
I am using GORM for orm in GO.
How do I fetch all the information for a story based on story id like all the paragraphs and all the sentences for each paragraph.
The GORM example show only with 2 models to use preload
This is what you're looking for:
db, err := gorm.Open("mysql", "user:password#/dbname?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
story := &Story{}
db.Preload("Paragraphs").Preload("Paragraphs.Sentences").First(story, 1)
It finds the story with the id = 1 and preloads its relationships
fmt.Printf("%+v\n", story)
This prints out the result nicely for you
Side note:
You can turn on log mode of Gorm so that you can see the underlying queries, to debug, or any other purposes:
db.LogMode(true)
Looking this [example][1] this One to many.
package main
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/kylelemons/godebug/pretty"
)
// Order
type Order struct {
gorm.Model
Status string
OrderItems []OrderItem
}
// Order line item
type OrderItem struct {
gorm.Model
OrderID uint
ItemID uint
Item Item
Quantity int
}
// Product
type Item struct {
gorm.Model
ItemName string
Amount float32
}
var (
items = []Item{
{ItemName: "Go Mug", Amount: 12.49},
{ItemName: "Go Keychain", Amount: 6.95},
{ItemName: "Go Tshirt", Amount: 17.99},
}
)
func main() {
db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
db.LogMode(true)
if err != nil {
log.Panic(err)
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&OrderItem{}, &Order{}, &Item{})
// Create Items
for index := range items {
db.Create(&items[index])
}
order := Order{Status: "pending"}
db.Create(&order)
item1 := OrderItem{OrderID: order.ID, ItemID: items[0].ID, Quantity: 1}
item2 := OrderItem{OrderID: order.ID, ItemID: items[1].ID, Quantity: 4}
db.Create(&item1)
db.Create(&item2)
// Query with joins
rows, err := db.Table("orders").Where("orders.id = ? and status = ?", order.ID, "pending").
Joins("Join order_items on order_items.order_id = orders.id").
Joins("Join items on items.id = order_items.id").
Select("orders.id, orders.status, order_items.order_id, order_items.item_id, order_items.quantity" +
", items.item_name, items.amount").Rows()
if err != nil {
log.Panic(err)
}
defer rows.Close()
// Values to load into
newOrder := &Order{}
newOrder.OrderItems = make([]OrderItem, 0)
for rows.Next() {
orderItem := OrderItem{}
item := Item{}
err = rows.Scan(&newOrder.ID, &newOrder.Status, &orderItem.OrderID, &orderItem.ItemID, &orderItem.Quantity, &item.ItemName, &item.Amount)
if err != nil {
log.Panic(err)
}
orderItem.Item = item
newOrder.OrderItems = append(newOrder.OrderItems, orderItem)
}
log.Print(pretty.Sprint(newOrder))
}
[1]: https://stackoverflow.com/questions/35821810/golang-gorm-one-to-many-with-has-one

Update with 0 value using Gorm

I am trying to update some values using gorm library but bytes and ints with 0 value are not updated
var treatment model.TreatmentDB
err = json.Unmarshal(b, &treatment)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fmt.Println(&treatment)
db := db.DB.Table("treatment").Where("id = ?", nID).Updates(&treatment)
this print value is {0 3 1 0 0 0 2018-01-01 4001-01-01} and those 0 are the byte value (tinyint(1) in database, if I change to int also not working) which are not updated, the rest of values work fine
if I update them without using Gorm this way it's working perfectly with 0 values
var query = fmt.Sprintf("UPDATE `pharmacy_sh`.`treatment` SET `id_med` = '%d', `morning` = '%d', `afternoon` = '%d', `evening` = '%d', `start_treatment` = '%s', `end_treatment` = '%s' WHERE (`id` = '%s')", treatment.IDMed, treatment.Morning, treatment.Afternoon, treatment.Evening, treatment.StartTreatment, treatment.EndTreatment, nID)
update, err := dbConnector.Exec(query)
and this is my model obj
type TreatmentDB struct {
gorm.Model
ID int `json:"id"`
IDMed int `json:"id_med"`
IDUser int `json:"id_user"`
Morning byte `json:"morning"`
Afternoon byte `json:"afternoon"`
Evening byte `json:"evening"`
StartTreatment string `json:"start_treatment"`
EndTreatment string `json:"end_treatment"`
}
Thanks for any help!!
I found a very tricky way to solve this problem.You just need to change your struct field type into a ptr.
change
type Temp struct{
String string
Bool bool
}
to
type Temp struct{
String *string
Bool *bool
}
if you wish save zero you must to write "Select" and put the column to change
db.Model(&user).Select("Name", "Age").Updates(User{Name: "new_name", Age: 0})
reference: https://gorm.io/docs/update.html#Update-Selected-Fields

golang grouping in mysql query

I have a mysql query, struct and code like that:
sqlQuery := "SELECT group_concat(Id), Title from Tbl WHERE SomeField = 3 GROUP BY Title ORDER BY Title LIMIT 20;"
type SomeStruct struct {
IDs []int `json:"ids"`
Title string `json:"title"`
SomeField int `json:"somefield"`
}
type SomeMap map[string]interface{}
var SomeObject []SomeMap
row, err := db.Query(sqlQuery)
checkErr(err)
for row.Next() {
var ids []int
var title string
var somefield int
err = row.Scan(&ids, &title, &somefield)
someMap := SomeMap{"ids":ids, "title": title, "somefield": somefield}
someObject = append(SomeObject, someMap)
}
How can I unmashal my object to struct where IDs look like []int type because golang tells that it might be []uint8 ??

Golang JSON Marshal/Unmarshal postgres now()

I'm using postgres' now() as a default for my created timestamp, which is generates this:
id | user_id | title | slug | content | created
----+---------+-------+------+---------+----------------------------
1 | 1 | Foo | foo | bar | 2014-12-16 19:41:31.428883
2 | 1 | Bar | bar | whiz | 2014-12-17 02:03:31.566419
I tried to use json.Marshal and json.Unmarshal and ended up getting this error:
parsing time ""2014-12-16 19:41:31.428883"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 19:41:31.428883"" as "T"
So I decided to try and create a custom time, but can't seem to get anything working.
Post.go
package models
type Post struct {
Id int `json:"id"`
UserId int `json:"user_id"`
Title string `json:"title"`
Slug string `json:"slug"`
Content string `json:"content"`
Created Tick `json:"created"`
User User `json:"user"`
}
Tick.go
package models
import (
"fmt"
"time"
)
type Tick struct {
time.Time
}
var format = "2006-01-02T15:04:05.999999-07:00"
func (t *Tick) MarshalJSON() ([]byte, error) {
return []byte(t.Time.Format(format)), nil
}
func (t *Tick) UnmarshalJSON(b []byte) (err error) {
b = b[1 : len(b)-1]
t.Time, err = time.Parse(format, string(b))
return
}
Any help would be much appreciated, running what I've wrote here gives me this:
json: error calling MarshalJSON for type models.Tick: invalid character '0' after top-level value
JSON requires strings to be quoted (and in JSON a date is a string), however your MarshalJSON function returns an unquoted string.
I've slightly amended your code and it works fine now:
package models
import (
"fmt"
"time"
)
type Tick struct {
time.Time
}
var format = "2006-01-02T15:04:05.999999-07:00"
func (t *Tick) MarshalJSON() ([]byte, error) {
// using `append` to avoid string concatenation
b := make([]byte, 0, len(format)+2)
b = append(b, '"')
b = append(b, t.Time.Format(format)...)
b = append(b, '"')
return b, nil
}
func (t *Tick) UnmarshalJSON(b []byte) (err error) {
b = b[1 : len(b)-1]
t.Time, err = time.Parse(format, string(b))
return
}
it's seems like you're using the wrong format. Postgres uses RFC 3339, which is already defined in the time package.
This should work:
time.Parse(time.RFC3339, string(b))