I have a function that generates a prepared statement for batch insert into postgres where I am trying to insert the string into type jsonb in postgres.
My struct looks like:
type struct1 struct {
id int
comment string
extra string
}
and my table schema looks like:
create table deal (
id bigserial,
comment varchar(75),
extra jsonb
)
and I want to dump []struct1 to Postgres DB "deal".
My function which generates the prepared statement looks like this:
func BulkInsert(str []struct1, ctx context.Context) string {
log.Debug("inserting records to DB")
query := fmt.Sprintf(`insert into deal (%s) values `, strings.Join(dbFields, ","))
var numFields = len(dbFields)
var values []interface{}
for i, database := range str {
values = append(values, database.Comment,`'`+database.Extra+`'`)
n := i * numFields
query += `(`
for j := 0; j < numFields; j++ {
query += `$` + strconv.Itoa(n+j+1) + `,`
}
query = query[:len(query)-1] + `),`
}
query = query[:len(query)-1]
return query
Expected results should be: I should be able to insert string to json or you can say cast string to json and dump it.
The actual result is :
could not save batch: pq: invalid input syntax for type json"
`'`+database.Extra+`'::jsonb`? And doesdatabase.Extrahold valid json format?'`+database.Extra+`'::jsonbdo not work I tried''(single quote string) is invalid json. So if extra is empty you have to provide "some" json, e.g.'{}', or'""'.::jsonbshould be appended to the parameter reference ($2::jsonb) and not the parameter itself.