README
ΒΆ
SQLink
SQLink is a modern, type-safe, and lightweight ORM for Go, built with the power of generics.
β¨ Features
- Type-Safe by Design: Uses Go generics to catch database field and type errors at compile time.
- Fluent & Chainable API: Write clean, readable, and expressive database queries.
- High Performance: Smart schema caching minimizes reflection overhead for production speed.
- Flexible Querying: Supports complex
AND/ORconditions,IN, andNOT. - Standard Library Core: Built on top of the native
database/sqlfor broad compatibility. - Rich Querying:
GROUP BY/HAVING/DISTINCT, ordering, aggregates (Sum/Avg/Max/Min),Pluck, and raw SQL. - Model Operations:
Save/UpdateModel/DeleteByPrimaryKey,Upsert, and lifecycle hooks (Before/AfterCreate/Update/Delete). - Schema Tools:
AutoMigrate,HasTable/DropTable,AddColumn/RenameColumn,CreateIndex, and custom table names viaTableName(). - Associations:
HasMany/HasOne/BelongsTowith eagerPreload.
π Installation
To get started, use go get to add Go-Sqlink to your project.
go get github.com/Kaguya233qwq/sqlink
You'll also need a database driver. SQLink ships with dialects for SQLite, MySQL/MariaDB, and PostgreSQL.
go get github.com/glebarez/go-sqlite # SQLite (pure Go)
go get github.com/go-sql-driver/mysql # MySQL / MariaDB
go get github.com/jackc/pgx/v5 # PostgreSQL (driver name "pgx")
π‘ Usage
Define Your Model
Define your model using standard Go structs. Use the db tag to specify the column name. orm.Field[T] is a generic wrapper that gracefully handles nullable values.
import "github.com/Kaguya233qwq/sqlink/orm"
type User struct {
ID orm.Field[int] `db:"id"`
Name orm.Field[string] `db:"name"`
Age orm.Field[int] `db:"age"`
IsAdmin orm.Field[bool] `db:"is_admin"`
}
Connect and Migrate
Open a database connection and create the table schema with AutoMigrate.
import (
"github.com/Kaguya233qwq/sqlink/orm"
_ "github.com/glebarez/go-sqlite"
)
func main() {
db, err := orm.OpenDB("sqlite", "test.db")
if err != nil {
panic(err)
}
defer db.Close()
// Enable the colorful logger
db.Logger = orm.NewDefaultLogger(os.Stdout)
// Configure connection pool via underlying *sql.DB
if sqlDB, err := db.DB(); err == nil {
sqlDB.SetMaxOpenConns(25)
sqlDB.SetMaxIdleConns(10)
}
// Create the 'User' table if it doesn't exist
if err := db.AutoMigrate(User{}); err != nil {
panic(err)
}
}
Create Records
Use the Create method to insert new records.
newUser := &User{
Name: orm.Field[string]{Value: "alice", Valid: true},
Age: orm.Field[int]{Value: 25, Valid: true},
IsAdmin: orm.Field[bool]{Value: false, Valid: true},
}
err := orm.Query[User](db).Create(newUser)
if err != nil {
// Handle error
}
Query Records
Querying is type-safe and fluent. Access your model's schema via the .Schema field.
Get the First Record
var alice User
q := orm.Query[User](db)
err := q.Where(q.Schema.Name.Is("alice")).First(&alice)
if err != nil {
if errors.Is(err, orm.ErrRecordNotFound) {
fmt.Println("User not found")
}
// Handle other errors
}
fmt.Printf("Found: %s, Age: %d\n", alice.Name.Value, alice.Age.Value)
Get Multiple Records
var allUsers []User
q := orm.Query[User](db)
// Find all users older than 20
err := q.Where(q.Schema.Age.Gt(20)).Find(&allUsers)
if err != nil {
// Handle error
}
for _, user := range allUsers {
fmt.Println(user.Name.Value)
}
Complex Queries
Combine conditions with orm.And, orm.Or, and orm.Not.
// Find admins OR users older than 30 named 'bob'
var results []User
q := orm.Query[User](db)
err := q.Where(
orm.Or(
q.Schema.IsAdmin.Is(true),
orm.And(
q.Schema.Age.Gt(30),
q.Schema.Name.Is("bob"),
),
),
).Find(&results)
Query Cloning & Branching
Use .Clone() to safely branch off a base query or share query templates across concurrent goroutines without mutating the original query or creating race conditions:
baseQ := orm.Query[User](db).Where(userSchema.Age.Gt(18))
// Branch 1: Active admins
var admins []User
err := baseQ.Clone().Where(userSchema.IsAdmin.Is(true)).Find(&admins)
// Branch 2: Non-admins with pagination (baseQ remains completely untouched)
var nonAdmins []User
err = baseQ.Clone().Where(userSchema.IsAdmin.Is(false)).Limit(10).Find(&nonAdmins)
Update and Delete
Updating and deleting records is just as straightforward.
q := orm.Query[User](db)
// Update
err := q.Where(userSchema.Name.Is("alice")).Update(map[string]interface{}{"age": 26})
// Delete
err = q.Where(userSchema.Name.Is("alice")).Delete()
π§ͺ Testing
The unit test suite runs against an in-memory/temp SQLite database and needs no external service:
go test ./...
Integration tests against live MariaDB/MySQL and PostgreSQL servers are gated on environment variables and are skipped when unset:
SQlink_TEST_MYSQL_DSN="user:pass@tcp(127.0.0.1:3306)/sqlink?parseTime=true" \
SQlink_TEST_POSTGRES_DSN="postgres://user:pass@127.0.0.1:5432/sqlink" \
go test ./orm/ -run 'TestIntegration' -v
π Acknowledgements
This project was inspired by the elegance of modern ORMs and the power of Go generics. A special thanks to the creators of projects like GORM and Bun for paving the way.
π License
Go-Sqlink is released under the MIT License. See the LICENSE file for more information.
Documentation
ΒΆ
There is no documentation for this package.