xorm: github.com/lunny/xorm Index | Files | Directories

package xorm

import "github.com/lunny/xorm"

Package xorm is a simple and powerful ORM for Go.

Installation

Make sure you have installed Go 1.1+ and then:

go get github.com/lunny/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 is enough. You can set it as package variable.

Raw Methods

Xorm also support raw sql execution:

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

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

2. exec sql, the returned results

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

ORM Methods

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

1. Insert one or multipe 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 from database

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

3. Query multiple records from database

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

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

raws, err := engine.Raws(...)
// SELECT * FROM user
for raws.Next() {
    raws.Scan(bean)
}

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

5. Update one or more records

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

6. Delete one or more records

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

7. Count records

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

Conditions

The above 7 methods could use with condition methods.

1. Id, In

engine.Id(1).Get(&user)
// SELECT * FROM user WHERE id = 1
engine.In("id", 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().Find()
// SELECT * FROM user LIMIT ..

5. Sql

engine.Sql("select * from user").Find()

6. Cols, Omit, Distinct

engine.Cols("col1, col2").Find()
// SELECT col1, col2 FROM user
engine.Omit("col1").Find()
// SELECT col2, col3 FROM user
engine.Distinct("col1").Find()
// SELECT DISTINCT col1 FROM user

7. Join, GroupBy, Having

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

More usage, please visit https://github.com/lunny/xorm/blob/master/docs/QuickStartEn.md

Index

Package Files

cache.go doc.go engine.go error.go filter.go helpers.go mapper.go mssql.go mymysql.go mysql.go oracle.go pool.go postgres.go processors.go rows.go session.go sqlite3.go statement.go table.go xorm.go

Constants

const (
    // default cache expired time
    CacheExpired = 60 * time.Minute
    // not use now
    CacheMaxMemory = 256
    // evey ten minutes to clear all expired nodes
    CacheGcInterval = 10 * time.Minute
    // each time when gc to removed max nodes
    CacheGcMaxRemoved = 20
)
const (
    POSTGRES = "postgres"
    SQLITE   = "sqlite3"
    MYSQL    = "mysql"
    MYMYSQL  = "mymysql"

    MSSQL = "mssql"

    ORACLE_OCI = "oci8"
    QL         = "ql"
)
const (
    IndexType = iota + 1
    UniqueType
)
const (
    TWOSIDES = iota + 1
    ONLYTODB
    ONLYFROMDB
)
const (
    Version string = "0.3.1"
)

Variables

var (
    ErrParamsType      error = errors.New("Params type error")
    ErrTableNotFound   error = errors.New("Not found table")
    ErrUnSupportedType error = errors.New("Unsupported type error")
    ErrNotExist        error = errors.New("Not exist error")
    ErrCacheFailed     error = errors.New("Cache failed")
    ErrNeedDeletedCond error = errors.New("Delete need at least one condition")
    ErrNotImplemented  error = errors.New("Not implemented.")
)
var (
    Bit       = "BIT"
    TinyInt   = "TINYINT"
    SmallInt  = "SMALLINT"
    MediumInt = "MEDIUMINT"
    Int       = "INT"
    Integer   = "INTEGER"
    BigInt    = "BIGINT"

    Char       = "CHAR"
    Varchar    = "VARCHAR"
    TinyText   = "TINYTEXT"
    Text       = "TEXT"
    MediumText = "MEDIUMTEXT"
    LongText   = "LONGTEXT"

    Date       = "DATE"
    DateTime   = "DATETIME"
    Time       = "TIME"
    TimeStamp  = "TIMESTAMP"
    TimeStampz = "TIMESTAMPZ"

    Decimal = "DECIMAL"
    Numeric = "NUMERIC"

    Real   = "REAL"
    Float  = "FLOAT"
    Double = "DOUBLE"

    Binary     = "BINARY"
    VarBinary  = "VARBINARY"
    TinyBlob   = "TINYBLOB"
    Blob       = "BLOB"
    MediumBlob = "MEDIUMBLOB"
    LongBlob   = "LONGBLOB"
    Bytea      = "BYTEA"

    Bool = "BOOL"

    Serial    = "SERIAL"
    BigSerial = "BIGSERIAL"
)

func SQLType2Type Uses

func SQLType2Type(st SQLType) reflect.Type

default sql type change to go types

type AfterDeleteProcessor Uses

type AfterDeleteProcessor interface {
    AfterDelete()
}

Executed after an object has been deleted

type AfterInsertProcessor Uses

type AfterInsertProcessor interface {
    AfterInsert()
}

Executed after an object is persisted to the database

type AfterUpdateProcessor Uses

type AfterUpdateProcessor interface {
    AfterUpdate()
}

Executed after an object has been updated

type BeforeDeleteProcessor Uses

type BeforeDeleteProcessor interface {
    BeforeDelete()
}

Executed before an object is deleted

type BeforeInsertProcessor Uses

type BeforeInsertProcessor interface {
    BeforeInsert()
}

Executed before an object is initially persisted to the database

type BeforeUpdateProcessor Uses

type BeforeUpdateProcessor interface {
    BeforeUpdate()
}

Executed before an object is updated

type CacheMapper Uses

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

func NewCacheMapper Uses

func NewCacheMapper(mapper IMapper) *CacheMapper

func (*CacheMapper) Obj2Table Uses

func (m *CacheMapper) Obj2Table(o string) string

func (*CacheMapper) Table2Obj Uses

func (m *CacheMapper) Table2Obj(t string) string

type CacheStore Uses

type CacheStore interface {
    Put(key, value interface{}) error
    Get(key interface{}) (interface{}, error)
    Del(key interface{}) error
}

CacheStore is a interface to store cache

type Cacher Uses

type Cacher interface {
    GetIds(tableName, sql string) interface{}
    GetBean(tableName string, id int64) interface{}
    PutIds(tableName, sql string, ids interface{})
    PutBean(tableName string, id int64, obj interface{})
    DelIds(tableName, sql string)
    DelBean(tableName string, id int64)
    ClearIds(tableName string)
    ClearBeans(tableName string)
}

Cacher is an interface to provide cache

type Column Uses

type Column struct {
    Name            string
    FieldName       string
    SQLType         SQLType
    Length          int
    Length2         int
    Nullable        bool
    Default         string
    Indexes         map[string]bool
    IsPrimaryKey    bool
    IsAutoIncrement bool
    MapType         int
    IsCreated       bool
    IsUpdated       bool
    IsCascade       bool
    IsVersion       bool
    DefaultIsEmpty  bool
}

database column

func (*Column) String Uses

func (col *Column) String(d dialect) string

generate column description string according dialect

func (*Column) ValueOf Uses

func (col *Column) ValueOf(bean interface{}) reflect.Value

return col's filed of struct's value

type Conversion Uses

type Conversion interface {
    FromDB([]byte) error
    ToDB() ([]byte, error)
}

Conversion is an interface. A type implements Conversion will according the custom method to fill into database and retrieve from database.

type Engine Uses

type Engine struct {
    TagIdentifier  string
    DriverName     string
    DataSourceName string

    Tables map[reflect.Type]*Table

    ShowSQL   bool
    ShowErr   bool
    ShowDebug bool
    ShowWarn  bool
    Pool      IConnectPool
    Filters   []Filter
    Logger    io.Writer
    Cacher    Cacher
    UseCache  bool
    // 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)

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

func (*Engine) After Uses

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

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

func (*Engine) AllCols Uses

func (engine *Engine) AllCols() *Session

func (*Engine) Asc Uses

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

Method Asc will generate "ORDER BY column1 DESC, 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

Database's autoincrement statement

func (*Engine) Before Uses

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

Apply before Processor, affected bean is passed to closure arg

func (*Engine) Cascade Uses

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

use cascade or not

func (*Engine) Charset Uses

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

set charset when create table, only support mysql now

func (*Engine) ClearCache Uses

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

If enabled cache, clear some tables' cache

func (*Engine) ClearCacheBean Uses

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

If enabled cache, clear the cache bean

func (*Engine) Close Uses

func (engine *Engine) Close() error

Close the engine

func (*Engine) Cols Uses

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

only use the paramters as select or update columns

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

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

create uniques

func (*Engine) DBMetas Uses

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

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

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

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

func (*Engine) Distinct Uses

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

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

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

func (*Engine) Exec Uses

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

Exec raw sql

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

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

Generate Group By statement

func (*Engine) Having Uses

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

Generate Having statement

func (*Engine) Id Uses

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

Id mehtod provoide a condition as (id) = ?

func (*Engine) Import Uses

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

Import SQL DDL file

func (*Engine) In Uses

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

This method will generate "column IN (?, ?)"

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)

Insert only one record

func (*Engine) IsTableEmpty Uses

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

If a table has any reocrd

func (*Engine) IsTableExist Uses

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

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(join_operator, tablename, condition string) *Session

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

This method will generate "LIMIT start, limit"

func (*Engine) LogDebug Uses

func (engine *Engine) LogDebug(contents ...interface{})

logging debug

func (*Engine) LogError Uses

func (engine *Engine) LogError(contents ...interface{})

logging error

func (*Engine) LogSQL Uses

func (engine *Engine) LogSQL(contents ...interface{})

logging sql

func (*Engine) LogWarn Uses

func (engine *Engine) LogWarn(contents ...interface{})

logging warn

func (*Engine) MapCacher Uses

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

Set a table use a special cacher

func (*Engine) MustCols Uses

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

func (*Engine) NewSession Uses

func (engine *Engine) NewSession() *Session

New a session

func (*Engine) NoAutoTime Uses

func (engine *Engine) NoAutoTime() *Session

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

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

func (*Engine) Omit Uses

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

Only not use the paramters as select or update columns

func (*Engine) OpenDB Uses

func (engine *Engine) OpenDB() (*sql.DB, error)

OpenDB provides a interface to operate database directly.

func (*Engine) OrderBy Uses

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

Method OrderBy will generate "ORDER BY order"

func (*Engine) Ping Uses

func (engine *Engine) Ping() error

Ping tests if database is alive.

func (*Engine) Query Uses

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

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

func (*Engine) Quote Uses

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

Use QuoteStr quote the string sql

func (*Engine) QuoteStr Uses

func (engine *Engine) QuoteStr() string

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

func (*Engine) Rows Uses

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

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

func (engine *Engine) SetColumnMapper(mapper IMapper)

func (*Engine) SetDefaultCacher Uses

func (engine *Engine) SetDefaultCacher(cacher Cacher)

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

func (*Engine) SetMapper Uses

func (engine *Engine) SetMapper(mapper IMapper)

func (*Engine) SetMaxConns Uses

func (engine *Engine) SetMaxConns(conns int)

SetMaxConns is only available for go 1.2+

func (*Engine) SetMaxIdleConns Uses

func (engine *Engine) SetMaxIdleConns(conns int)

SetMaxIdleConns

func (*Engine) SetPool Uses

func (engine *Engine) SetPool(pool IConnectPool) error

Set engine's pool, the pool default is Go's standard library's connection pool.

func (*Engine) SetTableMapper Uses

func (engine *Engine) SetTableMapper(mapper IMapper)

func (*Engine) Sql Uses

func (engine *Engine) Sql(querystring string, args ...interface{}) *Session

Sql method let's you manualy 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 *Column) string

A simple wrapper to dialect's SqlType method

func (*Engine) StoreEngine Uses

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

set store engine when create table, only support mysql now

func (*Engine) SupportInsertMany Uses

func (engine *Engine) SupportInsertMany() bool

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

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

Temporarily change the Get, Find, Update's table

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

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 paramters, it will use all the bool field of struct, or it will use paramters's columns

func (*Engine) Where Uses

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

Where method provide a condition query

type Filter Uses

type Filter interface {
    Do(sql string, session *Session) string
}

Filter is an interface to filter SQL

type IConnectPool Uses

type IConnectPool interface {
    Init(engine *Engine) error
    RetrieveDB(engine *Engine) (*sql.DB, error)
    ReleaseDB(engine *Engine, db *sql.DB)
    Close(engine *Engine) error
    SetMaxIdleConns(conns int)
    MaxIdleConns() int
    SetMaxConns(conns int)
    MaxConns() int
}

Interface IConnecPool is a connection pool interface, all implements should implement Init, RetrieveDB, ReleaseDB and Close methods. Init for init when engine be created or invoke SetPool RetrieveDB for requesting a connection to db; ReleaseDB for releasing a db connection; Close for invoking when engine.Close

func NewNoneConnectPool Uses

func NewNoneConnectPool() IConnectPool

NewNoneConnectPool new a NoneConnectPool.

func NewSimpleConnectPool Uses

func NewSimpleConnectPool() IConnectPool

NewSimpleConnectPool new a SimpleConnectPool

func NewSysConnectPool Uses

func NewSysConnectPool() IConnectPool

NewSysConnectPool new a SysConnectPool.

type IMapper Uses

type IMapper interface {
    Obj2Table(string) string
    Table2Obj(string) string
}

name translation between struct, fields names and table, column names

type IdFilter Uses

type IdFilter struct {
}

IdFilter filter SQL replace (id) to primary key column name

func (*IdFilter) Do Uses

func (i *IdFilter) Do(sql string, session *Session) string

type Index Uses

type Index struct {
    Name string
    Type int
    Cols []string
}

database index

func NewIndex Uses

func NewIndex(name string, indexType int) *Index

new an index

func (*Index) AddColumn Uses

func (index *Index) AddColumn(cols ...string)

add columns which will be composite index

type IterFunc Uses

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

IterFunc only use by Iterate

type LRUCacher Uses

type LRUCacher struct {
    Max int

    Expired time.Duration

    GcInterval time.Duration
    // contains filtered or unexported fields
}

LRUCacher implements Cacher according to LRU algorithm

func NewLRUCacher Uses

func NewLRUCacher(store CacheStore, max int) *LRUCacher

func NewLRUCacher2 Uses

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

func (*LRUCacher) ClearBeans Uses

func (m *LRUCacher) ClearBeans(tableName string)

func (*LRUCacher) ClearIds Uses

func (m *LRUCacher) ClearIds(tableName string)

func (*LRUCacher) DelBean Uses

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

func (*LRUCacher) DelIds Uses

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

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 int64) interface{}

Get bean according tableName and id from cache

func (*LRUCacher) GetIds Uses

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

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

func (*LRUCacher) PutBean Uses

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

func (*LRUCacher) PutIds Uses

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

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 implements CacheStore provide local machine memory store

func NewMemoryStore Uses

func NewMemoryStore() *MemoryStore

func (*MemoryStore) Del Uses

func (s *MemoryStore) Del(key interface{}) error

func (*MemoryStore) Get Uses

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

func (*MemoryStore) Put Uses

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

type NoneConnectPool Uses

type NoneConnectPool struct {
}

Struct NoneConnectPool is a implement for IConnectPool. It provides directly invoke driver's open and release connection function

func (*NoneConnectPool) Close Uses

func (p *NoneConnectPool) Close(engine *Engine) error

Close do nothing

func (*NoneConnectPool) Init Uses

func (p *NoneConnectPool) Init(engine *Engine) error

Init do nothing

func (*NoneConnectPool) MaxConns Uses

func (p *NoneConnectPool) MaxConns() int

not implemented

func (*NoneConnectPool) MaxIdleConns Uses

func (p *NoneConnectPool) MaxIdleConns() int

func (*NoneConnectPool) ReleaseDB Uses

func (p *NoneConnectPool) ReleaseDB(engine *Engine, db *sql.DB)

ReleaseDB directly close a connection

func (*NoneConnectPool) RetrieveDB Uses

func (p *NoneConnectPool) RetrieveDB(engine *Engine) (db *sql.DB, err error)

RetrieveDB directly open a connection

func (*NoneConnectPool) SetMaxConns Uses

func (p *NoneConnectPool) SetMaxConns(conns int)

not implemented

func (*NoneConnectPool) SetMaxIdleConns Uses

func (p *NoneConnectPool) SetMaxIdleConns(conns int)

type PK Uses

type PK []interface{}

type PgSeqFilter Uses

type PgSeqFilter struct {
}

PgSeqFilter filter SQL replace ?, ? ... to $1, $2 ...

func (*PgSeqFilter) Do Uses

func (s *PgSeqFilter) Do(sql string, session *Session) string

type PrefixMapper Uses

type PrefixMapper struct {
    Mapper IMapper
    Prefix string
}

provide prefix table name support

func NewPrefixMapper Uses

func NewPrefixMapper(mapper IMapper, prefix string) PrefixMapper

func (PrefixMapper) Obj2Table Uses

func (mapper PrefixMapper) Obj2Table(name string) string

func (PrefixMapper) Table2Obj Uses

func (mapper PrefixMapper) Table2Obj(name string) string

type QuoteFilter Uses

type QuoteFilter struct {
}

QuoteFilter filter SQL replace ` to database's own quote character

func (*QuoteFilter) Do Uses

func (s *QuoteFilter) Do(sql string, session *Session) string

type Rows Uses

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

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

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 SQLType Uses

type SQLType struct {
    Name           string
    DefaultLength  int
    DefaultLength2 int
}

xorm SQL types

func Type2SQLType Uses

func Type2SQLType(t reflect.Type) (st SQLType)

func (*SQLType) IsBlob Uses

func (s *SQLType) IsBlob() bool

func (*SQLType) IsText Uses

func (s *SQLType) IsText() bool

type SameMapper Uses

type SameMapper struct {
}

SameMapper implements IMapper and provides same name between struct and database table

func (SameMapper) Obj2Table Uses

func (m SameMapper) Obj2Table(o string) string

func (SameMapper) Table2Obj Uses

func (m SameMapper) Table2Obj(t string) string

type Session Uses

type Session struct {
    Db                     *sql.DB
    Engine                 *Engine
    Tx                     *sql.Tx
    Statement              Statement
    IsAutoCommit           bool
    IsCommitedOrRollbacked bool
    TransType              string
    IsAutoClose            bool
    // contains filtered or unexported fields
}

Struct 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

Apply after Processor, affected bean is passed to closure arg

func (*Session) AllCols Uses

func (session *Session) AllCols() *Session

func (*Session) And Uses

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

Method Where provides custom query condition.

func (*Session) Asc Uses

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

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

func (*Session) Before Uses

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

Apply before Processor, affected bean is passed to closure arg

func (*Session) Begin Uses

func (session *Session) Begin() error

Begin a transaction

func (*Session) Cascade Uses

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

Method Cascade indicates if loading sub Struct

func (*Session) Charset Uses

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

Method StoreEngine is only avialble charset dialect currently

func (*Session) Close Uses

func (session *Session) Close()

Method Close release the connection from pool

func (*Session) Cols Uses

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

Method Cols provides some columns to special

func (*Session) Commit Uses

func (session *Session) Commit() error

When using transaction, Commit will commit all operations.

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

create indexes

func (*Session) CreateTable Uses

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

this function create a table according a bean

func (*Session) CreateUniques Uses

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

create uniques

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

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

func (*Session) Distinct Uses

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

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

drop indexes

func (*Session) DropTable Uses

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

DropTable drop a table and all indexes of the table

func (*Session) Exec Uses

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

Exec raw sql

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

Generate Group By statement

func (*Session) Having Uses

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

Generate Having statement

func (*Session) Id Uses

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

Method Id provides converting id as a query condition

func (*Session) In Uses

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

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

func (*Session) Init Uses

func (session *Session) Init()

Method Init reset the session as the init status.

func (*Session) Insert Uses

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

insert one or more beans

func (*Session) InsertMulti Uses

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

Insert multiple records

func (*Session) InsertOne Uses

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

Method 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) 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(join_operator, tablename, condition string) *Session

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

func (*Session) Limit Uses

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

Method Limit provide limit and offset query condition

func (*Session) MustCols Uses

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

func (*Session) NoAutoTime Uses

func (session *Session) NoAutoTime() *Session

Method 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

Method 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

func (*Session) Omit Uses

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

Only not use the paramters as select or update columns

func (*Session) Or Uses

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

Method Where provides custom query condition.

func (*Session) OrderBy Uses

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

Method 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

Test if database is ok

func (*Session) Query Uses

func (session *Session) Query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error)

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

func (*Session) Rollback Uses

func (session *Session) Rollback() error

When using transaction, you can rollback if any error

func (*Session) Rows Uses

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

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(querystring string, args ...interface{}) *Session

Method 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) StoreEngine Uses

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

Method StoreEngine is only avialble mysql dialect currently

func (*Session) Table Uses

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

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

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

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 paramters, it will use all the bool field of struct, or it will use paramters's columns

func (*Session) Where Uses

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

Method Where provides custom query condition.

type SimpleConnectPool Uses

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

Struct SimpleConnectPool is a simple implementation for IConnectPool. It's a custom connection pool and not use system connection pool. Opening or Closing a database connection must be enter a lock. This implements will be improved in furture.

func (*SimpleConnectPool) Close Uses

func (p *SimpleConnectPool) Close(engine *Engine) error

Close release all db

func (*SimpleConnectPool) Init Uses

func (s *SimpleConnectPool) Init(engine *Engine) error

func (*SimpleConnectPool) MaxConns Uses

func (p *SimpleConnectPool) MaxConns() int

not implemented

func (*SimpleConnectPool) MaxIdleConns Uses

func (p *SimpleConnectPool) MaxIdleConns() int

func (*SimpleConnectPool) ReleaseDB Uses

func (p *SimpleConnectPool) ReleaseDB(engine *Engine, db *sql.DB)

ReleaseDB release a db from connection pool

func (*SimpleConnectPool) RetrieveDB Uses

func (p *SimpleConnectPool) RetrieveDB(engine *Engine) (*sql.DB, error)

RetrieveDB get a connection from connection pool

func (*SimpleConnectPool) SetMaxConns Uses

func (p *SimpleConnectPool) SetMaxConns(conns int)

not implemented

func (*SimpleConnectPool) SetMaxIdleConns Uses

func (p *SimpleConnectPool) SetMaxIdleConns(conns int)

type SnakeMapper Uses

type SnakeMapper struct {
}

SnakeMapper implements IMapper and provides name transaltion between struct and database table

func (SnakeMapper) Obj2Table Uses

func (mapper SnakeMapper) Obj2Table(name string) string

func (SnakeMapper) Table2Obj Uses

func (mapper SnakeMapper) Table2Obj(name string) string

type Statement Uses

type Statement struct {
    RefTable   *Table
    Engine     *Engine
    Start      int
    LimitN     int
    WhereStr   string
    IdParam    *PK
    Params     []interface{}
    OrderStr   string
    JoinStr    string
    GroupByStr string
    HavingStr  string
    ColumnStr  string

    OmitStr      string
    ConditionStr string
    AltTableName string
    RawSQL       string
    RawParams    []interface{}
    UseCascade   bool
    UseAutoJoin  bool
    StoreEngine  string
    Charset      string
    BeanArgs     []interface{}
    UseCache     bool
    UseAutoTime  bool
    IsDistinct   bool
    // contains filtered or unexported fields
}

statement save all the sql info for executing SQL

func (*Statement) AllCols Uses

func (statement *Statement) AllCols() *Statement

Update use only: update all columns

func (*Statement) And Uses

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

add Where & and statment

func (*Statement) Cols Uses

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

Generate "col1, col2" statement

func (*Statement) Distinct Uses

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

Generate "Distince col1, col2 " statment

func (*Statement) GroupBy Uses

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

Generate "Group By keys" statement

func (*Statement) Having Uses

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

Generate "Having conditions" statement

func (*Statement) Id Uses

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

Generate "where id = ? " statment or for composite key "where key1 = ? and key2 = ?"

func (*Statement) In Uses

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

Generate "Where column IN (?) " statment

func (*Statement) Init Uses

func (statement *Statement) Init()

init

func (*Statement) Join Uses

func (statement *Statement) Join(join_operator, tablename, condition string) *Statement

The join_operator 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

Generate LIMIT start, limit statement

func (*Statement) MustCols Uses

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

Update use only: must update columns

func (*Statement) Omit Uses

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

do not use the columns

func (*Statement) Or Uses

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

add Where & Or statment

func (*Statement) OrderBy Uses

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

Generate "Order By order" statement

func (*Statement) Sql Uses

func (statement *Statement) Sql(querystring string, args ...interface{}) *Statement

add the raw sql statement

func (*Statement) Table Uses

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

tempororily set table name

func (*Statement) TableName Uses

func (statement *Statement) TableName() string

return current tableName

func (*Statement) Top Uses

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

Generate LIMIT limit statement

func (*Statement) UseBool Uses

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

indicates that use bool fields as update contents and query contiditions

func (*Statement) Where Uses

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

add Where statment

type SuffixMapper Uses

type SuffixMapper struct {
    Mapper IMapper
    Suffix string
}

provide suffix table name support

func NewSuffixMapper Uses

func NewSuffixMapper(mapper IMapper, suffix string) SuffixMapper

func (SuffixMapper) Obj2Table Uses

func (mapper SuffixMapper) Obj2Table(name string) string

func (SuffixMapper) Table2Obj Uses

func (mapper SuffixMapper) Table2Obj(name string) string

type SysConnectPool Uses

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

Struct SysConnectPool is a simple wrapper for using system default connection pool. About the system connection pool, you can review the code database/sql/sql.go It's currently default Pool implments.

func (*SysConnectPool) Close Uses

func (p *SysConnectPool) Close(engine *Engine) error

Close closed the only db

func (*SysConnectPool) Init Uses

func (s *SysConnectPool) Init(engine *Engine) error

Init create a db immediately and keep it util engine closed.

func (*SysConnectPool) MaxConns Uses

func (p *SysConnectPool) MaxConns() int

not implemented

func (*SysConnectPool) MaxIdleConns Uses

func (p *SysConnectPool) MaxIdleConns() int

func (*SysConnectPool) ReleaseDB Uses

func (s *SysConnectPool) ReleaseDB(engine *Engine, db *sql.DB)

ReleaseDB do nothing

func (*SysConnectPool) RetrieveDB Uses

func (s *SysConnectPool) RetrieveDB(engine *Engine) (db *sql.DB, err error)

RetrieveDB just return the only db

func (*SysConnectPool) SetMaxConns Uses

func (p *SysConnectPool) SetMaxConns(conns int)

not implemented

func (*SysConnectPool) SetMaxIdleConns Uses

func (p *SysConnectPool) SetMaxIdleConns(conns int)

type Table Uses

type Table struct {
    Name          string
    Type          reflect.Type
    ColumnsSeq    []string
    Columns       map[string]*Column
    Indexes       map[string]*Index
    PrimaryKeys   []string
    AutoIncrement string
    Created       map[string]bool
    Updated       string
    Version       string
    Cacher        Cacher
}

database table

func (*Table) AddColumn Uses

func (table *Table) AddColumn(col *Column)

add a column to table

func (*Table) AddIndex Uses

func (table *Table) AddIndex(index *Index)

add an index or an unique to table

func (*Table) AutoIncrColumn Uses

func (table *Table) AutoIncrColumn() *Column

func (*Table) PKColumns Uses

func (table *Table) PKColumns() []*Column

if has primary key, return column

func (*Table) VersionColumn Uses

func (table *Table) VersionColumn() *Column

Directories

PathSynopsis
examples
xorm

Package xorm imports 18 packages (graph) and is imported by 68 packages. Updated 2017-01-31. Refresh now. Tools for package owners.