Below code:
package data
import (
"context"
"encoding/json"
"fmt"
"time"
pgxmock "github.com/pashagolub/pgxmock/v3"
)
type Timestamp struct {
time.Time
}
type Model struct {
Column1 string `db:"col_1_name"`
Column2 Column2Type `db:"col_2_name"`
}
type Column2Type []*T
type T struct {
ID int `json:"id"`
CreatedAt Timestamp `json:"created_at"`
}
func F() {
const tableQuery = `
-- query
SELECT
col_1_name,
col_2_name
FROM table1;
`
mockDBSetupFunc := func(m pgxmock.PgxConnIface) {
t, _ := time.Parse("2006-01-02T15:04:05", "2024-06-25T04:33:55")
// helper to fill column 2
getColumn2 := func() []byte {
c := Column2Type{
&T{
ID: 2,
CreatedAt: Timestamp{Time: t},
},
}
b, err := json.Marshal(c)
if err != nil {
panic(err)
}
return b
}
m.ExpectQuery(tableQuery).
WillReturnRows(pgxmock.NewRows([]string{
"col_1_name",
"col_2_name",
}).AddRow(
"4432",
getColumn2(),
))
}
mockDb, err := pgxmock.NewConn(pgxmock.QueryMatcherOption(pgxmock.QueryMatcherEqual))
if err != nil {
fmt.Printf("failed to set up fake db: %vn", err)
panic(err)
}
mockDBSetupFunc(mockDb)
rows, err := mockDb.Query(context.Background(), tableQuery)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var model Model
if err := rows.Scan(
&model.Column1,
&model.Column2,
); err != nil {
panic(err)
}
fmt.Println(model)
}
}
gives error: panic: Destination kind 'slice' not supported for value kind 'slice' of column 'col_2_name'
on rows.Scan()
Why mismatch on second member type in Model
? on invoking below code:
package main
import (
"github.com/a/b/data"
)
func main() {
data.F()
}