missing destination name field_name in struct model - sql-server

I am using sqlx with mssql driver in golang
here is my struct model :
type Employee struct {
ID string `json:"id,omitempty" validate:"required"`
EmployeeNo int `json:"employeeno,omitempty" validate:"required"`
FullName string `json:"fullname,omitempty" validate:"required"`
}
and here is the rest of the code :
type EmployeeRepo interface {
GetEmployees() (*[]db_models.Employee, error)
}
type employeeRepo struct {
logger *zap.SugaredLogger
db db.DBFactory
}
var _ EmployeeRepo = (*employeeRepo)(nil)
func EmployeeRepoProvider(db db.DBFactory, logger *zap.SugaredLogger) EmployeeRepo {
return &employeeRepo{db: db, logger: logger}
}
func (e *employeeRepo) GetEmployees() (*[]db_models.Employee, error) {
fmt.Println("======= Getting Employees REPOO=======")
employees := &[]db_models.Employee{}
var err error
err = e.db.AuthDB.Select(employees, `SELECT * FROM testEmployees`)
if err != nil {
fmt.Println("err getting emp : ", err)
return nil, err
} else {
return employees, nil
}
}
whenever I try to get data from db I get this :
*missing destination name EmployeeNo in []db_models.Employee
already check issues 234 and 322 and did not work with me

Related

We retriever data and sending a data into database, but its not working

Actually, i create a for loop
(for _, data := range b.CabinBookingRecords )
*, for the pointing array of *CabinBookingRecords *. from this object we retrieving data and sending a data into a data base ,But its not working ,yaa that's it. ***
I'm trying that, pointing bcabinbooking *,In that im using array of pointer *CabinBookingRecords []CabinBookingDetails in this we create a struct CabinBookingDetails in this we create many objects. Problem is their controllers not goes to for loop i think for loop getting something wrong
func (b *CabinBooking) UpdateCabinBooking(id int16, id1 int16) error {
dt := time.Now()
for _, data := range b.CabinBookingRecords {
cBD := new(CabinBookingDetails)
cBD.CityId = data.CityId
cBD.BuildingId = data.BuildingId
cBD.FloorId = data.FloorId
cBD.CabinBookingId = data.CabinBookingId
cBD.CabinId = data.CabinId
cBD.BookingDate = data.BookingDate
cBD.BookedBy = data.BookedBy
cBD.BookingSlot = data.BookingSlot
cBD.BookingSlotHrs = data.BookingSlotHrs
cBD.CancelledBy = data.CancelledBy
cBD.Active = data.Active
fmt.Println(id, " cabinBookingId", id1, "cabinBookingDetailsId", " slot", cBD.BookingSlot, cBD.BookingSlotHrs)
query := "UPDATE cabin_booking_details SET city_id=$1, building_id=$2, floor_id=$3, cabin_id=$4,booking_date=$5, booked_by=$6, booking_slot=$7,booking_slot_hrs=$8, updated_at=$9 WHERE id=$10 AND cabin_booking_id = $11"
d := migration.DbPool.QueryRow(
context.Background(), query, cBD.CityId, cBD.BuildingId, cBD.FloorId, cBD.CabinId, cBD.BookingDate, cBD.BookedBy, cBD.BookingSlot, cBD.BookingSlotHrs, dt, id1, id,
)
err := d.Scan(&b.Id, &b.CreatedAt, &b.UpdatedAt)
if err != nil {
return err
}
}
return nil
}`
func UpdateCabinBooking(c *fiber.Ctx) error {
id := c.Query("cabin_booking_id")
id1 := c.Query("id") //cabin_booking_details_id
i, e := strconv.Atoi(id)
j, e1 := strconv.Atoi(id1)
if e != nil || e1 != nil {
return c.Status(400).SendString(e.Error())
}
cabinBookingId := int16(i)
cabinBookingDetailsId := int16(j)
workspaceParams := new(model.CabinBooking)
workspaceParams.UpdateCabinBooking(cabinBookingId, cabinBookingDetailsId)
fmt.Println("working")
if err := c.JSON(&fiber.Map{
"success": true,
"message": "Cabin Booking successfully updated",
}); err != nil {
return utility.ErrResponse(c, "Error in response", 500, err)
}
return nil
}
and this router......
api.Put("/cabin_workspace", func(c *fiber.Ctx) error {
user := c.Locals("verify")
if user == "true" {
return controller.UpdateCabinBooking(c)
}
return c.SendStatus(fiber.StatusForbidden)
})
type CabinBooking struct {
Id int16 `json:"id"`
BookingDates []string `json:"booking_dates"`
CabinBookingRecords []*CabinBookingDetails `json:"cabin_booking_records"`
Active bool `json:"active"`
BookedBy int16 `json:"booked_by"` //userID
CancelledBy int16 `json:"cancelled_by"` //userID
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type CabinBookingDetails struct {
Id int16 `json:"id"`
CabinBookingId int16 `json:"cabin_booking_id"`
CabinId int16 `json:"cabin_id"`
CityId int16 `json:"city_id"`
BuildingId int16 `json:"building_id"`
FloorId int16 `json:"floor_id"`
BookingDate string `json:"booking_date"`
BookedBy int16 `json:"booked_by"` //userID
CancelledBy int16 `json:"cancelled_by"` //userID
BookingSlot string `json:"booking_slot"`
BookingSlotHrs int16 `json:"booking_slot_hrs"`
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
we sending(retrieving) input from postman(api testing), but update the data base:-
{  
"booking_dates": ["2022-12-30",
               "2022-12-31",
            "2022-12-27"
            ],
    "cabin_booking_records" : [
       {
    "booking_date": "2022-12-30",
        "cabin_id": 1,
        "city_id": 1,
        "building_id" : 1,
        "floor_id" : 1,
        "booking_slot": "First_half",
        "booking_slot_hrs":4,
        "active" : true,
        "booked_by" : 5,
        "canceled_by" : 0
        }
    ],
      "active" : true, 
       "booked_by" : 5,
        "canceled_by" : 0
}

How to insert an array in Postgresql with data from REST echo

I receive data into my echo rest api by post method. I have two arrays. I import pq library.
My structure is
type Lien struct {
LinkID int `json: "linkID"`
Linklabel string `json: "label"`
Linkaddress string `json: "address"`
Langs []string `json: "langs"`
Cats []int `json: "cats"`
}
My post function is
func createLink(c echo.Context) error {
l := new(Lien)
if err := c.Bind(l); err != nil {
return err
}
sqlStatement := "INSERT INTO link_test (label, address,langs, cats)VALUES ($1, $2, $3, $4)"
res, err := db.Query(sqlStatement, l.Linklabel, l.Linkaddress, pq.Array(l.Langs), pq.Array(l.Cats))
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
return c.JSON(http.StatusCreated, l)
}
return c.String(http.StatusOK, "ok")
}
It works for the first two fields but not for the arrays, I always get a null value.

Select in Golang

I want to connect a MSSQL database, in python I get connecting to this database but in Go I can not.
When I exec this code I receive this error:
2017/08/04 12:25:39 Select failed:Login error: EOF
why?
Code:
package main
import (
"database/sql"
"flag"
"fmt"
"log"
_ "github.com/denisenkom/go-mssqldb"
)
var (
debug = flag.Bool("debug", false, "enable debugging")
password = flag.String("password", "********", "the database password")
port *int = flag.Int("port", 1433, "the database port")
server = flag.String("server", "sql2008v\\2k8", "the database server")
user = flag.String("user", "usuario", "the database user")
)
func main() {
flag.Parse()
if *debug {
fmt.Printf(" password:%s\n", *password)
fmt.Printf(" port:%d\n", *port)
fmt.Printf(" server:%s\n", *server)
fmt.Printf(" user:%s\n", *user)
}
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d", *server, *user, *password, *port)
if *debug {
fmt.Printf(" connString:%s\n", connString)
}
conn, err := sql.Open("mssql", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer conn.Close()
rows, err := conn.Query("SELECT TOP (1000) * FROM [jiradb].[jiraschema].[jiraissue]")
if err != nil {
log.Fatal("Select failed:", err.Error())
}
defer rows.Close()
fmt.Printf("bye\n")
}

Compile error on type comparison

I get the compile error shown below saying that the ErrFieldMismatch type is missing an Error() method, but as shown in the last code chunk, it is not.
Any idea to why I cannot perform the type comparison for this?
Error
impossible type switch case: err (type error) cannot have dynamic type "google.golang.org/appengine/datastore".ErrFieldMismatch (missing Error method)
my code
type Program struct {
aemodel.Base
Name string `json:"name" required:"true"`
Public bool `json:"isPublic"`
Description string `json:"description" required:"true"`
Default bool `json:"isDefault"`
Tags []string `json:"tags"`
// Level int
}
// Load - PropertyLoadSaver interface
func (p *Program) Load(ps []datastore.Property) error {
if err := datastore.LoadStruct(p, ps); err != nil {
switch err.(type) {
case datastore.ErrFieldMismatch: // <-- Failure point
return nil
default:
return err
}
}
return nil
}
appengine code
type ErrFieldMismatch struct {
StructType reflect.Type
FieldName string
Reason string
}
func (e *ErrFieldMismatch) Error() string {
return fmt.Sprintf("datastore: cannot load field %q into a %q: %s",
e.FieldName, e.StructType, e.Reason)
}
Error method is defined on the type that is a pointer to datastore.ErrFieldMismatch, i.e., Error is defined on *datastore.ErrFieldMismatch, hence it's only *datastore.ErrFieldMismatch that implements the Error interface.
Try changing your case expression:
func (p *Program) Load(ps []datastore.Property) error {
if err := datastore.LoadStruct(p, ps); err != nil {
switch err.(type) {
case *datastore.ErrFieldMismatch: // use pointer type here
return nil
default:
return err
}
}
return nil
}

How to sort slices in GAE Go

I am trying to sort slices. How to this in gae using go?
I have struct
type courseData struct {
Key *datastore.Key
FormKey *datastore.Key
Selected bool
User string
Name string
Description string
Date time.Time
}
I would like to sort slice of this entity kind in the Name field.
q := datastore.NewQuery("Course")
var courses []*courseData
if keys, err := q.GetAll(c, &courses); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
for i := range courses {
courses[i].Key = keys[i]
}
}
I tried the
Sort(data Interface)
but not sure how to use it.
Please help. Thanks!
For example,
package main
import (
"fmt"
"sort"
"time"
)
type Course struct {
Key string // *datastore.Key
FormKey string // *datastore.Key
Selected bool
User string
Name string
Description string
Date time.Time
}
type Courses []*Course
func (s Courses) Len() int { return len(s) }
func (s Courses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByName struct{ Courses }
func (s ByName) Less(i, j int) bool { return s.Courses[i].Name < s.Courses[j].Name }
func main() {
var courses = Courses{
&Course{Name: "John"},
&Course{Name: "Peter"},
&Course{Name: "Jane"},
}
sort.Sort(ByName{courses})
for _, course := range courses {
fmt.Println(course.Name)
}
Output:
Jane
John
Peter
Course and Courses need to be exported for use by the sort package.
To avoid making the example dependent on GAE, type *datastore.Key was changed to string.
Why not just ask for the entities in the correct order from the datastore?
q := datastore.NewQuery("Course").Order("Name")

Resources