pgparty

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: MIT Imports: 32 Imported by: 0

README

pgparty

Postgres database/sql access layer with Go generics 1.18+.

You can easily create go structures as models with tag descriptions for tables, fields and indexes in postgres schemas.

pgparty implements it in the database, with automatic migration between model descriptions in your service and database.

We use a special table with model descriptions for migration.

Basic usage

Create shards repository with only one shard with one database connect

shs, ctx := pgparty.NewShards(pgparty.WithLoggingQuery(context.Background()))

db, err = pgparty.InitDB(pgparty.DatabaseDSN{Postgres: databaseUrl})
if err != nil {
    return err
}

shard := shs.SetShard("shard1", db, "shard1")

One shard contains one postgres schema. Its automatically created if not exist.

Define some models, that implements Storable interface:

type BasicModel struct {
	ID       pgparty.UUID[BasicModel]      `json:"id"`
	Data     pgparty.NullJsonB             `json:"data"`
	AppXID   pgparty.XID[pgparty.AppXID]   `json:"appId"`
	TraceXID pgparty.XID[pgparty.TraceXID] `json:"traceId"`
}

func (BasicModel) StoreName() string { return "basic_models" }
func (BasicModel) UUIDPrefix() string { return "basic_model_" }

Now, register some models in shard:

if err := pgparty.Register(shard, pgparty.MD[BasicModel]{}); err != nil {
    t.Errorf("pgparty.Register error: %s", err)
    return
}

With each shard we can migrate models in database to current structure. At any time.

if err := shard.Migrate(ctx, nil); err != nil {
    t.Errorf("shard.Migrate error: %s", err)
    return
}

This produces sql queries:

CREATE TABLE shard1.basic_models (app_xid CHAR(20) NOT NULL,data jsonb,id UUID NOT NULL,trace_xid CHAR(20) NOT NULL,PRIMARY KEY (id))
CREATE UNIQUE INDEX basic_modelsappidx ON shard1.basic_models(app_xid )
CREATE INDEX basic_modelstraceappidx ON shard1.basic_models(app_xid, trace_xid )
INSERT INTO shard1._config (table_name,storej) VALUES($1,$2) ON CONFLICT(table_name) DO UPDATE SET storej=excluded.storej

where $1 = basic_models , $2 =

{
    "table":"basic_models",
    "cols":[
        {"ColName":"app_xid","DataType":"CHAR(20)","DefaultValue":"","NotNull":true,"PrimaryKey":false},
        {"ColName":"data","DataType":"jsonb","DefaultValue":"","NotNull":false,"PrimaryKey":false},
        {"ColName":"id","DataType":"UUID","DefaultValue":"","NotNull":true,"PrimaryKey":true},
        {"ColName":"trace_xid","DataType":"CHAR(20)","DefaultValue":"","NotNull":true,"PrimaryKey":false}
        ],
    "idxs":[
        {"name":"appidx","isUnique":true,"columns":["app_xid"]},
        {"name":"traceappidx","columns":["app_xid","trace_xid"]}
        ]
}

Future migrations use this '_config' table for building differencies as ALTER DDL queries.

Next time, create a model element

el := BasicModel{
	ID: pgparty.NewUUID[BasicModel](),
	Data: *pgparty.NewNullJsonB(map[string]any{
		"field1": "string data",
		"field2": 1344,
		"field3": pgparty.NowUTC(),
	}),
    AppXID:   pgparty.NewXID[pgparty.AppXID](),
    TraceXID: pgparty.NewXID[pgparty.TraceXID](),
}

Then replace it in database by id

if err := pgparty.WithTxInShard(ctx, shard.ID, func(ctx context.Context) error {
    return pgparty.Replace[BasicModel](ctx, el)
}); err != nil {
    t.Errorf("pgparty.Replace error: %s", err)
    return
}

This produces sql queries:

INSERT INTO shard1.basic_models (id,data,app_xid,trace_xid) VALUES($1,$2,$3,$4) 
ON CONFLICT(id) DO UPDATE SET (data,app_xid,trace_xid)=(excluded.data,excluded.app_xid,excluded.trace_xid)

Now, select written data from database:

var els []BasicModel
if err := shard.WithTx(ctx, func(ctx context.Context) error {
    return 
        pgparty.Select[BasicModel](ctx, 
            `SELECT * FROM &BasicModel`, // &BasicModel - model named by golang struct type name
        &els)
}); err != nil {
    t.Errorf("pgparty.Select error: %s", err)
    return
}

This produces sql queries:

SELECT * FROM shard1.basic_models

Documentation

Index

Constants

View Source
const (
	TagSql       = "sql"
	TagStore     = "store"
	TagKey       = "key"
	TagGinKey    = "ginkey"
	TagLen       = "len"
	TagDBName    = "db"
	TagPrec      = "prec"
	TagDefVal    = "defval"
	TagFullText  = "fulltext"
	TagUniqueKey = "unikey"
	TagPK        = "pk" // `pk:""` - поле входит в первичный ключ, актуально только для новых таблиц

	IDField        = "ID"
	CreatedAtField = "CreatedAt"
	UpdatedAtField = "UpdatedAt"
	DeletedAtField = "DeletedAt"
)
View Source
const BrowserDateFormat = `"2006-01-02"`

date

View Source
const BrowserDateTimeFormat = `"2006-01-02T15:04"`

datetime-local

View Source
const (
	DriverPostgreSQL = "pgx"
)
View Source
const ISOTimeFormat = `"2006-01-02T15:04:05.999Z07:00"`

Date()

View Source
const SQL_ColumnsInfo = `` /* 191-byte string literal not displayed */

Variables

This section is empty.

Functions

func DeleteShard

func DeleteShard(ctx context.Context, id string) error

func EnsureModelSchema

func EnsureModelSchema(ctx context.Context, md *ModelDesc) error

func Exec

func Exec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func Field added in v1.0.1

func Field[T Storable, F any](ctx context.Context, modelItem T, defval F, fieldName string) (F, error)

get field value by struct field name defval must be Model{}.Field

func Get

func Get[T any](ctx context.Context, query string, dest *T, args ...interface{}) error

func GetBuffer

func GetBuffer() *bytes.Buffer

func GetByID added in v1.0.1

func GetByID[T Storable](ctx context.Context, dest *T, id interface{}) error

func IdentifyPanic added in v1.0.9

func IdentifyPanic() string

func In

func In(query string, args ...interface{}) (string, []interface{}, error)

In expands slice values in args, returning the modified query string and a new arg list that can be executed by a database. The `query` should use the `?` or `$n` bindVar. The return value uses the `?` bindVar.

func IndexEqualDBIndex

func IndexEqualDBIndex(tname string, idx modelcols.SQLIndex, dbidx DBIndexDef) bool

func IndexesEqualToDBIndexes

func IndexesEqualToDBIndexes(sqs *modelcols.SQLModel, dbidxs DBIndexDefs) bool

func InitDB

func InitDB(c DatabaseDSN) (*sqlx.DB, error)

func IsJsonView added in v1.0.12

func IsJsonView(v interface{}) bool

func IsLoggingQuery

func IsLoggingQuery(ctx context.Context) bool

func IsSimpleProtocol

func IsSimpleProtocol(ctx context.Context) bool

func PutBuffer

func PutBuffer(b *bytes.Buffer)

func Query

func Query(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)

func Rebind

func Rebind(query string) string

Rebind a query from the default bindtype (QUESTION) to the target bindtype. Escaping: ?? translate to ?

func Register

func Register[T ModelDescriber](sh Shard, m T) error

func Replace

func Replace[T Storable](ctx context.Context, modelItem T, skipFields ...string) error

func SQLAllowNull added in v1.0.3

func SQLAllowNull(ft reflect.Type) bool

func SQLAlterModel

func SQLAlterModel(ctx context.Context, md *ModelDesc, mddbidxs DBIndexDefs, last, to *modelcols.SQLModel) error

func SQLAlterTable

func SQLAlterTable(schema, tname string, last, to *modelcols.SQLModel, dbcolinfos []DBColInfo, dbidxs DBIndexDefs) []string

func SQLAlterView added in v1.1.1

func SQLAlterView(schema, tname string, last, to *modelcols.SQLModel, dbidxs DBIndexDefs) []string

func SQLCreateModelWithColumns

func SQLCreateModelWithColumns(ctx context.Context, md *ModelDesc, sqs *modelcols.SQLModel) error

func SQLCreateTableWithColumns

func SQLCreateTableWithColumns(pt *PatchTable, sqs *modelcols.SQLModel)

func SQLCreateView added in v1.1.1

func SQLCreateView(pt *PatchView, sqs *modelcols.SQLModel)

func SQLDefaultValue added in v1.0.2

func SQLDefaultValue(ft reflect.Type) string

func SQLType

func SQLType(ft reflect.Type, ln, prec int) string

func Select

func Select[T any](ctx context.Context, query string, dest *[]T, args ...interface{}) error

func SelectCursorWalk

func SelectCursorWalk[T any](ctx context.Context, cursorName, selectQuery string, destSlice *[]T, fetchSize int,
	f func(destSlice interface{}) error, args ...interface{},
) error

func SelectShard

func SelectShard(ctx context.Context, id string) (context.Context, error)

func ToSnakeCase2

func ToSnakeCase2(str string) string

func UniqAdd added in v1.0.1

func UniqAdd[T comparable](sl []T, av T) []T

func WalkShards

func WalkShards(ctx context.Context, f func(Shard) error) error

func WithLoggingQuery

func WithLoggingQuery(ctx context.Context) context.Context

func WithShard

func WithShard(ctx context.Context, s Shard) context.Context

func WithShards

func WithShards(ctx context.Context, s *Shards) context.Context

func WithSimpleProtocol

func WithSimpleProtocol(ctx context.Context) context.Context

func WithTx

func WithTx(ctx context.Context, f func(context.Context) error) error

func WithTxInShard

func WithTxInShard(ctx context.Context, shardId string, f func(context.Context) error) error

Types

type AnyObjectMap

type AnyObjectMap map[string]interface{}

func (AnyObjectMap) ConvertTo

func (f AnyObjectMap) ConvertTo(value interface{}) error

func (AnyObjectMap) MarshalJSON

func (f AnyObjectMap) MarshalJSON() ([]byte, error)

func (AnyObjectMap) PostgresAllowNull added in v1.0.3

func (u AnyObjectMap) PostgresAllowNull() bool

func (AnyObjectMap) PostgresDefaultValue added in v1.0.2

func (AnyObjectMap) PostgresDefaultValue() string

func (AnyObjectMap) PostgresType added in v1.0.2

func (AnyObjectMap) PostgresType() string

func (*AnyObjectMap) Scan

func (f *AnyObjectMap) Scan(value interface{}) error

func (AnyObjectMap) String

func (f AnyObjectMap) String() string

func (*AnyObjectMap) UnmarshalJSON

func (f *AnyObjectMap) UnmarshalJSON(b []byte) error

func (AnyObjectMap) Value

func (f AnyObjectMap) Value() (driver.Value, error)

type AppUUID added in v1.0.1

type AppUUID struct{}

func (AppUUID) IDPrefix added in v1.0.1

func (u AppUUID) IDPrefix() string

type AppXID added in v1.0.1

type AppXID struct{}

func (AppXID) XIDPrefix added in v1.0.1

func (u AppXID) XIDPrefix() string

type BigSerial

type BigSerial sql.NullInt64

func (*BigSerial) ConvertFrom

func (n *BigSerial) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (BigSerial) MarshalJSON

func (n BigSerial) MarshalJSON() ([]byte, error)

func (BigSerial) PostgresAllowNull added in v1.0.3

func (u BigSerial) PostgresAllowNull() bool

func (BigSerial) PostgresDefaultValue added in v1.0.2

func (BigSerial) PostgresDefaultValue() string

func (BigSerial) PostgresType added in v1.0.2

func (BigSerial) PostgresType() string

func (*BigSerial) Scan

func (n *BigSerial) Scan(value interface{}) error

func (*BigSerial) UnmarshalJSON

func (n *BigSerial) UnmarshalJSON(b []byte) error

func (BigSerial) Value

func (n BigSerial) Value() (driver.Value, error)

type Bool

type Bool bool

func (Bool) Bool added in v1.0.2

func (n Bool) Bool() bool

func (*Bool) ConvertFrom

func (b *Bool) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (Bool) MarshalJSON added in v1.0.2

func (n Bool) MarshalJSON() ([]byte, error)

func (Bool) PostgresAllowNull added in v1.0.3

func (Bool) PostgresAllowNull() bool

func (Bool) PostgresDefaultValue added in v1.0.2

func (Bool) PostgresDefaultValue() string

func (Bool) PostgresType added in v1.0.2

func (Bool) PostgresType() string

func (*Bool) Scan added in v1.0.2

func (n *Bool) Scan(value interface{}) error

func (*Bool) SetBool added in v1.0.2

func (n *Bool) SetBool(b bool)

func (*Bool) UnmarshalJSON added in v1.0.2

func (n *Bool) UnmarshalJSON(b []byte) error

func (Bool) Value added in v1.0.2

func (n Bool) Value() (driver.Value, error)

type CtxShard

type CtxShard struct{}

type CtxShards

type CtxShards struct{}

type DBColInfo

type DBColInfo struct {
	Name       string `db:"column_name"`
	Type       string `db:"udt_name"`
	IsNullable string `db:"is_nullable"`
	CharLen    *int   `db:"character_maximum_length"`
	NumLen     *int   `db:"numeric_precision"`
	NumPrec    *int   `db:"numeric_precision_radix"`
}

func DBColumnsInfo

func DBColumnsInfo(ctx context.Context, tx *sqlx.Tx, schema, tname string) ([]DBColInfo, error)

type DBIndexDef

type DBIndexDef struct {
	Name   string      `db:"indname"`
	Table  string      `db:"tablename"`
	Schema string      `db:"nspname"`
	Fields StringArray `db:"indkey_names"`
}

func (DBIndexDef) String

func (d DBIndexDef) String() string

type DBIndexDefs

type DBIndexDefs []DBIndexDef

func CurrentSchemaIndexes

func CurrentSchemaIndexes(ctx context.Context, tablename string) (DBIndexDefs, error)

func (DBIndexDefs) FindByName

func (idxs DBIndexDefs) FindByName(n string) (DBIndexDef, bool)

type DatabaseDSN

type DatabaseDSN struct {
	Postgres        string        `json:"postgres" yaml:"postgres"`
	MaxIdleConns    int           `json:"max_idle_conns" yaml:"max_idle_conns"`
	MaxOpenConns    int           `json:"max_open_conns" yaml:"max_open_conns"`
	ConnMaxLifetime time.Duration `json:"conn_max_lifetime" yaml:"conn_max_lifetime"`
}

type DbConfig

type DbConfig []DbConfigTable

func NewDbConfig

func NewDbConfig() *DbConfig

func (*DbConfig) LoadAll

func (c *DbConfig) LoadAll(ctx context.Context, tx *sqlx.Tx, schema string) error

type DbConfigTable

type DbConfigTable struct {
	TableName string              `db:"table_name"`
	Storej    *modelcols.SQLModel `db:"storej"`
}

func (*DbConfigTable) IsEmpty

func (c *DbConfigTable) IsEmpty() bool

func (*DbConfigTable) LoadTable

func (c *DbConfigTable) LoadTable(ctx context.Context, table string) error

func (DbConfigTable) SaveTable

func (c DbConfigTable) SaveTable(ctx context.Context) error

type Decimal

type Decimal []byte

func Float64ToDecimal

func Float64ToDecimal(v float64) Decimal

func NegOne

func NegOne() Decimal

func NewDecimalFromAny

func NewDecimalFromAny(v interface{}) (*Decimal, error)

func NewDecimalFromFloat64

func NewDecimalFromFloat64(x float64) Decimal

func NewDecimalFromInt

func NewDecimalFromInt(x int) Decimal

func NewDecimalFromInt64

func NewDecimalFromInt64(x int64) Decimal

func NewDecimalFromUint64

func NewDecimalFromUint64(x uint64) Decimal

func One

func One() Decimal

func Zero

func Zero() Decimal

func (Decimal) Add

func (x Decimal) Add(d2 Decimal) Decimal

func (Decimal) Bool

func (x Decimal) Bool() bool

func (*Decimal) ConvertFrom

func (d *Decimal) ConvertFrom(v interface{}) error

store.Converter interface, d must contain zero value before call

func (Decimal) Div

func (x Decimal) Div(d2 Decimal) Decimal

func (Decimal) Equal

func (x Decimal) Equal(d2 Decimal) bool

func (Decimal) Float

func (x Decimal) Float() float64

func (Decimal) GetNumber

func (d Decimal) GetNumber() (*decimal.Big, error)

func (Decimal) Int

func (x Decimal) Int() int64

func (Decimal) Less

func (x Decimal) Less(d2 Decimal) bool

func (Decimal) LessOrEqual

func (x Decimal) LessOrEqual(d2 Decimal) bool

func (Decimal) MarshalJSON

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

func (Decimal) MarshalText

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

func (Decimal) Mod

func (x Decimal) Mod(d2 Decimal) Decimal

func (Decimal) Mul

func (x Decimal) Mul(d2 Decimal) Decimal

func (Decimal) Negative

func (x Decimal) Negative() Decimal

func (*Decimal) ParseGoType

func (x *Decimal) ParseGoType(v interface{})

func (Decimal) PostgresAllowNull added in v1.0.3

func (u Decimal) PostgresAllowNull() bool

func (Decimal) PostgresDefaultValue added in v1.0.2

func (Decimal) PostgresDefaultValue() string

func (Decimal) PostgresTypeWithLenPrec added in v1.0.3

func (Decimal) PostgresTypeWithLenPrec(ln, prec int) string

func (Decimal) Pow

func (x Decimal) Pow(d2 Decimal) Decimal

func (Decimal) RoundHalfUp

func (x Decimal) RoundHalfUp() int64

до целого

func (Decimal) RoundHalfUpTo2Sign

func (x Decimal) RoundHalfUpTo2Sign() Decimal

два знака после запятой 0.00

func (Decimal) RoundTo

func (x Decimal) RoundTo(n int, m decimal.RoundingMode) Decimal

func (*Decimal) Scan

func (d *Decimal) Scan(value interface{}) error

func (*Decimal) SetNumber

func (d *Decimal) SetNumber(dd *decimal.Big)

func (Decimal) String

func (d Decimal) String() string

func (Decimal) Sub

func (x Decimal) Sub(d2 Decimal) Decimal

func (Decimal) Uint

func (x Decimal) Uint() uint64

func (*Decimal) UnmarshalJSON

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

func (*Decimal) UnmarshalText

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

func (Decimal) Value

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

type Decimal152 added in v1.0.2

type Decimal152 Decimal

func (Decimal152) PostgresType added in v1.0.2

func (Decimal152) PostgresType() string

type Decimal153 added in v1.0.2

type Decimal153 Decimal

func (Decimal153) PostgresType added in v1.0.2

func (Decimal153) PostgresType() string

type Decimal192 added in v1.0.2

type Decimal192 Decimal

func (Decimal192) PostgresType added in v1.0.2

func (Decimal192) PostgresType() string

type ErrorNoTransaction

type ErrorNoTransaction struct{}

Ошибка транзакции

func (ErrorNoTransaction) Error

func (e ErrorNoTransaction) Error() string

type ErrorNotFound

type ErrorNotFound struct {
	ID      interface{}
	Type    reflect.Type
	Message string
}

Ошибка "не найден"

type FD added in v1.0.2

type FD[T Valuer, PT Scanner[T]] struct {
	V     T
	Valid bool
	// contains filtered or unexported fields
}

func NewFD added in v1.0.2

func NewFD[T Valuer, PT Scanner[T]](structField reflect.StructField) *FD[T, PT]

func (*FD[T, PT]) FD added in v1.0.2

func (fdt *FD[T, PT]) FD() *FieldDescription

func (FD[T, PT]) MarshalJSON added in v1.0.2

func (n FD[T, PT]) MarshalJSON() ([]byte, error)

func (FD[T, PT]) PostgresType added in v1.0.2

func (n FD[T, PT]) PostgresType() string

func (*FD[T, PT]) Scan added in v1.0.2

func (n *FD[T, PT]) Scan(value any) error

func (*FD[T, PT]) UnmarshalJSON added in v1.0.2

func (n *FD[T, PT]) UnmarshalJSON(b []byte) error

func (FD[T, PT]) Value added in v1.0.2

func (n FD[T, PT]) Value() (driver.Value, error)

type FieldDescriber added in v1.0.2

type FieldDescriber interface {
	FD() *FieldDescription
}

type FieldDescription

type FieldDescription struct {
	Idx             int                 // индекс в слайсе ModelDescription.Columns
	StructField     reflect.StructField // поле с базовыми характеристиками поля структуры
	ElemType        reflect.Type        // тип элемента, который характеризует структура
	Name            string              // store name (имя в хранилище)
	JsonName        string
	Ln              int
	Prec            int
	SQLTypeDef      string
	DefVal          string
	Indexes         []string
	GinIndexes      []string
	UniqIndexes     []string
	Nullable        bool
	Skip            bool
	SkipReplace     bool // игнорится только при реплейсе
	FullTextEnabled bool
	PK              bool
	JsonSkip        bool
	JsonOmitEmpty   bool
}

FieldDescription - универсальная структура, используемая во многих моделях и структурах.

func NewFieldDescription

func NewFieldDescription(structField reflect.StructField) *FieldDescription

func (*FieldDescription) IsStored

func (fd *FieldDescription) IsStored() bool

Говорит о том, сохраняется ли текущее поле в хранилище или нет

func (*FieldDescription) MarshalJSON

func (fd *FieldDescription) MarshalJSON() ([]byte, error)

func (*FieldDescription) MarshalText

func (fd *FieldDescription) MarshalText() (text []byte, err error)

func (FieldDescription) String

func (fd FieldDescription) String() string

Вывод FieldDescription в виде сткроки

type Float64

type Float64 float64

func (*Float64) ConvertFrom

func (f *Float64) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (Float64) Float64 added in v1.0.2

func (n Float64) Float64() float64

func (Float64) MarshalJSON added in v1.0.2

func (n Float64) MarshalJSON() ([]byte, error)

func (Float64) PostgresAllowNull added in v1.0.3

func (Float64) PostgresAllowNull() bool

func (Float64) PostgresDefaultValue added in v1.0.2

func (Float64) PostgresDefaultValue() string

func (Float64) PostgresType added in v1.0.2

func (Float64) PostgresType() string

func (*Float64) Scan added in v1.0.2

func (n *Float64) Scan(value interface{}) error

func (*Float64) SetFloat64 added in v1.0.2

func (n *Float64) SetFloat64(f float64)

func (*Float64) UnmarshalJSON added in v1.0.2

func (n *Float64) UnmarshalJSON(b []byte) error

func (Float64) Value added in v1.0.2

func (n Float64) Value() (driver.Value, error)

type Int64

type Int64 int64

func (*Int64) ConvertFrom

func (f *Int64) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (Int64) Int added in v1.0.2

func (n Int64) Int() int

func (Int64) MarshalJSON added in v1.0.2

func (n Int64) MarshalJSON() ([]byte, error)

func (Int64) PostgresAllowNull added in v1.0.3

func (Int64) PostgresAllowNull() bool

func (Int64) PostgresDefaultValue added in v1.0.2

func (Int64) PostgresDefaultValue() string

func (Int64) PostgresType added in v1.0.2

func (Int64) PostgresType() string

func (*Int64) Scan added in v1.0.2

func (n *Int64) Scan(value interface{}) error

func (*Int64) SetInt added in v1.0.2

func (n *Int64) SetInt(i int)

func (*Int64) UnmarshalJSON added in v1.0.2

func (n *Int64) UnmarshalJSON(b []byte) error

func (Int64) Value added in v1.0.2

func (n Int64) Value() (driver.Value, error)

type JsonB

type JsonB struct {
	// Val содержит указатель на значение
	// После анмаршала (из базы/json) тип его всегда становится map[string]interface{} или другим, как указано в описании к json.Unmarshal
	// вне зависимости от того, что там было до этого
	Val interface{}
}

func NewJsonB

func NewJsonB(val interface{}) *JsonB

func (*JsonB) ConvertFrom

func (n *JsonB) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (JsonB) ConvertTo

func (n JsonB) ConvertTo(value interface{}) error

func (JsonB) MarshalJSON

func (n JsonB) MarshalJSON() ([]byte, error)

func (JsonB) PostgresAllowNull added in v1.0.3

func (u JsonB) PostgresAllowNull() bool

func (JsonB) PostgresDefaultValue added in v1.0.2

func (JsonB) PostgresDefaultValue() string

func (JsonB) PostgresType added in v1.0.2

func (JsonB) PostgresType() string

func (*JsonB) Scan

func (n *JsonB) Scan(value interface{}) error

func (*JsonB) UnmarshalJSON

func (n *JsonB) UnmarshalJSON(b []byte) error

func (JsonB) Value

func (n JsonB) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type JsonErr added in v1.0.7

type JsonErr struct {
	Err error `json:"_err"`
}

type JsonView added in v1.0.2

type JsonView[T Storable] struct {
	V      T
	MD     *ModelDesc
	Filled []*FieldDescription
}

func NewJsonView added in v1.0.2

func NewJsonView[T Storable]() (*JsonView[T], error)

func (*JsonView[T]) IsFilled added in v1.0.2

func (mo *JsonView[T]) IsFilled(structFieldNames ...string) bool

func (*JsonView[T]) IsFullFilled added in v1.0.2

func (mo *JsonView[T]) IsFullFilled() bool

func (*JsonView[T]) MarshalJSON added in v1.0.2

func (mo *JsonView[T]) MarshalJSON() ([]byte, error)

func (*JsonView[T]) SQLView added in v1.0.4

func (jv *JsonView[T]) SQLView() *SQLView[T]

func (*JsonView[T]) Scan added in v1.0.4

func (mo *JsonView[T]) Scan(value interface{}) error

sql database json/jsonb value

func (*JsonView[T]) SetFilled added in v1.0.2

func (mo *JsonView[T]) SetFilled(structFieldNames ...string) error

func (*JsonView[T]) SetFullFilled added in v1.0.2

func (mo *JsonView[T]) SetFullFilled()

func (*JsonView[T]) SetUnfilled added in v1.0.2

func (mo *JsonView[T]) SetUnfilled(structFieldNames ...string) error

func (*JsonView[T]) UnmarshalJSON added in v1.0.2

func (mo *JsonView[T]) UnmarshalJSON(b []byte) error

func (*JsonView[T]) Valid added in v1.0.2

func (mo *JsonView[T]) Valid() bool

func (*JsonView[T]) Value added in v1.0.4

func (mo *JsonView[T]) Value() (driver.Value, error)

sql database json/jsonb value

type JsonViewErr added in v1.0.5

type JsonViewErr[T Storable] struct {
	Value *JsonView[T]
	Err   error `json:"_err,omitempty"`
}

func (JsonViewErr[T]) MarshalJSON added in v1.0.7

func (v JsonViewErr[T]) MarshalJSON() ([]byte, error)

func (JsonViewErr[T]) SQLView added in v1.0.5

func (v JsonViewErr[T]) SQLView() SQLViewErr[T]

func (*JsonViewErr[T]) UnmarshalJSON added in v1.0.7

func (v *JsonViewErr[T]) UnmarshalJSON(b []byte) error

type JsonViewErrer added in v1.0.8

type JsonViewErrer[T Storable] interface {
	JsonView() JsonViewErr[T]
}

type JsonViewer added in v1.0.6

type JsonViewer[T Storable] interface {
	JsonView() *JsonView[T]
}

type MD

type MD[T Storable] struct {
	Val T
}

func (MD[T]) MD

func (m MD[T]) MD() (*ModelDesc, error)

type MaterializedViewable added in v1.1.1

type MaterializedViewable interface {
	Viewable
	MaterializedView() // not called, define with empty body
}

MaterializedViewable is an interface that the materialized view-model structure must implement

type Mdjs

type Mdjs struct {
	ModelName string      `json:"model"`
	Md        *ModelDesc  `json:"-"`
	Fields    []MdjsField `json:"fields"`
}

func ModelsAndFields

func ModelsAndFields(ctx context.Context, st *PgStore) ([]Mdjs, error)

type MdjsField

type MdjsField struct {
	Name   string            `json:"name"`
	DBName string            `json:"dbname"`
	Type   reflect.Type      `json:"-"`
	Desc   *FieldDescription `json:"-"`
}

type MigrationProcessor

type MigrationProcessor interface {
	AfterCreateNewSchemaTable(ctx context.Context, stx *PgStore, md *ModelDesc, schema string) error
	AfterAlterModelError(ctx context.Context, err error, stx *PgStore, md *ModelDesc, sqsdb, sqsmd *modelcols.SQLModel, schema string) error
	AfterMigrate(ctx context.Context, stx *PgStore, reg MigrationRegistrator, sqsdb, sqsmd *modelcols.SQLModel, schema string) error
	AfterCommit(ctx context.Context, stx *PgStore) error
}

type MigrationRegistrator

type MigrationRegistrator interface {
	Start(ctx context.Context, stx *PgStore, schema, migrname string) error
	CheckStarted(ctx context.Context, stx *PgStore, schema, migrname string) (bool, error)
	Stop(ctx context.Context, stx *PgStore, schema, migrname string) error
}

type Model added in v1.0.10

type Model struct {
	ID        UUIDv4   `json:"id"`
	CreatedAt Time     `json:"createdAt"`
	UpdatedAt Time     `json:"updatedAt"`
	DeletedAt NullTime `json:"-" key:"deleted_at_idx"`
}

func (*Model) IsIDEmpty added in v1.0.10

func (m *Model) IsIDEmpty() bool

func (*Model) MarkUpdated added in v1.0.10

func (m *Model) MarkUpdated()

type Model58 added in v1.0.10

type Model58 struct {
	ID        UUID58   `json:"id"`
	CreatedAt Time     `json:"createdAt"`
	UpdatedAt Time     `json:"updatedAt"`
	DeletedAt NullTime `json:"-" key:"deleted_at_idx"`
}

func (*Model58) IsIDEmpty added in v1.0.10

func (m *Model58) IsIDEmpty() bool

func (*Model58) MarkUpdated added in v1.0.10

func (m *Model58) MarkUpdated()

type ModelDesc

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

func NewModelDescription

func NewModelDescription[T Storable](m T) (*ModelDesc, error)

func (ModelDesc) ColumnByFieldName

func (md ModelDesc) ColumnByFieldName(fieldName string) (*FieldDescription, error)

GetColumnByFieldName - get fd by struct field name

func (ModelDesc) ColumnByJsonName

func (md ModelDesc) ColumnByJsonName(jsonName string) (*FieldDescription, error)

func (ModelDesc) ColumnByStoreName added in v1.0.2

func (md ModelDesc) ColumnByStoreName(storeName string) (*FieldDescription, error)

func (*ModelDesc) ColumnPtr

func (md *ModelDesc) ColumnPtr(i int) *FieldDescription

func (*ModelDesc) ColumnPtrsCount

func (md *ModelDesc) ColumnPtrsCount() int

func (ModelDesc) ColumnsByFieldNames

func (md ModelDesc) ColumnsByFieldNames(fieldNames ...string) (res []*FieldDescription)

GetColumnsByFieldNames - get fd's by struct field name

func (ModelDesc) CreateElemPtr added in v1.0.1

func (md ModelDesc) CreateElemPtr() interface{}

func (ModelDesc) CreateSlicePtr

func (md ModelDesc) CreateSlicePtr() interface{}

func (*ModelDesc) CreatedAtField

func (md *ModelDesc) CreatedAtField() *FieldDescription

func (*ModelDesc) DeletedAtField

func (md *ModelDesc) DeletedAtField() *FieldDescription

func (*ModelDesc) IdField

func (md *ModelDesc) IdField() *FieldDescription

func (ModelDesc) IsMaterialized added in v1.1.1

func (md ModelDesc) IsMaterialized() bool

func (ModelDesc) IsView added in v1.1.1

func (md ModelDesc) IsView() bool

func (ModelDesc) ModelType

func (md ModelDesc) ModelType() reflect.Type

Получение типа модели

func (*ModelDesc) ReplaceEntries

func (md *ModelDesc) ReplaceEntries(schema string) ([]string, map[string]ReplaceEntry, error)

ReplaceEntries создает map[Old]New - замены текста в запросе для нужной модели

func (ModelDesc) StoreName

func (md ModelDesc) StoreName() string

Получение название типа модели

func (ModelDesc) UniqName

func (md ModelDesc) UniqName() string

Уникальные длинное имя

func (*ModelDesc) UpdatedAtField

func (md *ModelDesc) UpdatedAtField() *FieldDescription

func (ModelDesc) ViewQuery added in v1.1.1

func (md ModelDesc) ViewQuery(ctx context.Context, sr *PgStore) (string, error)

func (*ModelDesc) WalkColumnPtrs

func (md *ModelDesc) WalkColumnPtrs(f func(i int, v *FieldDescription) error) error

type ModelDescriber added in v1.0.2

type ModelDescriber interface {
	MD() (*ModelDesc, error)
}

type ModelObject added in v1.0.1

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

func ModelObjectFrom added in v1.0.1

func ModelObjectFrom[T Storable](ctx context.Context, modelItem T) (ModelObject, error)

type ModelQueryEngine added in v1.0.9

type ModelQueryEngine[T Storable, R RowsGenerator] struct {
	// contains filtered or unexported fields
}

func (*ModelQueryEngine[T, R]) ResponseList added in v1.0.9

func (q *ModelQueryEngine[T, R]) ResponseList(rowsGen R) ([]JsonViewer[T], error)

type NullBool

type NullBool sql.NullBool

func (*NullBool) ConvertFrom

func (n *NullBool) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (NullBool) MarshalJSON

func (n NullBool) MarshalJSON() ([]byte, error)

func (NullBool) PostgresAllowNull added in v1.0.3

func (u NullBool) PostgresAllowNull() bool

func (NullBool) PostgresDefaultValue added in v1.0.2

func (NullBool) PostgresDefaultValue() string

func (NullBool) PostgresType added in v1.0.2

func (NullBool) PostgresType() string

func (*NullBool) Scan

func (n *NullBool) Scan(value interface{}) error

func (*NullBool) UnmarshalJSON

func (n *NullBool) UnmarshalJSON(b []byte) error

func (NullBool) Value

func (n NullBool) Value() (driver.Value, error)

type NullDecimal

type NullDecimal struct {
	Decimal Decimal
	Valid   bool // Valid is true if Decimal is not NULL
}

Nullable decimal, length 19 precision 6

func (*NullDecimal) ConvertFrom

func (d *NullDecimal) ConvertFrom(v interface{}) error

func (NullDecimal) MarshalJSON

func (n NullDecimal) MarshalJSON() ([]byte, error)

func (NullDecimal) PostgresAllowNull added in v1.0.3

func (u NullDecimal) PostgresAllowNull() bool

func (NullDecimal) PostgresDefaultValue added in v1.0.2

func (NullDecimal) PostgresDefaultValue() string

func (NullDecimal) PostgresTypeWithLenPrec added in v1.0.3

func (NullDecimal) PostgresTypeWithLenPrec(ln, prec int) string

func (*NullDecimal) Scan

func (n *NullDecimal) Scan(value interface{}) error

Scan implements the Scanner interface.

func (*NullDecimal) UnmarshalJSON

func (n *NullDecimal) UnmarshalJSON(b []byte) error

func (NullDecimal) Value

func (n NullDecimal) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullDecimal152 added in v1.0.2

type NullDecimal152 NullDecimal

func (NullDecimal152) PostgresType added in v1.0.2

func (NullDecimal152) PostgresType() string

type NullDecimal153 added in v1.0.2

type NullDecimal153 NullDecimal

func (NullDecimal153) PostgresType added in v1.0.2

func (NullDecimal153) PostgresType() string

type NullDecimal192 added in v1.0.2

type NullDecimal192 NullDecimal

func (NullDecimal192) PostgresType added in v1.0.2

func (NullDecimal192) PostgresType() string

type NullFloat64

type NullFloat64 sql.NullFloat64

func (*NullFloat64) ConvertFrom

func (n *NullFloat64) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (NullFloat64) MarshalJSON

func (n NullFloat64) MarshalJSON() ([]byte, error)

func (NullFloat64) PostgresAllowNull added in v1.0.3

func (u NullFloat64) PostgresAllowNull() bool

func (NullFloat64) PostgresDefaultValue added in v1.0.2

func (NullFloat64) PostgresDefaultValue() string

func (NullFloat64) PostgresType added in v1.0.2

func (NullFloat64) PostgresType() string

func (*NullFloat64) Scan

func (n *NullFloat64) Scan(value interface{}) error

func (*NullFloat64) UnmarshalJSON

func (n *NullFloat64) UnmarshalJSON(b []byte) error

func (NullFloat64) Value

func (n NullFloat64) Value() (driver.Value, error)

type NullInt64

type NullInt64 sql.NullInt64

func (*NullInt64) ConvertFrom

func (n *NullInt64) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (NullInt64) MarshalJSON

func (n NullInt64) MarshalJSON() ([]byte, error)

func (NullInt64) PostgresAllowNull added in v1.0.3

func (u NullInt64) PostgresAllowNull() bool

func (NullInt64) PostgresDefaultValue added in v1.0.2

func (NullInt64) PostgresDefaultValue() string

func (NullInt64) PostgresType added in v1.0.2

func (NullInt64) PostgresType() string

func (*NullInt64) Scan

func (n *NullInt64) Scan(value interface{}) error

func (*NullInt64) UnmarshalJSON

func (n *NullInt64) UnmarshalJSON(b []byte) error

func (NullInt64) Value

func (n NullInt64) Value() (driver.Value, error)

type NullJsonB

type NullJsonB struct {
	// Val содержит указатель на значение
	// После анмаршала (из базы/json) тип его всегда становится map[string]interface{} или другим, как указано в описании к json.Unmarshal
	// вне зависимости от того, что там было до этого
	Val   interface{}
	Valid bool // Valid is true if Time is not NULL
}

func NewNullJsonB

func NewNullJsonB(val interface{}) *NullJsonB

func (*NullJsonB) ConvertFrom

func (n *NullJsonB) ConvertFrom(v interface{}) error

func (NullJsonB) ConvertTo

func (n NullJsonB) ConvertTo(value interface{}) error

func (NullJsonB) MarshalJSON

func (n NullJsonB) MarshalJSON() ([]byte, error)

func (NullJsonB) PostgresAllowNull added in v1.0.3

func (u NullJsonB) PostgresAllowNull() bool

func (NullJsonB) PostgresDefaultValue added in v1.0.2

func (NullJsonB) PostgresDefaultValue() string

func (NullJsonB) PostgresType added in v1.0.2

func (NullJsonB) PostgresType() string

func (*NullJsonB) Scan

func (n *NullJsonB) Scan(value interface{}) error

func (*NullJsonB) UnmarshalJSON

func (n *NullJsonB) UnmarshalJSON(b []byte) error

func (NullJsonB) Value

func (n NullJsonB) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type NullString

type NullString sql.NullString

func (*NullString) ConvertFrom

func (n *NullString) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (NullString) MarshalJSON

func (n NullString) MarshalJSON() ([]byte, error)

func (NullString) PostgresAllowNull added in v1.0.3

func (u NullString) PostgresAllowNull() bool

func (NullString) PostgresDefaultValue added in v1.0.2

func (NullString) PostgresDefaultValue() string

func (NullString) PostgresType added in v1.0.2

func (NullString) PostgresType() string

func (*NullString) Scan

func (n *NullString) Scan(value interface{}) error

func (*NullString) UnmarshalJSON

func (n *NullString) UnmarshalJSON(b []byte) error

func (NullString) Value

func (n NullString) Value() (driver.Value, error)

type NullText

type NullText sql.NullString

func (*NullText) ConvertFrom

func (n *NullText) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (NullText) MarshalJSON

func (n NullText) MarshalJSON() ([]byte, error)

func (NullText) PostgresAllowNull added in v1.0.3

func (u NullText) PostgresAllowNull() bool

func (NullText) PostgresDefaultValue added in v1.0.2

func (NullText) PostgresDefaultValue() string

func (NullText) PostgresType added in v1.0.2

func (NullText) PostgresType() string

func (*NullText) Scan

func (n *NullText) Scan(value interface{}) error

func (*NullText) UnmarshalJSON

func (n *NullText) UnmarshalJSON(b []byte) error

func (NullText) Value

func (n NullText) Value() (driver.Value, error)

type NullTime

type NullTime struct {
	Time  Time
	Valid bool // Valid is true if Time is not NULL
}

func (*NullTime) ConvertFrom

func (t *NullTime) ConvertFrom(v interface{}) error

store.Converter interface, t must contain zero value before call

func (NullTime) MarshalJSON

func (n NullTime) MarshalJSON() ([]byte, error)

func (NullTime) PostgresAllowNull added in v1.0.3

func (u NullTime) PostgresAllowNull() bool

func (NullTime) PostgresDefaultValue added in v1.0.2

func (u NullTime) PostgresDefaultValue() string

func (NullTime) PostgresType added in v1.0.2

func (u NullTime) PostgresType() string

func (*NullTime) Scan

func (nt *NullTime) Scan(value interface{}) (err error)

func (NullTime) String

func (nt NullTime) String() string

func (*NullTime) UnmarshalJSON

func (n *NullTime) UnmarshalJSON(b []byte) error

func (NullTime) Value

func (nt NullTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type PatchAddColumn

type PatchAddColumn struct {
	Col modelcols.SQLColumn
}

func (PatchAddColumn) String

func (c PatchAddColumn) String() string

type PatchAlterColumnDefVal

type PatchAlterColumnDefVal struct {
	Col modelcols.SQLColumn
}

func (PatchAlterColumnDefVal) String

func (c PatchAlterColumnDefVal) String() string

type PatchAlterColumnNullable

type PatchAlterColumnNullable struct {
	Col modelcols.SQLColumn
}

func (PatchAlterColumnNullable) String

func (c PatchAlterColumnNullable) String() string

type PatchAlterColumnType

type PatchAlterColumnType struct {
	Col modelcols.SQLColumn
}

func (PatchAlterColumnType) String

func (c PatchAlterColumnType) String() string

type PatchCreateIndex

type PatchCreateIndex struct {
	Schema string
	Table  string
	Index  modelcols.SQLIndex
}

func (PatchCreateIndex) String

func (c PatchCreateIndex) String() string

type PatchCreateTable

type PatchCreateTable struct {
	Schema string
	Table  string
	Cols   modelcols.SQLColumns
}

func (PatchCreateTable) String

func (c PatchCreateTable) String() string

type PatchCreateView added in v1.1.1

type PatchCreateView struct {
	Schema       string
	Table        string
	Query        string
	Materialized bool
}

func (PatchCreateView) String added in v1.1.1

func (c PatchCreateView) String() string

type PatchDropIndex

type PatchDropIndex struct {
	Schema string
	Table  string
	Index  string
	Force  bool
}

func (PatchDropIndex) String

func (c PatchDropIndex) String() string

type PatchDropView added in v1.1.1

type PatchDropView struct {
	Schema string
	Table  string
}

func (PatchDropView) String added in v1.1.1

func (c PatchDropView) String() string

type PatchTable

type PatchTable struct {
	Schema string
	Name   string

	DropIndexes   []fmt.Stringer
	UpdateNulls   []fmt.Stringer
	AlterCols     []fmt.Stringer
	CreateTables  []fmt.Stringer
	CreateIndexes []fmt.Stringer
}

func (*PatchTable) AddColumnPatch

func (pt *PatchTable) AddColumnPatch(cp fmt.Stringer)

func (*PatchTable) AddCreateIndexPatch

func (pt *PatchTable) AddCreateIndexPatch(cp fmt.Stringer)

func (*PatchTable) AddCreateTablePatch

func (pt *PatchTable) AddCreateTablePatch(cp fmt.Stringer)

func (*PatchTable) AddDropIndexPatch

func (pt *PatchTable) AddDropIndexPatch(cp fmt.Stringer)

func (*PatchTable) AddUpdateNullsPatch

func (pt *PatchTable) AddUpdateNullsPatch(cp fmt.Stringer)

func (PatchTable) Queries

func (pt PatchTable) Queries() []string

type PatchUpdateNulls

type PatchUpdateNulls struct {
	Schema string
	Table  string
	Col    modelcols.SQLColumn
}

func (PatchUpdateNulls) String

func (c PatchUpdateNulls) String() string

type PatchView added in v1.1.1

type PatchView struct {
	Schema string
	Name   string

	DropViews     []fmt.Stringer
	CreateViews   []fmt.Stringer
	DropIndexes   []fmt.Stringer
	CreateIndexes []fmt.Stringer
}

func (*PatchView) AddCreateIndexPatch added in v1.1.1

func (pt *PatchView) AddCreateIndexPatch(cp fmt.Stringer)

func (*PatchView) AddCreateViewPatch added in v1.1.1

func (pt *PatchView) AddCreateViewPatch(cp fmt.Stringer)

func (*PatchView) AddDropIndexPatch added in v1.1.1

func (pt *PatchView) AddDropIndexPatch(cp fmt.Stringer)

func (*PatchView) AddDropViewPatch added in v1.1.1

func (pt *PatchView) AddDropViewPatch(cp fmt.Stringer)

func (PatchView) Queries added in v1.1.1

func (pt PatchView) Queries() []string

type PgSelect added in v1.0.1

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

func (*PgSelect) Field added in v1.0.1

func (ps *PgSelect) Field(model Storable, defval any, fieldName string) *PgSelect

func (*PgSelect) From added in v1.0.1

func (ps *PgSelect) From(model Storable) *PgSelect

type PgStore

type PgStore struct {
	Store
	// contains filtered or unexported fields
}

func NewPgStore

func NewPgStore(db *sqlx.DB, schema string) *PgStore

func (PgStore) Begin

func (sr PgStore) Begin(ctx context.Context) (*PgStore, error)

func (*PgStore) CheckStarted

func (sr *PgStore) CheckStarted(ctx context.Context, stx *PgStore, schema, migrname string) (bool, error)

func (*PgStore) Close

func (sr *PgStore) Close()

func (PgStore) Commit

func (sr PgStore) Commit() error

func (*PgStore) DbConfigTableFromModel added in v1.1.1

func (sr *PgStore) DbConfigTableFromModel(ctx context.Context, md *ModelDesc) (*DbConfigTable, error)

func (*PgStore) Field added in v1.0.1

func (sr *PgStore) Field(modelItem Storable, fieldName string) (interface{}, error)

get field value by struct field name

func (*PgStore) MD2SQLModel added in v1.1.1

func (sr *PgStore) MD2SQLModel(ctx context.Context, md *ModelDesc) (*modelcols.SQLModel, error)

func (*PgStore) Migrate

func (sr *PgStore) Migrate(ctx context.Context, mProcessor MigrationProcessor) error

func (*PgStore) ModelObjectFrom added in v1.0.1

func (sr *PgStore) ModelObjectFrom(modelItem Storable) (ModelObject, error)

func (*PgStore) PrepExec

func (sr *PgStore) PrepExec(ctx context.Context, query string, args ...interface{}) (sql.Result, error)

func (*PgStore) PrepGet

func (sr *PgStore) PrepGet(ctx context.Context, query string, dest interface{}, args ...interface{}) error

func (*PgStore) PrepQueryx

func (sr *PgStore) PrepQueryx(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)

func (*PgStore) PrepSelect

func (sr *PgStore) PrepSelect(ctx context.Context, query string, dest interface{}, args ...interface{}) error

func (*PgStore) PrepSelectCursorWalk

func (sr *PgStore) PrepSelectCursorWalk(ctx context.Context, cursorName, selectQuery string, destSlice interface{}, fetchSize int,
	f func(destSlice interface{}) error, args ...interface{},
) error

func (*PgStore) PrepareQuery

func (sr *PgStore) PrepareQuery(ctx context.Context, query string) (string, error)

func (*PgStore) Replace

func (sr *PgStore) Replace(ctx context.Context, modelItem Storable, skipFields ...string) error

Replace is "insert or update" operation using ID field as key

func (PgStore) Rollback

func (sr PgStore) Rollback() error

func (*PgStore) SaveModelConfig added in v1.1.1

func (sr *PgStore) SaveModelConfig(ctx context.Context, md *ModelDesc) error

func (PgStore) Schema

func (sr PgStore) Schema() string

func (*PgStore) Select added in v1.0.1

func (s *PgStore) Select(ctx context.Context) *PgSelect

func (*PgStore) SetUnsafe

func (sr *PgStore) SetUnsafe()

SetUnsafe sets a version of Tx which will silently succeed to scan when columns in the SQL result have no fields in the destination struct.

func (*PgStore) Start

func (sr *PgStore) Start(ctx context.Context, stx *PgStore, schema, migrname string) error

func (*PgStore) Stop

func (sr *PgStore) Stop(ctx context.Context, stx *PgStore, schema, migrname string) error

func (PgStore) String

func (sr PgStore) String() string

func (PgStore) Tx

func (sr PgStore) Tx() *sqlx.Tx

func (PgStore) WithBeginTx

func (sr PgStore) WithBeginTx(ctx context.Context, f func(storeCopy *PgStore) error) (err error)

func (PgStore) WithTx

func (sr PgStore) WithTx(ctx context.Context, f func(storeCopy *PgStore) error) (err error)

type PostgresDefaultValuer added in v1.0.2

type PostgresDefaultValuer interface {
	PostgresDefaultValue() string
}

type PostgresNullable added in v1.0.3

type PostgresNullable interface {
	PostgresAllowNull() bool
}

type PostgresTyper added in v1.0.1

type PostgresTyper interface {
	PostgresType() string
}

type PostgresTyperLn added in v1.0.3

type PostgresTyperLn interface {
	PostgresTypeWithLen(ln int) string
}

type PostgresTyperLnPrec added in v1.0.3

type PostgresTyperLnPrec interface {
	PostgresTypeWithLenPrec(ln, prec int) string
}

type ReplaceEntry

type ReplaceEntry struct {
	To     string
	Schema string
	Typ    reflect.Type
}

type RowScanner added in v1.0.7

type RowScanner interface {
	Scan(rows sqlx.ColScanner, prefix string) error
}

type RowsGenerator added in v1.0.9

type RowsGenerator interface {
	QueryRows() (*sqlx.Rows, error)
}

type SQLView added in v1.0.2

type SQLView[T Storable] struct {
	V      T
	MD     *ModelDesc
	Filled []*FieldDescription
}

func NewSQLView added in v1.0.2

func NewSQLView[T Storable]() (*SQLView[T], error)

func (*SQLView[T]) Columns added in v1.0.2

func (mo *SQLView[T]) Columns() []string

func (*SQLView[T]) IsFilled added in v1.0.2

func (mo *SQLView[T]) IsFilled(structFieldNames ...string) bool

func (*SQLView[T]) IsFullFilled added in v1.0.2

func (mo *SQLView[T]) IsFullFilled() bool

func (*SQLView[T]) JsonView added in v1.0.4

func (sv *SQLView[T]) JsonView() *JsonView[T]

func (*SQLView[T]) Scan added in v1.0.2

func (mo *SQLView[T]) Scan(rows sqlx.ColScanner, prefix string) error

prefix is table alias with point at end, or empty string

func (*SQLView[T]) SetFilled added in v1.0.2

func (mo *SQLView[T]) SetFilled(structFieldNames ...string) error

func (*SQLView[T]) SetFullFilled added in v1.0.2

func (mo *SQLView[T]) SetFullFilled()

func (*SQLView[T]) SetUnfilled added in v1.0.2

func (mo *SQLView[T]) SetUnfilled(structFieldNames ...string) error

func (*SQLView[T]) Valid added in v1.0.2

func (mo *SQLView[T]) Valid() bool

func (*SQLView[T]) Values added in v1.0.2

func (mo *SQLView[T]) Values() []interface{}

type SQLViewErr added in v1.0.5

type SQLViewErr[T Storable] struct {
	Value *SQLView[T]
	Err   error `json:"_err,omitempty"`
}

func (SQLViewErr[T]) JsonView added in v1.0.5

func (v SQLViewErr[T]) JsonView() JsonViewErr[T]

func (*SQLViewErr[T]) Scan added in v1.0.7

func (v *SQLViewErr[T]) Scan(rows sqlx.ColScanner, prefix string) error

prefix is table alias with point at end, or empty string

type SQLViewErrer added in v1.0.8

type SQLViewErrer[T Storable] interface {
	SQLView() SQLViewErr[T]
}

type SQLViewer added in v1.0.6

type SQLViewer[T Storable] interface {
	SQLView() *SQLView[T]
}

type Scanner added in v1.0.2

type Scanner[T any] interface {
	*T
	Scan(src any) error
}

type Shard

type Shard struct {
	ID    string
	Store *PgStore
}

func SetShard

func SetShard(ctx context.Context, id string, db *sqlx.DB, schema string) (Shard, error)

func ShardByID

func ShardByID(ctx context.Context, id string) (Shard, error)

func ShardFromContext

func ShardFromContext(ctx context.Context) (Shard, error)

func (Shard) Migrate

func (s Shard) Migrate(ctx context.Context, mProcessor MigrationProcessor) error

func (Shard) WithTx

func (s Shard) WithTx(ctx context.Context, f func(context.Context) error) error

type Shards

type Shards struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewShards

func NewShards(ctx context.Context) (*Shards, context.Context)

func ShardsFromContext

func ShardsFromContext(ctx context.Context) (*Shards, error)

func (*Shards) AnalyzeAndReplaceQuery

func (shs *Shards) AnalyzeAndReplaceQuery(sr *PgStore, query string) (string, map[string]ReplaceEntry, error)

func (*Shards) DeleteShard

func (s *Shards) DeleteShard(id string)

func (*Shards) SetShard

func (s *Shards) SetShard(id string, db *sqlx.DB, schema string) Shard

func (*Shards) ShardByID

func (s *Shards) ShardByID(id string) (Shard, bool)

func (*Shards) Walk

func (s *Shards) Walk(f func(Shard) error) error

type SomeUUID added in v1.0.1

type SomeUUID struct{}

func (SomeUUID) IDPrefix added in v1.0.1

func (u SomeUUID) IDPrefix() string

type SomeXID added in v1.0.1

type SomeXID struct{}

func (SomeXID) XIDPrefix added in v1.0.1

func (u SomeXID) XIDPrefix() string

type Storable

type Storable interface {
	StoreName() string
}

Storable is an interface that the model structure must implement

type Store

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

func (*Store) Close

func (s *Store) Close()

func (Store) GetModelDescription

func (s Store) GetModelDescription(model Storable) (*ModelDesc, bool)

func (Store) GetModelDescriptionByType

func (s Store) GetModelDescriptionByType(typ reflect.Type) (*ModelDesc, bool)

Получение описания модели из его reflect.Type

func (*Store) Init

func (s *Store) Init()

func (*Store) JSONBuildObjectSQL

func (sr *Store) JSONBuildObjectSQL(md *ModelDesc, prefix string, onlyStructFieldNames ...string) string

создает строку вида json_build_object('jsonFieldName', prefixStructFieldName ...) если берутся поля от модели, то нужно использовать префикс ":". если от именованной таблицы tabl, то нужно использвать префикс "tabl.:" если с префиксом модели, то нужно использвать префикс ":ModelName."

func (Store) ModelDescriptions

func (s Store) ModelDescriptions() map[reflect.Type]*ModelDesc

func (Store) QueryReplacers

func (s Store) QueryReplacers() map[sqlPattern]map[string]ReplaceEntry

type String

type String string

func (*String) ConvertFrom

func (s *String) ConvertFrom(v interface{}) error

store.Converter interface, n must contain zero value before call

func (String) MarshalJSON added in v1.0.2

func (n String) MarshalJSON() ([]byte, error)

func (String) PostgresAllowNull added in v1.0.3

func (String) PostgresAllowNull() bool

func (String) PostgresDefaultValue added in v1.0.2

func (String) PostgresDefaultValue() string

func (String) PostgresType added in v1.0.2

func (String) PostgresType() string

func (*String) Scan added in v1.0.2

func (n *String) Scan(value interface{}) error

func (*String) SetString added in v1.0.2

func (n *String) SetString(s string)

func (String) String added in v1.0.2

func (n String) String() string

func (*String) UnmarshalJSON added in v1.0.2

func (n *String) UnmarshalJSON(b []byte) error

func (String) Value added in v1.0.2

func (n String) Value() (driver.Value, error)

type StringArray

type StringArray []string

func (StringArray) MarshalJSON

func (f StringArray) MarshalJSON() ([]byte, error)

func (StringArray) PostgresAllowNull added in v1.0.3

func (u StringArray) PostgresAllowNull() bool

func (StringArray) PostgresDefaultValue added in v1.0.2

func (StringArray) PostgresDefaultValue() string

func (StringArray) PostgresType added in v1.0.2

func (StringArray) PostgresType() string

func (*StringArray) Scan

func (f *StringArray) Scan(value interface{}) error

func (*StringArray) UnmarshalJSON

func (f *StringArray) UnmarshalJSON(b []byte) error

func (StringArray) Value

func (f StringArray) Value() (driver.Value, error)

type Text

type Text string

func (*Text) ConvertFrom

func (s *Text) ConvertFrom(v interface{}) error

func (Text) PostgresAllowNull added in v1.0.3

func (u Text) PostgresAllowNull() bool

func (Text) PostgresDefaultValue added in v1.0.2

func (Text) PostgresDefaultValue() string

func (Text) PostgresType added in v1.0.2

func (Text) PostgresType() string

func (*Text) Scan added in v1.0.2

func (u *Text) Scan(src interface{}) error

func (Text) Value added in v1.0.2

func (u Text) Value() (driver.Value, error)

type Time

type Time time.Time

func NowUTC

func NowUTC() Time

func (Time) AssignTo

func (t Time) AssignTo(v reflect.Value)

AssignToустанавливает значение целевой переменной с учетом ее типа. Поддерживаются типы: time.Time, Time, NullTime и указатели на них

func (*Time) ConvertFrom

func (t *Time) ConvertFrom(v interface{}) error

store.Converter interface, t must contain zero value before call

func (Time) FormatRus

func (t Time) FormatRus(f string) string

д (d) - день месяца (цифрами) без лидирующего нуля дд (dd) - день месяца (цифрами) с лидирующим нулем ддд (ddd) - краткое название дня недели дддд (dddd) - полное название дня недели М (M) - номер месяца (цифрами) без лидирующего нуля ММ (MM) - номер месяца (цифрами) с лидирующим нулем МММ (MMM) - краткое название месяца ММММ (MMMM) - полное название месяца К (Q) - номер квартала в году г (y) - номер года без века и лидирующего нуля гг (yy) - номер года без века с лидирующим нулем гггг (yyyy) - номер года с веком ч (h) - час в 24 часовом варианте без лидирующих нулей чч (hh) - час в 24 часовом варианте с лидирующим нулем м (m) - минута без лидирующего нуля мм (mm) - минута с лидирующим нулем с (s) - секунда без лидирующего нуля сс (ss) - секунда с лидирующим нулем ссс (sss) - миллисекунда с лидирующим нулем

func (*Time) GobDecode

func (t *Time) GobDecode(data []byte) error

func (Time) GobEncode

func (t Time) GobEncode() ([]byte, error)

func (Time) MarshalBinary

func (t Time) MarshalBinary() ([]byte, error)

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

func (Time) PostgresAllowNull added in v1.0.3

func (u Time) PostgresAllowNull() bool

func (Time) PostgresDefaultValue added in v1.0.2

func (u Time) PostgresDefaultValue() string

func (Time) PostgresType added in v1.0.2

func (u Time) PostgresType() string

func (Time) Round

func (t Time) Round(d time.Duration) Time

func (*Time) Scan

func (t *Time) Scan(value interface{}) (err error)

Scan implements the Scanner interface.

func (Time) String

func (t Time) String() string

func (Time) Time

func (t Time) Time() time.Time

func (*Time) UnmarshalBinary

func (t *Time) UnmarshalBinary(data []byte) error

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

func (Time) Value

func (t Time) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type TraceUUID added in v1.0.1

type TraceUUID struct{}

func (TraceUUID) IDPrefix added in v1.0.1

func (a TraceUUID) IDPrefix() string

type TraceXID added in v1.0.1

type TraceXID struct{}

func (TraceXID) XIDPrefix added in v1.0.1

func (a TraceXID) XIDPrefix() string

type UUID added in v1.0.1

type UUID[T UUIDType] UUIDv4

func NewUUID added in v1.0.1

func NewUUID[T UUIDType]() UUID[T]

func NilUUID added in v1.0.1

func NilUUID[T UUIDType]() UUID[T]

func ParseUUID added in v1.0.1

func ParseUUID[T UUIDType](s string) (UUID[T], error)

func (*UUID[T]) ConvertFrom added in v1.0.1

func (u *UUID[T]) ConvertFrom(v interface{}) error

func (UUID[T]) IsZero added in v1.0.1

func (u UUID[T]) IsZero() bool

func (UUID[T]) MarshalJSON added in v1.0.1

func (u UUID[T]) MarshalJSON() ([]byte, error)

func (UUID[T]) PostgresAllowNull added in v1.0.3

func (UUID[T]) PostgresAllowNull() bool

func (UUID[T]) PostgresDefaultValue added in v1.0.2

func (UUID[T]) PostgresDefaultValue() string

func (UUID[T]) PostgresType added in v1.0.1

func (UUID[T]) PostgresType() string

func (*UUID[T]) Scan added in v1.0.1

func (u *UUID[T]) Scan(src interface{}) error

func (UUID[T]) String added in v1.0.1

func (id UUID[T]) String() string

func (*UUID[T]) UnmarshalJSON added in v1.0.1

func (u *UUID[T]) UnmarshalJSON(b []byte) error

func (UUID[T]) Value added in v1.0.1

func (u UUID[T]) Value() (driver.Value, error)

type UUID58 added in v1.0.10

type UUID58 UUIDv4

func UUID58FromString added in v1.0.10

func UUID58FromString(s string) (UUID58, error)

func UUID58MustFromString added in v1.0.10

func UUID58MustFromString(s string) UUID58

func UUIDNew58 added in v1.0.10

func UUIDNew58() UUID58

func (*UUID58) ConvertFrom added in v1.0.10

func (u *UUID58) ConvertFrom(v interface{}) error

store.Converter interface, u must contain zero value before call

func (*UUID58) GobDecode added in v1.0.10

func (u *UUID58) GobDecode(data []byte) error

func (UUID58) GobEncode added in v1.0.10

func (u UUID58) GobEncode() ([]byte, error)

func (UUID58) IsZero added in v1.0.10

func (u UUID58) IsZero() bool

func (UUID58) MarshalJSON added in v1.0.10

func (u UUID58) MarshalJSON() ([]byte, error)

func (UUID58) PostgresAllowNull added in v1.0.10

func (UUID58) PostgresAllowNull() bool

func (UUID58) PostgresDefaultValue added in v1.0.10

func (UUID58) PostgresDefaultValue() string

func (UUID58) PostgresType added in v1.0.10

func (UUID58) PostgresType() string

func (*UUID58) Scan added in v1.0.10

func (u *UUID58) Scan(src interface{}) error

func (UUID58) String added in v1.0.10

func (u UUID58) String() string

func (*UUID58) UnmarshalJSON added in v1.0.10

func (u *UUID58) UnmarshalJSON(b []byte) error

func (UUID58) Value added in v1.0.10

func (u UUID58) Value() (driver.Value, error)

type UUIDJsonTyped added in v1.0.1

type UUIDJsonTyped[T UUIDType] UUID[T]

func (UUIDJsonTyped[T]) MarshalJSON added in v1.0.1

func (u UUIDJsonTyped[T]) MarshalJSON() ([]byte, error)

func (*UUIDJsonTyped[T]) UnmarshalJSON added in v1.0.1

func (u *UUIDJsonTyped[T]) UnmarshalJSON(b []byte) error

type UUIDType added in v1.0.1

type UUIDType interface {
	UUIDPrefix() string
}

type UUIDv4

type UUIDv4 struct {
	uuid.UUID
}

func UUIDFromString added in v1.0.1

func UUIDFromString(s string) (UUIDv4, error)

func UUIDMustFromString added in v1.0.1

func UUIDMustFromString(s string) UUIDv4

func UUIDNewV4 added in v1.0.1

func UUIDNewV4() UUIDv4

func (*UUIDv4) ConvertFrom

func (u *UUIDv4) ConvertFrom(v interface{}) error

store.Converter interface, u must contain zero value before call

func (*UUIDv4) GobDecode

func (u *UUIDv4) GobDecode(data []byte) error

func (UUIDv4) GobEncode

func (u UUIDv4) GobEncode() ([]byte, error)

func (UUIDv4) IsZero

func (u UUIDv4) IsZero() bool

func (UUIDv4) MarshalJSON

func (u UUIDv4) MarshalJSON() ([]byte, error)

func (UUIDv4) PostgresAllowNull added in v1.0.3

func (UUIDv4) PostgresAllowNull() bool

func (UUIDv4) PostgresDefaultValue added in v1.0.2

func (UUIDv4) PostgresDefaultValue() string

func (UUIDv4) PostgresType added in v1.0.2

func (UUIDv4) PostgresType() string

func (*UUIDv4) Scan

func (u *UUIDv4) Scan(src interface{}) error

func (UUIDv4) String

func (u UUIDv4) String() string

func (*UUIDv4) UnmarshalJSON

func (u *UUIDv4) UnmarshalJSON(b []byte) error

func (UUIDv4) Value

func (u UUIDv4) Value() (driver.Value, error)

type UUIDv4Array

type UUIDv4Array []UUIDv4

func (UUIDv4Array) MarshalJSON

func (a UUIDv4Array) MarshalJSON() ([]byte, error)

func (UUIDv4Array) PostgresAllowNull added in v1.0.3

func (UUIDv4Array) PostgresAllowNull() bool

func (UUIDv4Array) PostgresDefaultValue added in v1.0.2

func (UUIDv4Array) PostgresDefaultValue() string

func (UUIDv4Array) PostgresType added in v1.0.2

func (UUIDv4Array) PostgresType() string

func (*UUIDv4Array) Raw

func (a *UUIDv4Array) Raw() []UUIDv4

func (*UUIDv4Array) Scan

func (a *UUIDv4Array) Scan(value interface{}) error

func (*UUIDv4Array) UnmarshalJSON

func (a *UUIDv4Array) UnmarshalJSON(b []byte) error

func (UUIDv4Array) Value

func (a UUIDv4Array) Value() (driver.Value, error)

type Uint64Array

type Uint64Array []uint64

func (Uint64Array) MarshalJSON

func (f Uint64Array) MarshalJSON() ([]byte, error)

func (Uint64Array) PostgresAllowNull added in v1.0.3

func (u Uint64Array) PostgresAllowNull() bool

func (Uint64Array) PostgresDefaultValue added in v1.0.2

func (Uint64Array) PostgresDefaultValue() string

func (Uint64Array) PostgresType added in v1.0.2

func (Uint64Array) PostgresType() string

func (*Uint64Array) Scan

func (f *Uint64Array) Scan(value interface{}) error

func (*Uint64Array) UnmarshalJSON

func (f *Uint64Array) UnmarshalJSON(b []byte) error

func (Uint64Array) Value

func (f Uint64Array) Value() (driver.Value, error)

type UniqueObjects added in v1.0.1

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

func NewUniqueObjects added in v1.0.1

func NewUniqueObjects() *UniqueObjects

func (*UniqueObjects) AddObject added in v1.0.1

func (uo *UniqueObjects) AddObject(data ModelObject) error

func (*UniqueObjects) Close added in v1.0.1

func (uo *UniqueObjects) Close()

func (*UniqueObjects) CopyObjects added in v1.0.1

func (uo *UniqueObjects) CopyObjects() (res []ModelObject)

func (*UniqueObjects) Object added in v1.0.1

func (uo *UniqueObjects) Object(id interface{}) (ModelObject, bool)

func (*UniqueObjects) Objects added in v1.0.1

func (uo *UniqueObjects) Objects() []ModelObject

func (*UniqueObjects) Reset added in v1.0.1

func (uo *UniqueObjects) Reset()

type Valuer added in v1.0.2

type Valuer interface {
	Value() (driver.Value, error)
	PostgresType() string
}

type Viewable added in v1.1.1

type Viewable interface {
	Storable
	ViewQuery() string
}

Viewable is an interface that the view-model structure must implement

type XID added in v1.0.1

type XID[T XIDType] xid.ID

func NewXID added in v1.0.1

func NewXID[T XIDType]() XID[T]

func NilXID added in v1.0.1

func NilXID[T XIDType]() XID[T]

func ParseXID added in v1.0.1

func ParseXID[T XIDType](s string) (XID[T], error)

func (XID[T]) MarshalJSON added in v1.0.1

func (u XID[T]) MarshalJSON() ([]byte, error)

func (XID[T]) PostgresAllowNull added in v1.0.3

func (XID[T]) PostgresAllowNull() bool

func (XID[T]) PostgresDefaultValue added in v1.0.2

func (XID[T]) PostgresDefaultValue() string

func (XID[T]) PostgresType added in v1.0.1

func (XID[T]) PostgresType() string

func (*XID[T]) Scan added in v1.0.1

func (u *XID[T]) Scan(src interface{}) error

func (XID[T]) String added in v1.0.1

func (id XID[T]) String() string

func (*XID[T]) UnmarshalJSON added in v1.0.1

func (u *XID[T]) UnmarshalJSON(b []byte) error

func (XID[T]) Value added in v1.0.1

func (u XID[T]) Value() (driver.Value, error)

type XIDJsonTyped added in v1.0.1

type XIDJsonTyped[T XIDType] XID[T]

func (XIDJsonTyped[T]) MarshalJSON added in v1.0.1

func (u XIDJsonTyped[T]) MarshalJSON() ([]byte, error)

func (*XIDJsonTyped[T]) UnmarshalJSON added in v1.0.1

func (u *XIDJsonTyped[T]) UnmarshalJSON(b []byte) error

type XIDType added in v1.0.1

type XIDType interface {
	XIDPrefix() string
}

Directories

Path Synopsis
Package crud implements nestjsx queries execution.
Package crud implements nestjsx queries execution.
Package list implements a doubly linked list.
Package list implements a doubly linked list.

Jump to

Keyboard shortcuts

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