db

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2019 License: Apache-2.0 Imports: 14 Imported by: 7

README

DB

DB is a package with helpers and wrappers for interacting with PostgreSQL using the squirrel.Builder.

Package types

  • Transactional is the interface for representing a db connector/query builder that support database transactions.
  • SQLConn is a connector for execution of queries to the PostgreSQL database.
  • PageQuery is the structure for building query with pagination
  • Table is the basis for implementing Querier for some model or table.

SQLConn

This is a database connector. SQLConn supports database transactions.

  • Clone returns sanitized copy of SQLConn instance backed by the same context and db. The result will not be bound to any transaction that the source is currently within.

  • Get casts given squirrel.Sqlizer to raw SQL string with arguments and execute GetRaw.

  • Exec casts given squirrel.Sqlizer to raw SQL string with arguments and execute ExecRaw

  • Select casts given squirrel.SelectBuilder to raw SQL string with arguments and execute SelectRaw.

  • GetRaw executes given SQL Select and returns only one record.

  • ExecRaw executes any given SQL query.

  • SelectRaw executes given SQL Select and returns all records.

PageQuery

Table

Usage

  • Connect and execute some query:
package main

import (
    "log"
    "github.com/lancer-kit/armory/db"
)

func main() {
    // initialize SQLConn singleton
    err := db.Init("postgres://user:user@localhost/user?sslmode=disable", nil)
    if err != nil {
        panic(err)
    }
    sqlConn := db.GetConnector()
    err = sqlConn.ExecRaw(`CREATE TABLE IF NOT EXIST users(
    id SERIAL, name VARCHAR(64), email VARCHAR(64), age INTEGER)`, nil)
    if err != nil {
        panic(err)
    }
}

Documentation

Index

Constants

View Source
const (
	DefaultPageSize uint64 = 20
	MaxPageSize     uint64 = 500

	OrderAscending  = "asc"
	OrderDescending = "desc"
)

Variables

View Source
var (
	ErrInvalidOrder = func(val string) error {
		return fmt.Errorf("order(%s): accept only %s|%s",
			val, OrderAscending, OrderDescending)
	}
	ErrTooBigPage = func(val uint64) error {
		return fmt.Errorf("pageSize(%d): shoud be less or equal %d", val, MaxPageSize)
	}
)

Functions

func Init

func Init(dbConnStr string, logger *logrus.Entry) error

Init initializes new connector with database.

func Migrate

func Migrate(connStr string, dir MigrateDir) (int, error)

Migrate connects to the database and applies migrations.

func SetAssets

func SetAssets(assets migrate.AssetMigrationSource)

SetAssets is a function for injection of precompiled by bindata migrations files.

Types

type Config

type Config struct {
	ConnURL     string `json:"conn_url" yaml:"conn_url"` //The database connection string.
	InitTimeout int    `json:"dbInitTimeout" yaml:"init_timeout"`
	// AutoMigrate if `true` execute db migrate up on start.
	AutoMigrate bool              `json:"auto_migrate" yaml:"auto_migrate"`
	WaitForDB   bool              `json:"wait_for_db" yaml:"wait_for_db"`
	Params      *ConnectionParams `json:"params" yaml:"params"`
}

func (*Config) URL added in v1.7.0

func (cfg *Config) URL() string

func (Config) Validate added in v1.7.0

func (cfg Config) Validate() error

type ConnectionParams added in v1.7.0

type ConnectionParams struct {
	MaxIdleConns int `json:"max_idle" yaml:"max_idle"`
	MaxOpenConns int `json:"max_open" yaml:"max_open"`
	// MaxLifetime time.Duration in Millisecond
	MaxLifetime int64 `json:"max_lifetime" yaml:"max_lifetime"`
}

type MigrateDir

type MigrateDir string

MigrateDir represents a direction in which to perform schema migrations.

const (
	// MigrateUp causes migrations to be run in the "up" direction.
	MigrateUp MigrateDir = "up"
	// MigrateDown causes migrations to be run in the "down" direction.
	MigrateDown MigrateDir = "down"
)

type PageQuery

type PageQuery struct {
	Order    string `json:"order"`
	Page     uint64 `json:"page"`
	PageSize uint64 `json:"pageSize"`
}

PageQuery is the structure for building query with pagination.

func ParsePageQuery

func ParsePageQuery(values url.Values) (pq PageQuery, err error)

ParsePageQuery extracts `PageQuery` from the url Query Values.

func (*PageQuery) Apply

func (pq *PageQuery) Apply(query sq.SelectBuilder, orderColumn string) sq.SelectBuilder

Apply sets limit and ordering params to SelectBuilder.

func (*PageQuery) FromRQuery

func (pq *PageQuery) FromRQuery(query url.Values) error

FromRQuery extracts `PageQuery` from the url Query Values and validate.

func (*PageQuery) Offset

func (pq *PageQuery) Offset() uint64

Offset calculates select offset.

func (*PageQuery) Validate

func (pq *PageQuery) Validate() error

Validate checks is correct values and set default values if `PageQuery` empty.

type SQLConn

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

SQLConn is a connector for interacting with the database.

func GetConnector

func GetConnector() *SQLConn

GetConnector returns an instance of the SQLConn.

func NewConnector added in v1.7.0

func NewConnector(cfg Config, logger *logrus.Entry) (*SQLConn, error)

NewConnector returns an new instance of the SQLConn.

func NewSQLConn

func NewSQLConn(db *sqlx.DB, logger *logrus.Entry) *SQLConn

NewSQLConn create new connector by passed connection params

func (*SQLConn) Begin

func (conn *SQLConn) Begin() error

Begin binds this SQLConn to a new transaction.

func (*SQLConn) Clone

func (conn *SQLConn) Clone() *SQLConn

Clone clones the receiver, returning a new instance backed by the same context and db. The result will not be bound to any transaction that the source is currently within.

func (*SQLConn) Commit

func (conn *SQLConn) Commit() error

Commit commits the current transaction.

func (*SQLConn) Exec

func (conn *SQLConn) Exec(sqq sq.Sqlizer) error

Exec compile `sqq` to SQL and runs query.

func (*SQLConn) ExecRaw

func (conn *SQLConn) ExecRaw(query string, args ...interface{}) error

ExecRaw runs `query` with `args`.

func (*SQLConn) Get

func (conn *SQLConn) Get(sqq sq.Sqlizer, dest interface{}) error

Get compile `sqq` to raw sql query, executes it and write first row into the `dest`.

func (*SQLConn) GetRaw

func (conn *SQLConn) GetRaw(dest interface{}, query string, args ...interface{}) error

GetRaw executes a raw sql query and write first row into the `dest`.

func (*SQLConn) InTx added in v1.6.0

func (conn *SQLConn) InTx() bool

InTx checks is transaction started. Return true if it is a transaction, and false if it is not a transaction

func (*SQLConn) Insert

func (conn *SQLConn) Insert(sqq sq.InsertBuilder) (id interface{}, err error)

Insert compile `sqq` to SQL and runs query. Return last inserted id

func (*SQLConn) IsInTx

func (conn *SQLConn) IsInTx() bool

IsInTx checks is transaction started. DEPRECATED: IsInTx works wrong

func (*SQLConn) Rollback

func (conn *SQLConn) Rollback() error

Rollback rolls back the current transaction

func (*SQLConn) Select

func (conn *SQLConn) Select(sqq sq.Sqlizer, dest interface{}) error

Select compile `sqq` to raw sql query, executes it, and write each row into dest, which must be a slice.

func (*SQLConn) SelectRaw

func (conn *SQLConn) SelectRaw(dest interface{}, query string, args ...interface{}) error

SelectRaw executes a raw sql query, and write each row into dest, which must be a slice.

func (*SQLConn) SetConnMaxLifetime

func (conn *SQLConn) SetConnMaxLifetime(d int64)

func (*SQLConn) SetConnParams added in v1.7.0

func (conn *SQLConn) SetConnParams(params *ConnectionParams)

func (*SQLConn) SetMaxIdleConns

func (conn *SQLConn) SetMaxIdleConns(n int)

func (*SQLConn) SetMaxOpenConns

func (conn *SQLConn) SetMaxOpenConns(n int)

func (*SQLConn) SetTx

func (conn *SQLConn) SetTx(tx *sqlx.Tx)

SetTx set new sqlx.Tx

func (*SQLConn) Stats

func (conn *SQLConn) Stats() sql.DBStats

func (*SQLConn) Transaction

func (conn *SQLConn) Transaction(fn func() error) (err error)

Transaction is generic helper method for specific Q's to implement Transaction capabilities

type Table

type Table struct {
	Name  string
	Alias string

	DB        sq.BaseRunner
	QBuilder  sq.SelectBuilder
	GQBuilder sq.SelectBuilder
	IQBuilder sq.InsertBuilder
	UQBuilder sq.UpdateBuilder
	DQBuilder sq.DeleteBuilder
	Page      *PageQuery
}

Table is the basis for implementing Querier for some model or table.

func (Table) AliasedName

func (t Table) AliasedName() string

AliasedName returns table name with the alias postfix.

func (*Table) ApplyPage

func (t *Table) ApplyPage(orderColumn string)

ApplyPage adds limit/offset and/or order to the queryBuilder.

func (*Table) SetPage

func (t *Table) SetPage(pq *PageQuery)

SetPage is a setter for Page field.

func (*Table) WithCount

func (t *Table) WithCount()

DEPRECATED! Do not use this method for counting, because it very slow and does count for each row, WithCount adds a column with the total number of records. ATTENTION! The model must have a destination for this `row_count` column.

type Transactional

type Transactional interface {
	// Begin starts a database transaction.
	Begin() error
	// Commit commits the transaction.
	Commit() error
	// Rollback aborts the transaction.
	Rollback() error
	// IsInTx checks is transaction started.
	// DEPRECATED: IsInTx works wrong
	IsInTx() bool
	// InTx checks is transaction started. Return true if it is a transaction, and false if it is not a transaction
	InTx() bool
}

Transactional is the interface for representing a db connector/query builder that support database transactions.

type WBase

type WBase struct {
	DB     Transactional
	Logger *logrus.Entry
	Ctx    context.Context
	Err    error
}

WBase is a base structure for worker which uses database and need transactions support.

func (*WBase) DBTxRollback

func (s *WBase) DBTxRollback()

func (*WBase) Recover

func (s *WBase) Recover()

Jump to

Keyboard shortcuts

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