This is an automated archive.

The original was posted on /r/golang by /u/kovadom on 2023-08-08 18:05:54+00:00.


I’m trying out a sql builder for the first time (never used ORM either). I’ve seen sqlc is very popular, and checked it out. It seems to generate a lot of boiler code right; but I’ve got few questions on “best practices” or general guide line what is a good design when using it.

I’ve the following struct for my app, which I use for my business logic.

# api/user.go

type UserStorager interface {
        Save(user *User) (int, error)
}

type User struct {
    Name string
    ID   int
}

type UserService struct {
        users map[id]*User
        storage UserStorager
}

# this interface and implementation currently resides at the db package
# db/storage.go

type userStorager { .. }

func (s userStorager) Save(user *User) (int, error) { .. }

I’ve created the relevant sqlc input files (schema.sql, queries.sql) which generated the following code in the db package (omitted irrelevant code for brevity …)

# db/postgres/models.go

type User struct {
ID     int32
Name   string

}

# db/postgres/query.sql.go

type SaveParams struct {
        ID     int32
Name string

}

Which is pretty much the code I would have write when I would implement the model, BUT – since there is a **postgres.User** struct and **api.User** struct, I need another layer of abstraction that wraps the database model.

Or there is another way? What other options do I have to map between the sqlc generated code, and my api package code?

Also, since the code is generated from source files, I think only the source needs to be committed to the git repo (without the generated files). Is my assumption correct?