xorm/engine.go

898 lines
24 KiB
Go
Raw Normal View History

2013-05-03 07:26:51 +00:00
package xorm
import (
"database/sql"
"errors"
"fmt"
"io"
2013-05-03 07:26:51 +00:00
"reflect"
"strconv"
"strings"
2013-06-16 03:05:16 +00:00
"sync"
2013-05-03 07:26:51 +00:00
)
const (
POSTGRES = "postgres"
SQLITE = "sqlite3"
MYSQL = "mysql"
MYMYSQL = "mymysql"
2013-05-03 07:26:51 +00:00
)
2013-09-30 07:08:34 +00:00
// a dialect is a driver's wrapper
type dialect interface {
2013-10-12 15:16:51 +00:00
Init(DriverName, DataSourceName string) error
SqlType(t *Column) string
SupportInsertMany() bool
QuoteStr() string
AutoIncrStr() string
SupportEngine() bool
SupportCharset() bool
2013-09-26 07:19:39 +00:00
IndexOnTable() bool
IndexCheckSql(tableName, idxName string) (string, []interface{})
TableCheckSql(tableName string) (string, []interface{})
ColumnCheckSql(tableName, colName string) (string, []interface{})
2013-10-12 15:16:51 +00:00
GetColumns(tableName string) ([]string, map[string]*Column, error)
2013-10-12 15:16:51 +00:00
GetTables() ([]*Table, error)
GetIndexes(tableName string) (map[string]*Index, error)
}
// Engine is the major struct of xorm, it means a database manager.
// Commonly, an application only need one engine
2013-05-03 07:26:51 +00:00
type Engine struct {
Mapper IMapper
TagIdentifier string
DriverName string
DataSourceName string
2013-10-12 15:16:51 +00:00
dialect dialect
Tables map[reflect.Type]*Table
mutex *sync.Mutex
ShowSQL bool
2013-09-23 02:20:45 +00:00
ShowErr bool
ShowDebug bool
ShowWarn bool
2013-08-29 09:26:33 +00:00
Pool IConnectPool
Filters []Filter
Logger io.Writer
Cacher Cacher
UseCache bool
}
2013-09-30 07:08:34 +00:00
// 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 *Engine) SupportInsertMany() bool {
2013-10-12 15:16:51 +00:00
return engine.dialect.SupportInsertMany()
}
2013-09-30 07:08:34 +00:00
// Engine's database use which charactor as quote.
// mysql, sqlite use ` and postgres use "
func (engine *Engine) QuoteStr() string {
2013-10-12 15:16:51 +00:00
return engine.dialect.QuoteStr()
}
2013-09-30 07:08:34 +00:00
// Use QuoteStr quote the string sql
func (engine *Engine) Quote(sql string) string {
2013-10-12 15:16:51 +00:00
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
}
2013-09-30 07:08:34 +00:00
// A simple wrapper to dialect's SqlType method
func (engine *Engine) SqlType(c *Column) string {
2013-10-12 15:16:51 +00:00
return engine.dialect.SqlType(c)
}
2013-09-30 07:08:34 +00:00
// Database's autoincrement statement
func (engine *Engine) AutoIncrStr() string {
2013-10-12 15:16:51 +00:00
return engine.dialect.AutoIncrStr()
}
2013-09-30 07:08:34 +00:00
// Set engine's pool, the pool default is Go's standard library's connection pool.
func (engine *Engine) SetPool(pool IConnectPool) error {
2013-08-29 09:26:33 +00:00
engine.Pool = pool
return engine.Pool.Init(engine)
2013-05-06 08:01:17 +00:00
}
2013-09-30 07:08:34 +00:00
// SetMaxConns is only available for go 1.2+
2013-09-01 02:37:46 +00:00
func (engine *Engine) SetMaxConns(conns int) {
engine.Pool.SetMaxConns(conns)
}
// SetMaxIdleConns
func (engine *Engine) SetMaxIdleConns(conns int) {
engine.Pool.SetMaxIdleConns(conns)
}
2013-09-30 07:08:34 +00:00
// SetDefaltCacher set the default cacher. Xorm's default not enable cacher.
func (engine *Engine) SetDefaultCacher(cacher Cacher) {
if cacher == nil {
engine.UseCache = false
} else {
engine.UseCache = true
engine.Cacher = cacher
}
}
2013-09-30 07:08:34 +00:00
// If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
2013-09-22 09:32:23 +00:00
func (engine *Engine) NoCache() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCache()
}
2013-09-30 07:08:34 +00:00
// Set a table use a special cacher
func (engine *Engine) MapCacher(bean interface{}, cacher Cacher) {
2013-09-30 01:17:35 +00:00
t := rType(bean)
engine.autoMapType(t)
engine.Tables[t].Cacher = cacher
}
2013-09-30 07:08:34 +00:00
// OpenDB provides a interface to operate database directly.
2013-09-30 06:45:34 +00:00
func (engine *Engine) OpenDB() (*sql.DB, error) {
return sql.Open(engine.DriverName, engine.DataSourceName)
2013-05-03 07:26:51 +00:00
}
2013-09-30 07:08:34 +00:00
// New a session
2013-06-16 03:05:16 +00:00
func (engine *Engine) NewSession() *Session {
session := &Session{Engine: engine}
2013-05-03 07:26:51 +00:00
session.Init()
2013-06-16 03:05:16 +00:00
return session
2013-05-03 07:26:51 +00:00
}
2013-09-30 07:08:34 +00:00
// Close the engine
func (engine *Engine) Close() error {
2013-08-29 09:26:33 +00:00
return engine.Pool.Close(engine)
}
// Ping tests if database is alive.
func (engine *Engine) Ping() error {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
defer session.Close()
engine.LogSQL("PING DATABASE", engine.DriverName)
return session.Ping()
}
// logging sql
func (engine *Engine) LogSQL(contents ...interface{}) {
if engine.ShowSQL {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging error
func (engine *Engine) LogError(contents ...interface{}) {
2013-09-23 02:20:45 +00:00
if engine.ShowErr {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
2013-06-16 03:05:16 +00:00
}
// logging debug
2013-09-23 15:59:42 +00:00
func (engine *Engine) LogDebug(contents ...interface{}) {
if engine.ShowDebug {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging warn
func (engine *Engine) LogWarn(contents ...interface{}) {
if engine.ShowWarn {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// 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
//
2013-06-16 03:05:16 +00:00
func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Sql(querystring, args...)
}
// 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 *Engine) NoAutoTime() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoAutoTime()
}
// Retrieve all tables, columns, indexes' informations from database.
2013-10-12 15:16:51 +00:00
func (engine *Engine) DBMetas() ([]*Table, error) {
tables, err := engine.dialect.GetTables()
if err != nil {
return nil, err
}
for _, table := range tables {
colSeq, cols, err := engine.dialect.GetColumns(table.Name)
2013-10-12 15:16:51 +00:00
if err != nil {
return nil, err
}
table.Columns = cols
table.ColumnsSeq = colSeq
2013-10-12 15:16:51 +00:00
indexes, err := engine.dialect.GetIndexes(table.Name)
if err != nil {
return nil, err
}
table.Indexes = indexes
2013-10-13 15:57:57 +00:00
for _, index := range indexes {
for _, name := range index.Cols {
if col, ok := table.Columns[name]; ok {
col.Indexes[index.Name] = true
} else {
return nil, errors.New("Unkonwn col " + name + " in indexes")
}
}
}
2013-10-12 15:16:51 +00:00
}
return tables, nil
}
// use cascade or not
2013-07-17 17:26:14 +00:00
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Cascade(trueOrFalse...)
}
// Where method provide a condition query
2013-06-16 03:05:16 +00:00
func (engine *Engine) Where(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Where(querystring, args...)
2013-05-06 08:01:17 +00:00
}
// Id mehtod provoide a condition as (id) = ?
2013-06-16 03:05:16 +00:00
func (engine *Engine) Id(id int64) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Id(id)
2013-05-09 01:56:58 +00:00
}
// set charset when create table, only support mysql now
func (engine *Engine) Charset(charset string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
return session.Charset(charset)
}
// set store engine when create table, only support mysql now
func (engine *Engine) StoreEngine(storeEngine string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
return session.StoreEngine(storeEngine)
}
// 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 *Engine) Distinct(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Distinct(columns...)
}
// only use the paramters as select or update columns
func (engine *Engine) Cols(columns ...string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
return session.Cols(columns...)
}
// 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 *Engine) UseBool(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.UseBool(columns...)
}
// Only not use the paramters as select or update columns
func (engine *Engine) Omit(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Omit(columns...)
}
// This method will generate "column IN (?, ?)"
2013-06-16 03:05:16 +00:00
func (engine *Engine) In(column string, args ...interface{}) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.In(column, args...)
2013-05-11 08:27:17 +00:00
}
// Temporarily change the Get, Find, Update's table
func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
return session.Table(tableNameOrBean)
2013-05-19 05:25:52 +00:00
}
// This method will generate "LIMIT start, limit"
2013-06-16 03:05:16 +00:00
func (engine *Engine) Limit(limit int, start ...int) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Limit(limit, start...)
2013-05-06 08:01:17 +00:00
}
// Method Desc will generate "ORDER BY column1 DESC, column2 DESC"
// This will
2013-09-02 02:06:32 +00:00
func (engine *Engine) Desc(colNames ...string) *Session {
2013-09-02 01:54:37 +00:00
session := engine.NewSession()
session.IsAutoClose = true
2013-09-02 02:06:32 +00:00
return session.Desc(colNames...)
2013-09-02 01:54:37 +00:00
}
// 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
//
2013-09-02 02:06:32 +00:00
func (engine *Engine) Asc(colNames ...string) *Session {
2013-09-02 01:54:37 +00:00
session := engine.NewSession()
session.IsAutoClose = true
2013-09-02 02:06:32 +00:00
return session.Asc(colNames...)
2013-09-02 01:54:37 +00:00
}
// Method OrderBy will generate "ORDER BY order"
2013-06-16 03:05:16 +00:00
func (engine *Engine) OrderBy(order string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.OrderBy(order)
2013-05-06 08:01:17 +00:00
}
2013-11-22 06:11:07 +00:00
// The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
2013-06-16 03:05:16 +00:00
func (engine *Engine) Join(join_operator, tablename, condition string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Join(join_operator, tablename, condition)
2013-05-06 08:01:17 +00:00
}
2013-11-22 06:11:07 +00:00
// Generate Group By statement
2013-06-16 03:05:16 +00:00
func (engine *Engine) GroupBy(keys string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.GroupBy(keys)
2013-05-06 08:01:17 +00:00
}
2013-11-22 06:11:07 +00:00
// Generate Having statement
2013-06-16 03:05:16 +00:00
func (engine *Engine) Having(conditions string) *Session {
session := engine.NewSession()
2013-09-02 01:54:37 +00:00
session.IsAutoClose = true
2013-07-17 17:26:14 +00:00
return session.Having(conditions)
2013-05-06 08:01:17 +00:00
}
func (engine *Engine) autoMapType(t reflect.Type) *Table {
2013-06-16 03:05:16 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
2013-05-13 11:56:38 +00:00
table, ok := engine.Tables[t]
if !ok {
table = engine.mapType(t)
2013-06-16 07:10:35 +00:00
engine.Tables[t] = table
2013-05-13 11:56:38 +00:00
}
2013-06-16 03:05:16 +00:00
return table
2013-05-13 11:56:38 +00:00
}
func (engine *Engine) autoMap(bean interface{}) *Table {
2013-09-30 01:17:35 +00:00
t := rType(bean)
return engine.autoMapType(t)
2013-05-13 11:56:38 +00:00
}
func (engine *Engine) newTable() *Table {
table := &Table{}
table.Indexes = make(map[string]*Index)
table.Columns = make(map[string]*Column)
table.ColumnsSeq = make([]string, 0)
table.Cacher = engine.Cacher
return table
}
func (engine *Engine) mapType(t reflect.Type) *Table {
table := engine.newTable()
2013-09-01 03:01:10 +00:00
table.Name = engine.Mapper.Obj2Table(t.Name())
table.Type = t
2013-08-08 16:03:33 +00:00
var idFieldColName string
2013-05-03 07:26:51 +00:00
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
2013-05-19 05:25:52 +00:00
ormTagStr := tag.Get(engine.TagIdentifier)
2013-08-08 16:03:33 +00:00
var col *Column
2013-05-03 07:26:51 +00:00
fieldType := t.Field(i).Type
if ormTagStr != "" {
2013-08-08 16:03:33 +00:00
col = &Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
2013-10-12 15:16:51 +00:00
IsAutoIncrement: false, MapType: TWOSIDES, Indexes: make(map[string]bool)}
2013-05-03 07:26:51 +00:00
tags := strings.Split(ormTagStr, " ")
2013-08-08 16:03:33 +00:00
2013-05-03 07:26:51 +00:00
if len(tags) > 0 {
if tags[0] == "-" {
continue
}
2013-08-08 16:03:33 +00:00
if (strings.ToUpper(tags[0]) == "EXTENDS") &&
(fieldType.Kind() == reflect.Struct) {
parentTable := engine.mapType(fieldType)
for name, col := range parentTable.Columns {
col.FieldName = fmt.Sprintf("%v.%v", fieldType.Name(), col.FieldName)
table.Columns[name] = col
2013-09-01 03:01:10 +00:00
table.ColumnsSeq = append(table.ColumnsSeq, name)
}
2013-08-08 16:03:33 +00:00
table.PrimaryKey = parentTable.PrimaryKey
continue
}
2013-10-12 15:16:51 +00:00
var indexType int
var indexName string
2013-05-03 07:26:51 +00:00
for j, key := range tags {
2013-08-08 16:03:33 +00:00
k := strings.ToUpper(key)
2013-05-13 05:24:45 +00:00
switch {
case k == "<-":
col.MapType = ONLYFROMDB
case k == "->":
col.MapType = ONLYTODB
2013-08-08 16:03:33 +00:00
case k == "PK":
2013-05-03 07:26:51 +00:00
col.IsPrimaryKey = true
2013-05-13 11:56:38 +00:00
col.Nullable = false
2013-08-08 16:03:33 +00:00
case k == "NULL":
col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT")
case k == "AUTOINCR":
2013-05-06 08:01:17 +00:00
col.IsAutoIncrement = true
2013-08-08 16:03:33 +00:00
case k == "DEFAULT":
2013-05-03 07:26:51 +00:00
col.Default = tags[j+1]
2013-09-02 14:50:40 +00:00
case k == "CREATED":
col.IsCreated = true
case k == "VERSION":
col.IsVersion = true
col.Default = "1"
2013-09-02 14:50:40 +00:00
case k == "UPDATED":
col.IsUpdated = true
case strings.HasPrefix(k, "INDEX(") && strings.HasSuffix(k, ")"):
2013-10-12 15:16:51 +00:00
indexType = IndexType
indexName = k[len("INDEX")+1 : len(k)-1]
case k == "INDEX":
2013-10-12 15:16:51 +00:00
indexType = IndexType
case strings.HasPrefix(k, "UNIQUE(") && strings.HasSuffix(k, ")"):
2013-10-12 15:16:51 +00:00
indexName = k[len("UNIQUE")+1 : len(k)-1]
indexType = UniqueType
case k == "UNIQUE":
2013-10-12 15:16:51 +00:00
indexType = UniqueType
case k == "NOTNULL":
col.Nullable = false
2013-08-08 16:03:33 +00:00
case k == "NOT":
2013-05-03 07:26:51 +00:00
default:
2013-09-02 14:50:40 +00:00
if strings.HasPrefix(k, "'") && strings.HasSuffix(k, "'") {
if key != col.Default {
col.Name = key[1 : len(key)-1]
}
} else if strings.Contains(k, "(") && strings.HasSuffix(k, ")") {
2013-08-08 16:03:33 +00:00
fs := strings.Split(k, "(")
if _, ok := sqlTypes[fs[0]]; !ok {
continue
}
col.SQLType = SQLType{fs[0], 0, 0}
fs2 := strings.Split(fs[1][0:len(fs[1])-1], ",")
if len(fs2) == 2 {
col.Length, _ = strconv.Atoi(fs2[0])
col.Length2, _ = strconv.Atoi(fs2[1])
} else if len(fs2) == 1 {
col.Length, _ = strconv.Atoi(fs2[0])
}
} else {
if _, ok := sqlTypes[k]; ok {
col.SQLType = SQLType{k, 0, 0}
2013-09-02 14:50:40 +00:00
} else if key != col.Default {
2013-08-08 16:03:33 +00:00
col.Name = key
}
2013-05-13 05:24:45 +00:00
}
2013-08-08 16:03:33 +00:00
engine.SqlType(col)
2013-05-03 07:26:51 +00:00
}
}
if col.SQLType.Name == "" {
col.SQLType = Type2SQLType(fieldType)
2013-05-13 05:24:45 +00:00
}
if col.Length == 0 {
2013-05-03 07:26:51 +00:00
col.Length = col.SQLType.DefaultLength
2013-05-13 05:24:45 +00:00
}
if col.Length2 == 0 {
2013-05-06 08:01:17 +00:00
col.Length2 = col.SQLType.DefaultLength2
2013-05-03 07:26:51 +00:00
}
if col.Name == "" {
col.Name = engine.Mapper.Obj2Table(t.Field(i).Name)
}
2013-10-12 15:16:51 +00:00
if indexType == IndexType {
if indexName == "" {
indexName = col.Name
}
if index, ok := table.Indexes[indexName]; ok {
index.AddColumn(col.Name)
col.Indexes[index.Name] = true
} else {
index := NewIndex(indexName, IndexType)
index.AddColumn(col.Name)
table.AddIndex(index)
col.Indexes[index.Name] = true
}
} else if indexType == UniqueType {
if indexName == "" {
indexName = col.Name
}
if index, ok := table.Indexes[indexName]; ok {
index.AddColumn(col.Name)
col.Indexes[index.Name] = true
} else {
index := NewIndex(indexName, UniqueType)
index.AddColumn(col.Name)
table.AddIndex(index)
col.Indexes[index.Name] = true
}
}
2013-05-03 07:26:51 +00:00
}
} else {
2013-05-03 07:26:51 +00:00
sqlType := Type2SQLType(fieldType)
2013-08-08 16:03:33 +00:00
col = &Column{engine.Mapper.Obj2Table(t.Field(i).Name), t.Field(i).Name, sqlType,
2013-10-12 15:16:51 +00:00
sqlType.DefaultLength, sqlType.DefaultLength2, true, "", make(map[string]bool), false, false,
TWOSIDES, false, false, false, false}
2013-08-08 16:03:33 +00:00
}
if col.IsAutoIncrement {
col.Nullable = false
}
2013-09-01 03:01:10 +00:00
table.AddColumn(col)
2013-08-08 16:03:33 +00:00
if col.FieldName == "Id" || strings.HasSuffix(col.FieldName, ".Id") {
idFieldColName = col.Name
}
}
if idFieldColName != "" && table.PrimaryKey == "" {
col := table.Columns[idFieldColName]
col.IsPrimaryKey = true
col.IsAutoIncrement = true
col.Nullable = false
table.PrimaryKey = col.Name
2013-05-03 07:26:51 +00:00
}
return table
}
2013-09-30 07:08:34 +00:00
// Map a struct to a table
func (engine *Engine) mapping(beans ...interface{}) (e error) {
2013-06-16 03:05:16 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
2013-05-03 07:26:51 +00:00
for _, bean := range beans {
2013-09-30 01:17:35 +00:00
t := rType(bean)
engine.Tables[t] = engine.mapType(t)
2013-05-03 07:26:51 +00:00
}
return
}
// If a table has any reocrd
2013-09-30 07:08:34 +00:00
func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
2013-09-30 01:17:35 +00:00
t := rType(bean)
if t.Kind() != reflect.Struct {
return false, errors.New("bean should be a struct or struct's point")
}
engine.autoMapType(t)
session := engine.NewSession()
defer session.Close()
rows, err := session.Count(bean)
return rows > 0, err
}
// If a table is exist
func (engine *Engine) IsTableExist(bean interface{}) (bool, error) {
2013-09-30 01:17:35 +00:00
t := rType(bean)
if t.Kind() != reflect.Struct {
return false, errors.New("bean should be a struct or struct's point")
}
table := engine.autoMapType(t)
session := engine.NewSession()
defer session.Close()
has, err := session.isTableExist(table.Name)
return has, err
}
2013-10-12 15:16:51 +00:00
// create indexes
func (engine *Engine) CreateIndexes(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateIndexes(bean)
}
// create uniques
func (engine *Engine) CreateUniques(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateUniques(bean)
}
2013-09-30 06:45:34 +00:00
// If enabled cache, clear the cache bean
func (engine *Engine) ClearCacheBean(bean interface{}, id int64) error {
2013-09-30 01:17:35 +00:00
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.autoMap(bean)
if table.Cacher != nil {
table.Cacher.ClearIds(table.Name)
table.Cacher.DelBean(table.Name, id)
}
return nil
}
2013-09-30 06:45:34 +00:00
// If enabled cache, clear some tables' cache
func (engine *Engine) ClearCache(beans ...interface{}) error {
for _, bean := range beans {
2013-09-30 01:17:35 +00:00
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.autoMap(bean)
if table.Cacher != nil {
table.Cacher.ClearIds(table.Name)
table.Cacher.ClearBeans(table.Name)
}
}
return nil
}
// Sync the new struct changes to database, this method will automatically add
2013-09-30 06:45:34 +00:00
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
func (engine *Engine) Sync(beans ...interface{}) error {
for _, bean := range beans {
table := engine.autoMap(bean)
s := engine.NewSession()
defer s.Close()
isExist, err := s.Table(bean).isTableExist(table.Name)
if err != nil {
return err
}
if !isExist {
err = engine.CreateTables(bean)
if err != nil {
return err
}
2013-09-29 01:02:01 +00:00
}
/*isEmpty, err := engine.IsEmptyTable(bean)
if err != nil {
return err
}*/
var isEmpty bool = false
if isEmpty {
err = engine.DropTables(bean)
if err != nil {
return err
2013-09-29 01:02:01 +00:00
}
err = engine.CreateTables(bean)
if err != nil {
return err
}
} else {
for _, col := range table.Columns {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
isExist, err := session.isColumnExist(table.Name, col.Name)
if err != nil {
return err
}
2013-09-29 01:02:01 +00:00
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
2013-09-29 01:02:01 +00:00
err = session.addColumn(col.Name)
if err != nil {
return err
}
}
2013-09-29 01:02:01 +00:00
}
for name, index := range table.Indexes {
2013-09-29 01:02:01 +00:00
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
2013-10-12 15:16:51 +00:00
if index.Type == UniqueType {
//isExist, err := session.isIndexExist(table.Name, name, true)
isExist, err := session.isIndexExist2(table.Name, index.Cols, true)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addUnique(table.Name, name)
if err != nil {
return err
}
}
2013-10-12 15:16:51 +00:00
} else if index.Type == IndexType {
isExist, err := session.isIndexExist2(table.Name, index.Cols, false)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addIndex(table.Name, name)
if err != nil {
return err
}
}
2013-10-12 15:16:51 +00:00
} else {
return errors.New("unknow index type")
}
}
}
}
return nil
}
func (engine *Engine) unMap(beans ...interface{}) (e error) {
2013-06-16 03:05:16 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
2013-05-03 07:26:51 +00:00
for _, bean := range beans {
2013-09-30 01:17:35 +00:00
t := rType(bean)
2013-05-08 14:50:19 +00:00
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
2013-05-03 07:26:51 +00:00
}
}
return
}
2013-09-30 06:45:34 +00:00
// Drop all mapped table
func (engine *Engine) dropAll() error {
2013-09-30 06:48:17 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
2013-06-16 03:05:16 +00:00
err := session.Begin()
2013-05-03 07:26:51 +00:00
if err != nil {
return err
}
2013-11-22 06:11:07 +00:00
err = session.dropAll()
2013-06-16 03:05:16 +00:00
if err != nil {
session.Rollback()
return err
2013-05-03 07:26:51 +00:00
}
2013-05-08 14:50:19 +00:00
return session.Commit()
2013-05-03 07:26:51 +00:00
}
2013-09-30 06:45:34 +00:00
// CreateTables create tabls according bean
2013-09-30 06:48:17 +00:00
func (engine *Engine) CreateTables(beans ...interface{}) error {
session := engine.NewSession()
2013-06-16 03:05:16 +00:00
err := session.Begin()
2013-06-21 04:33:54 +00:00
defer session.Close()
2013-05-03 07:26:51 +00:00
if err != nil {
return err
}
2013-05-03 07:26:51 +00:00
for _, bean := range beans {
2013-05-19 05:25:52 +00:00
err = session.CreateTable(bean)
2013-05-03 07:26:51 +00:00
if err != nil {
session.Rollback()
2013-05-08 14:50:19 +00:00
return err
2013-05-03 07:26:51 +00:00
}
}
2013-05-08 14:50:19 +00:00
return session.Commit()
2013-05-03 07:26:51 +00:00
}
2013-09-30 06:48:17 +00:00
func (engine *Engine) DropTables(beans ...interface{}) error {
session := engine.NewSession()
2013-07-27 13:47:22 +00:00
err := session.Begin()
defer session.Close()
if err != nil {
return err
}
for _, bean := range beans {
err = session.DropTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) createAll() error {
2013-09-30 06:48:17 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
2013-11-22 06:11:07 +00:00
return session.createAll()
2013-05-03 07:26:51 +00:00
}
2013-11-22 06:11:07 +00:00
// Exec raw sql
2013-05-08 13:42:22 +00:00
func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-08 13:42:22 +00:00
defer session.Close()
return session.Exec(sql, args...)
}
2013-11-22 06:11:07 +00:00
// Exec a raw sql and return records as []map[string][]byte
2013-05-08 13:42:22 +00:00
func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-08 13:42:22 +00:00
defer session.Close()
return session.Query(sql, paramStr...)
}
2013-11-22 06:11:07 +00:00
// Insert one or more records
2013-05-03 07:26:51 +00:00
func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
return session.Insert(beans...)
}
2013-11-22 06:11:07 +00:00
// Insert only one record
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.InsertOne(bean)
}
2013-11-22 06:11:07 +00:00
// 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
2013-05-08 13:42:22 +00:00
func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
2013-05-08 13:42:22 +00:00
return session.Update(bean, condiBeans...)
2013-05-03 07:26:51 +00:00
}
2013-11-22 06:11:07 +00:00
// Delete records, bean's non-empty fields are conditions
2013-05-03 07:26:51 +00:00
func (engine *Engine) Delete(bean interface{}) (int64, error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
return session.Delete(bean)
}
2013-11-22 06:11:07 +00:00
// Get retrieve one record from table, bean's non-empty fields
// are conditions
2013-06-16 03:05:16 +00:00
func (engine *Engine) Get(bean interface{}) (bool, error) {
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
return session.Get(bean)
}
2013-11-22 06:11:07 +00:00
// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
2013-05-08 13:42:22 +00:00
func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
2013-05-08 13:42:22 +00:00
return session.Find(beans, condiBeans...)
2013-05-03 07:26:51 +00:00
}
2013-11-22 06:11:07 +00:00
// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.
func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
session := engine.NewSession()
defer session.Close()
return session.Iterate(bean, fun)
}
2013-11-22 06:11:07 +00:00
// Count counts the records. bean's non-empty fields
// are conditions.
2013-05-03 07:26:51 +00:00
func (engine *Engine) Count(bean interface{}) (int64, error) {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
return session.Count(bean)
}