odm

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2022 License: Apache-2.0 Imports: 13 Imported by: 1

README

A project of SENROK Open Source

Go ODM

Go-odm, a Golang Object Document Mapping for MongoDB.

GoDoc

Table of contents

Features

  • Define your models and perform CRUD operations with hooks before/after each operation.
  • Built-in Soft-Delete
  • Support the Multi-Database Instance
  • Wrap the official Mongo Go Driver.

Installation

go get github.com/senrok/go-odm

Get started

Setup a db config:

	opts, err := DefaultOpts(SetDatabase(MONGODB_URL, MONGODB_DB_NAME))

Define Model

type Doc struct {
	DefaultModel `bson:",inline"`

	Name string `bson:"name"`
	Age  int    `bson:"age"`
}

Insert a new Document

	err := opts.Coll(&doc).Create(context.TODO(), &doc)

Update a document

        docs:=getYourData()
        updatedAt := docs[0].UpdatedAt
        docs[0].Name = "weny updated"
        err := opts.Coll(&Doc{}).UpdateOne(context.TODO(), docs[0])

Soft-Delete a document

	err := opts.Coll(&Doc{}).SoftDeleteOne(context.TODO(), data[0])

Restore a document

	err = opts.Coll(&Doc{}).RestoreOne(context.TODO(), data[0])

Delete a document

	err := opts.Coll(&Doc{}).DeleteOne(context.TODO(), data[0])

Find a document

	err := opts.Coll(&Doc{}).FindOne(context.TODO(), bson.M{"name": "weny"}, &result)
Transactions
    err := opts.TransactionWithCtx(context.TODO(), func(session mongo.Session, sc mongo.SessionContext) error {

		err := opts.Coll(d).Create(sc, d)

		if err != nil {
			return err
		}

		return session.CommitTransaction(sc)
	})

Documentation

GoDoc

License

The Project is licensed under the Apache License.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	InvalidatedModels = errors.New("invalidated models input\n try []*YourModel")

	UnableSoftDeletable = errors.New("unable soft-delete")
)

Functions

func CollName

func CollName(m IModel) string

CollName returns a model's collection name. The `CollectionNameGetter` will be used if the model implements this interface. Otherwise, the collection name is inferred based on the model's type using reflection.

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase returns snake_case of the provided value.

func TransactionWithClient

func TransactionWithClient(ctx context.Context, client *mongo.Client, f TransactionFunc) error

TransactionWithClient creates a transaction with the given client.

Types

type Collection

type Collection struct {
	*mongo.Collection
	// contains filtered or unexported fields
}

func (*Collection) Count

func (c *Collection) Count(ctx context.Context, filter bson.M, opts ...*options.CountOptions) (int64, error)

Count returns the number of documents in the collection

Example
opts := setupDefaultOpts()
resetDB(opts)
data := seedDoc(opts)
_ = opts.Coll(&Doc{}).SoftDeleteOne(context.TODO(), data[0])
result, err := opts.Coll(&Doc{}).Count(context.TODO(), bson.M{})
if err != nil {
	panic(err)
}
fmt.Println(result == int64(len(data)))
Output:

false

func (*Collection) Create

func (c *Collection) Create(ctx context.Context, model IModel, opts ...*options.InsertOneOptions) error

Create method insert a new record into database.

Example
opts := setupDefaultOpts()
resetDB(opts)
doc := Doc{
	Name: "weny",
	Age:  12,
}
_ = opts.Coll(&doc).Create(context.TODO(), &doc)
Output:

func (*Collection) CreateMany

func (c *Collection) CreateMany(ctx context.Context, input interface{}, opts ...*options.InsertManyOptions) error

CreateMany inserts multi-records into databases. Notes: by default, inserts records ordered.

Example
opts := setupDefaultOpts()
resetDB(opts)
docs := []*Doc{{Name: "weny"}, {Name: "leo"}}
_ = opts.Coll(&Doc{}).CreateMany(context.TODO(), &docs)
Output:

func (*Collection) DeleteMany

func (c *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) error

DeleteMany deletes multi soft-deleted records form collection.

Example
opts := setupDefaultOpts()
resetDB(opts)
_ = seedDoc(opts)

// deleting
_ = opts.Coll(&Doc{}).DeleteMany(context.TODO(), bson.M{})
Output:

func (*Collection) DeleteOne

func (c *Collection) DeleteOne(ctx context.Context, model IModel, opts ...*options.DeleteOptions) error

DeleteOne deletes a soft-deleted record form collection.

Example
opts := setupDefaultOpts()
resetDB(opts)
data := seedDoc(opts)

// deleting
_ = opts.Coll(&Doc{}).DeleteOne(context.TODO(), data[0])
Output:

func (*Collection) DeleteOneByPk added in v0.1.4

func (c *Collection) DeleteOneByPk(ctx context.Context, id interface{}, opts ...*options.DeleteOptions) error

DeleteOneByPk deletes a soft-deleted record form collection.

func (*Collection) Find

func (c *Collection) Find(ctx context.Context, filter bson.M, result interface{}, opts ...*options.FindOptions) error

Find searches and returns records in the search results.

Example
opts := setupDefaultOpts()
resetDB(opts)
var result []Doc
_ = opts.Coll(&Doc{}).Find(context.TODO(), bson.M{}, &result)
Output:

func (*Collection) FindByPK added in v0.1.2

func (c *Collection) FindByPK(ctx context.Context, id interface{}, result interface{}, opts ...*options.FindOneOptions) error

FindByPK finds and returns the document where the primary key equals id

Example
opts := setupDefaultOpts()
resetDB(opts)
inserted := &Doc{Name: "weny"}
_ = opts.Coll(&Doc{}).Create(context.TODO(), inserted)
fmt.Println(inserted.ID)
var result Doc
_ = opts.Coll(&Doc{}).FindByPK(context.TODO(), inserted.ID, &result)
Output:

func (*Collection) FindOne

func (c *Collection) FindOne(ctx context.Context, filter bson.M, result interface{}, opts ...*options.FindOneOptions) error

FindOne searches and returns the first document in the search results.

Example
opts := setupDefaultOpts()
seedDoc(opts)
var result Doc
_ = opts.Coll(&Doc{}).FindOne(context.TODO(), bson.M{"name": "weny"}, &result)
Output:

func (*Collection) RestoreMany

func (c *Collection) RestoreMany(ctx context.Context, filter bson.M, opts ...*options.UpdateOptions) error

RestoreMany restores multi soft-deleted records form collection. // Notes: if your Model doesn't specify the deletedAt fields, then you will get an error.

Example
opts := setupDefaultOpts()
resetDB(opts)
seedDoc(opts)
// soft-deleting
_ = opts.Coll(&Doc{}).SoftDeleteMany(context.TODO(), bson.M{})
var result []Doc
// checking
_ = opts.Coll(&Doc{}).Find(context.TODO(), bson.M{}, &result)
// restoring
_ = opts.Coll(&Doc{}).RestoreMany(context.TODO(), bson.M{})
Output:

func (*Collection) RestoreOne

func (c *Collection) RestoreOne(ctx context.Context, model IModel, opts ...*options.UpdateOptions) error

RestoreOne restores a soft-deleted record form collection. Notes: if your Model doesn't specify the deletedAt fields, then you will get an error.

Example
opts := setupDefaultOpts()
resetDB(opts)
data := seedDoc(opts)
// soft-deleting
_ = opts.Coll(&Doc{}).SoftDeleteOne(context.TODO(), data[0])
// restoring
_ = opts.Coll(&Doc{}).RestoreOne(context.TODO(), data[0])
Output:

func (*Collection) RestoreOneByPK added in v0.1.4

func (c *Collection) RestoreOneByPK(ctx context.Context, id interface{}, opts ...*options.UpdateOptions) error

RestoreOneByPK restores a soft-deleted record form collection.

func (*Collection) SoftDeleteMany

func (c *Collection) SoftDeleteMany(ctx context.Context, filter bson.M, opts ...*options.UpdateOptions) error

SoftDeleteMany soft-deletes soft-delete multi-records form collection. Notes: if your Model doesn't specify the deletedAt fields, then you will get an error.

Example
opts := setupDefaultOpts()
resetDB(opts)
data := seedDoc(opts)
fmt.Println(data[0])
time.Sleep(100 * time.Millisecond)
_ = opts.Coll(&Doc{}).SoftDeleteMany(context.TODO(), bson.M{})
fmt.Println(data[0])
var result []Doc
_ = opts.Coll(&Doc{}).Find(context.TODO(), bson.M{}, &result)
Output:

func (*Collection) SoftDeleteOne

func (c *Collection) SoftDeleteOne(ctx context.Context, model IModel, opts ...*options.UpdateOptions) error

SoftDeleteOne soft-deletes a records form collection. Notes: if your Model doesn't specify the deletedAt fields, then you will get an error.

Example
opts := setupDefaultOpts()
resetDB(opts)
data := seedDoc(opts)
fmt.Println(data[0])
_ = opts.Coll(&Doc{}).SoftDeleteOne(context.TODO(), data[0])
Output:

func (*Collection) SoftDeleteOneByPK added in v0.1.4

func (c *Collection) SoftDeleteOneByPK(ctx context.Context, pk interface{}, opts ...*options.UpdateOptions) error

SoftDeleteOneByPK soft-deletes a records form collection.

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context, model IModel, opts ...*options.UpdateOptions) error

UpdateOne updates a record.

Example
opts := setupDefaultOpts()
resetDB(opts)
docs := seedDoc(opts)
docs[0].Name = "weny updated"
_ = opts.Coll(&Doc{}).UpdateOne(context.TODO(), docs[0])
Output:

type CollectionGetter

type CollectionGetter interface {
	// Collection method return collection
	Collection() *mongo.Collection
}

CollectionGetter interface contains a method to return a model's custom collection.

type CollectionNameGetter

type CollectionNameGetter interface {
	// CollectionName method return model collection's name.
	CollectionName() string
}

CollectionNameGetter interface contains a method to return the collection name of a model.

type Collections

type Collections sync.Map

type CreatedHook

type CreatedHook interface {
	Created(ctx context.Context) error
}

CreatedHook is called after a model has been created

type CreatingHook

type CreatingHook interface {
	Creating(ctx context.Context, cfg *FieldsConfig) error
}

CreatingHook is called before saving a new model to the database

type DefaultModel

type DefaultModel struct {
	IDField         `bson:",inline"`
	TimestampFields `bson:",inline"`
	DeletedAtField  `bson:",inline"`
}

DefaultModel type contains default IDField, Auto-update CreatedAt UpdatedAt TimestampFields, DeletedAtFields which allow user soft-delete data.

func (*DefaultModel) Creating

func (f *DefaultModel) Creating(ctx context.Context, cfg *FieldsConfig) error

func (*DefaultModel) Restoring

func (f *DefaultModel) Restoring(ctx context.Context, cfg *FieldsConfig) error

func (*DefaultModel) Saving

func (f *DefaultModel) Saving(ctx context.Context, cfg *FieldsConfig) error

func (*DefaultModel) SoftDeleting

func (f *DefaultModel) SoftDeleting(ctx context.Context, cfg *FieldsConfig) error

type DeletedAtField

type DeletedAtField struct {
	DeletedAt time.Time `json:"deleted_at,omitempty" bson:"deleted_at,omitempty" odm:"deleteTime"`
}

type DeletedHook

type DeletedHook interface {
	Deleted(ctx context.Context, result *mongo.DeleteResult) error
}

DeletedHook is called after a model is deleted

type DeletingHook

type DeletingHook interface {
	Deleting(ctx context.Context, cfg *FieldsConfig) error
}

DeletingHook is called before a model is deleted

type FieldInfo

type FieldInfo struct {
	Name     string
	BsonName string
	RawTag   string
	Tags     []string
	Index    []int
}

type FieldsConfig

type FieldsConfig struct {
	AutoCreateTimeField string
	AutoUpdateTimeField string
	DeleteTimeField     string
	PrimaryIDField      string
	PrimaryIDBsonField  string
	DeleteTimeBsonField string
}

func (FieldsConfig) SoftDeletable

func (info FieldsConfig) SoftDeletable() bool

type FieldsInfo

type FieldsInfo []FieldInfo

type IDField

type IDField struct {
	ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty" odm:"primaryID"`
}

func (*IDField) GetID

func (f *IDField) GetID() interface{}

GetID method returns a model's ID

func (*IDField) PrepareID

func (f *IDField) PrepareID(id interface{}) (interface{}, error)

PrepareID method prepares the ID value to ObjectID

func (*IDField) SetID

func (f *IDField) SetID(id interface{})

SetID sets the value of a model's ID field.

type IModel

type IModel interface {
	PrepareID(id interface{}) (interface{}, error)
	GetID() interface{}
	SetID(id interface{})
	SoftDeleting(ctx context.Context, cfg *FieldsConfig) error
	Creating(ctx context.Context, cfg *FieldsConfig) error
	Saving(ctx context.Context, cfg *FieldsConfig) error
}

IModel interface

type IModels

type IModels []IModel

func (IModels) At

func (models IModels) At(i int) IModel

func (IModels) Interfaces

func (models IModels) Interfaces() (output []interface{})

type Option

type Option func(opts *Options) error

func SetDatabase

func SetDatabase(url string, dbName string, opts ...*options.ClientOptions) Option

SetDatabase set up the client connection via a specific connection string and specific database name

type Options

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

func DefaultOpts

func DefaultOpts(opts ...Option) (*Options, error)

DefaultOpts returns a Options cloned from defaultOptions

Example
_, err := DefaultOpts(SetDatabase(MONGODB_URL, MONGODB_DB_NAME))
if err != nil {
	panic(err)
}
Output:

func NewOpts

func NewOpts(opts ...Option) (*Options, error)

NewOpts returns a new Options

Example
_, err := NewOpts(func(opts *Options) error {
	url := "your connection string"
	c, err := mongo.NewClient(options.Client().ApplyURI(url))
	if err != nil {
		return err
	}
	// specify the database for opts
	opts.db = c.Database("your database name")
	return nil
})
if err != nil {
	panic(err)
}
Output:

func (*Options) Client added in v1.0.0

func (o *Options) Client() *mongo.Client

Client returns *mongo.Client

func (*Options) Clone

func (o *Options) Clone() *Options

Clone the Options

func (*Options) Coll

func (o *Options) Coll(m IModel, opts ...*options.CollectionOptions) *Collection

Coll gets a collection or return a new collection

func (*Options) CollWithName added in v0.1.3

func (o *Options) CollWithName(m IModel, meta string, opts ...*options.CollectionOptions) *Collection

CollWithName gets a collection or return a new collection with a specific name

func (*Options) Database added in v1.0.0

func (o *Options) Database() *mongo.Database

Database returns *mongo.Database

func (*Options) NewCollection

func (o *Options) NewCollection(m IModel, name string, opts ...*options.CollectionOptions) *Collection

NewCollection returns a new collection using the current configuration values.

func (Options) TransactionWithCtx

func (o Options) TransactionWithCtx(ctx context.Context, f TransactionFunc) error

TransactionWithCtx creates a transaction with the given context and the default client.

type RestoredHook

type RestoredHook interface {
	Restored(ctx context.Context, result *mongo.UpdateResult) error
}

RestoredHook is called after soft restoring a model

type RestoringHook

type RestoringHook interface {
	Restoring(ctx context.Context, cfg *FieldsConfig) error
}

RestoringHook is called before soft restoring a model

type SavedHook

type SavedHook interface {
	Saved(ctx context.Context) error
}

SavedHook is called after a model is saved to the database.

type SavingHook

type SavingHook interface {
	Saving(ctx context.Context, cfg *FieldsConfig) error
}

SavingHook is called before a model (new or existing) is saved to the database.

type SoftDeletedHook

type SoftDeletedHook interface {
	SoftDeleted(ctx context.Context, result *mongo.UpdateResult) error
}

SoftDeletedHook is called after soft deleting a model

type SoftDeletingHook

type SoftDeletingHook interface {
	SoftDeleting(ctx context.Context, cfg *FieldsConfig) error
}

SoftDeletingHook is called before soft deleting a model

type TimestampFields

type TimestampFields struct {
	CreatedAt time.Time `json:"created_at,omitempty" bson:"created_at,omitempty" odm:"autoCreateTime"`
	UpdatedAt time.Time `json:"updated_at,omitempty" bson:"updated_at,omitempty" odm:"autoUpdateTime"`
}

type TransactionFunc

type TransactionFunc func(session mongo.Session, sc mongo.SessionContext) error

TransactionFunc is a handler to manage a transaction.

type UpdatedHook

type UpdatedHook interface {
	Updated(ctx context.Context, result *mongo.UpdateResult) error
}

UpdatedHook is called after a model is updated

type UpdatingHook

type UpdatingHook interface {
	Updating(ctx context.Context) error
}

UpdatingHook is called before updating a model

Directories

Path Synopsis
examples
basic Module

Jump to

Keyboard shortcuts

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