sqlgen

sqlgen is not an ORM, it's a code generator instead. It parse the go struct and generate the necessary struct methods for you.
What is sqlgen?
- sqlgen is based on a Code first approach — You don't require to write SQL first, but Go code instead.
- sqlgen enables Codegen — We generate the boring bits, so you can focus on building your app quickly.
- sqlgen prioritizes Performance — Most of the things will define in compile time instead of runtime.
- sqlgen embrace Generics — We use generics to eliminate runtime reflection costs and reduce memory allocation.
- sqlgen eliminates Side Effects - You will get expected results instead of side effects when mutate your models.
- sqlgen has ZERO Dependencies - It has no dependencies at all, it only rely on the standard library.
- sqlgen support dynamic query - It provide multiple insert, multiple upsert and pagination which sqlc doesn't able to provide.
SQL driver support
| Driver |
Support |
mysql |
✅ |
postgres |
✅ |
sqlite |
✅ |
Quick start
-
Install sqlgen.
go install github.com/si3nloong/sqlgen/cmd/sqlgen@main
-
Define your model struct.
model/user.go
package model
import "time"
type LongText string
type User struct {
ID int64 `sql:",auto_increment"`
Name string
Age uint8
Address LongText
Created time.Time
}
-
Generate the output files.
# sqlgen generate <source_file>
sqlgen generate model/user.go
-
Generated code will be as follow.
model/generated.go
// Code generated by sqlgen. DO NOT EDIT.
package model
import (
"database/sql/driver"
"time"
"github.com/si3nloong/sqlgen/sequel/types"
)
func (User) TableName() string {
return "`user`"
}
func (User) Columns() []string {
return []string{"`id`", "`name`", "`age`", "`address`", "`created`"}
}
func (v User) IsAutoIncr() {}
func (v User) PK() (columnName string, pos int, value driver.Value) {
return "`id`", 0, int64(v.ID)
}
func (v User) Values() []any {
return []any{int64(v.ID), string(v.Name), int64(v.Age), string(v.Address), time.Time(v.Created)}
}
func (v *User) Addrs() []any {
return []any{types.Integer(&v.ID), types.String(&v.Name), types.Integer(&v.Age), types.String(&v.Address), (*time.Time)(&v.Created)}
}
More help to get started:
Benchmark
As you can see, sqlgen is perform as close as Raw query, and having low memory allocations.
Reporting Issues
If you think you've found a bug, or something isn't behaving the way you think it should, please raise an issue on GitHub.
Contributing
We welcome contributions, Read our Contribution Guidelines to learn more about contributing to sqlgen
Inspired By
License
MIT
Copyright (c) 2023-present, SianLoong Lee