gormen

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2026 License: MIT Imports: 5 Imported by: 0

README

gormen

Go library for enhancing Gorm (CRUD, Hexagonal Architecture, Paging, Sorting and Filtering)

Description

This library provides a high-level, ergonomic API for enhancing Gorm. It offers a CRUD API, Paging, Sorting and Filtering. Allowing simple implementation or hexagonal architecture decoupling interface. Roughly inspired in Java CrudRepository and PagingAndSortingRepository interfaces.

Caveats

  • This library requires Go 1.23+

Intallation

go get -u github.com/javiorfo/gormen@latest

Example Std Repository

More examples here
package main

import (
  "context"
  "log"
  "github.com/glebarez/sqlite"
  "github.com/javiorfo/gormen"
  "github.com/javiorfo/gormen/pagination/sort"
  "github.com/javiorfo/gormen/std"
  "github.com/javiorfo/gormen/where"
  "gorm.io/gorm"
)

func main() {
  ctx := context.Background()

  var repo gormen.Repository[UserDB]
  repo = std.NewRepository[UserDB](SetupDB())

  user1 := UserDB{
    Username: "batch1",
    Password: "1234",
    Person: PersonDB{
      Name:  "Batch 1",
      Email: "b1@mail.com",
    },
  }
  user2 := UserDB{
    Username: "batch2",
    Password: "1234",
    Person: PersonDB{
      Name:  "Batch 2",
      Email: "b2@mail.com",
    },
  }	
  user3 := UserDB{
    Username: "batch3",
    Password: "1234",
    Person: PersonDB{
      Name:  "Batch 3",
      Email: "b3@mail.com",
    },
  }
  users := []UserDB{user1, user2, user3}

  err = repo.CreateAll(ctx, &users, 3)
  if err != nil {
    log.Fatalf("Error creating users %v", err)
  }

  user, _ := repo.FindBy(ctx, gormen.NewWhere(where.Like("username", "2%")).Build(), "Person")
  log.Printf("%+v", user)

  orders := []sort.Order{sort.NewOrder("username", sort.Descending)}
  users, err = repo.FindAllOrdered(ctx, orders, "Person")
  if err != nil {
    log.Fatalf("Error searching users %v", err)
  }
  log.Printf("%+v", users)
}

Example Converter Repository (Hexagonal Arch)

More examples here
// Converter data must satisfies converter interface

// User model
type User struct {
  ID       uint
  Username string
  Password string
  Enable   bool
}

// User DB
type UserDB struct {
  ID       uint   `gorm:"primaryKey;autoIncrement"`
  Username string `gorm:"not null"`
  Password string `gorm:"not null"`
  Enable   bool
}

func (udb UserDB) TableName() string {
  return "users"
}

// Satisfies converter interface
func (udb *UserDB) From(u User) {
  udb.ID = u.ID
  udb.Username = u.Username
  udb.Password = u.Password
  udb.Enable = u.Enable
}

// Satisfies converter interface
func (udb UserDB) Into() User {
  return User{
    ID:       udb.ID,
    Username: udb.Username,
    Password: udb.Password,
    Enable:   udb.Enable,
  }
}

// Then the implementation
type userRepo struct {
  gormen.Repository[User]
}

func NewUserRepo(db *gorm.DB) userRepo {
  return userRepo{
    // converter.Repository converts inside from UserDB to User and vice versa
    // Applying From(M) or Into() M, as needed
    Repository: converter.NewRepository[UserDB, *UserDB](db),
  }
}

func (u *userRepo) FindAll(ctx context.Context, pageable pagination.Pageable) (*pagination.Page[User], error) {
  return u.FindAllPaginated(ctx, pageable)
}

func (u *userRepo) FindByUsername(ctx context.Context, username string) (*User, error) {
  return u.FindBy(ctx, gormen.NewWhere(where.Equal("username", username)).Build())
}

Available interfaces

Any of these satisfies std.Repository or converter.Repository
// Repository defines a generic interface combining CUD (Create, Update, Delete)
// and Read operations for a model type M.
type Repository[M any] interface {
  CudRepository[M]
  ReadRepository[M]
}

// CudRepository defines generic Create, Update, and Delete operations for model M.
type CudRepository[M any] interface {
  Create(ctx context.Context, model *M) error
  CreateAll(ctx context.Context, model *[]M, batchSize int) error
  Delete(ctx context.Context, model *M) error
  DeleteAll(ctx context.Context, model []M) error
  DeleteAllBy(ctx context.Context, where Where) error
  Save(ctx context.Context, model *M) error
  SaveAll(ctx context.Context, model []M) error
}

// ReadRepository defines generic read/query operations for model M.
type ReadRepository[M any] interface {
  Count(ctx context.Context) (int64, error)
  CountBy(ctx context.Context, where Where) (int64, error)
  FindBy(ctx context.Context, where Where, preloads ...Preload) (*M, error)
  FindAll(ctx context.Context, preloads ...Preload) ([]M, error)
  FindAllBy(ctx context.Context, where Where, preloads ...Preload) ([]M, error)
  FindAllPaginated(ctx context.Context, pageable pagination.Pageable, preloads ...Preload) (*pagination.Page[M], error)
  FindAllPaginatedBy(ctx context.Context, pageable pagination.Pageable, where Where, preloads ...Preload) (*pagination.Page[M], error)
  FindAllOrdered(ctx context.Context, orders []sort.Order, preloads ...Preload) ([]M, error)
}

Donate
  • Bitcoin (QR) 1GqdJ63RDPE4eJKujHi166FAyigvHu5R7v
  • Paypal

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CudRepository

type CudRepository[M any] interface {
	// Create inserts a new record for the given model.
	Create(ctx context.Context, model *M) error
	// CreateAll inserts multiple records in batches of specified size.
	CreateAll(ctx context.Context, model *[]M, batchSize int) error
	// Delete removes the specified model record.
	Delete(ctx context.Context, model *M) error
	// DeleteAll removes all specified model records.
	DeleteAll(ctx context.Context, model []M) error
	// DeleteAllBy removes all records matching the given Where condition.
	DeleteAllBy(ctx context.Context, where Where) error
	// Save creates or updates the given model record.
	Save(ctx context.Context, model *M) error
	// SaveAll creates or updates multiple model records.
	SaveAll(ctx context.Context, model []M) error
}

CudRepository defines generic Create, Update, and Delete operations for model M.

type Join

type Join = string

Join represents a string identifier for SQL join operations in Gorm

type Preload

type Preload = string

Preload represents a string identifier for preloading related entities in Gorm

type ReadRepository

type ReadRepository[M any] interface {
	// Count returns the total number of records.
	Count(ctx context.Context) (int64, error)
	// CountBy returns the number of records matching a specific condition.
	CountBy(ctx context.Context, where Where) (int64, error)
	// FindBy returns a single record matching the condition or nil if not found.
	FindBy(ctx context.Context, where Where, preloads ...Preload) (*M, error)
	// FindAll returns all records.
	FindAll(ctx context.Context, preloads ...Preload) ([]M, error)
	// FindAllBy returns all records matching a condition.
	FindAllBy(ctx context.Context, where Where, preloads ...Preload) ([]M, error)
	// FindAllPaginated returns a paginated list of all records.
	FindAllPaginated(ctx context.Context, pageable pagination.Pageable, preloads ...Preload) (*pagination.Page[M], error)
	// FindAllPaginatedBy returns a paginated list of records filtered by a condition.
	FindAllPaginatedBy(ctx context.Context, pageable pagination.Pageable, where Where, preloads ...Preload) (*pagination.Page[M], error)
	// FindAllOrdered returns all records ordered by given sort criteria.
	FindAllOrdered(ctx context.Context, orders []sort.Order, preloads ...Preload) ([]M, error)
}

ReadRepository defines generic read/query operations for model M.

type Repository

type Repository[M any] interface {
	CudRepository[M]
	ReadRepository[M]
}

Repository defines a generic interface combining CUD (Create, Update, Delete) and Read operations for a model type M.

type Where

type Where struct {
	// contains filtered or unexported fields
}

Where holds SQL query conditions and join clauses to build complex queries.

func NewWhere

func NewWhere(c where.Condition) *Where

NewWhere creates a new Where instance with an initial condition and no logical operator.

func (*Where) And

func (w *Where) And(c where.Condition) *Where

And adds a condition combined with a logical AND to the Where clause.

func (*Where) Build

func (w *Where) Build() Where

Build finalizes and returns a copy of the Where instance.

func (Where) Conditions

func (w Where) Conditions() conditions

Conditions returns the map of conditions and their logical operators.

func (Where) Joins

func (w Where) Joins() []Join

Joins returns the list of join clauses included in the query.

func (*Where) Or

func (w *Where) Or(c where.Condition) *Where

Or adds a condition combined with a logical OR to the Where clause.

func (*Where) WithJoin

func (w *Where) WithJoin(joins ...Join) *Where

WithJoin sets the list of join clauses to include in the Where query.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL