util

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2024 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const PostgresPlaceholderLimit = 65535

Variables

View Source
var (
	ErrNotBytes                        = errors.New("error not bytes")
	ErrCannotDeleteModelWithInvPurpose = errors.New("cannot delete model with inv purpose")
)
View Source
var DBTimestamptzFormat = "2006-01-02 15:04:05Z07"
View Source
var DateFormat = time.DateOnly
View Source
var DefaultLoggingLevel = zerolog.InfoLevel
View Source
var LOG = NewLogger("default")
View Source
var NoPagination = Page{Off: true}
View Source
var Psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)
View Source
var TimestamptzFormat = time.RFC3339
View Source
var Validator = validator.New()

Functions

func AndWhere

func AndWhere(wheres []string) string

func ArrGet

func ArrGet[T any](arr []T, idx []int) (ret []T)

func Avg

func Avg[T int | float32 | float64](arr []T) (ret T)

func Bind

func Bind(ctx echo.Context, a any) error

func CamelToSnake

func CamelToSnake(s string) string

func CheckHeaderEqual

func CheckHeaderEqual(ctx echo.Context, header, value string) bool

func CloseToPlaceholderLimit

func CloseToPlaceholderLimit(cnt, stride int) int

func CollectBy

func CollectBy[T any, R int | string](arr []T, fn func(T) R) (ret map[R]T)

func ContainInt

func ContainInt(sl []int, elem int) bool

func Contains

func Contains[T any](a T, b []T) bool

check if b has at least one of element in a equality is simply by converting the type to string

func ContainsAll

func ContainsAll[T any](a, b []T) bool

b contains all elements in a

func ContainsAny

func ContainsAny[T any](a, b []T) bool

whether at least one of the elements in a is present in b

func ContainsBy

func ContainsBy[T any](a T, b []T, fn func(a, b T) bool) bool

func Create added in v0.1.8

func Create[T any](log zerolog.Logger, con sq.BaseRunner, table string, req T, returning []string, partitionFunc PartitionFunc) (id int, err error)

func CreateMany added in v0.1.8

func CreateMany[T any](log zerolog.Logger, con sq.BaseRunner, table string, reqs []T, returning []string, partitionFunc PartitionFunc) (ids []int, err error)

func DBArrayValues

func DBArrayValues[T any](array []T) string

func DateFromToday

func DateFromToday(daysOffset int, tz TZ) time.Time

func DateFromTodayUTC

func DateFromTodayUTC(offset int) time.Time

func DateUTC

func DateUTC(y, m, d int) time.Time

func DateUTCFromTime

func DateUTCFromTime(t time.Time) time.Time

func Dates

func Dates(startDate, endDate time.Time) (ret []time.Time)

func DatesBetweenIncl

func DatesBetweenIncl(a, b time.Time) (ret []time.Time)

func DatesFromToday

func DatesFromToday(start, end int, tz TZ) (ret []time.Time)

func Dedup

func Dedup[T any](arr []T) (ret []T)

func Delete added in v0.1.8

func Delete(log zerolog.Logger, con sq.BaseRunner, table string, where []string) (err error)

func EQx

func EQx[T any](name string, v T) string

func EitherRunner

func EitherRunner(tx *sqlx.Tx, db *sqlx.DB) squirrel.BaseRunner

func EndOfDay

func EndOfDay(a time.Time) time.Time

func EndOfMonth

func EndOfMonth(a time.Time) time.Time

func EndOfMonthOrYesterday

func EndOfMonthOrYesterday(a time.Time) time.Time

end of month

func EndOfWeek

func EndOfWeek(a time.Time) time.Time

func EndOfWeekOrYesterday

func EndOfWeekOrYesterday(a time.Time) time.Time

end of month

func ErrBadRequest

func ErrBadRequest(msg string) error

func ErrForbidden

func ErrForbidden(msg string) error

func ErrInternal

func ErrInternal(msg string) error

func ErrUnauthorized

func ErrUnauthorized(msg string) error

func Except

func Except[T any](base, except []T) (ret []T)

remove all items find in `except` from `base`, naive implementation with string equality

func ExistM added in v0.1.8

func ExistM(log zerolog.Logger, con *sqlx.DB, table string, where map[string]any) (ret bool, err error)

func ExistS added in v0.1.8

func ExistS(log zerolog.Logger, con *sqlx.DB, table string, where []string) (bool, error)

func ExtractDBTags

func ExtractDBTags(input any) (tags []string, vals []any)

func ExtractTags

func ExtractTags(input any, tagName string) (tags []string, vals []any)

func Filter

func Filter[T any](arr []T, filterFunc func(t T) bool) (ret []T)

func FilterMap

func FilterMap[T, R any](arr []T, fn func(t T) (R, bool)) (ret []R)

func Filterm

func Filterm[K comparable, V any](m map[K]V, fn func(k K, v V) bool) (ret map[K]V)

func FindAll added in v0.1.2

func FindAll[T any](arr []T, fn func(T) bool) (ret []T)

func FindOne added in v0.1.2

func FindOne[T any](arr []T, fn func(T) bool) (ret T)

func FirstN

func FirstN[T any](arr []T, n int) (ret []T)

func FlatMap

func FlatMap[T, R any](arr []T, fn func(T) []R) (ret []R)

func Flatten

func Flatten[T any](arr [][]T) (ret []T)

func ForEach

func ForEach[T any](arr []T, sideEffectFunc func(t T))

func FromAnys

func FromAnys[T any](arr []any) []T

func GetID

func GetID[T int | string](ctx echo.Context) (t T, err error)

func GetIDsByComma added in v0.1.5

func GetIDsByComma[T int | string](ctx echo.Context) (ret []T, err error)

func GetM added in v0.1.8

func GetM[T any](log zerolog.Logger, con *sqlx.DB, table string, where map[string]any) (ret T, err error)

func GetManyM added in v0.1.8

func GetManyM[T any](log zerolog.Logger, con *sqlx.DB, table string, where map[string]any, orderby []string) (ret []T, err error)

func GetManyS added in v0.1.8

func GetManyS[T any](log zerolog.Logger, con *sqlx.DB, table string, where []string, orderby []string) (ret []T, err error)

func GetParam

func GetParam[T int | string](ctx echo.Context, name string) (t T, err error)

func GetPayload

func GetPayload[T any](ctx echo.Context) (t T, err error)

GetPayload takes care of marshaling the payload from request 1) if the payload was never read before, then it read the payload, and it saves within the context 2) if the payload has already been read, then it read directly from the context can only work if the http verb is NOT [GET DELETE HEAD] for payload in body

func GetPayloads

func GetPayloads[T any](ctx echo.Context) (t []T, err error)

func GetQuery

func GetQuery[T int | string | bool](ctx echo.Context, name string) (t T, err error)

func GetS added in v0.1.8

func GetS[T any](log zerolog.Logger, con *sqlx.DB, table string, where []string) (ret T, err error)

func GetUniqueDirPath

func GetUniqueDirPath(dir string) string

func HasIntersect

func HasIntersect[T any](base []T, another []T, emptyTrue bool) bool

HasIntersect check if another slices has at least one element in the base slice equality check is done by converting element to string

func Head[T any, K comparable](arr []T) (ret T)

func HrBtw

func HrBtw(t time.Time, min, max int) bool

func INx

func INx[T any](name string, ins []T) string

func In

func In[T any](in T, space []T) bool

func InBracket

func InBracket(s, left, right string) bool

func IndexOf

func IndexOf[T any](arr []T, equalFunc func(t T) bool) int

func IndexesExcept

func IndexesExcept[T any](sub, super []T) (ret []int)

func IndexesOf

func IndexesOf[T any](sub, super []T) (ret []int, valid bool)

func Intersect

func Intersect[T string | int | float64](a, b []T) (ret []T)

this implementation didn't take consider if a, b has duplicates

func IsLastDayOfMonth

func IsLastDayOfMonth(a time.Time) bool

func IsStartOfMonth

func IsStartOfMonth(a time.Time) bool

func JoinByComma

func JoinByComma[T any](t []T) string

func Last

func Last[T any](arr []T) (ret T)

func LastDayOfTheMonth

func LastDayOfTheMonth(date time.Time) time.Time

func LastDayOfTheWeek

func LastDayOfTheWeek(date time.Time) time.Time

func LastMonth

func LastMonth() time.Time

func LastN

func LastN[T any](arr []T, n int) (ret []T)

func ListFlex added in v0.1.8

func ListFlex[T any](log zerolog.Logger, con *sqlx.DB, page Page, table string, selects, where, orderby []string) (ret []T, total int, err error)

func ListM added in v0.1.8

func ListM[T any](log zerolog.Logger, con *sqlx.DB, page Page, table string, where map[string]any, orderBy []string) (ret []T, total int, err error)

func ListS added in v0.1.8

func ListS[T any](log zerolog.Logger, con *sqlx.DB, page Page, table string, wheres, order []string) (ret []T, total int, err error)

func Map

func Map[T, R any](arr []T, mapFunc func(t T) R) (ret []R)

func MapE

func MapE[T, R any](arr []T, mapFunc func(t T) (R, error)) (ret []R, err error)

func MapIf added in v0.1.2

func MapIf[T, R any](arr []T, fn func(T) R, pred func(T) bool) (ret []R)

func MapInPlace

func MapInPlace[T any](arr []T, mapFunc func(t T) T)

func MapInPlaceE

func MapInPlaceE[T any](arr []T, mapFunc func(t T) (T, error)) (err error)

func Mapm

func Mapm[K comparable, V, O any](m map[K]V, fn func(k K, v V) O) (ret []O)

func MarshalResp added in v0.1.7

func MarshalResp[T any](resp *http.Response) (ret T, err error)

func Max

func Max[T int | float32 | float64](a, b T) T

func MaxBy

func MaxBy[T any, R int | float64](arr []T, maxBy func(t T) R) (max R)

func MaxDayInMonth

func MaxDayInMonth(month int) (day int)

func MaxTime

func MaxTime(a, b time.Time) time.Time

func Min

func Min[T int | float32 | float64 | uint64](a, b T) T

func MinTime

func MinTime(a, b time.Time) time.Time

func MonthFromToday

func MonthFromToday(monthOffset int) time.Time

func MonthsFromToday

func MonthsFromToday(start, end int) (ret []time.Time)

func MultipleJsonbSet

func MultipleJsonbSet(fieldName string, setMap map[string]any) (ret string)

func MustTime

func MustTime(str string) time.Time

func NewDB added in v0.1.8

func NewDB(dbName, url string, dcfg DBConfig) *sqlx.DB

func NewLogger

func NewLogger(from string) zerolog.Logger

func NewLoggerWithLevel

func NewLoggerWithLevel(from string, minLevel zerolog.Level) zerolog.Logger

func NewRand

func NewRand() *rand.Rand

func NewTestDB added in v0.1.9

func NewTestDB(migrationPath string) *sqlx.DB

base db name and access is hardcoded, and it's linked with Storage-Up in Makefile

func NotNullCount

func NotNullCount(ts ...interface{}) int

func NowByTZ

func NowByTZ(tz TZ) time.Time

func OkJSON

func OkJSON(ctx echo.Context, data any) error

func OneOf

func OneOf[T any](t T, arr []T) bool

func OrDefault

func OrDefault(value string, defaultValue string) string

func Paginate

func Paginate[T any](arr []T, page Page) []T

func Panic

func Panic(err error)

func ParseDBArray

func ParseDBArray[T any](repr string) (ret []T, err error)

ParseDBArray supported type is based on the needed usecases (number, time, etc)

func ParseJSONToStruct

func ParseJSONToStruct(src interface{}, dest interface{}) error

func ParseTime

func ParseTime(s string) (ret time.Time, err error)

func Partition

func Partition[T int | string](partitionTableName string, fullTableName string, partitionValue T) (res string)

func PartitionTruncate

func PartitionTruncate(t time.Time, timeLevel AggLevel) time.Time

func PickRandom

func PickRandom[T any](choices []T) (ret T)

func PostJSON

func PostJSON[REQ, RESP any](req REQ, url string) (ret RESP, err error)

func PostJSONWH added in v0.1.3

func PostJSONWH[REQ, RESP any](req REQ, url string, extraHeader map[string]string) (ret RESP, err error)

func Print

func Print(obj ...any)

func RM

func RM(t time.Time) time.Time

random moment in the same date

func RandInDayStr

func RandInDayStr(dateStr string) time.Time

func Random added in v0.1.2

func Random[T any](arr []T) T

func RandomAlphabets

func RandomAlphabets(l int, lowerCase bool) string

func RandomAlphanumeric

func RandomAlphanumeric(l int, lowerCase bool) string

func RandomBool

func RandomBool() bool

func RandomFloat64

func RandomFloat64(low float64, high float64) float64

func RandomInt

func RandomInt(low int, high int) int

func RandomIntBetween

func RandomIntBetween(min, max int) int

func RandomMomentInADay

func RandomMomentInADay(t time.Time) time.Time

func RandomString

func RandomString(low int, high int) (ret string)

func RandomizeTime

func RandomizeTime(t time.Time, parts string) time.Time

func Range

func Range(start, end int) (ret []int)

func ReadCSVFile

func ReadCSVFile(filename string) (map[string][]string, error)

func RespCSV

func RespCSV(ctx echo.Context, err error, csv string) error

func RespJSON

func RespJSON(ctx echo.Context, err error, payload any) error

func RespNoContent

func RespNoContent(ctx echo.Context, err error) error

func SameDate

func SameDate(a, b time.Time) bool

func SelectStr

func SelectStr(cols ...string) string

func SetActive added in v0.1.8

func SetActive(log zerolog.Logger, con *sqlx.DB, table string, id int, active bool) (err error)

func SetDelete added in v0.1.8

func SetDelete(log zerolog.Logger, con *sqlx.DB, table string, id int, del bool) (err error)

func SetDifference

func SetDifference[T comparable](a, b map[T]bool) (ret map[T]bool)

func SetIntersect

func SetIntersect[T comparable](a, b map[T]bool) (ret map[T]bool)

func SetValues

func SetValues[T comparable](a map[T]bool) (ret []T)

func SetupLocalStorage added in v0.1.8

func SetupLocalStorage(newDB, baseDB, baseUrl, migrationFile string)

skip migration if migration file path is empty

func Shuffle

func Shuffle[T any](arr []T)

func SimpleFloatEqual

func SimpleFloatEqual(a, b, epsilon float64) bool

can use relative tolerance, but for now absolute tolerance is sufficient

func SliceEqual

func SliceEqual[T any](a, b []T) bool

func SortAsStr

func SortAsStr[T any](arr []T) []T

func SortTime

func SortTime(ts []time.Time)

func StartOfDay

func StartOfDay(a time.Time) time.Time

func StartOfMonth

func StartOfMonth(a time.Time) time.Time

func StartOfPrevMonth

func StartOfPrevMonth(a time.Time) time.Time

func StartOfWeek

func StartOfWeek(a time.Time) time.Time

func StructDataType

func StructDataType(s interface{}) []string

func StructTags

func StructTags(s interface{}, tagName string, except map[string]any) (ret []string)

func Sum

func Sum[T int | float32 | float64](arr []T) (ret T)

func Tail

func Tail[T any](arr []T) (ret T)

func TimeByTz

func TimeByTz(t time.Time, tz TZ) time.Time

func TimeEqual

func TimeEqual(a, b time.Time) bool

TimeEqual compare if two time is the same without considering the nano second

func TimeIncr

func TimeIncr(t time.Time, aggLevel AggLevel) (time.Time, error)

func TimePointsFiller

func TimePointsFiller(ids []string, pts []time.Time) string

func Timestamp

func Timestamp(y, m, d, h, min, s int) time.Time

func ToAnys

func ToAnys[T any](arr []T) []any

func ToDate

func ToDate(t time.Time) time.Time

func ToDateUTC

func ToDateUTC(t time.Time) time.Time

func ToFloat64

func ToFloat64(x any) (val float64, err error)

func ToMap

func ToMap[T comparable](arr []T) (ret map[T]bool)

func ToMid

func ToMid(handler echo.HandlerFunc) echo.MiddlewareFunc

ToMid means ToMIddleware convert HandlerFunc to one type of middleware, next() is at the bottom

func ToPqStrArray

func ToPqStrArray[T any](arr []T) (ret pq.StringArray)

func ToStr

func ToStr[T any](a T) string

func Truncate

func Truncate(t time.Time, timeLevel AggLevel) time.Time

func Unique

func Unique[T any](arr []T) (ret []T)

func UniqueBy

func UniqueBy[T any](arr []T, fn func(T) string) (ret []T)

func UniqueOf

func UniqueOf[T, R any](arr []T, fn func(T) R) (ret []R)

func UpdateClause

func UpdateClause(headers, pks []string, mergeStrategy map[string]string) string

func UpdateM added in v0.1.8

func UpdateM(log zerolog.Logger, con sq.BaseRunner, table string, where map[string]any, sets map[string]any) (err error)

func UpdateMore added in v0.1.8

func UpdateMore(log zerolog.Logger, con sq.BaseRunner, table string, ids []int, sets map[string]any) (err error)

func UpdateS added in v0.1.8

func UpdateS(log zerolog.Logger, con sq.BaseRunner, table string, where []string, sets map[string]any) (err error)

func UpdateWithID added in v0.1.8

func UpdateWithID(log zerolog.Logger, con sq.BaseRunner, table string, id int, sets map[string]any) (err error)

func UpsertManyNoPartition added in v0.1.8

func UpsertManyNoPartition[T any](log zerolog.Logger, con sq.BaseRunner, table string, pks []string, tag string, toInsert []T, mergeStrategy map[string]string) (err error)

func UpsertQuery

func UpsertQuery(cols []string) string

func ValueList

func ValueList[T any](arr []T, label string, withOrder bool) string

func ValueListTable

func ValueListTable[T any](arr []T, label string) string

func YesterdayByTZ

func YesterdayByTZ(tz TZ) time.Time

func YesterdayOf

func YesterdayOf(t time.Time) time.Time

Types

type AggLevel

type AggLevel string
const (
	LevelNA    AggLevel = "n/a"
	LevelHour  AggLevel = "hour"
	LevelDay   AggLevel = "day"
	LevelWeek  AggLevel = "week"
	LevelMonth AggLevel = "month"
)

type Checkable

type Checkable interface {
	Check() error
}

type CustomValidator

type CustomValidator struct {
	Validator *validator.Validate
}

type DBConfig added in v0.1.8

type DBConfig struct {
	MaxOpenConn     int
	MaxIdelConn     int
	ConnMaxIdleTime time.Duration
	ConnMaxLifetime time.Duration
}

func (*DBConfig) SetDefault added in v0.1.8

func (d *DBConfig) SetDefault()

type Decimal added in v0.1.3

type Decimal decimal.Decimal

func NewDecimal added in v0.1.3

func NewDecimal(s string) Decimal

func NewDecimalF added in v0.1.3

func NewDecimalF(f float64) Decimal

func (Decimal) MarshalJSON added in v0.1.3

func (d Decimal) MarshalJSON() ([]byte, error)

func (*Decimal) Scan added in v0.1.3

func (o *Decimal) Scan(value any) (err error)

func (Decimal) String added in v0.1.3

func (d Decimal) String() string

func (*Decimal) UnmarshalJSON added in v0.1.3

func (d *Decimal) UnmarshalJSON(data []byte) error

func (Decimal) Unwrap added in v0.1.3

func (d Decimal) Unwrap() decimal.Decimal

func (Decimal) Value added in v0.1.3

func (o Decimal) Value() (driver.Value, error)

type Err

type Err struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

func ErrNotFound added in v0.1.4

func ErrNotFound(msg string) Err

func NewErr

func NewErr(code int, msg string, data any) Err

func (Err) Error

func (e Err) Error() string

type InsertHelper

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

func NewInsertHelper

func NewInsertHelper(table string, cols []string, mergeStrategy string, execer sqlx.Execer) InsertHelper

func (*InsertHelper) Add

func (ih *InsertHelper) Add(args []any) (err error)

func (*InsertHelper) Finish

func (ih *InsertHelper) Finish() (err error)

type Obj

type Obj map[string]any

func ToObj

func ToObj(s any) (ret Obj)

type Page

type Page struct {
	Page    int `query:"page"`
	PerPage int `query:"per_page"`
	Off     bool
}

func GetPagination

func GetPagination(ctx echo.Context) (ret Page, err error)

func (Page) DBSlice

func (p Page) DBSlice(col string) string

only valid for database array, has off by one error for go array

func (Page) GoSliceStartEnd

func (p Page) GoSliceStartEnd(slen int) (int, int)

func (Page) Limit

func (p Page) Limit() uint64

func (Page) Offset

func (p Page) Offset() uint64

type PaginatedResult

type PaginatedResult struct {
	Total int `json:"total"`
	Data  any `json:"data"`
}

func (PaginatedResult) Error

func (PaginatedResult) Error() string

Error implements error

type PartitionFunc added in v0.1.8

type PartitionFunc func(runner sq.BaseRunner, table string) error

type ReqCtx

type ReqCtx struct {
	Req  *http.Request
	Resp *httptest.ResponseRecorder
	Ctx  echo.Context
}

func NewHttpTestKit

func NewHttpTestKit(engine *echo.Echo, r RequestCfg) ReqCtx

type RequestCfg

type RequestCfg struct {
	Method      string
	URL         string
	Headers     StrMap
	QueryParams StrMap
	Cookies     []http.Cookie
	Payload     any // should be a struct
	CtxKVs      Obj
}

type StrMap

type StrMap map[string]string

type TZ

type TZ string // +08:00

func ParseTZ

func ParseTZ(t time.Time) (ret TZ)

func ToTZ

func ToTZ(ts string) (ret TZ, err error)

type TsPoint

type TsPoint struct {
	T time.Time `json:"t" db:"t"`
	V float64   `json:"v" db:"v"`
}

type TsPoints

type TsPoints []TsPoint

func (TsPoints) Sort

func (t TsPoints) Sort()

type TsRange

type TsRange struct {
	Start    time.Time
	End      time.Time
	AggLevel AggLevel
}

func (TsRange) Times

func (t TsRange) Times() (ret []time.Time, err error)

func (TsRange) TimesAny

func (t TsRange) TimesAny() (ret []any, err error)

func (TsRange) TimesBeforeTodayDesc

func (t TsRange) TimesBeforeTodayDesc() (ret []time.Time, err error)

Jump to

Keyboard shortcuts

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