Datsik
Datsik

Reputation: 14824

Golang How can I keep my SQL queries out of my code?

I'm stuck on trying to decide the best way to organize sql queries, and code.

Right now I have a models/ folder in my package which contains all my tables, each in their own .go file, which contains a struct that matches the database table.

I've been making a mess of my code though by throwing a ton of sqlQueries into it, especially with transactions and what not.

How exactly can I structure my code, without littering it with SQL queries.

(I don't want to use an ORM to accomplish this)

Upvotes: 3

Views: 3049

Answers (1)

basgys
basgys

Reputation: 4400

You can implement something that looks like a data mapper pattern.

Example from the EAA catalog:

enter image description here

In Go:

model/person.go

type Person struct {
  Lastname   string
  Firstname  string
  Dependents int
}

mapper/person.go

package mapper

import m "whatever/model"

type PersonMap struct { }

func (m *PersonMap) Insert(p *m.Person) error {
  // SQL query
  return nil
}

func (m *PersonMap) Update(p *m.Person) error {
  // SQL query
  return nil
}

func (m *PersonMap) Delete(p *m.Person) error {
  // SQL query
  return nil
}

However, that solution would only be a part of the solution. Regarding the DB transactions, I think you should manage them from another "layer".

Upvotes: 1

Related Questions