velum

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 21, 2025 License: MIT Imports: 8 Imported by: 0

README

velum

Build Status Go Report Card GoDoc Coverage Status

type Customer struct {
	ID 			int  		`dbw:"pk,gen=serial"` 
	FirstName 	string 
	LastName 	string 
	BirthDate   date.Date   `dbw:"bd"`     
	SSN         string 		`dbw:"ssn"`
	Address 	struct {
		Line1 	string 
		Line2 	*string
		CityID 	int 
		Country int 
		Zip 	string 
	} 
	Origin string  		 	`dbw:"-"`
	RowVersion 	int64		`dbw:"version"`
	CreatedAt 	time.Time  	`dbw:"insert"`
	UpdatedAt 	*time.Time 	`dbw:"update"`
	DeletedAt 	*time.Time 	`dbw:"delete"`
	DeletedBy 	*int       	`dbw:"delete"`
}

	// once
	dbSql, err = sql.Open("postgres", connectionString)
	dbwSql = sqlw.NewDatabaseWrapper(dbSql) // database sql wrapper here, pgx supported too
	tbl := velum.NewTable[Customer]()

	// get table row by primary key value
	c, err := tbl.GetByPK(ctx, dbwSql, 42)
	
	nc := Customer{FirstName: "Robert", LastName : "Egorov"}
	err := tbl.Insert(ctx, dbSql, &nc)
	fmt.Println("new customer id: ", nc.ID)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoPrimaryKey     = errors.New("no primary key defined")
	ErrInvalidScopePair = errors.New("invalid scope pair")
)
View Source
var (
	TagKey                      = "dbw"
	VersionField          Scope = "version"
	InsertScope           Scope = "insert"
	UpdateScope           Scope = "update"
	DeleteScope           Scope = "delete"
	PrimaryKeyTagOption         = "pk"
	StandardPrimaryKeyCol       = "id"
	SystemScope           Scope = "system"
)
View Source
var DefaultColumnNameBuilder = ToSnakeCase

DefaultColumnNameBuilder refers to the function that converts the field name to the column name.

View Source
var DefaultFieldTag = "dbw"
View Source
var DefaultFriendlySequenceNameBuilder = TableWithSeqSuffix

DefaultFriendlySequenceNameBuilder refers to the function that converts the table name to the sequence name.

Usually the sequence naming convention is <table_name>_seq, etc.

View Source
var DefaultParamPlaceholderBuilder = ArgAsNumber

DefaultParamPlaceholderBuilder refers to the function that converts the argument position to the placeholder in the SQL query.

View Source
var (
	ErrScopeMismatch = errors.New("scope mismatch")
)

SystemScopes holds the system scopes.

Functions

func ArgAsNumber

func ArgAsNumber(i int) string

func ArgAsQuestionMark

func ArgAsQuestionMark(i int) string

func InsertArgument

func InsertArgument(genMethod ColumnValueGenMethod, valueGenerator string, regularParam string) (sqlParam string)

InsertArgument returns the argument for the insert command if the value of the column is generated by the database. If the value is not generated by the database, it returns the regularParam.

func IsSystemScope

func IsSystemScope(s Scope) bool

IsSystemScope returns true if the scope is a system scope.

func IsTagOptionExist

func IsTagOptionExist(tag string, tagOption string) bool

IsTagOptionExists checks if the tag contains the tagOption. dbw:"name=customer_id,pk" -> IsTagOptionExists("name=customer_id,pk", "pk") returns true. dbw:"name=customer_id,pk" -> IsTagOptionExists("name=customer_id,pk", "name") returns true.

func ShiftParamPositions

func ShiftParamPositions(sqlWhere string, fromIndex int) string

ShiftParamPositions replaces "id = $1 OR id > $1 AND name < $2" with "id = $10 OR id > $10 AND name < $11" if fromIndex is 10.

func StructPluralName

func StructPluralName(v any) string

StructPluralName converts the struct name to the table name. By default, it converts the struct name to snake case and pluralizes it.

func TableWithSeqSuffix

func TableWithSeqSuffix(tablename string) string

func ToPluralName

func ToPluralName(s string) string

func ToSnakeCase

func ToSnakeCase(attr, tag string) string

ToSnakeCase takes 'customer_id' if attribute tag is `dbw:"name=customer_id"`, otherwise it converts the attribute name to snake case: CustomerID int -> customer_id.

Types

type ArgFormatter

type ArgFormatter func(i int) string

type Column

type Column struct {
	// Name is the name of the column in the database.
	Name string
	// Path is the path to the column in the struct.
	Path []int
	// Tag holds parsed tags from the struct field.
	Tag reflectx.TagPairs
	// ValueGenerationMethod is the method used to generate the value of
	// the column, if any.
	ValueGenerationMethod ColumnValueGenMethod
	// ValueGenerator is the name of a sequence or a stored function used to
	// generate the value of the column.
	ValueGenerator string
}

func (*Column) IsSystem

func (c *Column) IsSystem() bool

IsSystem returns true if the column is a system column. System columns are columns that are not part of the application data. They are used for versioning, soft delete, etc.

func (*Column) IsValueGeneratedByDB

func (c *Column) IsValueGeneratedByDB() bool

IsValueGeneratedByDB returns true if the value of the column is generated by the database. This is used for the insert command.

type ColumnValueGenMethod

type ColumnValueGenMethod string

ColumnValueGenMethod defines the method to generate the value of a field.

const (
	// Default sequence generation method. It is used when no sequence generation method is defined.
	// The function SequenceNameBuilder is used to generate sequence name by table name.
	FriendlySequence ColumnValueGenMethod = ""

	// SerialFieleType says the field is serial and it is generated by database.
	SerialFieleType ColumnValueGenMethod = "serial"

	// UuidFileType says the field is uuid and it is generated by database.
	UuidFileType ColumnValueGenMethod = "uuid"

	// NoSequence says the field value is generated and assigned by application.
	NoSequence ColumnValueGenMethod = "no"

	// CustomSequece holds the sequence name to be used for the field in insert operation.
	CustomSequece ColumnValueGenMethod = "customseq"
)

type Command

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

func (*Command[T]) Exec

func (c *Command[T]) Exec(ctx context.Context, q Executer, row *T, args ...any) (Result, error)

type CommandContanier

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

func NewCommandContainer

func NewCommandContainer[T any](
	t *Table[T],
	sfpe StructFieldPtrExtractor[T],
	sc map[scopeKey]clause,
	anb ArgFormatter,
) *CommandContanier[T]

func (*CommandContanier[T]) Delete

func (cc *CommandContanier[T]) Delete(clauses string) Command[T]

func (*CommandContanier[T]) DeleteReturning

func (cc *CommandContanier[T]) DeleteReturning(retScope Scope, clauses string) ReturningCommand[T]

func (*CommandContanier[T]) Func

func (cc *CommandContanier[T]) Func(typ FunctionalCommandEnum, clauses string) FunctionalCommand[T]

func (*CommandContanier[T]) Insert

func (cc *CommandContanier[T]) Insert(scope Scope) Command[T]

func (*CommandContanier[T]) InsertReturning

func (cc *CommandContanier[T]) InsertReturning(argScope, retScope Scope) ReturningCommand[T]

func (*CommandContanier[T]) Select

func (cc *CommandContanier[T]) Select(scope Scope, clauses string) SelectCommand[T]

func (*CommandContanier[T]) Update

func (cc *CommandContanier[T]) Update(scope Scope, condition UpdateByOption) Command[T]

func (*CommandContanier[T]) UpdateReturning

func (cc *CommandContanier[T]) UpdateReturning(argScope, retScope Scope, condition UpdateByOption) ReturningCommand[T]

type CommandTypeEnum

type CommandTypeEnum int
const (
	Insert CommandTypeEnum = iota
	Update
	Delete
	CommandTypeEnumMax_
)

type DatabaseWrapper added in v0.0.2

type DatabaseWrapper interface {
	Executer
	QueryRowExecuter
	QueryExecuter
	IsNotFound(err error) bool
	Begin(context.Context) (Transaction, error)
	InTx(context.Context, func(Transaction) error) error
}

type DoubleScopeKey

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

type Executer

type Executer interface {
	ExecContext(ctx context.Context, sql string, args ...any) (Result, error)
}

type FuncCommandKey

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

type FunctionalCommand

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

func (*FunctionalCommand[T]) Call

func (c *FunctionalCommand[T]) Call(ctx context.Context, q QueryRowExecuter, dst any, args ...any) error

type FunctionalCommandEnum

type FunctionalCommandEnum int
const (
	Exist FunctionalCommandEnum = iota
	ExistByPK
	Count
)

type IsolationLevel

type IsolationLevel int

IsolationLevel is the transaction isolation level used in TxOptions.

const (
	LevelDefault IsolationLevel = iota
	LevelReadUncommitted
	LevelReadCommitted
	LevelWriteCommitted
	LevelRepeatableRead
	LevelSnapshot
	LevelSerializable
	LevelLinearizable
)

type QueryExecuter

type QueryExecuter interface {
	QueryContext(ctx context.Context, sql string, args ...any) (Rows, error)
}

type QueryRowExecuter

type QueryRowExecuter interface {
	QueryRowContext(ctx context.Context, sql string, args ...any) Row
}

type Result

type Result interface {

	// RowsAffected returns the number of rows affected by an
	// update, insert, or delete. Not every database or database
	// driver may support this.
	RowsAffected() (int64, error)
}

type ReturningCommand

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

func (*ReturningCommand[T]) Query

func (c *ReturningCommand[T]) Query(ctx context.Context, q QueryExecuter, args ...any) ([]T, error)

func (*ReturningCommand[T]) QueryRow

func (c *ReturningCommand[T]) QueryRow(ctx context.Context, q QueryRowExecuter, str *T, args ...any) (*T, error)

func (*ReturningCommand[T]) QueryRowTo added in v0.0.2

func (c *ReturningCommand[T]) QueryRowTo(ctx context.Context, q QueryRowExecuter, str *T, args ...any) error

type Row

type Row interface {
	Scan(args ...any) error
	Err() error
}

type Rows

type Rows interface {
	// Close closes the rows, making the connection ready for use again. It is safe
	// to call Close after rows is already closed.
	Close() error

	// Err returns any error that occurred while reading. Err must only be called after the Rows is closed (either by
	// calling Close or by Next returning false). If it is called early it may return nil even if there was an error
	// executing the query.
	Err() error

	// Next prepares the next row for reading. It returns true if there is another
	// row and false if no more rows are available or a fatal error has occurred.
	// It automatically closes rows when all rows are read.
	//
	// Callers should check rows.Err() after rows.Next() returns false to detect
	// whether result-set reading ended prematurely due to an error. See
	// Conn.Query for details.
	//
	// For simpler error handling, consider using the higher-level pgx v5
	// CollectRows() and ForEachRow() helpers instead.
	Next() bool

	// Scan reads the values from the current row into dest values positionally.
	// dest can include pointers to core types, values implementing the Scanner
	// interface, and nil. nil will skip the value entirely. It is an error to
	// call Scan without first calling Next() and checking that it returned true.
	Scan(dest ...any) error
}

type Scope

type Scope string

Scope defines the group of the fields in the struct to be used in the query operation.

const (
	EmptyScope Scope = ""

	// FullScope is the scope that includes all fields, including system fields.
	FullScope Scope = "*"
)

type SelectCommand

type SelectCommand[T any] Command[T]

func (*SelectCommand[T]) Get

func (c *SelectCommand[T]) Get(ctx context.Context, q QueryRowExecuter, args ...any) (*T, error)

func (*SelectCommand[T]) GetMany

func (c *SelectCommand[T]) GetMany(ctx context.Context, q QueryExecuter, args ...any) ([]T, error)

func (*SelectCommand[T]) GetToPtr

func (c *SelectCommand[T]) GetToPtr(ctx context.Context, q QueryRowExecuter, dst []any, args ...any) error

type SingleScopeKey

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

type StructFieldPtrExtractor

type StructFieldPtrExtractor[T any] interface {
	StructFieldPtrs(v *T, fieldPositions []int) *[]any
	Release(*[]any)
}

type SystemColumn

type SystemColumn struct {
	*Column
	// Pos is the position of the column in the columns slice.
	Pos int
}

SystemColumn describes a column in the database that is used for versioning, soft delete, etc. It is a wrapper around the Column struct to add the position of the column in the columns slice.

type Table

type Table[T any] struct {
	ObjPool *sync.Pool
	// contains filtered or unexported fields
}

Table is a struct that represents a database table.

func NewTable

func NewTable[T any](tablename string, opts ...TableOption) *Table[T]

func (*Table[T]) ArgNumerator

func (t *Table[T]) ArgNumerator() ArgFormatter

func (*Table[T]) Columns

func (t *Table[T]) Columns() []Column

func (*Table[T]) CommandContainer

func (t *Table[T]) CommandContainer() *CommandContanier[T]

func (*Table[T]) Count

func (t *Table[T]) Count(ctx context.Context, q QueryRowExecuter, clauses string, args ...any) (int, error)

func (*Table[T]) Created

func (t *Table[T]) Created() []SystemColumn

func (*Table[T]) Delete

func (t *Table[T]) Delete(ctx context.Context, q Executer, clauses string, args ...any) (Result, error)

func (*Table[T]) DeleteByPK

func (t *Table[T]) DeleteByPK(ctx context.Context, q Executer, pk any) (Result, error)

func (*Table[T]) DeleteReturning

func (t *Table[T]) DeleteReturning(ctx context.Context, q QueryRowExecuter, row *T, clauses string) (*T, error)

func (*Table[T]) DeleteReturningByPK

func (t *Table[T]) DeleteReturningByPK(ctx context.Context, q QueryRowExecuter, row *T) (*T, error)

func (*Table[T]) Deleted

func (t *Table[T]) Deleted() []SystemColumn

func (*Table[T]) Exist

func (t *Table[T]) Exist(ctx context.Context, q QueryRowExecuter, clauses string, args ...any) (bool, error)

func (*Table[T]) ExistByPK

func (t *Table[T]) ExistByPK(ctx context.Context, q QueryRowExecuter, pk any) (bool, error)

func (*Table[T]) FormatArg

func (t *Table[T]) FormatArg(pos int) string

func (*Table[T]) FriendlySequence

func (t *Table[T]) FriendlySequence() string

func (*Table[T]) Get

func (t *Table[T]) Get(ctx context.Context, q QueryRowExecuter, scope Scope, clauses string, clausArgs ...any) (*T, error)

func (*Table[T]) GetByPK

func (t *Table[T]) GetByPK(ctx context.Context, q QueryRowExecuter, pk any) (*T, error)

func (*Table[T]) GetTo

func (t *Table[T]) GetTo(ctx context.Context, q QueryRowExecuter, dst []any, pk any) error

func (*Table[T]) Insert

func (t *Table[T]) Insert(ctx context.Context, q QueryRowExecuter, row *T) error

func (*Table[T]) InsertReturning

func (t *Table[T]) InsertReturning(ctx context.Context, q QueryRowExecuter, row *T, scope, retScope Scope) (*T, error)

func (*Table[T]) InsertScope added in v0.0.2

func (t *Table[T]) InsertScope(ctx context.Context, q Executer, row *T, scope Scope) (Result, error)

func (*Table[T]) Name

func (t *Table[T]) Name() string

Name returns the table name.

func (*Table[T]) Object

func (t *Table[T]) Object(scope Scope) (*T, *[]any)

func (*Table[T]) ObjectPut

func (t *Table[T]) ObjectPut(v *T, ptrs *[]any)

func (*Table[T]) PK

func (t *Table[T]) PK() *SystemColumn

func (*Table[T]) Scope

func (t *Table[T]) Scope(s string) Scope

Scope returns a scope by its name. If the scope is not found, it panics. This function is used to validate the scope by the caller.

func (*Table[T]) ScopeContainer

func (t *Table[T]) ScopeContainer() map[scopeKey]clause

func (*Table[T]) Select

func (t *Table[T]) Select(ctx context.Context, q QueryExecuter, scope Scope, clauses string, args ...any) ([]T, error)

func (*Table[T]) SelectAll added in v0.0.2

func (t *Table[T]) SelectAll(ctx context.Context, q QueryExecuter) ([]T, error)

func (*Table[T]) SoftDeleteByPK

func (t *Table[T]) SoftDeleteByPK(ctx context.Context, q Executer, row *T) (Result, error)

func (*Table[T]) SoftDeleteReturningByPK

func (t *Table[T]) SoftDeleteReturningByPK(ctx context.Context, q QueryRowExecuter, row *T) (*T, error)

func (*Table[T]) TouchByPK

func (t *Table[T]) TouchByPK(ctx context.Context, q Executer, row *T) (Result, error)

func (*Table[T]) Update

func (t *Table[T]) Update(ctx context.Context, q Executer, row *T, scope Scope, clauses string) (Result, error)

func (*Table[T]) UpdateByPK

func (t *Table[T]) UpdateByPK(ctx context.Context, q Executer, row *T, scope Scope) (Result, error)

func (*Table[T]) UpdateReturning

func (t *Table[T]) UpdateReturning(ctx context.Context, q QueryRowExecuter, row *T, scope, retScope Scope, clauses string) (*T, error)

func (*Table[T]) UpdateReturningByPK

func (t *Table[T]) UpdateReturningByPK(ctx context.Context, q QueryRowExecuter, row *T, scope, retScope Scope) (*T, error)

func (*Table[T]) Updated

func (t *Table[T]) Updated() []SystemColumn

func (*Table[T]) Validate

func (t *Table[T]) Validate(ctx context.Context) error

func (*Table[T]) Version

func (t *Table[T]) Version() *SystemColumn

type TableConfig

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

type TableOption

type TableOption func(*TableConfig)

func WithArgFormatter

func WithArgFormatter(f ArgFormatter) TableOption

func WithColumnNameBuilder

func WithColumnNameBuilder(f func(attr string, tag string) string) TableOption

func WithName

func WithName(name string) TableOption

func WithSequenceNameBuilder

func WithSequenceNameBuilder(f func(string) string) TableOption

func WithTag

func WithTag(tag string) TableOption

type Tabler

type Tabler interface {
	Name() string
	Columns() []Column
	PK() *SystemColumn
	FormatArg(int) string
}

type Transaction

type Transaction interface {
	Executer
	QueryRowExecuter
	QueryExecuter
	Commit(context.Context) error
	Rollback(context.Context) error
}

type UpdateByOption

type UpdateByOption func() string

func ByClauses

func ByClauses(clauses string) UpdateByOption

func ByPK

func ByPK() UpdateByOption

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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