gopg

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2024 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/boxgo/box/pkg/client/gopg"
)

type (
	TestUserinfo struct {
		UserName string
		Age      int
	}
)

func main() {
	pg := gopg.StdConfig("default").Build()

	ts := &TestUserinfo{
		UserName: "box",
		Age:      18,
	}
	if err := pg.Model(ts).CreateTable(&gopg.CreateTableOptions{
		IfNotExists: true,
		Temp:        false,
	}); err != nil {
		panic(err)
	}

	if _, err := pg.Model(ts).Insert(); err != nil {
		panic(err)
	}

	fmt.Println(pg.Model(ts).DropTable(&gopg.DropTableOptions{}))
}
Output:

<nil>

Index

Examples

Constants

View Source
const (
	PrimaryKeyFlag = orm.PrimaryKeyFlag
	ForeignKeyFlag = orm.ForeignKeyFlag
	NotNullFlag    = orm.NotNullFlag
	UseZeroFlag    = orm.UseZeroFlag
	UniqueFlag     = orm.UniqueFlag
	ArrayFlag      = orm.ArrayFlag
)
View Source
const (
	InvalidRelation   = orm.InvalidRelation
	HasOneRelation    = orm.HasOneRelation
	BelongsToRelation = orm.BelongsToRelation
	HasManyRelation   = orm.HasManyRelation
	Many2ManyRelation = orm.Many2ManyRelation
)

Variables

View Source
var (
	// Discard is used with Query and QueryOne to discard rows.
	Discard = pg.Discard

	// ErrMultiRows is returned by QueryOne and ExecOne when query returned multiple rows but exactly one row is expected.
	ErrMultiRows = pg.ErrMultiRows

	// ErrNoRows is returned by QueryOne and ExecOne when query returned zero rows but at least one row is expected.
	ErrNoRows = pg.ErrNoRows

	// ErrTxDone is returned by any operation that is performed on a transaction that has already been committed or rolled back.
	ErrTxDone = pg.ErrTxDone
)
View Source
var (
	// Array accepts a slice and returns a wrapper for working with PostgreSQL
	// array data type.
	//
	// For struct fields you can use array tag:
	//
	//    Emails  []string `pg:",array"`
	Array = pg.Array

	// Hstore accepts a map and returns a wrapper for working with hstore data type.
	// Supported map types are:
	//   - map[string]string
	//
	// For struct fields you can use hstore tag:
	//
	//    Attrs map[string]string `pg:",hstore"`
	Hstore = pg.Hstore

	// In accepts a slice and returns a wrapper that can be used with PostgreSQL
	// IN operator:
	//
	//    Where("id IN (?)", pg.In([]int{1, 2, 3, 4}))
	//
	// produces
	//
	//    WHERE id IN (1, 2, 3, 4)
	In = pg.In

	// InMulti accepts multiple values and returns a wrapper that can be used
	// with PostgreSQL IN operator:
	//
	//    Where("(id1, id2) IN (?)", pg.InMulti([]int{1, 2}, []int{3, 4}))
	//
	// produces
	//
	//    WHERE (id1, id2) IN ((1, 2), (3, 4))
	InMulti = pg.InMulti

	// SafeQuery replaces any placeholders found in the query.
	SafeQuery = pg.SafeQuery

	// Scan returns ColumnScanner that copies the columns in the
	// row into the values.
	Scan = pg.Scan

	// RegisterTable registers a struct as SQL table.
	// It is usually used to register intermediate table
	// in many to many relationship.
	RegisterTable = orm.RegisterTable

	// SetTableNameInflector overrides the default func that pluralizes
	// model name to get table name, e.g. my_article becomes my_articles.
	SetTableNameInflector = orm.SetTableNameInflector
)
View Source
var (
	// Default instance
	Default = StdConfig("default").Build()
)

Functions

func Begin

func Begin() (*pg.Tx, error)

func BeginContext

func BeginContext(ctx context.Context) (*pg.Tx, error)

func Conn

func Conn() *pg.Conn

func Context

func Context() context.Context

func CopyFrom

func CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res pg.Result, err error)

func CopyTo

func CopyTo(w io.Writer, query interface{}, params ...interface{}) (res pg.Result, err error)

func Exec

func Exec(query interface{}, params ...interface{}) (res pg.Result, err error)

func ExecContext

func ExecContext(c context.Context, query interface{}, params ...interface{}) (pg.Result, error)

func ExecOne

func ExecOne(query interface{}, params ...interface{}) (pg.Result, error)

func ExecOneContext

func ExecOneContext(ctx context.Context, query interface{}, params ...interface{}) (pg.Result, error)

func Formatter

func Formatter() orm.QueryFormatter

func Listen

func Listen(ctx context.Context, channels ...string) *pg.Listener

func Model

func Model(model ...interface{}) *orm.Query

func ModelContext

func ModelContext(c context.Context, model ...interface{}) *orm.Query

func Param

func Param(param string) interface{}

func Ping

func Ping(ctx context.Context) error

func PoolStats

func PoolStats() *pg.PoolStats

func Prepare

func Prepare(q string) (*pg.Stmt, error)

func Query

func Query(model, query interface{}, params ...interface{}) (res pg.Result, err error)

func QueryContext

func QueryContext(c context.Context, model, query interface{}, params ...interface{}) (pg.Result, error)

func QueryOne

func QueryOne(model, query interface{}, params ...interface{}) (pg.Result, error)

func QueryOneContext

func QueryOneContext(ctx context.Context, model, query interface{}, params ...interface{}) (pg.Result, error)

func RunInTransaction

func RunInTransaction(ctx context.Context, fn func(*pg.Tx) error) error

func WithContext

func WithContext(ctx context.Context) *pg.DB

func WithParam

func WithParam(param string, value interface{}) *pg.DB

func WithTimeout

func WithTimeout(d time.Duration) *pg.DB

Types

type AfterDeleteHook

type AfterDeleteHook = pg.AfterDeleteHook

type AfterInsertHook

type AfterInsertHook = pg.AfterInsertHook

type AfterScanHook

type AfterScanHook = pg.AfterScanHook

type AfterSelectHook

type AfterSelectHook = pg.AfterSelectHook

type AfterUpdateHook

type AfterUpdateHook = pg.AfterUpdateHook

type BeforeDeleteHook

type BeforeDeleteHook = pg.BeforeDeleteHook

type BeforeInsertHook

type BeforeInsertHook = pg.BeforeInsertHook

type BeforeScanHook

type BeforeScanHook = pg.BeforeScanHook

type BeforeUpdateHook

type BeforeUpdateHook = pg.BeforeUpdateHook

type Config

type Config struct {
	Debug                 bool          `config:"debug" desc:"print all queries (even those without an error)"`
	URI                   string        `config:"uri" desc:"pg connection url. example: postgres://user:pass@localhost:5432/db_name?k=v"`
	ApplicationName       string        `config:"applicationName" desc:"ApplicationName is the application name. Used in logs on Pg side. Only available from pg-9.0."`
	Network               string        `config:"network" desc:"Network type, either tcp or unix. Default is tcp."`
	Addr                  string        `config:"addr" desc:"TCP host:port or Unix socket depending on Network."`
	User                  string        `config:"user"`
	Password              string        `config:"password"`
	Database              string        `config:"database"`
	DialTimeout           time.Duration `config:"dialTimeout" desc:"Dial timeout for establishing new connections. Default is 5 seconds."`
	ReadTimeout           time.Duration `config:"readTimeout" desc:"Timeout for socket reads. If reached, commands will fail and user is authenticated."`
	WriteTimeout          time.Duration `config:"writeTimeout" desc:"Timeout for socket writes. If reached, commands will fail with a timeout instead of blocking."`
	MaxRetries            int           `config:"maxRetries" desc:"Maximum number of retries before giving up. Default is to not retry failed queries."`
	RetryStatementTimeout bool          `config:"retryStatementTimeout" desc:"Whether to retry queries cancelled because of statement_timeout."`
	MinRetryBackoff       time.Duration `config:"minRetryBackoff" desc:"Minimum backoff between each retry. Default is 250 milliseconds; -1 disables backoff."`
	MaxRetryBackoff       time.Duration `config:"maxRetryBackoff" desc:"Maximum backoff between each retry. Default is 4 seconds; -1 disables backoff."`
	PoolSize              int           `` /* 133-byte string literal not displayed */
	MinIdleConns          int           `` /* 135-byte string literal not displayed */
	MaxConnAge            time.Duration `` /* 186-byte string literal not displayed */
	PoolTimeout           time.Duration `` /* 218-byte string literal not displayed */
	IdleTimeout           time.Duration `` /* 178-byte string literal not displayed */
	IdleCheckFrequency    time.Duration `` /* 228-byte string literal not displayed */
	// contains filtered or unexported fields
}

Config 配置

func DefaultConfig

func DefaultConfig(key string) *Config

DefaultConfig 默认配置

func StdConfig

func StdConfig(key string, optionFunc ...OptionFunc) *Config

StdConfig 标准配置

func (*Config) Build

func (c *Config) Build() *PostgreSQL

Build 构建实例

func (*Config) Path

func (c *Config) Path() string

Path 实例配置目录

type CreateCompositeOptions

type CreateCompositeOptions = orm.CreateCompositeOptions

type CreateTableOptions

type CreateTableOptions = orm.CreateTableOptions

type DB

type DB = pg.DB

type DebugHook

type DebugHook struct {
	// Verbose causes hook to print all queries (even those without an error).
	Verbose bool
}

DebugHook is a query hook that logs an error with a query if there are any. It can be installed with:

db.AddQueryHook(pgext.DebugHook{})

Copy from https://github.com/go-pg/pg/tree/v10/extra/pgdebug

func (DebugHook) AfterQuery

func (h DebugHook) AfterQuery(ctx context.Context, evt *pg.QueryEvent) error

func (DebugHook) BeforeQuery

func (h DebugHook) BeforeQuery(ctx context.Context, evt *pg.QueryEvent) (context.Context, error)

type DropCompositeOptions

type DropCompositeOptions = orm.DropCompositeOptions

type DropTableOptions

type DropTableOptions = orm.DropTableOptions

type Error

type Error = pg.Error

type Ident

type Ident = pg.Ident

type NullTime

type NullTime = pg.NullTime

type OptionFunc

type OptionFunc func(*Config)

OptionFunc 选项信息

func WithDialer

func WithDialer(fn func(ctx context.Context, network, addr string) (net.Conn, error)) OptionFunc

func WithOnConnect

func WithOnConnect(fn func(ctx context.Context, cn *pg.Conn) error) OptionFunc

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) OptionFunc

type Options

type Options = pg.Options

type PgConn

type PgConn = pg.Conn

type PgQuery

type PgQuery = orm.Query

type PostgreSQL

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

func (*PostgreSQL) Begin

func (pg *PostgreSQL) Begin() (*pg.Tx, error)

func (*PostgreSQL) BeginContext

func (pg *PostgreSQL) BeginContext(ctx context.Context) (*pg.Tx, error)

func (*PostgreSQL) Conn

func (pg *PostgreSQL) Conn() *pg.Conn

func (*PostgreSQL) Context

func (pg *PostgreSQL) Context() context.Context

func (*PostgreSQL) CopyFrom

func (pg *PostgreSQL) CopyFrom(r io.Reader, query interface{}, params ...interface{}) (res pg.Result, err error)

func (*PostgreSQL) CopyTo

func (pg *PostgreSQL) CopyTo(w io.Writer, query interface{}, params ...interface{}) (res pg.Result, err error)

func (*PostgreSQL) Exec

func (pg *PostgreSQL) Exec(query interface{}, params ...interface{}) (res pg.Result, err error)

func (*PostgreSQL) ExecContext

func (pg *PostgreSQL) ExecContext(c context.Context, query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) ExecOne

func (pg *PostgreSQL) ExecOne(query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) ExecOneContext

func (pg *PostgreSQL) ExecOneContext(ctx context.Context, query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) Formatter

func (pg *PostgreSQL) Formatter() orm.QueryFormatter

func (*PostgreSQL) Listen

func (pg *PostgreSQL) Listen(ctx context.Context, channels ...string) *pg.Listener

func (*PostgreSQL) Model

func (pg *PostgreSQL) Model(model ...interface{}) *orm.Query

func (*PostgreSQL) ModelContext

func (pg *PostgreSQL) ModelContext(c context.Context, model ...interface{}) *orm.Query

func (*PostgreSQL) Name added in v1.0.6

func (pg *PostgreSQL) Name() string

func (*PostgreSQL) Param

func (pg *PostgreSQL) Param(param string) interface{}

func (*PostgreSQL) Ping

func (pg *PostgreSQL) Ping(ctx context.Context) error

func (*PostgreSQL) PoolStats

func (pg *PostgreSQL) PoolStats() *pg.PoolStats

func (*PostgreSQL) Prepare

func (pg *PostgreSQL) Prepare(q string) (*pg.Stmt, error)

func (*PostgreSQL) Query

func (pg *PostgreSQL) Query(model, query interface{}, params ...interface{}) (res pg.Result, err error)

func (*PostgreSQL) QueryContext

func (pg *PostgreSQL) QueryContext(c context.Context, model, query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) QueryOne

func (pg *PostgreSQL) QueryOne(model, query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) QueryOneContext

func (pg *PostgreSQL) QueryOneContext(ctx context.Context, model, query interface{}, params ...interface{}) (pg.Result, error)

func (*PostgreSQL) RunInTransaction

func (pg *PostgreSQL) RunInTransaction(ctx context.Context, fn func(*pg.Tx) error) error

func (*PostgreSQL) Serve

func (pg *PostgreSQL) Serve(ctx context.Context) error

func (*PostgreSQL) Shutdown

func (pg *PostgreSQL) Shutdown(ctx context.Context) error

func (*PostgreSQL) WithContext

func (pg *PostgreSQL) WithContext(ctx context.Context) *pg.DB

func (*PostgreSQL) WithParam

func (pg *PostgreSQL) WithParam(param string, value interface{}) *pg.DB

func (*PostgreSQL) WithTimeout

func (pg *PostgreSQL) WithTimeout(d time.Duration) *pg.DB

type Result

type Result = pg.Result

type Safe

type Safe = pg.Safe

type Stmt

type Stmt = pg.Stmt

type Tx

type Tx = pg.Tx

Jump to

Keyboard shortcuts

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