gormutil

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2024 License: MIT Imports: 11 Imported by: 0

README

gormutil

Opinionated utilities for Gorm

Install

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

Usage

package main

import (
    "log"

    "github.com/nutsdb/nutsdb"
)

func main() {
    dsn := "./data/sqlite.db"
    if fd := os.Getenv("MYAPP_DSN"); fd != "" {
        dsn = fd
    }
    sqlitedb, err := gormutil.Open(
        sqlite.Open(dsn),
        gormutil.WithLogger(zerologger.NewDefault()),
        gormutil.WithLocks(),
    )
    if err != nil {
        return err
    }
    db = sqlitedb
}

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 AfterCreate hook
	HookAfterCreate = "AfterCreate"
	// HookAfterUpdate is event name for AfterUpdate hook
	HookAfterUpdate = "AfterUpdate"
	// HookAfterDelete is event name for AfterDelete hook
	HookAfterDelete = "AfterDelete"
)

Variables

This section is empty.

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

Types

type ConfigureFunc added in v1.4.0

type ConfigureFunc func(*DB) error

ConfigureFunc defines configurator func

func WithLocks added in v1.4.0

func WithLocks() ConfigureFunc

WithLocks enables mutex locks during create/update/delete calls

func WithLogger added in v1.4.0

func WithLogger(l logger.Interface) ConfigureFunc

WithLogger sets given logger as gorm logger

func WithNowFunc added in v1.4.0

func WithNowFunc(fn func() time.Time) ConfigureFunc

WithNowFunc sets given func as gorm now func

type DB

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

DB defines db container

func Open

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

Open initializes 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 returns 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()

WithHooks enables hooks pub/sub

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

Directories

Path Synopsis
Package zerologger implements gorm zerolog adapter
Package zerologger implements gorm zerolog adapter

Jump to

Keyboard shortcuts

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