session

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2026 License: BSD-3-Clause Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EngineSession sessionType = false
	GroupSession  sessionType = true
)

Variables

View Source
var (
	// ErrPtrSliceType represents a type error
	ErrPtrSliceType = errors.New("A point to a slice is needed")
	// ErrParamsType params error
	ErrParamsType = errors.New("Params type error")
	// ErrTableNotFound table not found error
	ErrTableNotFound = errors.New("Table not found")
	// ErrUnSupportedType unsupported error
	ErrUnSupportedType = errors.New("Unsupported type error")
	// ErrNotExist record does not exist error
	ErrNotExist = errors.New("Record does not exist")
	// ErrCacheFailed cache failed error
	ErrCacheFailed = errors.New("Cache failed")
	// ErrConditionType condition type unsupported
	ErrConditionType = errors.New("Unsupported condition type")
)
View Source
var ErrNeedDeletedCond = errors.New("Delete action needs at least one condition")

ErrNeedDeletedCond delete needs less one condition error

View Source
var (
	ErrNoColumnsTobeUpdated = statements.ErrNoColumnsTobeUpdated
)

enumerated all errors

View Source
var ErrNoElementsOnSlice = errors.New("no element on slice when insert")

ErrNoElementsOnSlice represents an error there is no element when insert

View Source
var (
	// ErrObjectIsNil return error of object is nil
	ErrObjectIsNil = errors.New("object should not be nil")
)

Functions

func SetDefaultJSONHandler

func SetDefaultJSONHandler(jsonHandler json.Interface)

Types

type AfterDeleteProcessor

type AfterDeleteProcessor interface {
	AfterDelete()
}

AfterDeleteProcessor executed after an object has been deleted

type AfterInsertProcessor

type AfterInsertProcessor interface {
	AfterInsert()
}

AfterInsertProcessor executed after an object is persisted to the database

type AfterLoadProcessor

type AfterLoadProcessor interface {
	AfterLoad()
}

AfterLoadProcessor executed after an ojbect has been loaded from database

type AfterLoadSessionProcessor

type AfterLoadSessionProcessor interface {
	AfterLoad(*Session)
}

AfterLoadSessionProcessor executed after an ojbect has been loaded from database with session parameter

type AfterSetProcessor

type AfterSetProcessor interface {
	AfterSet(string, Cell)
}

AfterSetProcessor executed after data set to the struct fields

type AfterUpdateProcessor

type AfterUpdateProcessor interface {
	AfterUpdate()
}

AfterUpdateProcessor executed after an object has been updated

type BeforeDeleteProcessor

type BeforeDeleteProcessor interface {
	BeforeDelete()
}

BeforeDeleteProcessor executed before an object is deleted

type BeforeInsertProcessor

type BeforeInsertProcessor interface {
	BeforeInsert()
}

BeforeInsertProcessor executed before an object is initially persisted to the database

type BeforeSetProcessor

type BeforeSetProcessor interface {
	BeforeSet(string, Cell)
}

BeforeSetProcessor executed before data set to the struct fields

type BeforeUpdateProcessor

type BeforeUpdateProcessor interface {
	BeforeUpdate()
}

BeforeUpdateProcessor executed before an object is updated

type Cell

type Cell *interface{}

Cell cell is a result of one column field

type ColumnsSchema

type ColumnsSchema struct {
	Fields     []*QueryedField
	FieldNames []string
	Types      []*sql.ColumnType
}

func ParseColumnsSchema

func ParseColumnsSchema(fieldNames []string, types []*sql.ColumnType, table *schemas.Table) *ColumnsSchema

func (*ColumnsSchema) ParseTableSchema

func (columnsSchema *ColumnsSchema) ParseTableSchema(table *schemas.Table)

type Engine

type Engine interface {
	DB() *core.DB
	Dialect() dialects.Dialect
	Driver() dialects.Driver
	TagParser() *tags.Parser
	LogSessionID() bool
	DefaultContext() context.Context
	DatabaseTZ() *time.Location
	TZLocation() *time.Location
	CacherManager() *caches.Manager
	Logger() log.ContextLogger
}

type ErrFieldIsNotExist

type ErrFieldIsNotExist struct {
	FieldName string
	TableName string
}

ErrFieldIsNotExist columns does not exist

func (ErrFieldIsNotExist) Error

func (e ErrFieldIsNotExist) Error() string

type ErrFieldIsNotValid

type ErrFieldIsNotValid struct {
	FieldName string
	TableName string
}

ErrFieldIsNotValid is not valid

func (ErrFieldIsNotValid) Error

func (e ErrFieldIsNotValid) Error() string

type IterFunc

type IterFunc func(idx int, bean interface{}) error

IterFunc only use by Iterate

type QueryedField

type QueryedField struct {
	FieldName      string
	LowerFieldName string
	ColumnType     *sql.ColumnType
	TempIndex      int
	ColumnSchema   *schemas.Column
}

type Rows

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

Rows rows wrapper a rows to

func (*Rows) Close

func (rows *Rows) Close() error

Close session if session.IsAutoClose is true, and claimed any opened resources

func (*Rows) Err

func (rows *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.

func (*Rows) Next

func (rows *Rows) Next() bool

Next move cursor to next record, return false if end has reached

func (*Rows) Scan

func (rows *Rows) Scan(beans ...interface{}) error

Scan row record to bean properties

type Session

type Session struct {
	TZLocation      *time.Location
	DatabaseTZ      *time.Location
	Dialect         dialects.Dialect
	Driver          dialects.Driver
	DriverName      string
	Logger          log.ContextLogger
	LogSessionID    bool
	TableNameMapper names.Mapper

	IsAutoClose bool

	SessionType sessionType
	// contains filtered or unexported fields
}

Session keep a pointer to sql.DB and provides all execution of all kind of database operations.

func NewSession

func NewSession(engine Engine) *Session

func (*Session) After

func (session *Session) After(closures func(interface{})) *Session

After Apply after Processor, affected bean is passed to closure arg

func (*Session) Alias

func (session *Session) Alias(alias string) *Session

Alias set the table alias

func (*Session) AllCols

func (session *Session) AllCols() *Session

AllCols ask all columns

func (*Session) And

func (session *Session) And(query interface{}, args ...interface{}) *Session

And provides custom query condition.

func (*Session) Asc

func (session *Session) Asc(colNames ...string) *Session

Asc provide asc order by query condition, the input parameters are columns.

func (*Session) Before

func (session *Session) Before(closures func(interface{})) *Session

Before Apply before Processor, affected bean is passed to closure arg

func (*Session) Begin

func (session *Session) Begin() error

Begin a transaction

func (*Session) BufferSize

func (session *Session) BufferSize(size int) *Session

BufferSize sets the buffersize for iterate

func (*Session) Cascade

func (session *Session) Cascade(trueOrFalse ...bool) *Session

Cascade indicates if loading sub Struct

func (*Session) Charset

func (session *Session) Charset(charset string) *Session

Charset is only avialble mysql dialect currently

func (*Session) Close

func (session *Session) Close() error

Close release the connection from pool

func (*Session) Cols

func (session *Session) Cols(columns ...string) *Session

Cols provides some columns to special

func (*Session) Commit

func (session *Session) Commit() error

Commit When using transaction, Commit will commit all operations.

func (*Session) Conds

func (session *Session) Conds() builder.Cond

Conds returns session query conditions except auto bean conditions

func (*Session) Context

func (session *Session) Context(ctx context.Context) *Session

Context sets the context on this session

func (*Session) ContextCache

func (session *Session) ContextCache(context contexts.ContextCache) *Session

ContextCache enable context cache or not

func (*Session) Count

func (session *Session) Count(bean ...interface{}) (int64, error)

Count counts the records. bean's non-empty fields are conditions.

func (*Session) CreateIndexes

func (session *Session) CreateIndexes(bean interface{}) error

CreateIndexes create indexes

func (*Session) CreateTable

func (session *Session) CreateTable(bean interface{}) error

CreateTable create a table according a bean

func (*Session) CreateUniques

func (session *Session) CreateUniques(bean interface{}) error

CreateUniques create uniques

func (*Session) DB

func (session *Session) DB() *core.DB

DB db return the wrapper of sql.DB

func (*Session) Decr

func (session *Session) Decr(column string, arg ...interface{}) *Session

Decr provides a query string like "count = count - 1"

func (*Session) Delete

func (session *Session) Delete(beans ...interface{}) (int64, error)

Delete records, bean's non-empty fields are conditions At least one condition must be set.

func (*Session) Desc

func (session *Session) Desc(colNames ...string) *Session

Desc provide desc order by query condition, the input parameters are columns.

func (*Session) Distinct

func (session *Session) Distinct(columns ...string) *Session

Distinct use for distinct columns. Caution: when you are using cache, distinct will not be cached because cache system need id, but distinct will not provide id

func (*Session) DropIndexes

func (session *Session) DropIndexes(bean interface{}) error

DropIndexes drop indexes

func (*Session) DropTable

func (session *Session) DropTable(beanOrTableName interface{}) error

DropTable drop table will drop table if exist, if drop failed, it will return error

func (*Session) Exec

func (session *Session) Exec(sqlOrArgs ...interface{}) (sql.Result, error)

Exec raw sql

func (*Session) Exist

func (session *Session) Exist(bean ...interface{}) (bool, error)

Exist returns true if the record exist otherwise return false

func (*Session) Find

func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error

Find retrieve records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct

func (*Session) FindAndCount

func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)

FindAndCount find the results and also return the counts

func (*Session) ForUpdate

func (session *Session) ForUpdate() *Session

ForUpdate Set Read/Write locking for UPDATE

func (*Session) Get

func (session *Session) Get(beans ...interface{}) (bool, error)

Get retrieve one record from database, bean's non-empty fields will be as conditions

func (*Session) GroupBy

func (session *Session) GroupBy(keys string) *Session

GroupBy Generate Group By statement

func (*Session) Having

func (session *Session) Having(conditions string) *Session

Having Generate Having statement

func (*Session) ID

func (session *Session) ID(id interface{}) *Session

ID provides converting id as a query condition

func (*Session) Import

func (session *Session) Import(r io.Reader) ([]sql.Result, error)

Import SQL DDL from io.Reader

func (*Session) ImportFile

func (session *Session) ImportFile(ddlPath string) ([]sql.Result, error)

ImportFile SQL DDL file

func (*Session) In

func (session *Session) In(column string, args ...interface{}) *Session

In provides a query string like "id in (1, 2, 3)"

func (*Session) Incr

func (session *Session) Incr(column string, arg ...interface{}) *Session

Incr provides a query string like "count = count + 1"

func (*Session) IndexHint

func (session *Session) IndexHint(op, forType, indexerOrColName string) *Session

func (*Session) Insert

func (session *Session) Insert(beans ...interface{}) (int64, error)

Insert insert one or more beans

func (*Session) InsertMulti

func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error)

InsertMulti insert multiple records

func (*Session) InsertOne

func (session *Session) InsertOne(bean interface{}) (int64, error)

InsertOne insert only one struct into database as a record. The in parameter bean must a struct or a point to struct. The return parameter is inserted and error Deprecated: Please use Insert directly

func (*Session) IsClosed

func (session *Session) IsClosed() bool

IsClosed returns if session is closed

func (*Session) IsInTx

func (session *Session) IsInTx() bool

IsInTx if current session is in a transaction

func (*Session) IsTableEmpty

func (session *Session) IsTableEmpty(bean interface{}) (bool, error)

IsTableEmpty if table have any records

func (*Session) IsTableExist

func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error)

IsTableExist if a table is exist

func (*Session) Iterate

func (session *Session) Iterate(bean interface{}, fun IterFunc) error

Iterate record by record handle records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct

func (*Session) Join

func (session *Session) Join(joinOperator string, tablename interface{}, condition interface{}, args ...interface{}) *Session

Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN

func (*Session) LastSQL

func (session *Session) LastSQL() (string, []interface{})

LastSQL returns last query information

func (*Session) Limit

func (session *Session) Limit(limit int, start ...int) *Session

Limit provide limit and offset query condition

func (*Session) MustCols

func (session *Session) MustCols(columns ...string) *Session

MustCols specify some columns must use even if they are empty

func (*Session) MustLogSQL

func (session *Session) MustLogSQL(logs ...bool) *Session

MustLogSQL means record SQL or not and don't follow engine's setting

func (*Session) NoAutoCondition

func (session *Session) NoAutoCondition(no ...bool) *Session

NoAutoCondition disable generate SQL condition from beans

func (*Session) NoAutoTime

func (session *Session) NoAutoTime() *Session

NoAutoTime means do not automatically give created field and updated field the current time on the current session temporarily

func (*Session) NoCache

func (session *Session) NoCache() *Session

NoCache ask this session do not retrieve data from cache system and get data from database directly.

func (*Session) NoCascade

func (session *Session) NoCascade() *Session

NoCascade indicate that no cascade load child object

func (*Session) NoVersionCheck

func (session *Session) NoVersionCheck() *Session

disable version check

func (*Session) NotIn

func (session *Session) NotIn(column string, args ...interface{}) *Session

NotIn provides a query string like "id in (1, 2, 3)"

func (*Session) Nullable

func (session *Session) Nullable(columns ...string) *Session

Nullable Set null when column is zero-value and nullable for update

func (*Session) Omit

func (session *Session) Omit(columns ...string) *Session

Omit Only not use the parameters as select or update columns

func (*Session) Or

func (session *Session) Or(query interface{}, args ...interface{}) *Session

Or provides custom query condition.

func (*Session) OrderBy

func (session *Session) OrderBy(order interface{}, args ...interface{}) *Session

OrderBy provide order by query condition, the input parameter is the content after order by on a sql statement.

func (*Session) Ping

func (session *Session) Ping() error

Ping test if database is ok

func (*Session) PingContext

func (session *Session) PingContext(ctx context.Context) error

PingContext test if database is ok

func (*Session) Prepare

func (session *Session) Prepare() *Session

Prepare set a flag to session that should be prepare statement before execute query

func (*Session) Query

func (session *Session) Query(sqlOrArgs ...interface{}) ([]map[string][]byte, error)

Query runs a raw sql and return records as []map[string][]byte

func (*Session) QueryInterface

func (session *Session) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)

QueryInterface runs a raw sql and return records as []map[string]interface{}

func (*Session) QuerySliceString

func (session *Session) QuerySliceString(sqlOrArgs ...interface{}) ([][]string, error)

QuerySliceString runs a raw sql and return records as [][]string

func (*Session) QueryString

func (session *Session) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)

QueryString runs a raw sql and return records as []map[string]string

func (*Session) Quote

func (session *Session) Quote(value string) string

Quote Use QuoteStr quote the string sql

func (*Session) QuoteTo

func (session *Session) QuoteTo(buf *strings.Builder, value string)

QuoteTo quotes string and writes into the buffer

func (*Session) Rollback

func (session *Session) Rollback() error

Rollback When using transaction, you can rollback if any error

func (*Session) Rows

func (session *Session) Rows(bean interface{}) (*Rows, error)

Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields are conditions.

func (*Session) SQL

func (session *Session) SQL(query interface{}, args ...interface{}) *Session

SQL provides raw sql input parameter. When you have a complex SQL statement and cannot use Where, Id, In and etc. Methods to describe, you can use SQL.

func (*Session) ScanInterfaceMap

func (session *Session) ScanInterfaceMap(rows *core.Rows) (map[string]interface{}, error)

ScanInterfaceMap scan result from *core.Rows and return a map

func (*Session) ScanInterfaceMaps

func (session *Session) ScanInterfaceMaps(rows *core.Rows) (resultsSlice []map[string]interface{}, err error)

ScanInterfaceMaps scan results from *core.Rows and return a slice of map

func (*Session) ScanStringMap

func (session *Session) ScanStringMap(rows *core.Rows) (map[string]string, error)

ScanStringMap scan results from *core.Rows and return a map

func (*Session) ScanStringMaps

func (session *Session) ScanStringMaps(rows *core.Rows) (resultsSlice []map[string]string, err error)

ScanStringMaps scan results from *core.Rows and return a slice of map

func (*Session) ScanStringSlice

func (session *Session) ScanStringSlice(rows *core.Rows) ([]string, error)

ScanStringSlice scan results from *core.Rows and return a slice of one row

func (*Session) ScanStringSlices

func (session *Session) ScanStringSlices(rows *core.Rows) (resultsSlice [][]string, err error)

ScanStringSlices scan results from *core.Rows and return a slice of all rows

func (*Session) Select

func (session *Session) Select(str string) *Session

Select provides some columns to special

func (*Session) SetExpr

func (session *Session) SetExpr(column string, expression interface{}) *Session

SetExpr provides a query string like "column = {expression}"

func (*Session) StoreEngine

func (session *Session) StoreEngine(storeEngine string) *Session

StoreEngine is only avialble mysql dialect currently

func (*Session) Sum

func (session *Session) Sum(bean interface{}, columnName string) (res float64, err error)

Sum call sum some column. bean's non-empty fields are conditions.

func (*Session) SumInt

func (session *Session) SumInt(bean interface{}, columnName string) (res int64, err error)

SumInt call sum some column. bean's non-empty fields are conditions.

func (*Session) Sums

func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error)

Sums call sum some columns. bean's non-empty fields are conditions.

func (*Session) SumsInt

func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error)

SumsInt sum specify columns and return as []int64 instead of []float64

func (*Session) Table

func (session *Session) Table(tableNameOrBean interface{}) *Session

Table can input a string or pointer to struct for special a table to operate.

func (*Session) TableInfo

func (session *Session) TableInfo(bean interface{}) (*schemas.Table, error)

TableInfo get table info according to bean's content

func (*Session) TableName

func (session *Session) TableName(bean interface{}, includeSchema ...bool) string

TableName returns table name with schema prefix if has

func (*Session) Truncate

func (session *Session) Truncate(beans ...interface{}) (int64, error)

Truncate records, bean's non-empty fields are conditions In contrast to Delete this method allows deletes without conditions.

func (*Session) Tx

func (session *Session) Tx() *core.Tx

Tx returns session tx

func (*Session) Unscoped

func (session *Session) Unscoped() *Session

Unscoped always disable struct tag "deleted"

func (*Session) Update

func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error)

Update records, bean's non-empty fields are updated contents, condiBean' non-empty filds are conditions CAUTION:

1.bool will defaultly be updated content nor conditions
 You should call UseBool if you have bool to use.
2.float32 & float64 may be not inexact as conditions

func (*Session) UseBool

func (session *Session) UseBool(columns ...string) *Session

UseBool automatically retrieve condition according struct, but if struct has bool field, it will ignore them. So use UseBool to tell system to do not ignore them. If no parameters, it will use all the bool field of struct, or it will use parameters's columns

func (*Session) Where

func (session *Session) Where(query interface{}, args ...interface{}) *Session

Where provides custom query condition.

Source Files

  • error.go
  • processors.go
  • rows.go
  • scan.go
  • session.go
  • session_cols.go
  • session_cond.go
  • session_delete.go
  • session_exist.go
  • session_find.go
  • session_get.go
  • session_insert.go
  • session_iterate.go
  • session_raw.go
  • session_schema.go
  • session_stats.go
  • session_tx.go
  • session_update.go

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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