Thomas McGoey-Smith

Working with SQL & Structs in Golang

Side: This is a post in my on going series about Rewriting Has It Shipped Yet in Go.

Right now I’m in the midst of rewriting the backend database models.

One issue I ran into was working with SQL & Go.

I have this Shop struct for my Shop Model, it looks like this:

// Shop - represents a Shop in the DB
type Shop struct {
  ID   string `json:"id" db:"-"`
  UUID []byte `json:"-" db:"id"`
  Name string `json:"name" db:"name"`

  Address1    string `json:"address1" db:"address1"`
  City        string `json:"city" db:"city"`
  Province    string `json:"province" db:"province"`

  // ... left some out for clarity

I’ve setup a similar structure in my MySQL table (see the db tags).

The problem I faced was writing a simple Insert query - like this:

INSERT INTO shops (id, name, address1) VALUES ("byte_uuid_string", "Not Your Mothers Buttons", "48 Cimarron Drive")

It works, but when your struct starts to become bigger and bigger (like mine did), it becomes harder and harder to write your SQL (mostly making small syntax errors). Just to give you an idea, I tried to seperate out the fields so that everyline there were only 3.

This works. But it sucks!

Now, there is a really two options you can do.

1) Suck it up, and hope you don’t make silly mistakes - basically just do what I did above. 2) Jump over to a “ORM”-like library. Something like gorp.

Number 1 was pretty problematic. But trying to use a ORM in go felt a bit too bloated and had too much magic.

After some research and trial and error. I was able to come across sqlx.

It’s pretty slick.

The main benefit is that you can use a struct (like my Shop one above) and modify your

@tamcgoey on Oct 30, 2015

Enjoyed the article? Subscribe to my newsletter for more.

© Thomas McGoey-Smith (2014-2018). RSS.