godb

package module
v1.11.6 Latest Latest
Warning

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

Go to latest
Published: May 27, 2022 License: BSD-2-Clause Imports: 17 Imported by: 0

README

GODB

The database wrapper for manage postgres db

Init connection example

import _ "github.com/lib/pq"

connectionConfig := godb.PostgresConnectionConfig{...}

dbo, err := godb.DBO{
    Options: godb.Options{
        Debug:  true,
        Logger: App.GetLogger(),
    },
    Connection: &connectionConfig,
}.Init()

Transaction functions

func StartTransaction() *godb.SqlTx {
	tx, err := dbo.Begin()
	if err != nil {
		panic(err)
		return nil
	}
	return tx
}

func EndTransaction(q *godb.SqlTx, e porterr.IError) {
	var err error
	if e != nil {
		err = q.Rollback()
	} else {
		err = q.Commit()
	}
	if err != nil {
		panic(err)
	}
	return
}

// usage

tx := StartTransaction()
defer func() { EndTransaction(tx, e) }()

Model generator

Will create model.go in app/models directory

err := godb.MakeModel(dbo, "app/models", "schema", "table", "vendor/github.com/dimonrus/godb/model.tmpl", godb.DefaultSystemColumnsSoft)
if err != nil {
   panic(err)
}

Documentation

Index

Constants

View Source
const (
	ConditionOperatorAnd = "AND"
	ConditionOperatorOr  = "OR"
	ConditionOperatorXor = "XOR"
)
View Source
const (
	// ConflictActionNothing On conflict action do nothing
	ConflictActionNothing = "NOTHING"

	// ConflictActionUpdate On conflict action do update nothing
	ConflictActionUpdate = "UPDATE"
)

Variables

View Source
var DefaultDictionaryTemplate string
View Source
var DefaultModelTemplate string
View Source
var DefaultSystemColumns = SystemColumns{Created: "created_at", Updated: "updated_at"}
View Source
var DefaultSystemColumnsSoft = SystemColumns{Created: "created_at", Updated: "updated_at", Deleted: "deleted_at"}

Functions

func CreateDictionaryTable

func CreateDictionaryTable(q Queryer) error

Create Table

func CreateModelFile

func CreateModelFile(schema string, table string, path string) (*os.File, string, error)

Create file in os

func GenerateDictionaryMapping

func GenerateDictionaryMapping(path string, q Queryer) error

Create or update dictionary mapping

func MakeModel

func MakeModel(db Queryer, dir string, schema string, table string, templatePath string, systemColumns SystemColumns) error

Create model

func ModelColumn added in v1.7.6

func ModelColumn(model IModel, field interface{}) string

Model column in db

func ModelColumns added in v1.11.0

func ModelColumns(model IModel, field ...interface{}) (columns []string)

Model columns by fileds

func ModelDeleteQuery added in v1.7.8

func ModelDeleteQuery(model IModel, condition *Condition) (sql string, e porterr.IError)

Model delete query

func ModelInsertQuery added in v1.8.5

func ModelInsertQuery(model IModel, fields ...interface{}) (sql string, columns []string, e porterr.IError)

Model insert query

func ModelUpdateQuery added in v1.7.7

func ModelUpdateQuery(model IModel, condition *Condition, fields ...interface{}) (sql string, params []interface{}, e porterr.IError)

Model update query

func ModelValues added in v1.8.6

func ModelValues(model IModel, columns ...string) (values []interface{})

Model values by columns

Types

type Column

type Column struct {
	Name              string  // DB column name
	ModelName         string  // Model name
	Default           *string // DB default value
	IsNullable        bool    // DB is nullable
	IsByteArray       bool    // Do not need type pointer for []byte
	DataType          string  // DB column type
	ModelType         string  // Model type
	Schema            string  // DB Schema
	Table             string  // DB table
	Sequence          *string // DB sequence
	ForeignSchema     *string // DB foreign schema name
	ForeignTable      *string // DB foreign table name
	ForeignColumnName *string // DB foreign column name
	ForeignIsSoft     bool    // DB foreign table is soft
	Description       *string // DB column description
	IsPrimaryKey      bool    // DB is primary key
	Tags              string  // Model Tags name
	Import            string  // Model Import custom lib
	IsArray           bool    // Array column
	IsCreated         bool    // Is created at column
	IsUpdated         bool    // Is updated at column
	IsDeleted         bool    // Is deleted at column
	HasUniqueIndex    bool    // If column is a part of unique index
	UniqueIndexName   *string // Unique index name
	DefaultTypeValue  *string // Default value for type
}

Column information

func (Column) GetModelFieldTag added in v1.11.1

func (c Column) GetModelFieldTag() (field ModelFiledTag)

GetModelFieldTag Prepare ModelFiledTag by Column

type Columns

type Columns []Column

Array of columns

func GetTableColumns

func GetTableColumns(dbo Queryer, schema string, table string, sysCols SystemColumns) (*Columns, error)

Get table columns from db

func (Columns) GetImports added in v1.2.3

func (c Columns) GetImports() []string

Get imports

type Condition added in v1.2.7

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

Condition type

func NewSqlCondition added in v1.1.0

func NewSqlCondition(operator string) *Condition

Init Condition

func (*Condition) AddArgument added in v1.2.9

func (c *Condition) AddArgument(values ...interface{}) *Condition

Add argument

func (*Condition) AddExpression added in v1.2.7

func (c *Condition) AddExpression(expression string, values ...interface{}) *Condition

Add expression

func (*Condition) GetArguments added in v1.2.7

func (c *Condition) GetArguments() []interface{}

Get arguments

func (*Condition) IsEmpty added in v1.7.2

func (c *Condition) IsEmpty() bool

Check if condition is empty

func (*Condition) Merge added in v1.2.7

func (c *Condition) Merge(operator string, conditions ...*Condition) *Condition

Merge with conditions

func (*Condition) String added in v1.2.7

func (c *Condition) String() string

Get string of conditions

type Connection

type Connection interface {
	String() string
	GetDbType() string
	GetMaxConnection() int
	GetConnMaxLifetime() int
	GetMaxIdleConns() int
}

Database Object Connection Interface

type ConnectionConfig

type ConnectionConfig struct {
	Host                   string
	Port                   int
	Name                   string
	User                   string
	Password               string
	MaxConnections         int `yaml:"maxConnections"`
	MaxIdleConnections     int `yaml:"maxIdleConnections"`
	ConnectionIdleLifetime int `yaml:"connectionIdleLifetime"`
}

Client connection config

func (*ConnectionConfig) GetConnMaxLifetime

func (cc *ConnectionConfig) GetConnMaxLifetime() int

Connection idle lifetime

func (*ConnectionConfig) GetMaxConnection

func (cc *ConnectionConfig) GetMaxConnection() int

Get Max Connection

func (*ConnectionConfig) GetMaxIdleConns

func (cc *ConnectionConfig) GetMaxIdleConns() int

Connection max idle connections

type DBO

type DBO struct {
	*sql.DB
	Options
	Connection Connection
}

Main Database Object

func (*DBO) Begin

func (dbo *DBO) Begin() (*SqlTx, error)

Begin transaction

func (*DBO) Exec

func (dbo *DBO) Exec(query string, args ...interface{}) (sql.Result, error)

SQL Exec

func (DBO) Init

func (dbo DBO) Init() (*DBO, error)

Init Database Object

func (*DBO) Prepare

func (dbo *DBO) Prepare(query string) (*SqlStmt, error)

Prepare statement

func (*DBO) Query

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

SQL Query

func (*DBO) QueryRow

func (dbo *DBO) QueryRow(query string, args ...interface{}) *sql.Row

SQL Query Row

type DictionaryModel

type DictionaryModel struct {
	Id        int        `json:"id"`        // Идентификатор значения справочника
	Type      string     `json:"type"`      // Тип значения справочника
	Code      string     `json:"code"`      // Код значения справочника
	Label     *string    `json:"label"`     // Описание значения справочника
	CreatedAt time.Time  `json:"createdAt"` // Время создания записи
	UpdatedAt *time.Time `json:"updatedAt"` // Время обновления записи
	DeletedAt *time.Time `json:"deletedAt"` // Время удаления записи
}

func (*DictionaryModel) Columns

func (m *DictionaryModel) Columns() []string

Model columns

func (*DictionaryModel) SearchDictionary

func (m *DictionaryModel) SearchDictionary(q Queryer) (*[]DictionaryModel, []int, error)

Search by filer

func (*DictionaryModel) Values

func (m *DictionaryModel) Values() (values []interface{})

Model values

type IMigrationFile

type IMigrationFile interface {
	Up(tx *SqlTx) error
	Down(tx *SqlTx) error
	GetVersion() string
}

Migration file interface

type IModel added in v1.6.0

type IModel interface {
	Table() string
	Columns() []string
	Values() []interface{}
	Load(q Queryer) porterr.IError
	Save(q Queryer) porterr.IError
	Delete(q Queryer) porterr.IError
}

DB model interface

type IModelCrud added in v1.11.0

type IModelCrud interface {
	GetLoadQuery() string
	GetInsertQuery() string
	GetUpdateQuery() string
	GetDeleteQuery() string
}

IModelCrud CRUD query interface

type ISoftModel added in v1.6.0

type ISoftModel interface {
	IModel
	SoftLoad(q Queryer) porterr.IError
	SoftDelete(q Queryer) porterr.IError
	SoftRecover(q Queryer) porterr.IError
}

DB model interface

type Insert added in v1.11.3

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

Insert query builder

func NewInsert added in v1.11.3

func NewInsert() *Insert

New Insert Query Builder

func (*Insert) AddReturning added in v1.11.3

func (i *Insert) AddReturning(returning ...string) *Insert

AddReturning Add returning expression

func (*Insert) AddValues added in v1.11.3

func (i *Insert) AddValues(values []any) *Insert

AddValues Add row values

func (*Insert) Columns added in v1.11.3

func (i *Insert) Columns(column ...string) *Insert

Columns Set columns

func (*Insert) Conflict added in v1.11.3

func (i *Insert) Conflict() *conflict

Conflict get conflict expression

func (*Insert) From added in v1.11.3

func (i *Insert) From(from string) *Insert

From insert from

func (*Insert) GetAllValues added in v1.11.3

func (i *Insert) GetAllValues() []any

GetAllValues get all values

func (*Insert) GetValues added in v1.11.3

func (i *Insert) GetValues(start, end int) []any

GetValues get values by indexes

func (*Insert) GetWith added in v1.11.3

func (i *Insert) GetWith(name string) *QB

Get With

func (*Insert) Into added in v1.11.3

func (i *Insert) Into(into string) *Insert

Into Set into value

func (*Insert) ResetColumns added in v1.11.3

func (i *Insert) ResetColumns() *Insert

Columns Set columns

func (*Insert) ResetFrom added in v1.11.3

func (i *Insert) ResetFrom() *Insert

ResetFrom clear from

func (*Insert) ResetInto added in v1.11.3

func (i *Insert) ResetInto() *Insert

ResetInto Set into empty string

func (*Insert) ResetReturning added in v1.11.3

func (i *Insert) ResetReturning() *Insert

ResetReturning Reset returning expressions

func (*Insert) ResetValues added in v1.11.3

func (i *Insert) ResetValues() *Insert

ResetValues Reset all values

func (*Insert) ResetWith added in v1.11.3

func (i *Insert) ResetWith() *Insert

ResetWith Reset With query

func (*Insert) SQL added in v1.11.3

func (i *Insert) SQL() (query string, params []any)

SQL return query with params

func (*Insert) SetValues added in v1.11.3

func (i *Insert) SetValues(index int, values []any) *Insert

SetValues Set row values by index

func (*Insert) String added in v1.11.3

func (i *Insert) String() string

Get sql insert query

func (*Insert) With added in v1.11.3

func (i *Insert) With(name string, qb *QB) *Insert

Add With

type Iterator added in v1.6.0

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

Iterator

func NewIterator added in v1.6.9

func NewIterator(len int) *Iterator

New Iterator

func (*Iterator) Count added in v1.6.0

func (c *Iterator) Count() int

Get count

func (*Iterator) Cursor added in v1.6.0

func (c *Iterator) Cursor() int

Get cursor

func (*Iterator) Next added in v1.6.0

func (c *Iterator) Next() bool

Iterator next

func (*Iterator) Reset added in v1.6.0

func (c *Iterator) Reset() *Iterator

Reset cursor

func (*Iterator) SetCount added in v1.6.0

func (c *Iterator) SetCount(count int) *Iterator

Set count

type Logger

type Logger interface {
	Print(v ...interface{})
	Println(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger

type Migration

type Migration struct {
	MigrationPath string
	DBO           *DBO
	Config        ConnectionConfig
	Registry      MigrationRegistry
	RegistryPath  string
	RegistryXPath string
}

Migration struct

func (*Migration) CreateMigrationFile

func (m *Migration) CreateMigrationFile(class string, name string) error

Create migration file

func (*Migration) Downgrade

func (m *Migration) Downgrade(class string, version string) error

Downgrade

func (*Migration) GetTemplate

func (m *Migration) GetTemplate() *template.Template

func (*Migration) InitMigration

func (m *Migration) InitMigration(class string) error

Init migration

func (*Migration) Upgrade

func (m *Migration) Upgrade(class string) error

Upgrade

type MigrationRegistry

type MigrationRegistry map[string][]IMigrationFile

Migration registry

type ModelFiledTag added in v1.11.0

type ModelFiledTag struct {
	// DB column name
	Column string `tag:"col"`
	// Foreign key definition
	ForeignKey string `tag:"frk"`
	// Has sequence
	IsSequence bool `tag:"seq"`
	// Is primary key
	IsPrimaryKey bool `tag:"prk"`
	// Is not null
	IsRequired bool `tag:"req"`
	// Is unique
	IsUnique bool `tag:"unq"`
	// Is created at column
	IsCreatedAt bool `tag:"cat"`
	// Is updated at column
	IsUpdatedAt bool `tag:"uat"`
	// Is deleted at column
	IsDeletedAt bool `tag:"dat"`
	// Is ingored column
	IsIgnored bool `tag:"ign"`
}

ModelFiledTag All possible model field tag properties tag must have 3 symbol length

func ParseModelFiledTag added in v1.11.0

func ParseModelFiledTag(tag string) (field ModelFiledTag)

ParseModelFiledTag parse validation tag for rule and arguments Example db:"col~created_at;seq;sys;prk;frk~master.table(id,name);req;unq'"

func (ModelFiledTag) String added in v1.11.0

func (t ModelFiledTag) String() string

Prepare string tag

type Options

type Options struct {
	Debug          bool
	Logger         Logger
	TransactionTTL time.Duration `yaml:"transactionTTL"`
}

Database Object Options

type PostgresConnectionConfig

type PostgresConnectionConfig struct {
	ConnectionConfig `yaml:",inline"`
	SSLMode          string `yaml:"sslMode"`
	BinaryParameters bool   `yaml:"binaryParameters"`
}

Postgres connection config

func (*PostgresConnectionConfig) GetDbType

func (pcc *PostgresConnectionConfig) GetDbType() string

Get database type

func (*PostgresConnectionConfig) String

func (pcc *PostgresConnectionConfig) String() string

To string

type QB added in v1.7.0

type QB struct {
	SubQuery bool
	// contains filtered or unexported fields
}

Query Builder struct Not Thread safety

func NewQB added in v1.7.0

func NewQB() *QB

New Query Builder

func (*QB) AddOrder added in v1.7.0

func (f *QB) AddOrder(expression ...string) *QB

Add Order

func (*QB) Columns added in v1.7.0

func (f *QB) Columns(column ...string) *QB

Add column

func (*QB) Except added in v1.9.15

func (f *QB) Except(qb *QB) *QB

Except

func (*QB) From added in v1.7.0

func (f *QB) From(table ...string) *QB

Add from

func (*QB) GetArguments added in v1.7.0

func (f *QB) GetArguments() []interface{}

Get arguments

func (*QB) GetWith added in v1.7.0

func (f *QB) GetWith(name string) *QB

Get With

func (*QB) GroupBy added in v1.7.0

func (f *QB) GroupBy(fields ...string) *QB

Add Group

func (*QB) Having added in v1.7.0

func (f *QB) Having() *Condition

Where conditions

func (*QB) Intersect added in v1.8.11

func (f *QB) Intersect(qb *QB) *QB

Intersect

func (*QB) ModelColumns added in v1.7.0

func (f *QB) ModelColumns(model ...IModel) *QB

Add column from model

func (*QB) ModelFrom added in v1.7.0

func (f *QB) ModelFrom(model ...IModel) *QB

Add from model

func (*QB) Relate added in v1.7.0

func (f *QB) Relate(relation ...string) *QB

Add join

func (*QB) ResetColumns added in v1.7.0

func (f *QB) ResetColumns() *QB

Reset column

func (*QB) ResetExcept added in v1.9.15

func (f *QB) ResetExcept() *QB

Reset Except

func (*QB) ResetFrom added in v1.7.0

func (f *QB) ResetFrom() *QB

Reset column

func (*QB) ResetGroupBy added in v1.7.0

func (f *QB) ResetGroupBy() *QB

Reset Group

func (*QB) ResetIntersect added in v1.8.11

func (f *QB) ResetIntersect() *QB

Reset Intersect

func (*QB) ResetOrder added in v1.7.0

func (f *QB) ResetOrder() *QB

Reset Order

func (*QB) ResetRelations added in v1.7.0

func (f *QB) ResetRelations() *QB

Reset join

func (*QB) ResetUnion added in v1.8.3

func (f *QB) ResetUnion() *QB

Reset Union

func (*QB) ResetWith added in v1.7.0

func (f *QB) ResetWith() *QB

Reset With

func (*QB) SetPagination added in v1.7.0

func (f *QB) SetPagination(limit int, offset int) *QB

Set pagination

func (*QB) String added in v1.7.0

func (f *QB) String() string

Make SQL query

func (*QB) Union added in v1.8.3

func (f *QB) Union(qb *QB) *QB

Union

func (*QB) Where added in v1.7.0

func (f *QB) Where() *Condition

Where conditions

func (*QB) With added in v1.7.0

func (f *QB) With(name string, qb *QB) *QB

Add With

type Queryer

type Queryer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Prepare(query string) (*SqlStmt, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(query string, args ...interface{}) *sql.Row
}

Queryer interface

type SqlStmt

type SqlStmt struct {
	*sql.Stmt
	Options
	// contains filtered or unexported fields
}

Stmt

func (*SqlStmt) Exec

func (st *SqlStmt) Exec(args ...interface{}) (sql.Result, error)

Stmt Exec

func (*SqlStmt) Query

func (st *SqlStmt) Query(args ...interface{}) (*sql.Rows, error)

Stmt Query

func (*SqlStmt) QueryRow

func (st *SqlStmt) QueryRow(args ...interface{}) *sql.Row

Stmt Query Row

type SqlTx

type SqlTx struct {
	*sql.Tx
	Options
	// contains filtered or unexported fields
}

Transaction

func (*SqlTx) Commit added in v1.8.0

func (tx *SqlTx) Commit() error

Commit

func (*SqlTx) Exec

func (tx *SqlTx) Exec(query string, args ...interface{}) (sql.Result, error)

Exec Transaction

func (*SqlTx) Prepare

func (tx *SqlTx) Prepare(query string) (*SqlStmt, error)

Prepare Stmt

func (*SqlTx) Query

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

Query Transaction

func (*SqlTx) QueryRow

func (tx *SqlTx) QueryRow(query string, args ...interface{}) *sql.Row

Query Row Transaction

func (*SqlTx) Rollback added in v1.8.0

func (tx *SqlTx) Rollback() error

Rollback

func (*SqlTx) Stmt

func (tx *SqlTx) Stmt(stmt *SqlStmt) *SqlStmt

Get Stmt

type SystemColumns added in v1.3.5

type SystemColumns struct {
	Created string
	Updated string
	Deleted string
}

type Transaction added in v1.8.0

type Transaction struct {
	// Time to live in unix timestampt
	// 0 - no TTL for transaction
	TTL int
	// contains filtered or unexported fields
}

Transaction params

type TransactionId added in v1.8.0

type TransactionId string

Transaction identifier

func GenTransactionId added in v1.8.0

func GenTransactionId() TransactionId

Generate transaction id

type TransactionPool added in v1.8.0

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

Transaction pool

func NewTransactionPool added in v1.8.2

func NewTransactionPool() *TransactionPool

Create Transaction pool

func (*TransactionPool) Count added in v1.8.2

func (p *TransactionPool) Count() int

Transaction count

func (*TransactionPool) Get added in v1.8.2

func (p *TransactionPool) Get(id TransactionId) *SqlTx

Get transaction if exists

func (*TransactionPool) Reset added in v1.8.2

func (p *TransactionPool) Reset() *TransactionPool

Reset pool

func (*TransactionPool) Set added in v1.8.2

Set transaction

func (*TransactionPool) UnSet added in v1.8.2

Unset transaction

Jump to

Keyboard shortcuts

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