lundi 20 avril 2015

Insert string array into postgres text array field

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)
    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
pq: array value must start with "{" or dimension information

How do I make use of tagArray?

Helpful reference:

Aucun commentaire:

Enregistrer un commentaire