Documentation ¶
Overview ¶
Package lyspg contains structs and functions providing generic CRUD operations on a Postgres database.
Index ¶
- Constants
- Variables
- func Archive[pkT PrimaryKeyType](ctx context.Context, tx pgx.Tx, schemaName, tableName, pKColName string, ...) error
- func BulkDelete[T any](ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, ...) error
- func BulkInsert[T any](ctx context.Context, db PoolOrTx, schemaName, tableName string, inputs []T) (rowsAffected int64, err error)
- func BulkUpdate[T any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, ...) error
- func CheckEnumValue(ctx context.Context, db PoolOrTx, dbEnum, testVal, enumName string) error
- func DeleteByValue(ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, ...) error
- func DeleteUnique(ctx context.Context, db *pgxpool.Pool, ...) error
- func Exists(ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, ...) (ret bool, err error)
- func ExistsConditions(ctx context.Context, db PoolOrTx, schemaName, tableName, match string, ...) (ret bool, err error)
- func GetRowCount(ctx context.Context, db PoolOrTx, schemaName, tableName string) (rowCount int64, err error)
- func GetRowCountExplain(ctx context.Context, db PoolOrTx, qry string, paramValues []any) (rowCount int64, err error)
- func GetRowCountPlaceholderQry(ctx context.Context, db PoolOrTx, qry string, paramValues []any) (rowCount int64, err error)
- func GetStatsRowCount(ctx context.Context, db PoolOrTx, schemaName, tableName string) (rowCount int64, err error)
- func GetTableColumnNames(ctx context.Context, db PoolOrTx, schemaName, tableName string) (colNames []string, err error)
- func GetTableComment(ctx context.Context, db PoolOrTx, schemaName, tableName string) (comment string, err error)
- func GetTableShortName(ctx context.Context, db PoolOrTx, schemaName, tableName string) (shortName string, err error)
- func Insert[inputT any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, ...) (newPk pkT, err error)
- func InsertSelect[inputT any, itemT any](ctx context.Context, db PoolOrTx, ...) (newItem itemT, err error)
- func Restore[pkT PrimaryKeyType](ctx context.Context, tx pgx.Tx, schemaName, tableName, pkColName string, ...) error
- func SelectArray[T any](ctx context.Context, db PoolOrTx, selectStmt string, params ...any) (ar []T, err error)
- func SelectByArray[inputT, itemT any](ctx context.Context, db PoolOrTx, schema, view, column string, ar []inputT) (items []itemT, err error)
- func SelectEnum(ctx context.Context, db PoolOrTx, enumName string, ...) (vals []string, err error)
- func SelectT[T any](ctx context.Context, db PoolOrTx, selectStmt string, params ...any) (items []T, err error)
- func SelectUnique[T any](ctx context.Context, db PoolOrTx, schema, view, column string, ...) (item T, err error)
- func Update[T any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, ...) error
- func UpdatePartial[pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, ...) error
- type Column
- type Condition
- type DataUpdateCols
- type ForeignKey
- type Operator
- type PoolOrTx
- type PrimaryKeyType
- type SelectParams
- type TotalCount
- type UpdateOption
Constants ¶
const ( ErrDescInsertScanFailed string = "db.QueryRow or Scan failed" ErrDescUpdateExecFailed string = "db.Exec failed" ErrDescGetRowsAffectedFailed string = "sqlRes.RowsAffected() failed" )
error strings used by internal errors
const MaxStmtPrintChars int = 5000
max number of characters of a statement to print in error logs
Variables ¶
var ( ArchivedTableSuffix = "_archived" ArchivedTableCols = []string{"archived_at", "archived_by_cascade"} )
var ( DataUpdateViewSuffix = "_data_update" DataUpdateColTags = []string{"data_update_id", "affected_id", "affected_at", "affected_by", "affected_old_values", "affected_new_values"} )
Functions ¶
func Archive ¶ added in v0.1.16
func Archive[pkT PrimaryKeyType](ctx context.Context, tx pgx.Tx, schemaName, tableName, pKColName string, pkVal pkT, isCascaded bool) error
Archive moves record(s) to a table's corresponding archived table using the supplied tx the archived table name must be the source table name plus ArchivedTableSuffix the archived table must have the same columns as the source table and also the ArchivedTableCols defined above the column order does not need to be the same in the source and archived tables if this func returns an error, rollback the tx
func BulkDelete ¶ added in v0.1.32
func BulkDelete[T any](ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, vals []T) error
BulkDelete deletes multiple records in the same table based on a column value partial success possible: if some vals are not found, an error will be returned containing the failed vals, but the other rows will be deleted
func BulkInsert ¶
func BulkInsert[T any](ctx context.Context, db PoolOrTx, schemaName, tableName string, inputs []T) (rowsAffected int64, err error)
BulkInsert inserts multiple records using the postgres COPY protocol T must be a struct with "db" tags
func BulkUpdate ¶ added in v0.1.32
func BulkUpdate[T any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, inputs []T, pkVals []pkT, options ...UpdateOption) error
BulkUpdate changes multiple records in the same table identified by pkVals with the values contained in inputs T must be a struct with "db" tags partial success possible: if some pkVals are not found, an error will be returned containing the failed pks, but the other rows will be updated
func CheckEnumValue ¶
CheckEnumValue returns an error if the suppied testVal is not found in the supplied pg enum type
func DeleteByValue ¶
func DeleteByValue(ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, val any) error
DeleteByValue deletes from the supplied database table using the value of any column must delete at least 1 row
func DeleteUnique ¶
func DeleteUnique(ctx context.Context, db *pgxpool.Pool, schemaName, tableName, columnName string, uniqueVal any) error
DeleteUnique is guaranteed to delete a single row from the supplied database table using the unique value supplied
func Exists ¶
func Exists(ctx context.Context, db PoolOrTx, schemaName, tableName, columnName string, val any) (ret bool, err error)
Exists returns true if 1+ records exist given the supplied criterion (columnName + val) pass val = nil to check for NULL
func ExistsConditions ¶
func ExistsConditions(ctx context.Context, db PoolOrTx, schemaName, tableName, match string, colValMap map[string]any) (ret bool, err error)
ExistsConditions returns true if 1+ records exist matching all/any the supplied criteria, depending on match param match must be AND or OR pass val = nil to check for NULL
func GetRowCount ¶
func GetRowCount(ctx context.Context, db PoolOrTx, schemaName, tableName string) (rowCount int64, err error)
GetRowCount returns a straight rowcount of the supplied table
func GetRowCountExplain ¶
func GetRowCountExplain(ctx context.Context, db PoolOrTx, qry string, paramValues []any) (rowCount int64, err error)
GetRowCountExplain returns the estimated rowcount of the supplied qry using the query planner EXPLAIN output qry must use placeholders for params, and paramValues must be supplied
func GetRowCountPlaceholderQry ¶
func GetRowCountPlaceholderQry(ctx context.Context, db PoolOrTx, qry string, paramValues []any) (rowCount int64, err error)
GetRowCountPlaceholderQry returns the exact rowcount of the supplied qry qry must use placeholders for params, and paramValues must be supplied
func GetStatsRowCount ¶
func GetTableColumnNames ¶
func GetTableComment ¶
func GetTableShortName ¶
func Insert ¶
func Insert[inputT any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, input inputT) (newPk pkT, err error)
Insert inserts a single record and then returns the new primary key, whose type is pkT inputT must be a struct with "db" tags
func InsertSelect ¶ added in v0.1.28
func InsertSelect[inputT any, itemT any](ctx context.Context, db PoolOrTx, schemaName, tableName, viewName, pkColName string, allFields []string, input inputT) (newItem itemT, err error)
InsertSelect inserts a single record and then returns it inputT must be a struct with "db" tags
func Restore ¶
func Restore[pkT PrimaryKeyType](ctx context.Context, tx pgx.Tx, schemaName, tableName, pkColName string, pkVal pkT, isCascaded bool) error
Restore moves a previously archived record to the corresponding table using the supplied tx if this func returns an error, rollback the tx
func SelectArray ¶ added in v0.1.12
func SelectArray[T any](ctx context.Context, db PoolOrTx, selectStmt string, params ...any) (ar []T, err error)
SelectArray is a wrapper for selecting into a non-struct type T (db.Query / pgx.CollectRows with RowTo) T must be a primitive type such as int64 or string
func SelectByArray ¶
func SelectByArray[inputT, itemT any](ctx context.Context, db PoolOrTx, schema, view, column string, ar []inputT) (items []itemT, err error)
SelectByArray returns multiple rows from the db depending on the array supplied inputT must be a primitive type such as int64 or string
func SelectEnum ¶
func SelectEnum(ctx context.Context, db PoolOrTx, enumName string, includeVals, excludeVals []string, sortVal string) (vals []string, err error)
SelectEnum returns all values of the supplied enum type includeVals = enum values to include excludeVals = enum values to exclude sortVal = either "" (no sort), "val" or "-val"
func SelectT ¶ added in v0.1.10
func SelectT[T any](ctx context.Context, db PoolOrTx, selectStmt string, params ...any) (items []T, err error)
SelectT is a wrapper for selecting into a struct type T (db.Query / pgx.CollectRows with RowToStructByNameLax)
func SelectUnique ¶
func SelectUnique[T any](ctx context.Context, db PoolOrTx, schema, view, column string, fields, allFields []string, uniqueVal any) (item T, err error)
SelectUnique returns a single row using the value of a unique column such as id
func Update ¶
func Update[T any, pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, input T, pkVal pkT, options ...UpdateOption) error
Update changes a single record with the values contained in input T must be a struct with "db" tags
func UpdatePartial ¶
func UpdatePartial[pkT PrimaryKeyType](ctx context.Context, db PoolOrTx, schemaName, tableName, pkColName string, allowedFields []string, assignmentsMap map[string]any, pkVal pkT) error
UpdatePartial updates only the supplied columns of the record assignmentsMap is a map of k = column name, v = new value
Types ¶
type Column ¶
type Condition ¶
type Condition struct { Field string Operator Operator // must be one of the Operator consts. if "IN" or "NOT IN", fill InValues, not Value Value string InValues []string }
Condition is a condition passed to a SELECT stmt
type DataUpdateCols ¶
type DataUpdateCols struct { DataUpdateId int64 `db:"data_update_id" json:"data_update_id,omitempty"` AffectedId int64 `db:"affected_id" json:"affected_id,omitempty"` AffectedAt lystype.Datetime `db:"affected_at" json:"affected_at,omitempty"` AffectedBy string `db:"affected_by" json:"affected_by,omitempty"` AffectedOldValues string `db:"affected_old_values" json:"affected_old_values,omitempty"` AffectedNewValues string `db:"affected_new_values" json:"affected_new_values,omitempty"` }
DataUpdateCols are the fields expected in a data update table
type ForeignKey ¶
type ForeignKey struct { ConstraintName string `db:"constraint_name"` ChildSchema string `db:"child_schema"` ChildTable string `db:"child_table"` ChildColumn string `db:"child_column"` ParentSchema string `db:"parent_schema"` ParentTable string `db:"parent_table"` ParentColumn string `db:"parent_column"` }
func GetChildForeignKeys ¶
func GetChildForeignKeys(ctx context.Context, db PoolOrTx, schemaName, tableName string) (fks []ForeignKey, err error)
GetChildForeignKeys returns the child FKs of the supplied table requires table owner: GRANT SELECT is not enough
func GetForeignKeys ¶
func GetForeignKeys(ctx context.Context, db PoolOrTx, schemaName, tableName string) (fks []ForeignKey, err error)
GetForeignKeys returns the parent FKs of the supplied table caution: will return incomplete or empty result set if user is not table owner
type Operator ¶
type Operator string
const ( OpEquals Operator = "=" OpNotEquals Operator = "!=" OpLessThan Operator = "<" OpLessThanEquals Operator = "<=" OpGreaterThan Operator = ">" OpGreaterThanEquals Operator = ">=" OpIn Operator = "IN" OpNotIn Operator = "NOT IN" OpStartsWith Operator = "StartsWith" OpEndsWith Operator = "EndsWith" OpContains Operator = "Contains" OpNotContains Operator = "NotContains" OpContainsAny Operator = "ContainsAny" OpEmpty Operator = "Empty" OpNotEmpty Operator = "NotEmpty" OpNull Operator = "Null" OpNotNull Operator = "NotNull" )
Valid condition operators
type PoolOrTx ¶
type PoolOrTx interface { Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row SendBatch(ctx context.Context, b *pgx.Batch) (br pgx.BatchResults) }
PoolOrTx is an abstraction of a pgx connection pool or transaction, e.g. pgxpool.Pool, pgx.Conn or pgx.Tx adapted from Querier in https://github.com/georgysavva/scany/blob/master/pgxscan/pgxscan.go
type PrimaryKeyType ¶ added in v0.1.28
type PrimaryKeyType interface { constraints.Integer | uuid.UUID | ~string }
PrimaryKeyType defines the type constraint of DB primary keys
type SelectParams ¶
type SelectParams struct { Fields []string Conditions []Condition Sorts []string Limit int Offset int GetUnpagedCount bool // if true, will estimate the total number of records returned by this query regardless of paging }
SelectParams holds the fields needed to modify a SELECT query
type TotalCount ¶
TotalCount contains the total number of table records. If IsEstimated is true, the Value was estimated using db statistics rather than calculated using a record count
type UpdateOption ¶
type UpdateOption struct {
OmitFields []string // db columns to exclude from update
}