sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Bulk update with pointer to struct slice not working.

Open kamleshkarwande opened this issue 4 years ago • 3 comments

This is the struct

type Role struct {
    Type  string
    Value string
}

database insert query addBulkRole string = "INSERT INTO roles(type,value) VALUES (:type,:value)"

insert query rows, err := repo.db.NamedExec(addBulkRole, roleReq)

here roleReq is a pointer to slice of stuct roleReq *[]models.Role

The error I am getting is echo: http: panic serving [::1]:61689: reflect: call of github.com/jmoiron/sqlx/reflectx.(*Mapper).TraversalsByNameFunc on slice Value

I am using github.com/jmoiron/sqlx v1.3.3 version of sqlx

Not sure what is going wrong.

kamleshkarwande avatar Apr 24 '21 19:04 kamleshkarwande

Bulk insert is supported for []map[string]interface{}.

First at all prepare maps to insert.

var pp []map[string]interface{}
for _, role := range *roleReq {
	pp = append(pp, map[string]interface{}{
		"type": role.Type, "value": role.Value,
	})
}

Then call NamedExec and check result. Pay attention the response type of db.NamedExec is sql.Result from sql/database package.

q := "INSERT INTO roles(type,value) VALUES (:type, :value)"
res, err := repo.db.NamedExec(q, pp)
if err != nil {
	log.Fatal(err)
}
n, err := res.RowsAffected()
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Inserted %d rows\n", n)

gurza avatar May 07 '21 12:05 gurza

Thanks @gurza.

But in my example converting roleReq *[]models.Role to roleReq []models.Role solved the problem.

But can we support pointers in future?

kamleshkarwande avatar May 14 '21 09:05 kamleshkarwande

I got the same problem on version v1.3.5

SenselessA avatar Jul 11 '23 11:07 SenselessA