gomodel

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: Apache-2.0 Imports: 1 Imported by: 0

README

GoModel

Go Reference Bitbucket Pipelines

Installation

go get bitbucket.org/amotus/gomodel@main

Usages

Implement the ModelInterface in your model


type MyModel struct {
    Id           int64           `gorm:"primaryKey"`
    DeletedAt    *gorm.DeletedAt `json:"deleted_at"`
}

func (d *MyModel) GetId() int64 {
	return d.Id
}
func (d *MyModel) SetId(id int64) {
	d.Id = id
}

func (d *MyModel) Query(db *gorm.DB, withTrash bool) *gorm.DB {
	if withTrash {
		return db.Unscoped().Model(&Device{})
	}
	return db.Model(&Device{})
}

Use Model[T]

once your struct implement the interface ModelInterface, you can use the New function to get a Model[T] object

modelPointer := gomodel.New[*MyModel](db, &MyModel{})

It is recommended to define a helper function in your model namespace

func NewMyModel(db *gorm.DB) *gomodel.Model[*MyModel] {
    return gomodel.New[*MyModel](db, &MyModel{})
}

Use the Model[T] object

// Create a new model
modelPointer := NewMyModel(db)

// Create a new model with data, *data is not saved to the database
modelPointer := NewMyModel(db).Set(&MyModel{
    Id: 1,
})

Model[T] methods

Type Chainable Ends
Accessor Get, Query
Data Accessor (query db) Find, Load, Fresh All, Exist
Mutator With, WithTrashed
Data Mutator Create, Update,
CreateOrUpdate,
Save, Delete, Restore

Save model to the database

Save is not chainable, it returns error if any


err := modelPointer.Save()
if err != nil {
    // Handle error
}

Create

Use directly the Create function to save into database a new model.

Create is chainable, it returns the model and in case of error, it is embedded in the model:

modelPointer := NewMyModel(db).Create(&MyModel{
    Id: 1,
})

if modelPointer.Err != nil {
    // Handle error
}

Find

Get a model from the database

Find is chainable, it returns the model and in case of error, it is embedded in the model:

modelStruct := NewMyModel(db).Find(1)
if modelPointer.Err != nil {
    // Handle error
}

All

Get all model from the database

// perform any filter on the db object before creating the model object.
//db = db.Scopes(isProject(1)) 

items, errDb := NewMyModel(db).All()
if errDb != nil {
    // Handle error
}
for _, item := range items {
    fmt.println(item)
}

Fresh

Refresh the model from the database

Fresh is chainable, it returns the model and in case of error, it is embedded in the model:

modelPointer.Fresh()
if modelPointer.Err != nil {
    // Handle error
}

Relations

Load relations of a model using the With function

item, errDb := NewMyModel(db).With("relation1", "relation2").Find(1).Get()
if errDb != nil {
    // Handle error
}
fmt.println(item.Relation1, item.Relation2)

If you already have a model loaded, you can use the Load function to add relations immediately

modelPointer.Load("relation1", "relation2") //Load will perform a Fresh() after adding relations

item, errDb := modelPointer.Get()
if errDb != nil {
    // Handle error
}
fmt.println(item.Relation1, item.Relation2)

Update

Update a model in database.

Update is chainable, it returns the model and in case of error, it is embedded in the model:

modelPointer := NewMyModel(db).Update(&MyModel{
    Name: "updated name",
})

if modelPointer.Err != nil {
    // Handle error
}

Create or Update

CreateOrUpdate is chainable, it returns the model and in case of error, it is embedded in the model:

modelPointer := NewMyModel(db).CreateOrUpdate(&MyModel{
    Id: 1,
})
if modelPointer.Err != nil {
    // Handle error
}

Delete a model

given the model id 1

errDb := modelPointer.Delete()
if errDb != nil {
    // Handle error
}

Restore a model

errDb := modelPointer.Restore()
if errDb != nil {
    // Handle error
}

Soft Delete

Use WithTrash to query model with deleted items included


exist, errDb := NewMyModel(db).WithTrash().Set(&MyModel{ Id: 1}).Exist()
if errDb != nil {
    // Handle error
}

Find methods doesn't use WithTrash, it will return the model only if it isn't trashed

Look at the model_test.go file for more examples

Documentation

Overview

Package gomodel provides a simple and eloquent way to interact with the GORM ORM.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Create

func Create(db *gorm.DB, m ModelInterface) error

Create a new model in the database.

func CreateOrUpdate

func CreateOrUpdate(db *gorm.DB, m ModelInterface) error

CreateOrUpdate a new model in the database or update it if it already exists.

func Delete

func Delete(db *gorm.DB, m ModelInterface, id int64) error

Delete the model from the database. If ModelInterface has a deleted_at field, it will be set to the current time.

func Exist

func Exist(db *gorm.DB, m ModelInterface, id int64, withTrashed bool) (bool, error)

Exist return true if the model with the primary key (id) exists in the database.

func Find

func Find[t ModelInterface](db *gorm.DB, m t, id int64, relations ...string) (t, error)

Find the model for a given id.

func MustExist added in v1.2.0

func MustExist(db *gorm.DB, m ModelInterface, id int64, withTrashed bool) bool

MustExist return true if the model with the primary key (id) exists in the database. Panic if an error occurs.

func Restore

func Restore(db *gorm.DB, m ModelInterface, id int64) error

Restore the model in the database. The deleted_at field will be set to nil.

func Update

func Update(db *gorm.DB, m ModelInterface) error

Update the model in the database.

Types

type Model

type Model[t ModelInterface] struct {
	Base t
	DB   *gorm.DB

	Err error
	// contains filtered or unexported fields
}

func New

func New[t ModelInterface](db *gorm.DB, m t) *Model[t]

New instantiate a new Model for the given t type.

func (*Model[t]) All

func (m *Model[t]) All() ([]t, error)

All get all models from the database. returns []t

func (*Model[t]) Create

func (m *Model[t]) Create(model t) *Model[t]

Create a new model in the database.

func (*Model[t]) CreateOrUpdate

func (m *Model[t]) CreateOrUpdate(model t) *Model[t]

CreateOrUpdate a new model in the database or update it if it already exists.

func (*Model[t]) Delete

func (m *Model[t]) Delete() error

Delete soft delete the model from the database.

func (*Model[t]) Exist

func (m *Model[t]) Exist() (bool, error)

Exist return true if the model with the primary key (id) exists in the database.

func (*Model[t]) Find

func (m *Model[t]) Find(id int64) *Model[t]

Find the model for a given id.

func (*Model[t]) Fresh

func (m *Model[t]) Fresh() *Model[t]

Fresh reload the model from the database.

func (*Model[t]) Get

func (m *Model[t]) Get() (t, error)

Get the model for a given id set on the model.

func (*Model[t]) Load added in v1.2.0

func (m *Model[t]) Load(relations ...string) *Model[t]

Load sets the relations ande load them from the database

func (*Model[t]) MustCreate

func (m *Model[t]) MustCreate(model t) *Model[t]

MustCreate a new model in the database. Panic if an error occurs.

func (*Model[t]) MustCreateOrUpdate

func (m *Model[t]) MustCreateOrUpdate(model t) *Model[t]

MustCreateOrUpdate a new model in the database or update it if it already exists. Panic if an error occurs.

func (*Model[t]) MustExist added in v1.2.0

func (m *Model[t]) MustExist() bool

MustExist return true if the model with the primary key (id) exists in the database. Panic if an error occurs.

func (*Model[t]) MustUpdate

func (m *Model[t]) MustUpdate(model t) *Model[t]

MustUpdate the model in the database. Panic if an error occurs.

func (*Model[t]) Query

func (m *Model[t]) Query() *gorm.DB

Query return a new query builder for the model's table.

func (*Model[t]) Restore

func (m *Model[t]) Restore() error

Restore restore a soft-deleted model instance. Set deleted_at to null.

func (*Model[t]) Save

func (m *Model[t]) Save() error

Save the model to the database. If the model doesn't exist yet, it will be created. Otherwise, it will be updated.

func (*Model[t]) Set

func (m *Model[t]) Set(model t) *Model[t]

Set sets the internal model to the given model, but doesn't save it to the database.

func (*Model[t]) Update

func (m *Model[t]) Update(model t) *Model[t]

Update the model in the database.

func (*Model[t]) With

func (m *Model[t]) With(relations ...string) *Model[t]

With sets the relations to be loaded when querying the database.

func (*Model[t]) WithTrashed

func (m *Model[t]) WithTrashed() *Model[t]

WithTrashed returns a new Model with the withTrashed flag set to true.

type ModelInterface

type ModelInterface interface {
	GetId() int64
	SetId(int64)
	Query(*gorm.DB, bool) *gorm.DB
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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