-1

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

7
  • can show the exact insert script ?? Commented Apr 20, 2015 at 10:35
  • you mean the database query? I have it here. Commented Apr 20, 2015 at 10:37
  • I meant the fully qualified insert statement i.e insert into table (col1,col2) values(1,'Some_Data') Commented Apr 20, 2015 at 10:39
  • You mean this? INSERT INTO articles (body, tags) VALUES (:body, :tags) RETURNING *; Commented Apr 20, 2015 at 10:41
  • 1
    possible duplicate of Inserting an array into a Postgresql database in Golang Commented Apr 20, 2015 at 12:08

1 Answer 1

0

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, ",") + "}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.