I have the json field like blow which I want to store in database
{
id: 1
name: "test entity 1"
description: "a test entity for some guy's blog"
status: "passed"
web_url: "http://localhost:3000"
jobs: [{
id: "1"
name: "test1"
status: "passed"
},
{
id: "2"
name: "test2"
status: "passed"
},
{
id: "3"
name: "test3"
status: "failed"
}]
}
I proceed with one way like for creating table uses:
CREATE TABLE test3 (id INT PRIMARY KEY, name VARCHAR, description VARCHAR, status VARCHAR, web_url VARCHAR, jobs JSON[]);
and for Inserting data uses:
sqlStatement := `
INSERT INTO jobs (id, name, description, status, web_url, jobs)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (id) DO UPDATE
SET status = $4
RETURNING id`
id := 0
err = database.Db.QueryRow(sqlStatement, y[i].ID, y[i].Name, y[i].Description, y[i].Status, y[i].WebURL, jobsdata).Scan(&id)
if err != nil {
panic(err)
}
But won't work, need help!!
Getting errors:
panic: sql: converting argument $6 type: unsupported type handler.Jobs, a slice of struct
What i want:
postgres=# SELECT * FROM test3;
id | name | description | status | web_url | jobs
------+------------------------------------------+--------+---------+----------------------------------------------------------+----------------------------------------------------------
1 | test entity 1 | a test entity for some guy's blog | passed | https://localhost:3000 | {id: "1",name: "test1", status: "passed"},{id: "2",name: "test2", status: "passed"},{id: "3",name: "test3", status: "failed"}
As the error indicates, you're trying to bind the sixth value from an unsupported data type, handler.Jobs
. You haven't told us what this type is, but from the error, it's clear that it does not implement the driver.Valuer
interface, so it won't work, because it has no way of knowing how to represent that value to the database.
You'll need to implement that interface, by adding a Value()
method to the handler.Jobs
type, or use a different data type.
sqlx has a type JSONText in github.com/jmoiron/sqlx/types that will do what you need.