sutando

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2023 License: MIT Imports: 17 Imported by: 0

README

Requirement

Required go 1.18 up

Query Parameters

  • Exists
  • And
  • Equal
  • NotEqual
  • Greater
  • GreaterOrEqual
  • Less
  • LessOrEqual
  • Contain
  • In
  • NotIn
  • Sort
  • Limit
  • Skip
  • Count
  • Regex

Guide

Installation

$ go get -u github.com/yanun0323/sutando@latest

Example

Connect To MongoDB
  • Create a new connection
    // connect through host and port.
    db, err := sutando.NewDB(ctx, sutando.Conn{
    	Username:  "example",
    	Password:  "example",
    	Host:      "example",
    	Port:      27017,
    	DB:        "example",
    	AdminAuth: true,
    	Pem:       "",
    	ClientOptionsHandler: func(opts *options.ClientOptions) {
    		opts.SetConnectTimeout(5 * time.Second)
    		opts.SetTimeout(15 * time.Second)
    	},
    })

    // connect through SRV.
    db, err := sutando.NewDB(ctx, sutando.ConnSrv{
    	Username:  "example",
    	Password:  "example",
    	Host:      "example.mongo.net",
    	DB:        "example",
    	AdminAuth: true,
    	Pem:       "",
    	ClientOptionsHandler: func(opts *options.ClientOptions) {
    		opts.SetConnectTimeout(5 * time.Second)
    		opts.SetTimeout(15 * time.Second)
    	},
    })
  • Model Declaration
    // Supported
    type Element struct {
        FirstName string                                // 'firstName' as mongo db field key 
        lastName string                                 // 'lastName' as mongo db field key
        Nickname bool               `bson:"nick_name"`  // using `bson:"xxx"` tag to assign field key to 'xxx'
        Healthy bool                `bson:"-"`          // using `bson:"-"` tag to ignore this field
        Children []string           `bson:",omitempty"` // using `bson:",omitempty"` tag to ignore this field when it's empty
        CareerPlan CustomStruct                         // 'careerPlan' as mongo db field key  works
        Hobbies map[string]string
        Live time.Time
        Salary decimal.Decimal
    }
  • Use an exist connection
    var client *mongo.Client
    ...
    database := "example"
    db := sutando.NewDBFromMongo(ctx, client, database)

Disconnect
    err := db.Disconnect(ctx)
Drop
    err := db.Collection("Collection").Drop(ctx)
Scalar
    // Count
    count, err := db.Collection("Collection").Find().Equal("Name", "sutando").Greater("Number", 300).Count(ctx, "_index_id_")
Find
    resultOne := struct{}
    err := db.Collection("Collection").Find().Equal("Name", "sutando").Greater("Number", 300).First().Exec(ctx, &resultOne)

    resultMany := []struct{}
    err := db.Collection("Collection").Find().Equal("Name", "sutando").Greater("Number", 300).Exec(ctx, &resultMany)
Create
    resultOne, _, err := db.Collection("Collection").Insert(&obj).Exec(ctx)

    _, resultMany, err := db.Collection("Collection").Insert(&obj1, &obj2, &obj3).Exec(ctx)
Update with Model (Will update all fields including empty fields)
    resultOne, err := db.Collection("Collection").UpdateWith(&data).Equal("Field", "sutando").First().Exec(su.ctx, false)

    resultMany, err := db.Collection("Collection").UpdateWith(&data).Equal("Field", "sutando").Exec(su.ctx, false)
Update with Set
    resultOne, err := db.Collection("Collection").Update().Equal("Field", "sutando").First().Set("Field", "hello").Exec(su.ctx, false)

    resultMany, err := db.Collection("Collection").Update().Equal("Field", "sutando").Set("Field", "hello").Exec(su.ctx, false)
Delete
    resultOne, err := db.Collection("Collection").Delete().Equal("Field", "sutando").First().Exec(su.ctx)

    resultMany, err := db.Collection("Collection").Delete().Equal("Field", "sutando").Exec(su.ctx)
Use original mongo-driver instance
    client := db.RawClient()
    database := db.RawDatabase()

Changelog

Version Description
1.4.2 - Added method Bson into Update Find Delete Scalar
1.4.1 - Completed comment for all struct, interface, function
1.4.0 - Remove all db execute functions
- Removed Query
- Removed method Bitwise
- Added ConnSrv connection structure
- Added method Drop into Collection() method chain
- Added comment for all methods
- Added option parameter into Regex method
- Rewrite the structure fo filters
- Renamed GetDriver to RawClient
- Renamed GetDriverDB to RawDatabase
- Fixed after invoking Find, didn't call defer cursor.Close()
1.3.7 - Added Scalar
- Moved method Count from Query to Scalar
1.3.6 - Added method Regex into Update Find Delete Query
1.3.5 - Fixed Find no document mismatch error
1.3.4 - Added method Count into Query
1.3.3 - Added methods Sort Limit Skip into Find
1.3.2 - Added deprecated comment for DB
1.3.1 - Renamed OptionHandler to ClientOptionsHandler
- Renamed SetupOption to SetupClientOptions
1.3.0 - Added Execute Chain
- Fixed error when input only one slice in insert function
- Fixed error when input only one param/slice in In/NotIn function
- Fixed bson omitempty supported
- Fixed embed structure lowercase Name issue
- Fixed map structure value lowercase Name issue
- Fixed array structure value lowercase Name issue
- Plan to remove db execute function in version 1.4.X
1.2.1 - Support mongodb-srv
- Fixed Conn ClientOptionsHandler nill pointer issue
1.2.0 - Added ClientOptionsHandler into Conn Interface
1.1.2 - Fixed testing structure tag issue
- Fixed error wrapping issue
1.1.1 - Added Disconnect function
1.0.4 - Fixed some testing mistakes
1.0.3 - Added NewDBFromMongo function
1.0.2 - Added MIT License
- Removed Makefile
1.0.1 - Fixed some testing mistakes
1.0.0 - Release

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoDocuments occurs when the operation
	// that created the SingleResult did not return
	// any document.
	ErrNoDocument = mongo.ErrNoDocuments

	// ErrDuplicatedKey occurs when there is a
	// unique key constraint violation.
	ErrDuplicatedKey = errors.New("mongo: duplicated key")
)

Functions

This section is empty.

Types

type Conn

type Conn struct {
	Username  string
	Password  string
	Host      string
	Port      uint   /* leave blank if you already add port in host */
	DB        string /* database name */
	Pem       string /* optional */
	AdminAuth bool

	ClientOptionsHandler func(*options.ClientOptions)
}

Conn is an implementation of the Connection interface for connecting mongo db through the host and port.

func (Conn) DSN

func (c Conn) DSN(cfg *tls.Config) (string, bool)

func (Conn) Database

func (c Conn) Database() string

func (Conn) SetupClientOptions added in v1.3.1

func (c Conn) SetupClientOptions(opt *options.ClientOptions)

type ConnSrv added in v1.4.0

type ConnSrv struct {
	Username  string
	Password  string
	Host      string
	DB        string /* database name */
	Pem       string /* optional */
	AdminAuth bool

	ClientOptionsHandler func(*options.ClientOptions)
}

ConnSrv is an implementation of the Connection interface for connecting mongo db through the SRV.

func (ConnSrv) DSN added in v1.4.0

func (c ConnSrv) DSN(cfg *tls.Config) (string, bool)

func (ConnSrv) Database added in v1.4.0

func (c ConnSrv) Database() string

func (ConnSrv) SetupClientOptions added in v1.4.0

func (c ConnSrv) SetupClientOptions(opt *options.ClientOptions)

type Connection

type Connection interface {
	DSN(cfg *tls.Config) (dns string, isPem bool)
	Database() string
	SetupClientOptions(*options.ClientOptions)
}

Connection provides a definition of connect configuration.

type DB

type DB interface {
	// RawClient returns the raw mongo client diver.
	RawClient() *mongo.Client

	// RawDatabase returns the raw mongo database diver.
	RawDatabase() *mongo.Database

	// Collection gets a handle for a collection with the given name configured with the given CollectionOptions.
	//
	//	col := db.Collection("col_name")
	//
	//	// insert
	//		col.Insert(&obj).Exec(ctx)
	//
	//	// find
	//		col.Find().Equal("name", "yanun").First().Exec(ctx, &result)
	//
	//	// update
	//		upsert := true
	//		col.Update().Set("name", "changed").Exec(ctx, upsert)
	//		col.UpdateWith(&obj).Exec(ctx, upsert)
	//
	//	// delete
	//		col.Delete().Greater("age", 20).Exec(ctx)
	Collection(name string, opts ...*options.CollectionOptions) builder

	// Disconnect closes sockets to the topology referenced by this Client. It will
	// shut down any monitoring goroutines, close the idle connection pool, and will
	// wait until all the in use connections have been returned to the connection
	// pool and closed before returning. If the context expires via cancellation,
	// deadline, or timeout before the in use connections have returned, the in use
	// connections will be closed, resulting in the failure of any in flight read
	// or write operations. If this method returns with no errors, all connections
	// associated with this Client have been closed.
	Disconnect(ctx context.Context) error
}

DB provides a definition of db behavior.

func NewDB

func NewDB(ctx context.Context, c Connection) (DB, error)

NewDB initializes a sutando.DB from providing connection configuration.

// connect through host and port.
db, err := sutando.NewDB(ctx, sutando.Conn{
	Username:  "example",
	Password:  "example",
	Host:      "example",
	Port:      27017,
	DB:        "example",
	AdminAuth: true,
	Pem:       "",
	ClientOptionsHandler: func(opts *options.ClientOptions) {
		opts.SetConnectTimeout(5 * time.Second)
		opts.SetTimeout(15 * time.Second)
	},
})

// connect through SRV.
db, err := sutando.NewDB(ctx, sutando.ConnSrv{
	Username:  "example",
	Password:  "example",
	Host:      "example.mongo.net",
	DB:        "example",
	AdminAuth: true,
	Pem:       "",
	ClientOptionsHandler: func(opts *options.ClientOptions) {
		opts.SetConnectTimeout(5 * time.Second)
		opts.SetTimeout(15 * time.Second)
	},
})

func NewDBFromMongo added in v1.0.3

func NewDBFromMongo(ctx context.Context, client *mongo.Client, database string) DB

NewDBFromMongo initializes a sutando.DB by using the mongoDB connection from an existed mongo-driver.

var client *mongo.Client
...
database := "example"
db := sutando.NewDBFromMongo(ctx, client, database)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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