Docs/Data & Authentication/Built-in ORM

Built-in ORM & Query Builder

Fluent, type-safe database queries with zero runtime reflection overhead.

GoKS includes a lightweight, type-safe Object-Relational Mapper (pkg/orm) with generic query building, automated timestamp management, soft deletes, and seamless multi-database driver support.

Supported Databases

  • SQLite (default):Zero-configuration pure-Go embedded database (orm.OpenSQLite("app.db")).
  • PostgreSQL:High-concurrency enterprise applications (orm.OpenPostgres(dsn)).
  • MySQL / MariaDB:Compatible with existing infrastructure (orm.OpenMySQL(dsn)).

Model Definition

Embedorm.Modelto inherit standard primary keys (ID uint),CreatedAt,UpdatedAt, and soft-deleteDeletedAtfields:

models/user.go
go
package models

import (
	"time"
	"github.com/misbakhul29/goks/pkg/orm"
)

type User struct {
	orm.Model
	Email     string     `db:"email" json:"email"`
	Name      string     `db:"name" json:"name"`
	Role      string     `db:"role" json:"role"`
	IsActive  bool       `db:"is_active" json:"is_active"`
}

Query Builder Example

services/user_service.go
go
package main

import (
	"context"
	"fmt"
	"github.com/misbakhul29/goks/pkg/orm"
	"github.com/user/myapp/models"
)

func main() {
	db, err := orm.OpenSQLite("app.db")
	if err != nil {
		panic(err)
	}

	ctx := context.Background()

	users, err := orm.Query[models.User](db).
		Where("is_active = ?", true).
		Where("role = ?", "admin").
		OrderBy("created_at DESC").
		Limit(10).
		All(ctx)

	for _, u := range users {
		fmt.Printf("Admin: %s (%s)\n", u.Name, u.Email)
	}
}

CRUD Operations

  • orm.Insert(db, &user): Inserts and populates the generated ID.
  • orm.Update(db, &user): Updates modified fields and advances UpdatedAt.
  • orm.Delete(db, &user): Performs soft delete (sets DeletedAt timestamp).
Powered byGoKS WASM16 topics