sqln

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2024 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrDatabaseNotInitialized string = "database connection not initialized"
	ErrMsgFailedConnect       string = "failed to connect to PostgreSQL: %w"
	ErrMsgFailedConnectionPig string = "failed to connect to PostgreSQL ping: %w"
	ErrMsgMigration           string = "an error occurred when validate database migrations: %v"

	ErrMsgQueryIsEmpty string = "query is empty"
	ErrPageIsEmpty     string = "page is empty, please create a pageable query"
	ErrMsgStmClose     string = "failed to close statement: %v\n"
)
View Source
const (
	MAX_OPEN_CONNS     = 10              // Número máximo de conexões abertas
	MAX_IDLE_CONNS     = 5               // Número máximo de conexões inativas no pool
	MAX_CONN_LIFE_TIME = time.Minute * 5 // Tempo máximo de vida de uma conexão no pool
)
View Source
const (
	ErrMsgInvalidLogialOp      = "invalid logical operator: %s"
	ErrMsgInvalidField         = "invalid field: %s"
	ErrMsgInvalidCondition     = "invalid condition: %s"
	ErrMsgUnsupportedTypeField = "unsupported value type for field"
	ErrMsgActionNotAllowed     = "action not allowed, invalid value for a filter: %s"
	ErrMsgInvalidSortingField  = "invalid sorting field: %s"
)
View Source
const (
	Eq             = "="
	LessOrEqual    = "<="
	GreaterOrEqual = ">="
	NotEqual       = "!="
	In             = "IN"
	Contains       = "LIKE"
	Between        = "BETWEEN"
)
View Source
const (
	Or  = "OR"
	And = "AND"
)
View Source
const (
	ErrMsgCouldNotConnectDB           string = "could not connect to database for migration %v"
	ErrMsgMigrationExecutionWithError string = "an error occurred during migration execution: %v"
	ErrMsgCreateMigrateInstance       string = "failed to create migrate instance"
)
View Source
const (
	DefaultPage          = uint16(0)
	DefaultLimit         = uint16(15)
	DefaultSortField     = "id"
	DefaultSortDirection = string(ASC)
)
View Source
const (
	SqlTxContextKey contextKey = "sqlTxContext"

	MsgTransactionIsolationIgnored = "transaction isolation only uses the first parameter, others are ignored"
	ErrExecuteTransaction          = "error when executing transaction error: %w"
	ErrTransactionRollback         = "error when executing transaction rollback: %v, original error: %w"
	ErrTransactionCommit           = "could not commit transaction: %w"
	ErrTransactionStart            = "could not start database transaction: %v"
)

Variables

View Source
var (
	NOT_ALLOWED_VALUES = []string{"DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "EXEC", "MERGE"}
)

Functions

func InstanceRedis

func InstanceRedis() *redis.Client

func NewCacheRedis

func NewCacheRedis()

func NewConnectionDB

func NewConnectionDB(databaseURL string, poolConfig *PoolConfig) error

Types

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}

func NewCache

func NewCache[T any](name string, ttl time.Duration) *Cache[T]

func (*Cache[T]) Del

func (c *Cache[T]) Del(ctx context.Context) error

func (*Cache[T]) List

func (c *Cache[T]) List(ctx context.Context) ([]T, error)

func (*Cache[T]) Set

func (c *Cache[T]) Set(ctx context.Context, data any) error

func (*Cache[T]) UniqueResult

func (c *Cache[T]) UniqueResult(ctx context.Context) (*T, error)

type ConnectionDB

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

func InstanceDatabase

func InstanceDatabase() *ConnectionDB

type FieldMapping

type FieldMapping struct {
	Key        string `json:"key"`
	Label      string `json:"label"`
	FilterType string `json:"filterType"`
	SearchType string `json:"searchType"`
}

type Filter

type Filter struct {
	Field           string `json:"field,omitempty"`
	Condition       string `json:"condition,omitempty"`
	Value           any    `json:"value,omitempty"`
	LogicalOperator string `json:"logicalOperator,omitempty"`
}

func AND

func AND() *Filter

func NewFilter

func NewFilter(field, condition string, value any) *Filter

func OR

func OR() *Filter

type FilterParams

type FilterParams struct {
	Page          uint16 `json:"page"`
	Limit         uint16 `json:"limit"`
	SortField     string `json:"sortField"`
	SortDirection string `json:"sortDirection"`
}

type Filters

type Filters struct {
	Params  *FilterParams `json:"params"`
	Filters []*Filter     `json:"filters"`
}

func NewFilters

func NewFilters() *Filters

func (*Filters) Add

func (f *Filters) Add(filter ...*Filter) *Filters

type FloatValue

type FloatValue float64 // currency

type IntValue

type IntValue int64 // integer

type ObjectManager

type ObjectManager[T any] struct {
	// contains filtered or unexported fields
}

func Find

func Find[T any](ctx context.Context, query string, params ...any) *ObjectManager[T]

func FindWithFilter

func FindWithFilter[T any](ctx context.Context, params *QueryParam) *ObjectManager[T]

func NewCustomQuery

func NewCustomQuery[T any](ctx context.Context, query string, params ...any) *ObjectManager[T]

func (*ObjectManager[T]) ExecuteListQuery

func (q *ObjectManager[T]) ExecuteListQuery(instance *sql.DB) ([]T, error)

func (*ObjectManager[T]) ExecutePagedQuery

func (q *ObjectManager[T]) ExecutePagedQuery(instance *sql.DB) (*Page[T], error)

func (*ObjectManager[T]) ExecuteUniqueResultQuery

func (q *ObjectManager[T]) ExecuteUniqueResultQuery(instance *sql.DB) (*T, error)

func (*ObjectManager[T]) List

func (q *ObjectManager[T]) List() ([]T, error)

func (*ObjectManager[T]) PagedList

func (q *ObjectManager[T]) PagedList() (*Page[T], error)

func (*ObjectManager[T]) UniqueResult

func (q *ObjectManager[T]) UniqueResult() (*T, error)

func (*ObjectManager[T]) WithCache

func (q *ObjectManager[T]) WithCache(cache *Cache[T]) *ObjectManager[T]

func (*ObjectManager[T]) WithPage

func (q *ObjectManager[T]) WithPage(page *PageRequest) *ObjectManager[T]

type Page

type Page[T any] struct {
	TotalPages       uint64 `json:"totalPages"`
	TotalElements    uint64 `json:"totalElements"`
	Size             uint64 `json:"size"`
	Number           uint64 `json:"number"`
	NumberOfElements uint64 `json:"numberOfElements"`
	Content          []T    `json:"content"`
}

type PageRequest

type PageRequest struct {
	Page  uint16
	Limit uint16
	Order []Sort
}

func NewPageRequest

func NewPageRequest(page uint16, limit uint16, order []Sort) *PageRequest

func NewPageRequestFilter

func NewPageRequestFilter(filter *Filters) *PageRequest

func (*PageRequest) GetOrder

func (p *PageRequest) GetOrder() string

type PoolConfig

type PoolConfig struct {
	MaxOpenConns    int
	MaxIdleConns    int
	MaxConnLifeTime time.Duration
}

func DefaultPoolConfig

func DefaultPoolConfig() *PoolConfig

type Query

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

func NewQuery

func NewQuery(ctx context.Context, query string, params ...any) *Query

func (*Query) FetchRow

func (q *Query) FetchRow(dbConn *sql.DB) *sql.Row

func (*Query) FetchRows

func (q *Query) FetchRows(dbConn *sql.DB) (*sql.Rows, error)

type QueryMapping

type QueryMapping struct {
	AllowedFields        []FieldMapping
	AllowedSortingFields map[string]string
	Operators            map[string]string
	LogicalOperators     map[string]string
}

func (*QueryMapping) Validate

func (qm *QueryMapping) Validate(items *Filters) error

type QueryParam

type QueryParam struct {
	Query  string
	Params []any
}

func NewQueryBuild

func NewQueryBuild(query string, filter *Filters) *QueryParam

type Sort

type Sort struct {
	Field     string        `json:"field"`
	Direction SortDirection `json:"direction"`
}

func NewSort

func NewSort(field string, direction SortDirection) Sort

type SortDirection

type SortDirection string
const (
	ASC  SortDirection = "ASC"
	DESC SortDirection = "DESC"
)

type Statement

type Statement interface {
	Execute() error
	Close()
}

func NewStatement

func NewStatement(ctx context.Context, query string, args ...interface{}) Statement

type StringValue

type StringValue string // string

type Transaction

type Transaction interface {
	Execute(ctx context.Context, fn func(ctx context.Context) error) error
}

func NewTransaction

func NewTransaction(isolation ...sql.IsolationLevel) Transaction

Jump to

Keyboard shortcuts

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