xorm: github.com/go-xorm/xorm Index | Files | Directories

package xorm

import "github.com/go-xorm/xorm"

Package xorm is a simple and powerful ORM for Go.

Installation

Make sure you have installed Go 1.6+ and then:

go get github.com/go-xorm/xorm

Create Engine

Firstly, we should new an engine for a database

engine, err := xorm.NewEngine(driverName, dataSourceName)

Method NewEngine's parameters is the same as sql.Open. It depends drivers' implementation. Generally, one engine for an application is enough. You can set it as package variable.

Raw Methods

XORM also support raw SQL execution:

1. query a SQL string, the returned results is []map[string][]byte

results, err := engine.Query("select * from user")

2. execute a SQL string, the returned results

affected, err := engine.Exec("update user set .... where ...")

ORM Methods

There are 8 major ORM methods and many helpful methods to use to operate database.

1. Insert one or multiple records to database

affected, err := engine.Insert(&struct)
// INSERT INTO struct () values ()
affected, err := engine.Insert(&struct1, &struct2)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values ()
affected, err := engine.Insert(&sliceOfStruct)
// INSERT INTO struct () values (),(),()
affected, err := engine.Insert(&struct1, &sliceOfStruct2)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values (),(),()

2. Query one record or one variable from database

has, err := engine.Get(&user)
// SELECT * FROM user LIMIT 1

var id int64
has, err := engine.Table("user").Where("name = ?", name).Get(&id)
// SELECT id FROM user WHERE name = ? LIMIT 1

3. Query multiple records from database

var sliceOfStructs []Struct
err := engine.Find(&sliceOfStructs)
// SELECT * FROM user

var mapOfStructs = make(map[int64]Struct)
err := engine.Find(&mapOfStructs)
// SELECT * FROM user

var int64s []int64
err := engine.Table("user").Cols("id").Find(&int64s)
// SELECT id FROM user

4. Query multiple records and record by record handle, there two methods, one is Iterate, another is Rows

err := engine.Iterate(...)
// SELECT * FROM user

rows, err := engine.Rows(...)
// SELECT * FROM user
defer rows.Close()
bean := new(Struct)
for rows.Next() {
    err = rows.Scan(bean)
}

5. Update one or more records

affected, err := engine.ID(...).Update(&user)
// UPDATE user SET ...

6. Delete one or more records, Delete MUST has condition

affected, err := engine.Where(...).Delete(&user)
// DELETE FROM user Where ...

7. Count records

counts, err := engine.Count(&user)
// SELECT count(*) AS total FROM user

counts, err := engine.SQL("select count(*) FROM user").Count()
// select count(*) FROM user

8. Sum records

sumFloat64, err := engine.Sum(&user, "id")
// SELECT sum(id) from user

sumFloat64s, err := engine.Sums(&user, "id1", "id2")
// SELECT sum(id1), sum(id2) from user

sumInt64s, err := engine.SumsInt(&user, "id1", "id2")
// SELECT sum(id1), sum(id2) from user

Conditions

The above 8 methods could use with condition methods chainable. Attention: the above 8 methods should be the last chainable method.

1. ID, In

engine.ID(1).Get(&user) // for single primary key
// SELECT * FROM user WHERE id = 1
engine.ID(core.PK{1, 2}).Get(&user) // for composite primary keys
// SELECT * FROM user WHERE id1 = 1 AND id2 = 2
engine.In("id", 1, 2, 3).Find(&users)
// SELECT * FROM user WHERE id IN (1, 2, 3)
engine.In("id", []int{1, 2, 3}).Find(&users)
// SELECT * FROM user WHERE id IN (1, 2, 3)

2. Where, And, Or

engine.Where().And().Or().Find()
// SELECT * FROM user WHERE (.. AND ..) OR ...

3. OrderBy, Asc, Desc

engine.Asc().Desc().Find()
// SELECT * FROM user ORDER BY .. ASC, .. DESC
engine.OrderBy().Find()
// SELECT * FROM user ORDER BY ..

4. Limit, Top

engine.Limit().Find()
// SELECT * FROM user LIMIT .. OFFSET ..
engine.Top(5).Find()
// SELECT TOP 5 * FROM user // for mssql
// SELECT * FROM user LIMIT .. OFFSET 0 //for other databases

5. SQL, let you custom SQL

var users []User
engine.SQL("select * from user").Find(&users)

6. Cols, Omit, Distinct

var users []*User
engine.Cols("col1, col2").Find(&users)
// SELECT col1, col2 FROM user
engine.Cols("col1", "col2").Where().Update(user)
// UPDATE user set col1 = ?, col2 = ? Where ...
engine.Omit("col1").Find(&users)
// SELECT col2, col3 FROM user
engine.Omit("col1").Insert(&user)
// INSERT INTO table (non-col1) VALUES ()
engine.Distinct("col1").Find(&users)
// SELECT DISTINCT col1 FROM user

7. Join, GroupBy, Having

engine.GroupBy("name").Having("name='xlw'").Find(&users)
//SELECT * FROM user GROUP BY name HAVING name='xlw'
engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find(&users)
//SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id

More usage, please visit http://xorm.io/docs

Index

Package Files

cache_lru.go cache_memory_store.go context.go convert.go dialect_mssql.go dialect_mysql.go dialect_oracle.go dialect_postgres.go dialect_sqlite3.go doc.go engine.go engine_cond.go engine_group.go engine_group_policy.go engine_maxlife.go error.go helpers.go helpler_time.go interface.go logger.go processors.go rows.go session.go session_cols.go session_cond.go session_convert.go session_delete.go session_exist.go session_find.go session_get.go session_insert.go session_iterate.go session_query.go session_raw.go session_schema.go session_stats.go session_tx.go session_update.go statement.go syslogger.go tag.go types.go xorm.go

Constants

const (
    DEFAULT_LOG_PREFIX = "[xorm]"
    DEFAULT_LOG_FLAG   = log.Ldate | log.Lmicroseconds
    DEFAULT_LOG_LEVEL  = core.LOG_DEBUG
)

default log options

const (
    // Version show the xorm's version
    Version string = "0.6.4.0910"
)

Variables

var (
    // ErrParamsType params error
    ErrParamsType = errors.New("Params type error")
    // ErrTableNotFound table not found error
    ErrTableNotFound = errors.New("Not found table")
    // ErrUnSupportedType unsupported error
    ErrUnSupportedType = errors.New("Unsupported type error")
    // ErrNotExist record is not exist error
    ErrNotExist = errors.New("Not exist error")
    // ErrCacheFailed cache failed error
    ErrCacheFailed = errors.New("Cache failed")
    // ErrNeedDeletedCond delete needs less one condition error
    ErrNeedDeletedCond = errors.New("Delete need at least one condition")
    // ErrNotImplemented not implemented
    ErrNotImplemented = errors.New("Not implemented")
    // ErrConditionType condition type unsupported
    ErrConditionType = errors.New("Unsupported conditon type")
)

func AutoIncrTagHandler Uses

func AutoIncrTagHandler(ctx *tagContext) error

AutoIncrTagHandler describes autoincr tag handler

func CacheTagHandler Uses

func CacheTagHandler(ctx *tagContext) error

CacheTagHandler describes cache tag handler

func CommentTagHandler Uses

func CommentTagHandler(ctx *tagContext) error

CommentTagHandler add comment to column

func CreatedTagHandler Uses

func CreatedTagHandler(ctx *tagContext) error

CreatedTagHandler describes created tag handler

func DefaultTagHandler Uses

func DefaultTagHandler(ctx *tagContext) error

DefaultTagHandler describes default tag handler

func DeletedTagHandler Uses

func DeletedTagHandler(ctx *tagContext) error

DeletedTagHandler describes deleted tag handler

func ExtendsTagHandler Uses

func ExtendsTagHandler(ctx *tagContext) error

ExtendsTagHandler describes extends tag handler

func IgnoreTagHandler Uses

func IgnoreTagHandler(ctx *tagContext) error

IgnoreTagHandler describes ignored tag handler

func IndexTagHandler Uses

func IndexTagHandler(ctx *tagContext) error

IndexTagHandler describes index tag handler

func LocalTagHandler Uses

func LocalTagHandler(ctx *tagContext) error

LocalTagHandler describes local tag handler

func NULLTagHandler Uses

func NULLTagHandler(ctx *tagContext) error

NULLTagHandler describes null tag handler

func NoCacheTagHandler Uses

func NoCacheTagHandler(ctx *tagContext) error

NoCacheTagHandler describes nocache tag handler

func NotNullTagHandler Uses

func NotNullTagHandler(ctx *tagContext) error

NotNullTagHandler describes notnull tag handler

func OnlyFromDBTagHandler Uses

func OnlyFromDBTagHandler(ctx *tagContext) error

OnlyFromDBTagHandler describes mapping direction tag handler

func OnlyToDBTagHandler Uses

func OnlyToDBTagHandler(ctx *tagContext) error

OnlyToDBTagHandler describes mapping direction tag handler

func PKTagHandler Uses

func PKTagHandler(ctx *tagContext) error

PKTagHandler decribes primary key tag handler

func SQLTypeTagHandler Uses

func SQLTypeTagHandler(ctx *tagContext) error

SQLTypeTagHandler describes SQL Type tag handler

func UTCTagHandler Uses

func UTCTagHandler(ctx *tagContext) error

UTCTagHandler describes utc tag handler

func UniqueTagHandler Uses

func UniqueTagHandler(ctx *tagContext) error

UniqueTagHandler describes unique tag handler

func UpdatedTagHandler Uses

func UpdatedTagHandler(ctx *tagContext) error

UpdatedTagHandler describes updated tag handler

func VersionTagHandler Uses

func VersionTagHandler(ctx *tagContext) error

VersionTagHandler describes version tag handler

type AfterDeleteProcessor Uses

type AfterDeleteProcessor interface {
    AfterDelete()
}

AfterDeleteProcessor executed after an object has been deleted

type AfterInsertProcessor Uses

type AfterInsertProcessor interface {
    AfterInsert()
}

AfterInsertProcessor executed after an object is persisted to the database

type AfterLoadProcessor Uses

type AfterLoadProcessor interface {
    AfterLoad()
}

AfterLoadProcessor executed after an ojbect has been loaded from database

type AfterLoadSessionProcessor Uses

type AfterLoadSessionProcessor interface {
    AfterLoad(*Session)
}

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

type AfterSetProcessor Uses

type AfterSetProcessor interface {
    AfterSet(string, Cell)
}

AfterSetProcessor executed after data set to the struct fields

type AfterUpdateProcessor Uses

type AfterUpdateProcessor interface {
    AfterUpdate()
}

AfterUpdateProcessor executed after an object has been updated

type BeforeDeleteProcessor Uses

type BeforeDeleteProcessor interface {
    BeforeDelete()
}

BeforeDeleteProcessor executed before an object is deleted

type BeforeInsertProcessor Uses

type BeforeInsertProcessor interface {
    BeforeInsert()
}

BeforeInsertProcessor executed before an object is initially persisted to the database

type BeforeSetProcessor Uses

type BeforeSetProcessor interface {
    BeforeSet(string, Cell)
}

BeforeSetProcessor executed before data set to the struct fields

type BeforeUpdateProcessor Uses

type BeforeUpdateProcessor interface {
    BeforeUpdate()
}

BeforeUpdateProcessor executed before an object is updated

type Cell Uses

type Cell *interface{}

Cell cell is a result of one column field

type DiscardLogger Uses

type DiscardLogger struct{}

DiscardLogger don't log implementation for core.ILogger

func (DiscardLogger) Debug Uses

func (DiscardLogger) Debug(v ...interface{})

Debug empty implementation

func (DiscardLogger) Debugf Uses

func (DiscardLogger) Debugf(format string, v ...interface{})

Debugf empty implementation

func (DiscardLogger) Error Uses

func (DiscardLogger) Error(v ...interface{})

Error empty implementation

func (DiscardLogger) Errorf Uses

func (DiscardLogger) Errorf(format string, v ...interface{})

Errorf empty implementation

func (DiscardLogger) Info Uses

func (DiscardLogger) Info(v ...interface{})

Info empty implementation

func (DiscardLogger) Infof Uses

func (DiscardLogger) Infof(format string, v ...interface{})

Infof empty implementation

func (DiscardLogger) IsShowSQL Uses

func (DiscardLogger) IsShowSQL() bool

IsShowSQL empty implementation

func (DiscardLogger) Level Uses

func (DiscardLogger) Level() core.LogLevel

Level empty implementation

func (DiscardLogger) SetLevel Uses

func (DiscardLogger) SetLevel(l core.LogLevel)

SetLevel empty implementation

func (DiscardLogger) ShowSQL Uses

func (DiscardLogger) ShowSQL(show ...bool)

ShowSQL empty implementation

func (DiscardLogger) Warn Uses

func (DiscardLogger) Warn(v ...interface{})

Warn empty implementation

func (DiscardLogger) Warnf Uses

func (DiscardLogger) Warnf(format string, v ...interface{})

Warnf empty implementation

type Engine Uses

type Engine struct {
    ColumnMapper  core.IMapper
    TableMapper   core.IMapper
    TagIdentifier string
    Tables        map[reflect.Type]*core.Table

    Cacher core.Cacher

    TZLocation *time.Location // The timezone of the application
    DatabaseTZ *time.Location // The timezone of the database
    // contains filtered or unexported fields
}

Engine is the major struct of xorm, it means a database manager. Commonly, an application only need one engine

func NewEngine Uses

func NewEngine(driverName string, dataSourceName string) (*Engine, error)

NewEngine new a db manager according to the parameter. Currently support four drivers

func (*Engine) After Uses

func (engine *Engine) After(closures func(interface{})) *Session

After apply after insert Processor, affected bean is passed to closure arg

func (*Engine) Alias Uses

func (engine *Engine) Alias(alias string) *Session

Alias set the table alias

func (*Engine) AllCols Uses

func (engine *Engine) AllCols() *Session

AllCols indicates that all columns should be use

func (*Engine) Asc Uses

func (engine *Engine) Asc(colNames ...string) *Session

Asc will generate "ORDER BY column1,column2 Asc" This method can chainable use.

engine.Desc("name").Asc("age").Find(&users)
// SELECT * FROM user ORDER BY name DESC, age ASC

func (*Engine) AutoIncrStr Uses

func (engine *Engine) AutoIncrStr() string

AutoIncrStr Database's autoincrement statement

func (*Engine) Before Uses

func (engine *Engine) Before(closures func(interface{})) *Session

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

func (*Engine) BufferSize Uses

func (engine *Engine) BufferSize(size int) *Session

BufferSize sets buffer size for iterate

func (*Engine) Cascade Uses

func (engine *Engine) Cascade(trueOrFalse ...bool) *Session

Cascade use cascade or not

func (*Engine) Charset Uses

func (engine *Engine) Charset(charset string) *Session

Charset set charset when create table, only support mysql now

func (*Engine) ClearCache Uses

func (engine *Engine) ClearCache(beans ...interface{}) error

ClearCache if enabled cache, clear some tables' cache

func (*Engine) ClearCacheBean Uses

func (engine *Engine) ClearCacheBean(bean interface{}, id string) error

ClearCacheBean if enabled cache, clear the cache bean

func (*Engine) Clone Uses

func (engine *Engine) Clone() (*Engine, error)

Clone clone an engine

func (*Engine) Close Uses

func (engine *Engine) Close() error

Close the engine

func (*Engine) Cols Uses

func (engine *Engine) Cols(columns ...string) *Session

Cols only use the parameters as select or update columns

func (*Engine) CondDeleted Uses

func (engine *Engine) CondDeleted(colName string) builder.Cond

CondDeleted returns the conditions whether a record is soft deleted.

func (*Engine) Count Uses

func (engine *Engine) Count(bean ...interface{}) (int64, error)

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

func (*Engine) CreateIndexes Uses

func (engine *Engine) CreateIndexes(bean interface{}) error

CreateIndexes create indexes

func (*Engine) CreateTables Uses

func (engine *Engine) CreateTables(beans ...interface{}) error

CreateTables create tabls according bean

func (*Engine) CreateUniques Uses

func (engine *Engine) CreateUniques(bean interface{}) error

CreateUniques create uniques

func (*Engine) DB Uses

func (engine *Engine) DB() *core.DB

DB return the wrapper of sql.DB

func (*Engine) DBMetas Uses

func (engine *Engine) DBMetas() ([]*core.Table, error)

DBMetas Retrieve all tables, columns, indexes' informations from database.

func (*Engine) DataSourceName Uses

func (engine *Engine) DataSourceName() string

DataSourceName return the current connection string

func (*Engine) Decr Uses

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

Decr provides a update string like "column = column - ?"

func (*Engine) Delete Uses

func (engine *Engine) Delete(bean interface{}) (int64, error)

Delete records, bean's non-empty fields are conditions

func (*Engine) Desc Uses

func (engine *Engine) Desc(colNames ...string) *Session

Desc will generate "ORDER BY column1 DESC, column2 DESC"

func (*Engine) Dialect Uses

func (engine *Engine) Dialect() core.Dialect

Dialect return database dialect

func (*Engine) Distinct Uses

func (engine *Engine) 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 (*Engine) DriverName Uses

func (engine *Engine) DriverName() string

DriverName return the current sql driver's name

func (*Engine) DropIndexes Uses

func (engine *Engine) DropIndexes(bean interface{}) error

DropIndexes drop indexes of a table

func (*Engine) DropTables Uses

func (engine *Engine) DropTables(beans ...interface{}) error

DropTables drop specify tables

func (*Engine) DumpAll Uses

func (engine *Engine) DumpAll(w io.Writer, tp ...core.DbType) error

DumpAll dump database all table structs and data to w

func (*Engine) DumpAllToFile Uses

func (engine *Engine) DumpAllToFile(fp string, tp ...core.DbType) error

DumpAllToFile dump database all table structs and data to a file

func (*Engine) DumpTables Uses

func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error

DumpTables dump specify tables to io.Writer

func (*Engine) DumpTablesToFile Uses

func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error

DumpTablesToFile dump specified tables to SQL file.

func (*Engine) Exec Uses

func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error)

Exec raw sql

func (*Engine) Exist Uses

func (engine *Engine) Exist(bean ...interface{}) (bool, error)

Exist returns true if the record exist otherwise return false

func (*Engine) Find Uses

func (engine *Engine) Find(beans interface{}, condiBeans ...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 (*Engine) Get Uses

func (engine *Engine) Get(bean interface{}) (bool, error)

Get retrieve one record from table, bean's non-empty fields are conditions

func (*Engine) GetColumnMapper Uses

func (engine *Engine) GetColumnMapper() core.IMapper

GetColumnMapper returns the column name mapper

func (*Engine) GetDefaultCacher Uses

func (engine *Engine) GetDefaultCacher() core.Cacher

GetDefaultCacher returns the default cacher

func (*Engine) GetTZDatabase Uses

func (engine *Engine) GetTZDatabase() *time.Location

GetTZDatabase returns time zone of the database

func (*Engine) GetTZLocation Uses

func (engine *Engine) GetTZLocation() *time.Location

GetTZLocation returns time zone of the application

func (*Engine) GetTableMapper Uses

func (engine *Engine) GetTableMapper() core.IMapper

GetTableMapper returns the table name mapper

func (*Engine) GobRegister Uses

func (engine *Engine) GobRegister(v interface{}) *Engine

GobRegister register one struct to gob for cache use

func (*Engine) GroupBy Uses

func (engine *Engine) GroupBy(keys string) *Session

GroupBy generate group by statement

func (*Engine) Having Uses

func (engine *Engine) Having(conditions string) *Session

Having generate having statement

func (*Engine) ID Uses

func (engine *Engine) ID(id interface{}) *Session

ID method provoide a condition as (id) = ?

func (*Engine) IDOf Uses

func (engine *Engine) IDOf(bean interface{}) core.PK

IDOf get id from one struct

func (*Engine) IDOfV Uses

func (engine *Engine) IDOfV(rv reflect.Value) core.PK

IDOfV get id from one value of struct

func (*Engine) Id Uses

func (engine *Engine) Id(id interface{}) *Session

Id will be deprecated, please use ID instead

func (*Engine) IdOf Uses

func (engine *Engine) IdOf(bean interface{}) core.PK

IdOf get id from one struct

Deprecated: use IDOf instead.

func (*Engine) IdOfV Uses

func (engine *Engine) IdOfV(rv reflect.Value) core.PK

IdOfV get id from one value of struct

Deprecated: use IDOfV instead.

func (*Engine) Import Uses

func (engine *Engine) Import(r io.Reader) ([]sql.Result, error)

Import SQL DDL from io.Reader

func (*Engine) ImportFile Uses

func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error)

ImportFile SQL DDL file

func (*Engine) In Uses

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

In will generate "column IN (?, ?)"

func (*Engine) Incr Uses

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

Incr provides a update string like "column = column + ?"

func (*Engine) Insert Uses

func (engine *Engine) Insert(beans ...interface{}) (int64, error)

Insert one or more records

func (*Engine) InsertOne Uses

func (engine *Engine) InsertOne(bean interface{}) (int64, error)

InsertOne insert only one record

func (*Engine) IsTableEmpty Uses

func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error)

IsTableEmpty if a table has any reocrd

func (*Engine) IsTableExist Uses

func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error)

IsTableExist if a table is exist

func (*Engine) Iterate Uses

func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error

Iterate record by record handle records from table, bean's non-empty fields are conditions.

func (*Engine) Join Uses

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

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

func (*Engine) Limit Uses

func (engine *Engine) Limit(limit int, start ...int) *Session

Limit will generate "LIMIT start, limit"

func (*Engine) Logger Uses

func (engine *Engine) Logger() core.ILogger

Logger return the logger interface

func (*Engine) MapCacher Uses

func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) error

MapCacher Set a table use a special cacher

func (*Engine) MustCols Uses

func (engine *Engine) MustCols(columns ...string) *Session

MustCols specify some columns must use even if they are empty

func (*Engine) NewDB Uses

func (engine *Engine) NewDB() (*core.DB, error)

NewDB provides an interface to operate database directly

func (*Engine) NewSession Uses

func (engine *Engine) NewSession() *Session

NewSession New a session

func (*Engine) NoAutoCondition Uses

func (engine *Engine) NoAutoCondition(no ...bool) *Session

NoAutoCondition disable auto generate Where condition from bean or not

func (*Engine) NoAutoTime Uses

func (engine *Engine) NoAutoTime() *Session

NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields will automatically be filled with current time when Insert or Update invoked. Call NoAutoTime if you dont' want to fill automatically.

func (*Engine) NoCache Uses

func (engine *Engine) NoCache() *Session

NoCache If you has set default cacher, and you want temporilly stop use cache, you can use NoCache()

func (*Engine) NoCascade Uses

func (engine *Engine) NoCascade() *Session

NoCascade If you do not want to auto cascade load object

func (*Engine) NotIn Uses

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

NotIn will generate "column NOT IN (?, ?)"

func (*Engine) Nullable Uses

func (engine *Engine) Nullable(columns ...string) *Session

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

func (*Engine) Omit Uses

func (engine *Engine) Omit(columns ...string) *Session

Omit only not use the parameters as select or update columns

func (*Engine) OrderBy Uses

func (engine *Engine) OrderBy(order string) *Session

OrderBy will generate "ORDER BY order"

func (*Engine) Ping Uses

func (engine *Engine) Ping() error

Ping tests if database is alive

func (*Engine) PingContext Uses

func (engine *Engine) PingContext(ctx context.Context) error

PingContext tests if database is alive

func (*Engine) Prepare Uses

func (engine *Engine) Prepare() *Session

Prepare enables prepare statement

func (*Engine) Query Uses

func (engine *Engine) Query(sqlorArgs ...interface{}) (resultsSlice []map[string][]byte, err error)

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

func (*Engine) QueryInterface Uses

func (engine *Engine) QueryInterface(sqlorArgs ...interface{}) ([]map[string]interface{}, error)

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

func (*Engine) QueryString Uses

func (engine *Engine) QueryString(sqlorArgs ...interface{}) ([]map[string]string, error)

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

func (*Engine) Quote Uses

func (engine *Engine) Quote(value string) string

Quote Use QuoteStr quote the string sql

func (*Engine) QuoteStr Uses

func (engine *Engine) QuoteStr() string

QuoteStr Engine's database use which character as quote. mysql, sqlite use ` and postgres use "

func (*Engine) QuoteTo Uses

func (engine *Engine) QuoteTo(buf *bytes.Buffer, value string)

QuoteTo quotes string and writes into the buffer

func (*Engine) Rows Uses

func (engine *Engine) 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 (*Engine) SQL Uses

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

SQL method let's you manually write raw SQL and operate For example:

engine.SQL("select * from user").Find(&users)

This code will execute "select * from user" and set the records to users

func (*Engine) SQLType Uses

func (engine *Engine) SQLType(c *core.Column) string

SQLType A simple wrapper to dialect's core.SqlType method

func (*Engine) Select Uses

func (engine *Engine) Select(str string) *Session

Select customerize your select columns or contents

func (*Engine) SetColumnMapper Uses

func (engine *Engine) SetColumnMapper(mapper core.IMapper)

SetColumnMapper set the column name mapping rule

func (*Engine) SetConnMaxLifetime Uses

func (engine *Engine) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

func (*Engine) SetDefaultCacher Uses

func (engine *Engine) SetDefaultCacher(cacher core.Cacher)

SetDefaultCacher set the default cacher. Xorm's default not enable cacher.

func (*Engine) SetDisableGlobalCache Uses

func (engine *Engine) SetDisableGlobalCache(disable bool)

SetDisableGlobalCache disable global cache or not

func (*Engine) SetExpr Uses

func (engine *Engine) SetExpr(column string, expression string) *Session

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

func (*Engine) SetLogLevel Uses

func (engine *Engine) SetLogLevel(level core.LogLevel)

SetLogLevel sets the logger level

func (*Engine) SetLogger Uses

func (engine *Engine) SetLogger(logger core.ILogger)

SetLogger set the new logger

func (*Engine) SetMapper Uses

func (engine *Engine) SetMapper(mapper core.IMapper)

SetMapper set the name mapping rules

func (*Engine) SetMaxIdleConns Uses

func (engine *Engine) SetMaxIdleConns(conns int)

SetMaxIdleConns set the max idle connections on pool, default is 2

func (*Engine) SetMaxOpenConns Uses

func (engine *Engine) SetMaxOpenConns(conns int)

SetMaxOpenConns is only available for go 1.2+

func (*Engine) SetTZDatabase Uses

func (engine *Engine) SetTZDatabase(tz *time.Location)

SetTZDatabase sets time zone of the database

func (*Engine) SetTZLocation Uses

func (engine *Engine) SetTZLocation(tz *time.Location)

SetTZLocation sets time zone of the application

func (*Engine) SetTableMapper Uses

func (engine *Engine) SetTableMapper(mapper core.IMapper)

SetTableMapper set the table name mapping rule

func (*Engine) ShowExecTime Uses

func (engine *Engine) ShowExecTime(show ...bool)

ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO

func (*Engine) ShowSQL Uses

func (engine *Engine) ShowSQL(show ...bool)

ShowSQL show SQL statement or not on logger if log level is great than INFO

func (*Engine) Sql Uses

func (engine *Engine) Sql(querystring string, 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.

Deprecated: use SQL instead.

func (*Engine) SqlType Uses

func (engine *Engine) SqlType(c *core.Column) string

SqlType will be deprecated, please use SQLType instead

Deprecated: use SQLType instead

func (*Engine) StoreEngine Uses

func (engine *Engine) StoreEngine(storeEngine string) *Session

StoreEngine set store engine when create table, only support mysql now

func (*Engine) Sum Uses

func (engine *Engine) Sum(bean interface{}, colName string) (float64, error)

Sum sum the records by some column. bean's non-empty fields are conditions.

func (*Engine) SumInt Uses

func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error)

SumInt sum the records by some column. bean's non-empty fields are conditions.

func (*Engine) Sums Uses

func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error)

Sums sum the records by some columns. bean's non-empty fields are conditions.

func (*Engine) SumsInt Uses

func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error)

SumsInt like Sums but return slice of int64 instead of float64.

func (*Engine) SupportInsertMany Uses

func (engine *Engine) SupportInsertMany() bool

SupportInsertMany If engine's database support batch insert records like "insert into user values (name, age), (name, age)". When the return is ture, then engine.Insert(&users) will generate batch sql and exeute.

func (*Engine) Sync Uses

func (engine *Engine) Sync(beans ...interface{}) error

Sync the new struct changes to database, this method will automatically add table, column, index, unique. but will not delete or change anything. If you change some field, you should change the database manually.

func (*Engine) Sync2 Uses

func (engine *Engine) Sync2(beans ...interface{}) error

Sync2 synchronize structs to database tables

func (*Engine) Table Uses

func (engine *Engine) Table(tableNameOrBean interface{}) *Session

Table temporarily change the Get, Find, Update's table

func (*Engine) TableInfo Uses

func (engine *Engine) TableInfo(bean interface{}) *Table

TableInfo get table info according to bean's content

func (*Engine) UnMapType Uses

func (engine *Engine) UnMapType(t reflect.Type)

UnMapType removes the datbase mapper of a type

func (*Engine) Unscoped Uses

func (engine *Engine) Unscoped() *Session

Unscoped always disable struct tag "deleted"

func (*Engine) Update Uses

func (engine *Engine) Update(bean interface{}, condiBeans ...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 (*Engine) UseBool Uses

func (engine *Engine) UseBool(columns ...string) *Session

UseBool xorm 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 (*Engine) Where Uses

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

Where method provide a condition query

type EngineGroup Uses

type EngineGroup struct {
    *Engine
    // contains filtered or unexported fields
}

EngineGroup defines an engine group

func NewEngineGroup Uses

func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error)

NewEngineGroup creates a new engine group

func (*EngineGroup) Close Uses

func (eg *EngineGroup) Close() error

Close the engine

func (*EngineGroup) Master Uses

func (eg *EngineGroup) Master() *Engine

Master returns the master engine

func (*EngineGroup) Ping Uses

func (eg *EngineGroup) Ping() error

Ping tests if database is alive

func (*EngineGroup) SetColumnMapper Uses

func (eg *EngineGroup) SetColumnMapper(mapper core.IMapper)

SetColumnMapper set the column name mapping rule

func (*EngineGroup) SetConnMaxLifetime Uses

func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration)

SetConnMaxLifetime sets the maximum amount of time a connection may be reused.

func (*EngineGroup) SetDefaultCacher Uses

func (eg *EngineGroup) SetDefaultCacher(cacher core.Cacher)

SetDefaultCacher set the default cacher

func (*EngineGroup) SetLogLevel Uses

func (eg *EngineGroup) SetLogLevel(level core.LogLevel)

SetLogLevel sets the logger level

func (*EngineGroup) SetLogger Uses

func (eg *EngineGroup) SetLogger(logger core.ILogger)

SetLogger set the new logger

func (*EngineGroup) SetMapper Uses

func (eg *EngineGroup) SetMapper(mapper core.IMapper)

SetMapper set the name mapping rules

func (*EngineGroup) SetMaxIdleConns Uses

func (eg *EngineGroup) SetMaxIdleConns(conns int)

SetMaxIdleConns set the max idle connections on pool, default is 2

func (*EngineGroup) SetMaxOpenConns Uses

func (eg *EngineGroup) SetMaxOpenConns(conns int)

SetMaxOpenConns is only available for go 1.2+

func (*EngineGroup) SetPolicy Uses

func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup

SetPolicy set the group policy

func (*EngineGroup) SetTableMapper Uses

func (eg *EngineGroup) SetTableMapper(mapper core.IMapper)

SetTableMapper set the table name mapping rule

func (*EngineGroup) ShowExecTime Uses

func (eg *EngineGroup) ShowExecTime(show ...bool)

ShowExecTime show SQL statement and execute time or not on logger if log level is great than INFO

func (*EngineGroup) ShowSQL Uses

func (eg *EngineGroup) ShowSQL(show ...bool)

ShowSQL show SQL statement or not on logger if log level is great than INFO

func (*EngineGroup) Slave Uses

func (eg *EngineGroup) Slave() *Engine

Slave returns one of the physical databases which is a slave according the policy

func (*EngineGroup) Slaves Uses

func (eg *EngineGroup) Slaves() []*Engine

Slaves returns all the slaves

type EngineInterface Uses

type EngineInterface interface {
    Interface

    Before(func(interface{})) *Session
    Charset(charset string) *Session
    CreateTables(...interface{}) error
    DBMetas() ([]*core.Table, error)
    Dialect() core.Dialect
    DropTables(...interface{}) error
    DumpAllToFile(fp string, tp ...core.DbType) error
    GetColumnMapper() core.IMapper
    GetDefaultCacher() core.Cacher
    GetTableMapper() core.IMapper
    GetTZDatabase() *time.Location
    GetTZLocation() *time.Location
    NewSession() *Session
    NoAutoTime() *Session
    Quote(string) string
    SetDefaultCacher(core.Cacher)
    SetLogLevel(core.LogLevel)
    SetMapper(core.IMapper)
    SetTZDatabase(tz *time.Location)
    SetTZLocation(tz *time.Location)
    ShowSQL(show ...bool)
    Sync(...interface{}) error
    Sync2(...interface{}) error
    StoreEngine(storeEngine string) *Session
    TableInfo(bean interface{}) *Table
    UnMapType(reflect.Type)
}

EngineInterface defines the interface which Engine, EngineGroup will implementate.

type GroupPolicy Uses

type GroupPolicy interface {
    Slave(*EngineGroup) *Engine
}

GroupPolicy is be used by chosing the current slave from slaves

type GroupPolicyHandler Uses

type GroupPolicyHandler func(*EngineGroup) *Engine

GroupPolicyHandler should be used when a function is a GroupPolicy

func LeastConnPolicy Uses

func LeastConnPolicy() GroupPolicyHandler

LeastConnPolicy implements GroupPolicy, every time will get the least connections slave

func RandomPolicy Uses

func RandomPolicy() GroupPolicyHandler

RandomPolicy implmentes randomly chose the slave of slaves

func RoundRobinPolicy Uses

func RoundRobinPolicy() GroupPolicyHandler

func WeightRandomPolicy Uses

func WeightRandomPolicy(weights []int) GroupPolicyHandler

WeightRandomPolicy implmentes randomly chose the slave of slaves

func WeightRoundRobinPolicy Uses

func WeightRoundRobinPolicy(weights []int) GroupPolicyHandler

func (GroupPolicyHandler) Slave Uses

func (h GroupPolicyHandler) Slave(eg *EngineGroup) *Engine

Slave implements the chosen of slaves

type Interface Uses

type Interface interface {
    AllCols() *Session
    Alias(alias string) *Session
    Asc(colNames ...string) *Session
    BufferSize(size int) *Session
    Cols(columns ...string) *Session
    Count(...interface{}) (int64, error)
    CreateIndexes(bean interface{}) error
    CreateUniques(bean interface{}) error
    Decr(column string, arg ...interface{}) *Session
    Desc(...string) *Session
    Delete(interface{}) (int64, error)
    Distinct(columns ...string) *Session
    DropIndexes(bean interface{}) error
    Exec(string, ...interface{}) (sql.Result, error)
    Exist(bean ...interface{}) (bool, error)
    Find(interface{}, ...interface{}) error
    Get(interface{}) (bool, error)
    GroupBy(keys string) *Session
    ID(interface{}) *Session
    In(string, ...interface{}) *Session
    Incr(column string, arg ...interface{}) *Session
    Insert(...interface{}) (int64, error)
    InsertOne(interface{}) (int64, error)
    IsTableEmpty(bean interface{}) (bool, error)
    IsTableExist(beanOrTableName interface{}) (bool, error)
    Iterate(interface{}, IterFunc) error
    Limit(int, ...int) *Session
    NoAutoCondition(...bool) *Session
    NotIn(string, ...interface{}) *Session
    Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session
    Omit(columns ...string) *Session
    OrderBy(order string) *Session
    Ping() error
    Query(sqlOrAgrs ...interface{}) (resultsSlice []map[string][]byte, err error)
    QueryInterface(sqlorArgs ...interface{}) ([]map[string]interface{}, error)
    QueryString(sqlorArgs ...interface{}) ([]map[string]string, error)
    Rows(bean interface{}) (*Rows, error)
    SetExpr(string, string) *Session
    SQL(interface{}, ...interface{}) *Session
    Sum(bean interface{}, colName string) (float64, error)
    SumInt(bean interface{}, colName string) (int64, error)
    Sums(bean interface{}, colNames ...string) ([]float64, error)
    SumsInt(bean interface{}, colNames ...string) ([]int64, error)
    Table(tableNameOrBean interface{}) *Session
    Unscoped() *Session
    Update(bean interface{}, condiBeans ...interface{}) (int64, error)
    UseBool(...string) *Session
    Where(interface{}, ...interface{}) *Session
}

Interface defines the interface which Engine, EngineGroup and Session will implementate.

type IterFunc Uses

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

IterFunc only use by Iterate

type LRUCacher Uses

type LRUCacher struct {
    MaxElementSize int
    Expired        time.Duration
    GcInterval     time.Duration
    // contains filtered or unexported fields
}

LRUCacher implments cache object facilities

func NewLRUCacher Uses

func NewLRUCacher(store core.CacheStore, maxElementSize int) *LRUCacher

NewLRUCacher creates a cacher

func NewLRUCacher2 Uses

func NewLRUCacher2(store core.CacheStore, expired time.Duration, maxElementSize int) *LRUCacher

NewLRUCacher2 creates a cache include different params

func (*LRUCacher) ClearBeans Uses

func (m *LRUCacher) ClearBeans(tableName string)

ClearBeans clears all beans in some table

func (*LRUCacher) ClearIds Uses

func (m *LRUCacher) ClearIds(tableName string)

ClearIds clears all sql-ids mapping on table tableName from cache

func (*LRUCacher) DelBean Uses

func (m *LRUCacher) DelBean(tableName string, id string)

DelBean deletes beans in some table

func (*LRUCacher) DelIds Uses

func (m *LRUCacher) DelIds(tableName, sql string)

DelIds deletes ids

func (*LRUCacher) GC Uses

func (m *LRUCacher) GC()

GC check ids lit and sql list to remove all element expired

func (*LRUCacher) GetBean Uses

func (m *LRUCacher) GetBean(tableName string, id string) interface{}

GetBean returns bean according tableName and id from cache

func (*LRUCacher) GetIds Uses

func (m *LRUCacher) GetIds(tableName, sql string) interface{}

GetIds returns all bean's ids according to sql and parameter from cache

func (*LRUCacher) PutBean Uses

func (m *LRUCacher) PutBean(tableName string, id string, obj interface{})

PutBean puts beans into table

func (*LRUCacher) PutIds Uses

func (m *LRUCacher) PutIds(tableName, sql string, ids interface{})

PutIds pus ids into table

func (*LRUCacher) RunGC Uses

func (m *LRUCacher) RunGC()

RunGC run once every m.GcInterval

type MemoryStore Uses

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

MemoryStore represents in-memory store

func NewMemoryStore Uses

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new store in memory

func (*MemoryStore) Del Uses

func (s *MemoryStore) Del(key string) error

Del deletes object

func (*MemoryStore) Get Uses

func (s *MemoryStore) Get(key string) (interface{}, error)

Get gets object from store

func (*MemoryStore) Put Uses

func (s *MemoryStore) Put(key string, value interface{}) error

Put puts object into store

type Rows Uses

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

Rows rows wrapper a rows to

func (*Rows) Close Uses

func (rows *Rows) Close() error

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

func (*Rows) Err Uses

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 Uses

func (rows *Rows) Next() bool

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

func (*Rows) Scan Uses

func (rows *Rows) Scan(bean interface{}) error

Scan row record to bean properties

type Session Uses

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

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

func (*Session) After Uses

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

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

func (*Session) Alias Uses

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

Alias set the table alias

func (*Session) AllCols Uses

func (session *Session) AllCols() *Session

AllCols ask all columns

func (*Session) And Uses

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

And provides custom query condition.

func (*Session) Asc Uses

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

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

func (*Session) Before Uses

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

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

func (*Session) Begin Uses

func (session *Session) Begin() error

Begin a transaction

func (*Session) BufferSize Uses

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

BufferSize sets the buffersize for iterate

func (*Session) Cascade Uses

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

Cascade indicates if loading sub Struct

func (*Session) Charset Uses

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

Charset is only avialble mysql dialect currently

func (*Session) Clone Uses

func (session *Session) Clone() *Session

Clone copy all the session's content and return a new session

func (*Session) Close Uses

func (session *Session) Close()

Close release the connection from pool

func (*Session) Cols Uses

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

Cols provides some columns to special

func (*Session) Commit Uses

func (session *Session) Commit() error

Commit When using transaction, Commit will commit all operations.

func (*Session) Conds Uses

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

Conds returns session query conditions except auto bean conditions

func (*Session) Count Uses

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

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

func (*Session) CreateIndexes Uses

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

CreateIndexes create indexes

func (*Session) CreateTable Uses

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

CreateTable create a table according a bean

func (*Session) CreateUniques Uses

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

CreateUniques create uniques

func (*Session) DB Uses

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

DB db return the wrapper of sql.DB

func (*Session) Decr Uses

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

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

func (*Session) Delete Uses

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

Delete records, bean's non-empty fields are conditions

func (*Session) Desc Uses

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

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

func (*Session) Distinct Uses

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 Uses

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

DropIndexes drop indexes

func (*Session) DropTable Uses

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 Uses

func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, error)

Exec raw sql

func (*Session) Exist Uses

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

Exist returns true if the record exist otherwise return false

func (*Session) Find Uses

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) ForUpdate Uses

func (session *Session) ForUpdate() *Session

ForUpdate Set Read/Write locking for UPDATE

func (*Session) Get Uses

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

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

func (*Session) GroupBy Uses

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

GroupBy Generate Group By statement

func (*Session) Having Uses

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

Having Generate Having statement

func (*Session) ID Uses

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

ID provides converting id as a query condition

func (*Session) Id Uses

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

Id provides converting id as a query condition

Deprecated: use ID instead

func (*Session) In Uses

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

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

func (*Session) Incr Uses

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

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

func (*Session) Init Uses

func (session *Session) Init()

Init reset the session as the init status.

func (*Session) Insert Uses

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

Insert insert one or more beans

func (*Session) InsertMulti Uses

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

InsertMulti insert multiple records

func (*Session) InsertOne Uses

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

func (*Session) IsClosed Uses

func (session *Session) IsClosed() bool

IsClosed returns if session is closed

func (*Session) IsTableEmpty Uses

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

IsTableEmpty if table have any records

func (*Session) IsTableExist Uses

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

IsTableExist if a table is exist

func (*Session) Iterate Uses

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 Uses

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

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

func (*Session) LastSQL Uses

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

LastSQL returns last query information

func (*Session) Limit Uses

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

Limit provide limit and offset query condition

func (*Session) MustCols Uses

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

MustCols specify some columns must use even if they are empty

func (*Session) NoAutoCondition Uses

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

NoAutoCondition disable generate SQL condition from beans

func (*Session) NoAutoTime Uses

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 Uses

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 Uses

func (session *Session) NoCascade() *Session

NoCascade indicate that no cascade load child object

func (*Session) NotIn Uses

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

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

func (*Session) Nullable Uses

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

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

func (*Session) Omit Uses

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

Omit Only not use the parameters as select or update columns

func (*Session) Or Uses

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

Or provides custom query condition.

func (*Session) OrderBy Uses

func (session *Session) OrderBy(order string) *Session

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

func (*Session) Ping Uses

func (session *Session) Ping() error

Ping test if database is ok

func (*Session) PingContext Uses

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

PingContext test if database is ok

func (*Session) Prepare Uses

func (session *Session) Prepare() *Session

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

func (*Session) Query Uses

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 Uses

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

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

func (*Session) QueryString Uses

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

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

func (*Session) Rollback Uses

func (session *Session) Rollback() error

Rollback When using transaction, you can rollback if any error

func (*Session) Rows Uses

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 Uses

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) Select Uses

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

Select provides some columns to special

func (*Session) SetExpr Uses

func (session *Session) SetExpr(column string, expression string) *Session

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

func (*Session) Sql Uses

func (session *Session) Sql(query string, 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.

Deprecated: use SQL instead.

func (*Session) StoreEngine Uses

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

StoreEngine is only avialble mysql dialect currently

func (*Session) Sum Uses

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 Uses

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 Uses

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 Uses

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

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

func (*Session) Sync2 Uses

func (session *Session) Sync2(beans ...interface{}) error

Sync2 synchronize structs to database tables

func (*Session) Table Uses

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

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

func (*Session) Unscoped Uses

func (session *Session) Unscoped() *Session

Unscoped always disable struct tag "deleted"

func (*Session) Update Uses

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 Uses

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 Uses

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

Where provides custom query condition.

type SimpleLogger Uses

type SimpleLogger struct {
    DEBUG *log.Logger
    ERR   *log.Logger
    INFO  *log.Logger
    WARN  *log.Logger
    // contains filtered or unexported fields
}

SimpleLogger is the default implment of core.ILogger

func NewSimpleLogger Uses

func NewSimpleLogger(out io.Writer) *SimpleLogger

NewSimpleLogger use a special io.Writer as logger output

func NewSimpleLogger2 Uses

func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger

NewSimpleLogger2 let you customrize your logger prefix and flag

func NewSimpleLogger3 Uses

func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger

NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel

func (*SimpleLogger) Debug Uses

func (s *SimpleLogger) Debug(v ...interface{})

Debug implement core.ILogger

func (*SimpleLogger) Debugf Uses

func (s *SimpleLogger) Debugf(format string, v ...interface{})

Debugf implement core.ILogger

func (*SimpleLogger) Error Uses

func (s *SimpleLogger) Error(v ...interface{})

Error implement core.ILogger

func (*SimpleLogger) Errorf Uses

func (s *SimpleLogger) Errorf(format string, v ...interface{})

Errorf implement core.ILogger

func (*SimpleLogger) Info Uses

func (s *SimpleLogger) Info(v ...interface{})

Info implement core.ILogger

func (*SimpleLogger) Infof Uses

func (s *SimpleLogger) Infof(format string, v ...interface{})

Infof implement core.ILogger

func (*SimpleLogger) IsShowSQL Uses

func (s *SimpleLogger) IsShowSQL() bool

IsShowSQL implement core.ILogger

func (*SimpleLogger) Level Uses

func (s *SimpleLogger) Level() core.LogLevel

Level implement core.ILogger

func (*SimpleLogger) SetLevel Uses

func (s *SimpleLogger) SetLevel(l core.LogLevel)

SetLevel implement core.ILogger

func (*SimpleLogger) ShowSQL Uses

func (s *SimpleLogger) ShowSQL(show ...bool)

ShowSQL implement core.ILogger

func (*SimpleLogger) Warn Uses

func (s *SimpleLogger) Warn(v ...interface{})

Warn implement core.ILogger

func (*SimpleLogger) Warnf Uses

func (s *SimpleLogger) Warnf(format string, v ...interface{})

Warnf implement core.ILogger

type Statement Uses

type Statement struct {
    RefTable *core.Table
    Engine   *Engine
    Start    int
    LimitN   int

    OrderStr string
    JoinStr  string

    GroupByStr string
    HavingStr  string
    ColumnStr  string

    OmitStr      string
    AltTableName string

    RawSQL      string
    RawParams   []interface{}
    UseCascade  bool
    UseAutoJoin bool
    StoreEngine string
    Charset     string
    UseCache    bool
    UseAutoTime bool

    IsDistinct  bool
    IsForUpdate bool
    TableAlias  string
    // contains filtered or unexported fields
}

Statement save all the sql info for executing SQL

func (*Statement) Alias Uses

func (statement *Statement) Alias(alias string) *Statement

Alias set the table alias

func (*Statement) AllCols Uses

func (statement *Statement) AllCols() *Statement

AllCols update use only: update all columns

func (*Statement) And Uses

func (statement *Statement) And(query interface{}, args ...interface{}) *Statement

And add Where & and statement

func (*Statement) Asc Uses

func (statement *Statement) Asc(colNames ...string) *Statement

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

func (*Statement) Cols Uses

func (statement *Statement) Cols(columns ...string) *Statement

Cols generate "col1, col2" statement

func (*Statement) Decr Uses

func (statement *Statement) Decr(column string, arg ...interface{}) *Statement

Decr Generate "Update ... Set column = column - arg" statement

func (*Statement) Desc Uses

func (statement *Statement) Desc(colNames ...string) *Statement

Desc generate `ORDER BY xx DESC`

func (*Statement) Distinct Uses

func (statement *Statement) Distinct(columns ...string) *Statement

Distinct generates "DISTINCT col1, col2 " statement

func (*Statement) ForUpdate Uses

func (statement *Statement) ForUpdate() *Statement

ForUpdate generates "SELECT ... FOR UPDATE" statement

func (*Statement) GroupBy Uses

func (statement *Statement) GroupBy(keys string) *Statement

GroupBy generate "Group By keys" statement

func (*Statement) Having Uses

func (statement *Statement) Having(conditions string) *Statement

Having generate "Having conditions" statement

func (*Statement) ID Uses

func (statement *Statement) ID(id interface{}) *Statement

ID generate "where id = ? " statement or for composite key "where key1 = ? and key2 = ?"

func (*Statement) In Uses

func (statement *Statement) In(column string, args ...interface{}) *Statement

In generate "Where column IN (?) " statement

func (*Statement) Incr Uses

func (statement *Statement) Incr(column string, arg ...interface{}) *Statement

Incr Generate "Update ... Set column = column + arg" statement

func (*Statement) Init Uses

func (statement *Statement) Init()

Init reset all the statement's fields

func (*Statement) Join Uses

func (statement *Statement) Join(joinOP string, tablename interface{}, condition string, args ...interface{}) *Statement

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

func (*Statement) Limit Uses

func (statement *Statement) Limit(limit int, start ...int) *Statement

Limit generate LIMIT start, limit statement

func (*Statement) MustCols Uses

func (statement *Statement) MustCols(columns ...string) *Statement

MustCols update use only: must update columns

func (*Statement) NoAutoCondition Uses

func (statement *Statement) NoAutoCondition(no ...bool) *Statement

NoAutoCondition if you do not want convert bean's field as query condition, then use this function

func (*Statement) NotIn Uses

func (statement *Statement) NotIn(column string, args ...interface{}) *Statement

NotIn generate "Where column NOT IN (?) " statement

func (*Statement) Nullable Uses

func (statement *Statement) Nullable(columns ...string)

Nullable Update use only: update columns to null when value is nullable and zero-value

func (*Statement) Omit Uses

func (statement *Statement) Omit(columns ...string)

Omit do not use the columns

func (*Statement) Or Uses

func (statement *Statement) Or(query interface{}, args ...interface{}) *Statement

Or add Where & Or statement

func (*Statement) OrderBy Uses

func (statement *Statement) OrderBy(order string) *Statement

OrderBy generate "Order By order" statement

func (*Statement) SQL Uses

func (statement *Statement) SQL(query interface{}, args ...interface{}) *Statement

SQL adds raw sql statement

func (*Statement) Select Uses

func (statement *Statement) Select(str string) *Statement

Select replace select

func (*Statement) SetExpr Uses

func (statement *Statement) SetExpr(column string, expression string) *Statement

SetExpr Generate "Update ... Set column = {expression}" statement

func (*Statement) Table Uses

func (statement *Statement) Table(tableNameOrBean interface{}) *Statement

Table tempororily set table name, the parameter could be a string or a pointer of struct

func (*Statement) TableName Uses

func (statement *Statement) TableName() string

TableName return current tableName

func (*Statement) Top Uses

func (statement *Statement) Top(limit int) *Statement

Top generate LIMIT limit statement

func (*Statement) Unscoped Uses

func (statement *Statement) Unscoped() *Statement

Unscoped always disable struct tag "deleted"

func (*Statement) UseBool Uses

func (statement *Statement) UseBool(columns ...string) *Statement

UseBool indicates that use bool fields as update contents and query contiditions

func (*Statement) Where Uses

func (statement *Statement) Where(query interface{}, args ...interface{}) *Statement

Where add Where statement

type SyslogLogger Uses

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

SyslogLogger will be depricated

func NewSyslogLogger Uses

func NewSyslogLogger(w *syslog.Writer) *SyslogLogger

NewSyslogLogger implements core.ILogger

func (*SyslogLogger) Debug Uses

func (s *SyslogLogger) Debug(v ...interface{})

Debug log content as Debug

func (*SyslogLogger) Debugf Uses

func (s *SyslogLogger) Debugf(format string, v ...interface{})

Debugf log content as Debug and format

func (*SyslogLogger) Error Uses

func (s *SyslogLogger) Error(v ...interface{})

Error log content as Error

func (*SyslogLogger) Errorf Uses

func (s *SyslogLogger) Errorf(format string, v ...interface{})

Errorf log content as Errorf and format

func (*SyslogLogger) Info Uses

func (s *SyslogLogger) Info(v ...interface{})

Info log content as Info

func (*SyslogLogger) Infof Uses

func (s *SyslogLogger) Infof(format string, v ...interface{})

Infof log content as Infof and format

func (*SyslogLogger) IsShowSQL Uses

func (s *SyslogLogger) IsShowSQL() bool

IsShowSQL if logging SQL

func (*SyslogLogger) Level Uses

func (s *SyslogLogger) Level() core.LogLevel

Level shows log level

func (*SyslogLogger) SetLevel Uses

func (s *SyslogLogger) SetLevel(l core.LogLevel)

SetLevel always return error, as current log/syslog package doesn't allow to set priority level after syslog.Writer created

func (*SyslogLogger) ShowSQL Uses

func (s *SyslogLogger) ShowSQL(show ...bool)

ShowSQL set if logging SQL

func (*SyslogLogger) Warn Uses

func (s *SyslogLogger) Warn(v ...interface{})

Warn log content as Warn

func (*SyslogLogger) Warnf Uses

func (s *SyslogLogger) Warnf(format string, v ...interface{})

Warnf log content as Warnf and format

type Table Uses

type Table struct {
    *core.Table
    Name string
}

Table table struct

func (*Table) IsValid Uses

func (t *Table) IsValid() bool

IsValid if table is valid

type TableName Uses

type TableName interface {
    TableName() string
}

TableName table name interface to define customerize table name

Directories

PathSynopsis
examples
migrate

Package xorm imports 28 packages (graph) and is imported by 838 packages. Updated 2017-12-13. Refresh now. Tools for package owners.