gormutil

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2024 License: MIT Imports: 13 Imported by: 0

README

gormutil

Opinionated utilities for Gorm

Requirements

gormutil includes

  • ModelBase
    • primary key named ID and is in uuid format
    • assumes each model has CreatedAt and UpdatedAt timestamps
  • Logger
    • backed by zerolog
    • respects LOG_LEVEL environment variable
  • Data Import/Export
    • Exports filterable tables into map[string]interface{}
    • Imports from map[string]interface{}
  • Create/Update helpers with respect of validation rules

Install

go get github.com/avakarev/go-util/gormutil

License

go-testutil is licensed under MIT license. (see LICENSE)

Documentation

Overview

Package gormutil implements gorm helpers

Index

Constants

View Source
const (
	// HookAfterCreate is event name for AfterCretate hook
	HookAfterCreate = "AfterCreate"
	// HookAfterUpdate is event name for AfterUpdate hook
	HookAfterUpdate = "AfterUpdate"
	// HookAfterDelete is event name for AfterDelete hook
	HookAfterDelete = "AfterDelete"
)

Variables

Logger is a zerolog-backed gorm logger

Functions

func Changeset

func Changeset(model interface{}, names []string) (map[string]interface{}, error)

Changeset extracts values of given field names from the model

func FilterTables

func FilterTables(tables []string, f *TableFilter) []string

FilterTables returns tables with respect of include/exclude filters

func Find

func Find[T any](tx *gorm.DB) []T

Find returns all rows models by the given query

func First

func First[T any](tx *gorm.DB) *T

First returns first row matching the given query

func NewLogger

func NewLogger(lvl logger.LogLevel) logger.Interface

NewLogger returns new logger value

Types

type DB

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

DB defines db container

func Open

func Open(dialector gorm.Dialector) (*DB, error)

Open initialize db session based on dialector

func (*DB) AfterCreateHook added in v1.1.0

func (db *DB) AfterCreateHook(model interface{})

AfterCreateHook publishes hook after create

func (*DB) AfterDeleteHook added in v1.1.0

func (db *DB) AfterDeleteHook(model interface{})

AfterDeleteHook publishes hook after delete

func (*DB) AfterUpdateHook added in v1.1.0

func (db *DB) AfterUpdateHook(model interface{})

AfterUpdateHook publishes hook after update

func (*DB) Conn

func (db *DB) Conn() *gorm.DB

Conn returns gorm's connection

func (*DB) Count

func (db *DB) Count(model interface{}) int64

Count returns number of record in given table

func (*DB) CountBy

func (db *DB) CountBy(model interface{}, cond interface{}, args ...interface{}) int64

CountBy returns number of record in given table with given conditions

func (*DB) Create

func (db *DB) Create(model interface{}) error

Create validates and persists new record

func (*DB) Delete added in v1.1.0

func (db *DB) Delete(model interface{}, conds ...interface{}) error

Delete deletes given record from the db table

func (*DB) DeleteByID added in v1.1.0

func (db *DB) DeleteByID(model interface{}, id string) error

DeleteByID deletes given record with given id from the db table

func (*DB) ExistsBy

func (db *DB) ExistsBy(model interface{}, cond interface{}, args ...interface{}) bool

ExistsBy checks whether given model exists with given conditions

@TODO: try to optimize the query to something like SELECT EXISTS(SELECT 1 FROM vaults WHERE id="foobar" LIMIT 1);

func (*DB) ExistsByID

func (db *DB) ExistsByID(model interface{}, id string) bool

ExistsByID checks whether given model exists with given id

func (*DB) Export

func (db *DB) Export(filter *TableFilter) (map[string]interface{}, error)

Export returns map of all tables with their rows

func (*DB) ExportTable

func (db *DB) ExportTable(table string) ([]map[string]interface{}, error)

ExportTable returns all rows of given table as slice of maps

func (*DB) Import

func (db *DB) Import(data map[string]interface{}, filter *TableFilter) error

Import inserts given data into db

func (*DB) ImportTable

func (db *DB) ImportTable(table string, rows []interface{}) error

ImportTable inserts given rows into given table

func (*DB) RegisterValidation added in v1.1.4

func (db *DB) RegisterValidation(tag string, fn validator.Func) error

RegisterValidation adds a custom validation for the given tag

func (*DB) RegisterValidationTagNameFunc added in v1.1.9

func (db *DB) RegisterValidationTagNameFunc(fn validator.TagNameFunc)

RegisterValidationTagNameFunc registers a function to get alternate names for StructFields

func (*DB) SubscribeHook added in v1.1.0

func (db *DB) SubscribeHook(model interface{}, fn HookHandlerFunc)

SubscribeHook creates subscription for create/update/delete changes of given model

func (*DB) Tables

func (db *DB) Tables(filter *TableFilter) ([]string, error)

Tables retuns list of existing db tables respecing the given filter

func (*DB) Update

func (db *DB) Update(model interface{}, names ...string) error

Update validates and persists existing record

func (*DB) Validate added in v1.1.12

func (db *DB) Validate(model interface{}) error

Validate validates given model struct

func (*DB) WithHooks added in v1.1.0

func (db *DB) WithHooks() *DB

WithHooks enables hooks pub/sub

func (*DB) WithLocking added in v1.1.5

func (db *DB) WithLocking() *DB

WithLocking enables mutex locking during create/update/delete calls

type Hook added in v1.1.0

type Hook struct {
	Table string
	Model interface{}
	Event HookEvent
}

Hook defines hook event

type HookBus added in v1.1.0

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

HookBus maintains the set of subscriptions and broadcast any incoming hooks

type HookEvent added in v1.1.0

type HookEvent string

HookEvent represents event that triggered hook

func (HookEvent) IsAfterCreate added in v1.1.0

func (e HookEvent) IsAfterCreate() bool

IsAfterCreate checks whether event is "AfterCreate"

func (HookEvent) IsAfterDelete added in v1.1.0

func (e HookEvent) IsAfterDelete() bool

IsAfterDelete checks whether event is "AfterDelete"

func (HookEvent) IsAfterUpdate added in v1.1.0

func (e HookEvent) IsAfterUpdate() bool

IsAfterUpdate checks whether event is "AfterUpdate"

func (HookEvent) String added in v1.1.0

func (e HookEvent) String() string

String returns event's string representation

type HookHandlerFunc added in v1.1.0

type HookHandlerFunc func(hook *Hook)

HookHandlerFunc is a subscription's callback

type HookSubscription added in v1.1.0

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

HookSubscription defines hook's subscription

type ModelBase

type ModelBase struct {
	ID        uuid.UUID `gorm:"type:uuid;primaryKey;uniqueIndex" json:"id" validate:"required"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

ModelBase contains common columns for all tables

func (*ModelBase) GenerateID

func (base *ModelBase) GenerateID() error

GenerateID generates and assigns new id value

type TableFilter

type TableFilter struct {
	IncludeTables []string `json:"includeTables"`
	ExcludeTables []string `json:"excludeTables"`
}

TableFilter defines table filtering options

Jump to

Keyboard shortcuts

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