pg

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MigrationPending MigrationState = 0 // This migration has not been applied yet.
	MigrationSuccess                = 1 // This migration succeeded. (Applied)
	MigrationFailed                 = 2 // This migration failed. (Applied)
)

Variables

View Source
var (
	ErrNoInstance    = errors.New("there is no active database instance")
	ErrManyInstances = errors.New("there is more than one active database instance")
)
View Source
var ErrOptimisticLock = errors.New("optimistic locking conflict occurs")
View Source
var ErrUnsupportedDataType = errors.New("unsupported data type")

Functions

func Jsonb

func Jsonb(value map[string]any) *jsonbValuer

func QuoteIdentifier

func QuoteIdentifier(name string) string

func QuoteLiteral

func QuoteLiteral(literal string) string

func ScanJsonb

func ScanJsonb(dest any) *jsonbScanner

Types

type Config

type Config struct {
	Username string              // The username to connect with.
	Password string              // The password to connect with
	Host     string              // Specifies the host name on which PostgreSQL is running.
	Port     int                 // The TCP port of the PostgreSQL server.
	Database string              // The PostgreSQL database to connect to.
	SSLMode  string              // Controls whether SSL is used, depending on server support.
	Params   map[string][]string // Connection params
	DebugSql bool                // debug queries
	Logger   Logger              // Logger instance
}

Config database config

func (*Config) ConnString

func (c *Config) ConnString(customParams map[string]string) string

type Database

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

func GetInstance

func GetInstance() (*Database, error)

func Open

func Open(config *Config) (*Database, error)

Open opens a database

func (*Database) AddMigration

func (d *Database) AddMigration(version, description string, prepare MigrationPrepare) error

AddMigration register a new migration

func (*Database) AddMigrations

func (d *Database) AddMigrations(dir fs.FS) error

AddMigrations automatically registers all migration files in a directory.

func (*Database) Begin

func (d *Database) Begin() (*Database, error)

Begin starts a transaction.

func (*Database) BeginTx

func (d *Database) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Database, error)

BeginTx starts a transaction.

func (*Database) Close

func (d *Database) Close() error

Close closes the database and prevents new queries from starting.

func (*Database) CloseConn

func (d *Database) CloseConn() error

CloseConn returns the connection to the connection pool.

func (*Database) Commit

func (d *Database) Commit() error

Commit commits the transaction.

func (*Database) Conn

func (d *Database) Conn() (*Database, error)

Conn returns a Database with a new connection

Every Conn must be returned to the pool after use by calling Database.CloseConn.

func (*Database) DeleteWhere

func (d *Database) DeleteWhere(table string, condition map[string]interface{}) (sql.Result, error)

DeleteWhere Executa um DELETE FROM WHERE

func (*Database) Execute

func (d *Database) Execute(query string, args ...interface{}) (sql.Result, error)

Execute executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (*Database) InsertInto

func (d *Database) InsertInto(schema, table string, values map[string]interface{}) (sql.Result, error)

InsertInto Executa um Insert Into

func (*Database) Migrate

func (d *Database) Migrate(config *MigrationConfig) error

Migrate run all migrations

func (*Database) Prepare

func (d *Database) Prepare(query string) (*sql.Stmt, error)

func (*Database) Query

func (d *Database) Query(query string, args ...interface{}) (*sql.Rows, error)

Query executes a prepared query statement with the given arguments and returns the query results as a *Rows.

func (*Database) QueryForBoolean

func (d *Database) QueryForBoolean(query string, args ...interface{}) (bool, error)

func (*Database) QueryForInt

func (d *Database) QueryForInt(query string, args ...interface{}) (int64, error)

QueryForInt Obtém o resultado de uma query que busca por um valor. IMPORTANTE! Quando a query nao retornar registros esse método ira retornar 0 como resposta

func (*Database) QueryRow

func (d *Database) QueryRow(query string, args ...interface{}) (row *sql.Row, err error)

func (*Database) QueryRowOld

func (d *Database) QueryRowOld(query string, args ...interface{}) *RowWraper

func (*Database) Rollback

func (d *Database) Rollback() error

Rollback aborts the transaction.

func (*Database) Savepoint

func (d *Database) Savepoint(savepoint string, callback func() error) error

Savepoint define a new savepoint within the current transaction

func (*Database) SelectRowWhere

func (d *Database) SelectRowWhere(table string, fields map[string]interface{}, condition map[string]interface{}) error

SelectRowWhere Executa um SELECT FROM WHERE

func (*Database) SetLogger

func (d *Database) SetLogger(logger Logger)

func (*Database) Transaction

func (d *Database) Transaction(callback func(db *Database) error) error

Transaction Executes this callback within a transaction

func (*Database) Update

func (d *Database) Update(
	schema, table string, values map[string]interface{}, condition map[string]interface{},
) (sql.Result, error)

Update Executa uma query UPDATE SET values WHERE condition

func (*Database) UpdateOptimisticLock

func (d *Database) UpdateOptimisticLock(
	schema, table string, values map[string]interface{}, condition map[string]interface{},
) (sql.Result, error)

UpdateOptimisticLock Executa uma query UPDATE SET values WHERE condition

func (*Database) Upsert

func (d *Database) Upsert(table string, values map[string]interface{}, conflictField string) (sql.Result, error)

Upsert Executa uma query INSERT INTO ON CONFLICT UPDATE SET

type Logger

type Logger interface {
	Error(err error)
	Info(string, ...interface{})
	Warn(string, ...interface{})
}

Logger is implemented by any logging system that is used for standard logs.

type Migration

type Migration struct {
	Repeat bool
	Info   *MigrationInfo

	Prepare MigrationPrepare
	// contains filtered or unexported fields
}

func (*Migration) ExecFn

func (m *Migration) ExecFn(name string, callback MigrationCommandFn, args ...interface{})

ExecFn Schedule the execution of a golang command in this migration

func (*Migration) ExecSql

func (m *Migration) ExecSql(sql string, args ...interface{})

ExecSql Schedule the execution of an SQL command in this migration

type MigrationCommandFn

type MigrationCommandFn func(db *Database, migration *Migration, args ...interface{}) error

type MigrationConfig

type MigrationConfig struct {
	Username string // The username to connect with.
	Password string // The password to connect with.
	Schema   string // migrationHistory schema name (defaults public)
	Table    string // migrationHistory table name (defaults pg_schema_history)
}

MigrationConfig database config

type MigrationInfo

type MigrationInfo struct {
	Version       string         // The Version of the schema after the migration is complete.
	State         MigrationState // The state of the migration (MigrationPending, MigrationSuccess, ...)
	Description   string         // The description of the migration
	InstalledRank int            // The rank of this installed migration.
	Checksum      string         // Computed checksum of the migration.
}

func (*MigrationInfo) Identifier

func (i *MigrationInfo) Identifier() string

type MigrationPrepare

type MigrationPrepare func(context *Migration)

type MigrationState

type MigrationState int

type MigrationStateInfo

type MigrationStateInfo struct {
	DisplayName string
	Applied     bool
	Failed      bool
}

MigrationStateInfo The state of a migration.

type Model

type Model[T any] struct {
	Data []T
}

func NewModel

func NewModel[T any](data []T) *Model[T]

func (Model[T]) Create

func (m Model[T]) Create() *T

func (*Model[T]) Method

func (m *Model[T]) Method(r *T) T

type Query

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

func NewQuery

func NewQuery(query string, mapper func(rows *Row) (model any, err error)) *Query

func (*Query) Retry

func (q *Query) Retry(retries int) *Query

func (*Query) SelectAll

func (q *Query) SelectAll(args ...any) (result []any, err error)

func (*Query) SelectOne

func (q *Query) SelectOne(args ...any) (result any, err error)

func (*Query) With

func (q *Query) With(db *Database) *Query

type Row

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

func (*Row) ColumnTypes

func (r *Row) ColumnTypes() ([]*sql.ColumnType, error)

func (*Row) Columns

func (r *Row) Columns() ([]string, error)

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

type RowWraper

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

RowWraper Wraper para trabalhar com o sql.Row, que tem propriedades privadas

func (*RowWraper) Err

func (r *RowWraper) Err() error

func (*RowWraper) Scan

func (r *RowWraper) Scan(dest ...interface{}) error

type Table

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

func NewTable

func NewTable[T any](schema, name string, model T) (*Table[T], error)

func (*Table[T]) Insert

func (t *Table[T]) Insert(values ...T) (bool, error)

func (*Table[T]) Using

func (t *Table[T]) Using(db *Database) *Table[T]

type UserModel

type UserModel struct {
	Id    string // "id    VARCHAR(27)  NOT NULL PRIMARY KEY"
	Email string // "email VARCHAR(255) NOT NULL"
}

Jump to

Keyboard shortcuts

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