dbre

package module
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2025 License: MIT Imports: 6 Imported by: 8

README

Basic Usage

Full Example example

Full Example with Clean Architecture example

Domain gen by https://github.com/smallnest/gen

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/dreamph/dbre"
	"github.com/dreamph/dbre/adapters/bun"
	bunpg "github.com/dreamph/dbre/adapters/bun/connectors/pg"
	"github.com/dreamph/dbre/adapters/gorm"
	gormpg "github.com/dreamph/dbre/adapters/gorm/connectors/pg"
	"github.com/dreamph/dbre/example/domain"
	"go.uber.org/zap"
)

func getBunDB(logger *zap.Logger) (dbre.AppIDB, dbre.DBTx, error) {
	bunDB, err := bunpg.Connect(&bunpg.Options{
		Host:           "127.0.0.1",
		Port:           "5432",
		DBName:         "dream",
		User:           "dream",
		Password:       "password",
		ConnectTimeout: 2000,
		Logger:         logger,
	})
	if err != nil {
		return nil, nil, err
	}

	appDB := bun.NewIDB(bunDB)
	dbTx := bun.NewDBTx(bunDB)

	return appDB, dbTx, nil
}

func getGormDB(logger *zap.Logger) (dbre.AppIDB, dbre.DBTx, error) {
	bunDB, err := gormpg.Connect(&gormpg.Options{
		Host:           "127.0.0.1",
		Port:           "5432",
		DBName:         "dream",
		User:           "dream",
		Password:       "password",
		ConnectTimeout: 2000,
		Logger:         logger,
	})
	if err != nil {
		return nil, nil, err
	}

	appDB := gorm.NewIDB(bunDB)
	dbTx := gorm.NewDBTx(bunDB)

	return appDB, dbTx, nil
}

func main() {
	logger, err := zap.NewDevelopment()
	if err != nil {
		log.Fatalf(err.Error())
	}
	defer logger.Sync()

	appDB, dbTx, err := getBunDB(logger)
	//appDB, dbTx, err := getGormDB(logger)
	if err != nil {
		log.Fatalf(err.Error())
	}
	defer func() {
		err := appDB.Close()
		if err != nil {
			log.Fatalf(err.Error())
		}
	}()

	ctx := context.Background()

	//Simple Usage
	countryDbQuery := bun.New[domain.Country](appDB)

	data := &domain.Country{
		Id:     "1",
		Code:   "C1",
		Name:   "Name",
		Status: 20,
	}

	// Create
	_, err = countryDbQuery.Create(ctx, data)
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Update
	_, err = countryDbQuery.Update(ctx, data)
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Find By PK
	_, err = countryDbQuery.FindByPK(ctx, &domain.Country{
		Id: "1",
	})
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Find One
	_, err = countryDbQuery.FindOne(ctx, &domain.Country{
		Code: "C1",
	})
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Delete
	err = countryDbQuery.Delete(ctx, &domain.Country{
		Id: "C1",
	})
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Upsert
	_, err = countryDbQuery.Upsert(ctx, data, nil)
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Find One Where
	wb := dbre.WhereBuilder{}
	wb.Where("code = ?", "C1")
	result, err := countryDbQuery.FindOneWhere(ctx, wb.WhereCauses())
	if err != nil {
		log.Fatalf(err.Error())
	}
	fmt.Println(result)

	// Query List Where
	wb = dbre.WhereBuilder{}
	wb.Where("status = ?", 20)

	list, total, err := countryDbQuery.QueryListWhere(ctx, wb.WhereCauses(), &dbre.Limit{Offset: 0, PageSize: 10}, []string{"name"})
	if err != nil {
		log.Fatalf(err.Error())
	}
	fmt.Println(list, total)

	// With Transaction
	err = dbTx.WithTx(ctx, func(ctx context.Context, appDB dbre.AppIDB) error {
		data2 := &domain.Country{
			Id:     "1",
			Code:   "C1",
			Name:   "Name",
			Status: 20,
		}
		_, err = countryDbQuery.WithTx(appDB).Create(ctx, data2)
		if err != nil {
			log.Fatalf(err.Error())
		}

		data2.Name = "Name2"
		data2.Status = 10

		_, err = countryDbQuery.WithTx(appDB).Update(ctx, data2)
		if err != nil {
			log.Fatalf(err.Error())
		}

		return nil
	})
	if err != nil {
		log.Fatalf(err.Error())
	}
}

Buy Me a Coffee

Documentation

Index

Constants

View Source
const (
	ASC  = "ASC"
	DESC = "DESC"
)
View Source
const (
	Or  = 2
	And = 1
)

Variables

View Source
var DbPoolDefault = &DbPoolOptions{
	MaxIdleConns:    5,
	MaxOpenConns:    10,
	ConnMaxLifetime: 10 * time.Minute,
}

Functions

func GetDB added in v1.0.10

func GetDB[T any](appDB AppIDB) T

func SetConnectionsPool

func SetConnectionsPool(db *sql.DB, pool *DbPoolOptions)

func SortSQL

func SortSQL(param *SortParam) (string, error)

Types

type AppIDB added in v1.0.10

type AppIDB interface {
	GetDB() any
	Close() error
}

type DB added in v1.0.10

type DB[T any] interface {
	WithTx(tx AppIDB) DB[T]
	RawExec(ctx context.Context, sqlQuery string, params []interface{}) (int64, error)
	RawQuery(ctx context.Context, sql string, params []interface{}, resultPtr interface{}) error
	Create(ctx context.Context, obj *T) (*T, error)
	CreateList(ctx context.Context, obj *[]T) (*[]T, error)
	Update(ctx context.Context, obj *T) (*T, error)
	UpdateList(ctx context.Context, obj *[]T) (*[]T, error)
	Upsert(ctx context.Context, obj *T, specifyUpdateFields []string) (*T, error)
	UpsertList(ctx context.Context, obj *[]T, specifyUpdateFields []string) (*[]T, error)
	UpdateForce(ctx context.Context, obj *T) (*T, error)
	FindByPK(ctx context.Context, obj *T) (*T, error)
	Delete(ctx context.Context, obj *T) error
	DeleteList(ctx context.Context, obj *[]T) error
	DeleteWhere(ctx context.Context, whereCauses *[]WhereCause) error
	Count(ctx context.Context, whereObj *T) (int64, error)
	List(ctx context.Context, whereObj *T) (*[]T, error)
	ListWhere(ctx context.Context, whereCauses *[]WhereCause, limit *Limit, sortBy []string) (*[]T, error)
	QueryListWhere(ctx context.Context, whereCauses *[]WhereCause, limit *Limit, sortBy []string) (*[]T, int64, error)
	FirstWhere(ctx context.Context, whereCauses *[]WhereCause, sortBy []string) (*T, error)
	FindOneWhere(ctx context.Context, whereCauses *[]WhereCause) (*T, error)
	FindOne(ctx context.Context, whereObj *T) (*T, error)
	CountWhere(ctx context.Context, whereCauses *[]WhereCause) (int64, error)
}

type DBTx added in v1.0.10

type DBTx interface {
	WithTx(ctx context.Context, fn TxFn) error
}

type DbPoolOptions

type DbPoolOptions struct {
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	MaxIdleConns int
	// SetMaxOpenConns sets the maximum number of open connections to the database.
	MaxOpenConns int
	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	ConnMaxLifetime time.Duration
}

type Limit added in v1.0.10

type Limit struct {
	Offset   int64 `json:"offset"`
	PageSize int64 `json:"pageSize"`
}

type SQLQueryBuilder

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

func NewSQLQueryBuilder

func NewSQLQueryBuilder() SQLQueryBuilder

func (*SQLQueryBuilder) AddParam

func (bd *SQLQueryBuilder) AddParam(params ...interface{}) *SQLQueryBuilder

func (*SQLQueryBuilder) AddQuery

func (bd *SQLQueryBuilder) AddQuery(sql string) *SQLQueryBuilder

func (*SQLQueryBuilder) AddQueryWithParam

func (bd *SQLQueryBuilder) AddQueryWithParam(sql string, params ...interface{}) *SQLQueryBuilder

func (*SQLQueryBuilder) GetQueryParams

func (bd *SQLQueryBuilder) GetQueryParams() []interface{}

func (*SQLQueryBuilder) ToSQLQuery

func (bd *SQLQueryBuilder) ToSQLQuery() string

type Sort

type Sort struct {
	SortBy        string `json:"sortBy"`
	SortDirection string `json:"sortDirection" example:"DESC" enums:"ASC,DESC"`
}

type SortParam

type SortParam struct {
	SortFieldMapping map[string]string
	Sort             *Sort
	DefaultSort      *Sort
}

type TxFn added in v1.0.10

type TxFn func(ctx context.Context, appDB AppIDB) error

type WhereBuilder added in v1.0.10

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

func NewWhereBuilder added in v1.0.10

func NewWhereBuilder() *WhereBuilder

func (*WhereBuilder) Where added in v1.0.10

func (w *WhereBuilder) Where(query string, args ...interface{}) *WhereBuilder

func (*WhereBuilder) WhereCauses added in v1.0.10

func (w *WhereBuilder) WhereCauses() *[]WhereCause

func (*WhereBuilder) WhereOr added in v1.0.10

func (w *WhereBuilder) WhereOr(query string, args ...interface{}) *WhereBuilder

type WhereCause added in v1.0.10

type WhereCause struct {
	Type  int
	Query string
	Args  []interface{}
}

Directories

Path Synopsis
adapters
bun module
gorm module

Jump to

Keyboard shortcuts

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