postgres

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 15 Imported by: 4

README

Storage: PostgreSQL

PostgreSQL implementation of the storage interfaces. Built on top of pgx driver and bun ORM.

Components

Storage

Top-level struct that holds the database connection and provides Transactable:

type Storage struct {
    Transactable storage.Transactable
}

Create a storage instance with Create:

func Create(ctx context.Context, cfg config.Database, init Init) (*Storage, error)

Init is a callback invoked after connection is established — use it for schema migrations, table creation, etc.:

storage, err := postgres.Create(ctx, cfg, func(ctx context.Context, conn *database.Bun) error {
    _, err := conn.DB().NewCreateTable().Model((*Person)(nil)).IfNotExists().Exec(ctx)
    return err
})

Methods:

  • Connection() *database.Bun — returns the underlying bun connection
  • Close() error — closes the storage
Table[M storage.Model]

Generic implementation of storage.Table[M] for a single model type:

persons := postgres.NewTable[Person](storage.Connection().DB())

person, err := persons.GetByID(ctx, 42)
err = persons.Save(ctx, Person{Name: "John"})
err = persons.Update(ctx, person)
list, err := persons.List(ctx, 10, 0, storage.SortOrderDesc)
items, err := persons.CursorList(ctx, lastID, 100, storage.SortOrderAsc, storage.ComparatorGt)
lastID, err := persons.LastID(ctx)

NewTable accepts any bun.IDB: pass storage.Connection().DB() to run queries on the connection pool, or tx.Tx() to bind the table to a transaction:

tx, err := storage.Transactable.BeginTransaction(ctx)
txPersons := postgres.NewTable[Person](tx.Tx())
err = txPersons.Save(ctx, Person{Name: "John"}) // visible only after tx.Flush

The table keeps the bun.IDB it was created with, so create it after the connection is established.

DB() bun.IDB returns that bun.IDB for building custom queries; they run in the same transaction when the table is bound to one.

Transaction

Implements storage.Transaction. Obtained via Transactable.BeginTransaction:

tx, err := storage.Transactable.BeginTransaction(ctx)
if err != nil {
    return err
}
defer tx.Close(ctx)

if err := tx.Add(ctx, model); err != nil {
    return tx.HandleError(ctx, err)
}
if err := tx.Flush(ctx); err != nil {
    return tx.HandleError(ctx, err)
}

Methods:

  • Add / Update — insert or update a single model
  • BulkSave — insert multiple models
  • Flush — commit the transaction
  • Rollback — rollback the transaction
  • Exec — execute raw SQL
  • Tx() *bun.Tx — access the underlying bun transaction
  • Pool() *pgx.Conn — access the underlying pgx connection
Numeric

Wrapper around big.Int for PostgreSQL numeric columns:

n := postgres.NewNumeric(bigInt)
n = postgres.FromInt64(42)
n, err = postgres.FromString("123456789012345678901234567890")

result := n.Add(other)
result = n.Sub(other)
result = n.Mul(other)
result = n.Div(other)
result = n.Neg()

i64 := n.ToInt64()
u64 := n.ToUInt64()

Implements driver.Valuer and sql.Scanner for seamless database integration.

Helper Functions

Query builders for common patterns:

// Offset-based pagination
query = postgres.Pagination(query, limit, offset, order)

// Cursor-based pagination
query = postgres.CursorPagination(query, id, limit, order, comparator)

// WHERE field IN (...)
query = postgres.In(query, "status", []string{"active", "pending"})

// WHERE field = ANY(...)
query = postgres.Any(query, "id", ids)
Bulk Copy

Efficient bulk insert using PostgreSQL COPY FROM:

err := postgres.SaveBulkWithCopy(ctx, tx, data, 100)

Falls back to regular insert if data size is below threshold.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Any

func Any[M any](query *bun.SelectQuery, field string, arr []M) *bun.SelectQuery

In - adds ANY clause to query:

WHERE field = Any (1,2,3)

If length of array equals 0 condition skips.

func CursorPagination

func CursorPagination(query *bun.SelectQuery, id uint64, limit int64, order storage.SortOrder, cmp storage.Comparator) *bun.SelectQuery

CursorPagination - adds limit, id where clause and sort to query. Query being like this:

query.Where("id > ?", id).Limit(limit).Order("id ?", order)

func In

func In[M any](query *bun.SelectQuery, field string, arr []M) *bun.SelectQuery

In - adds IN clause to query:

WHERE field IN (1,2,3)

If length of array equals 0 condition skips.

func Pagination

func Pagination(query *bun.SelectQuery, limit, offset int64, order storage.SortOrder) *bun.SelectQuery

Pagination - adds limit, offset and sort to query. Query being like this:

query.Limit(limit).Offset(offset).Order("id ?", order)

func SaveBulkWithCopy added in v0.0.9

func SaveBulkWithCopy[T storage.Copiable](ctx context.Context, tx storage.Transaction, data []T, copyThreashold int) error

SaveBulkWithCopy -

Types

type Init

type Init func(ctx context.Context, conn *database.Bun) error

Init - type of initialization function which called after creating connection to database. For example, can be used for indexes creation.

type Numeric

type Numeric big.Int

Numeric -

func FromInt64

func FromInt64(x int64) *Numeric

func FromString

func FromString(x string) (*Numeric, error)

func NewNumeric

func NewNumeric(x *big.Int) *Numeric

NewNumeric -

func (*Numeric) Add

func (b *Numeric) Add(x *Numeric) *Numeric

func (*Numeric) Div

func (b *Numeric) Div(x *Numeric) *Numeric

func (*Numeric) FromBigInt

func (b *Numeric) FromBigInt(x *big.Int) *Numeric

same as NewBigint()

func (*Numeric) Mul

func (b *Numeric) Mul(x *Numeric) *Numeric

func (*Numeric) Neg

func (b *Numeric) Neg() *Numeric

func (*Numeric) Scan

func (b *Numeric) Scan(value interface{}) error

func (*Numeric) String

func (b *Numeric) String() string

func (*Numeric) Sub

func (b *Numeric) Sub(x *Numeric) *Numeric

func (*Numeric) ToInt64

func (b *Numeric) ToInt64() int64

func (*Numeric) ToUInt64

func (b *Numeric) ToUInt64() uint64

func (*Numeric) Value

func (b *Numeric) Value() (driver.Value, error)

type Storage

type Storage struct {
	Transactable storage.Transactable
	// contains filtered or unexported fields
}

Storage - default storage structure containing Transactable interface and connection to database

func Create

func Create(ctx context.Context, cfg config.Database, init Init) (*Storage, error)

Create - creates storage connection entity

func (*Storage) Close

func (s *Storage) Close() error

Close - closes storage

func (*Storage) Connection

func (s *Storage) Connection() *database.Bun

Connection - returns connection structure

type Table

type Table[M storage.Model] struct {
	// contains filtered or unexported fields
}

Table - Postgres realization of Table interface

func NewTable

func NewTable[M storage.Model](db bun.IDB) *Table[M]

NewTable - creates Table structure

func (*Table[M]) CursorList

func (s *Table[M]) CursorList(ctx context.Context, id uint64, limit int64, order storage.SortOrder, cmp storage.Comparator) ([]M, error)

CursorList - returns array of rows by cursor pagination

func (*Table[M]) DB

func (s *Table[M]) DB() bun.IDB

DB - returns Postgres connection

func (*Table[M]) GetByID

func (s *Table[M]) GetByID(ctx context.Context, id uint64) (m M, err error)

GetByID - returns row by id

func (*Table[M]) IsNoRows

func (s *Table[M]) IsNoRows(err error) bool

IsNoRows - checks errors is pg.ErrNoRows

func (*Table[M]) LastID

func (s *Table[M]) LastID(ctx context.Context) (uint64, error)

LastID - returns last used id

func (*Table[M]) List

func (s *Table[M]) List(ctx context.Context, limit, offset int64, order storage.SortOrder) ([]M, error)

List - returns array of rows

func (*Table[M]) Save

func (s *Table[M]) Save(ctx context.Context, m M) error

Save - inserts row to table and returns id.

func (*Table[M]) Update

func (s *Table[M]) Update(ctx context.Context, m M) error

Update - updates table row by primary key.

type Transactable

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

Transactable - realization of Transactable interface for Postgres

func NewTransactable

func NewTransactable(db *database.Bun) *Transactable

NewTransactable - creates Transactable structure

func (*Transactable) BeginTransaction

func (t *Transactable) BeginTransaction(ctx context.Context) (storage.Transaction, error)

BeginTransaction - opens atomic transaction to communication with Postgres

type Transaction

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

Transaction -

func (*Transaction) Add

func (t *Transaction) Add(ctx context.Context, model any) error

Add -

func (*Transaction) BulkSave

func (t *Transaction) BulkSave(ctx context.Context, models []any) error

BulkSave -

func (*Transaction) Close

func (t *Transaction) Close(ctx context.Context) error

Close -

func (*Transaction) Exec

func (t *Transaction) Exec(ctx context.Context, query string, params ...any) (int64, error)

Exec - executes query and returns the number of affected rows

func (*Transaction) Flush

func (t *Transaction) Flush(ctx context.Context) error

Flush -

func (*Transaction) HandleError

func (t *Transaction) HandleError(ctx context.Context, err error) error

HandleError -

func (*Transaction) Pool added in v0.0.9

func (t *Transaction) Pool() *pgx.Conn

func (*Transaction) Rollback

func (t *Transaction) Rollback(ctx context.Context) error

Rollback -

func (*Transaction) Tx

func (t *Transaction) Tx() *bun.Tx

Tx - returns bun.Tx pointer for custom queries

func (*Transaction) Update

func (t *Transaction) Update(ctx context.Context, model any) error

Update -

Jump to

Keyboard shortcuts

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