I'm trying to make an article taggable.
Article table:
type Article struct {
ID int64
Body string
Tags string
}
Preparing values:
tags := r.FormValue("tags")
tagArray := fmt.Sprintf("%q", strings.Split(tags, ", ")) // How do I make use of this?
t := Article{
Body: "this is a post",
Tags: `{"apple", "orange"}`, // I have to hard code this for this to work.
}
if err := t.Insert(Db); err != nil {
// Error handling
}
Database query:
func (t *Article) Insert(db *sqlx.DB) error {
nstmt, err := db.PrepareNamed(`INSERT INTO articles
(body, tags)
VALUES (:body, :tags)
RETURNING *;
`)
if err != nil {
return err
}
defer nstmt.Close()
err = nstmt.QueryRow(t).StructScan(t)
if err, ok := err.(*pq.Error); ok {
return err
}
return err
}
Postgres setup for tags field:
tags character varying(255)[] DEFAULT '{}',
It seems like I have to hard code the value for tags for it to work. Otherwise I would get errors like these:
pq: missing dimension value
OR
pq: array value must start with "{" or dimension information
How do I make use of tagArray
?
Helpful reference: https://gist.github.com/adharris/4163702
You need to format your tags with the proper array input format, the same as your hard-coded value.
The following code will work if the tags don't contain any special characters that need to be escaped differently from how strconv.Quote would escape them:
tags := "apple, orange"
tagArray := strings.Split(tags, ", ")
for i, s := range tagArray {
tagArray[i] = strconv.Quote(s)
}
final := "{" + strings.Join(tagArray, ",") + "}"