xorm/engine.go

1006 lines
26 KiB
Go
Raw Normal View History

2013-05-03 07:26:51 +00:00
package xorm
import (
2013-12-18 03:31:32 +00:00
"bufio"
"bytes"
"database/sql"
"errors"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"sync"
2013-05-03 07:26:51 +00:00
)
const (
2013-12-18 03:31:32 +00:00
POSTGRES = "postgres"
SQLITE = "sqlite3"
MYSQL = "mysql"
MYMYSQL = "mymysql"
2013-12-20 06:53:40 +00:00
MSSQL = "mssql"
2013-12-20 07:11:56 +00:00
2013-12-19 14:32:00 +00:00
ORACLE_OCI = "oci8"
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-12-18 03:31:32 +00:00
Init(DriverName, DataSourceName string) error
2013-12-31 04:22:36 +00:00
URI() *uri
2013-12-20 06:53:40 +00:00
DBType() string
2013-12-18 03:31:32 +00:00
SqlType(t *Column) string
SupportInsertMany() bool
QuoteStr() string
AutoIncrStr() string
SupportEngine() bool
SupportCharset() bool
IndexOnTable() bool
IndexCheckSql(tableName, idxName string) (string, []interface{})
TableCheckSql(tableName string) (string, []interface{})
ColumnCheckSql(tableName, colName string) (string, []interface{})
GetColumns(tableName string) ([]string, map[string]*Column, error)
GetTables() ([]*Table, error)
GetIndexes(tableName string) (map[string]*Index, error)
}
2013-12-17 01:38:20 +00:00
type PK []interface{}
// 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 {
2013-12-18 03:31:32 +00:00
columnMapper IMapper
tableMapper IMapper
TagIdentifier string
DriverName string
DataSourceName string
dialect dialect
Tables map[reflect.Type]*Table
mutex *sync.Mutex
ShowSQL bool
ShowErr bool
ShowDebug bool
ShowWarn bool
Pool IConnectPool
Filters []Filter
Logger io.Writer
Cacher Cacher
UseCache bool
}
2013-11-27 07:53:05 +00:00
func (engine *Engine) SetMapper(mapper IMapper) {
2013-12-18 03:31:32 +00:00
engine.SetTableMapper(mapper)
engine.SetColumnMapper(mapper)
2013-11-27 07:53:05 +00:00
}
func (engine *Engine) SetTableMapper(mapper IMapper) {
2013-12-18 03:31:32 +00:00
engine.tableMapper = mapper
2013-11-27 07:53:05 +00:00
}
func (engine *Engine) SetColumnMapper(mapper IMapper) {
2013-12-18 03:31:32 +00:00
engine.columnMapper = mapper
2013-11-27 07:53:05 +00:00
}
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-12-18 03:31:32 +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-12-18 03:31:32 +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-12-18 03:31:32 +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-12-18 03:31:32 +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-12-18 03:31:32 +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-12-18 03:31:32 +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) {
2013-12-18 03:31:32 +00:00
engine.Pool.SetMaxConns(conns)
2013-09-01 02:37:46 +00:00
}
// SetMaxIdleConns
func (engine *Engine) SetMaxIdleConns(conns int) {
2013-12-18 03:31:32 +00:00
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) {
2013-12-18 03:31:32 +00:00
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCache()
}
2013-12-19 14:32:00 +00:00
func (engine *Engine) NoCascade() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCascade()
}
2013-09-30 07:08:34 +00:00
// Set a table use a special cacher
func (engine *Engine) MapCacher(bean interface{}, cacher Cacher) {
2013-12-18 03:31:32 +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) {
2013-12-18 03:31:32 +00:00
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 {
2013-12-18 03:31:32 +00:00
session := &Session{Engine: engine}
session.Init()
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-12-18 03:31:32 +00:00
return engine.Pool.Close(engine)
}
// Ping tests if database is alive.
func (engine *Engine) Ping() error {
2013-12-18 03:31:32 +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{}) {
2013-12-18 03:31:32 +00:00
if engine.ShowSQL {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// logging error
func (engine *Engine) LogError(contents ...interface{}) {
2013-12-18 03:31:32 +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{}) {
2013-12-18 03:31:32 +00:00
if engine.ShowDebug {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
2013-09-23 15:59:42 +00:00
}
// logging warn
func (engine *Engine) LogWarn(contents ...interface{}) {
2013-12-18 03:31:32 +00:00
if engine.ShowWarn {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
// Sql method let's you manualy write raw sql and operate
// For example:
//
2013-12-09 02:29:23 +00:00
// engine.Sql("select * from user").Find(&users)
//
2013-12-09 02:29:23 +00:00
// 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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Sql(querystring, args...)
2013-07-17 17:26:14 +00:00
}
// 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 {
2013-12-18 03:31:32 +00:00
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) {
2013-12-18 03:31:32 +00:00
tables, err := engine.dialect.GetTables()
if err != nil {
return nil, err
}
for _, table := range tables {
colSeq, cols, err := engine.dialect.GetColumns(table.Name)
if err != nil {
return nil, err
}
table.Columns = cols
table.ColumnsSeq = colSeq
indexes, err := engine.dialect.GetIndexes(table.Name)
if err != nil {
return nil, err
}
table.Indexes = indexes
for _, index := range indexes {
for _, name := range index.Cols {
if col, ok := table.Columns[name]; ok {
col.Indexes[index.Name] = true
} else {
2013-12-20 06:53:40 +00:00
return nil, fmt.Errorf("Unknown col "+name+" in indexes %v", table.Columns)
2013-12-18 03:31:32 +00:00
}
}
}
}
return tables, nil
2013-10-12 15:16:51 +00:00
}
// use cascade or not
2013-07-17 17:26:14 +00:00
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Where(querystring, args...)
2013-05-06 08:01:17 +00:00
}
// Id mehtod provoide a condition as (id) = ?
2013-12-17 01:38:20 +00:00
func (engine *Engine) Id(id interface{}) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Id(id)
2013-05-09 01:56:58 +00:00
}
// Apply before Processor, affected bean is passed to closure arg
func (engine *Engine) Before(closures func(interface{})) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Before(closures)
2013-12-04 10:39:22 +00:00
}
// Apply after insert Processor, affected bean is passed to closure arg
func (engine *Engine) After(closures func(interface{})) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.After(closures)
2013-12-04 10:39:22 +00:00
}
// set charset when create table, only support mysql now
func (engine *Engine) Charset(charset string) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Charset(charset)
}
// set store engine when create table, only support mysql now
func (engine *Engine) StoreEngine(storeEngine string) *Session {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
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 {
2013-12-18 03:31:32 +00:00
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
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 {
2013-12-18 03:31:32 +00:00
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 {
2013-12-18 03:31:32 +00:00
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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-12-18 03:31:32 +00:00
session := engine.NewSession()
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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.
//
2013-12-09 02:29:23 +00:00
// 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-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
session.IsAutoClose = true
return session.Having(conditions)
2013-05-06 08:01:17 +00:00
}
func (engine *Engine) autoMapType(t reflect.Type) *Table {
2013-12-18 03:31:32 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
table, ok := engine.Tables[t]
if !ok {
table = engine.mapType(t)
engine.Tables[t] = table
}
return table
2013-05-13 11:56:38 +00:00
}
func (engine *Engine) autoMap(bean interface{}) *Table {
2013-12-18 03:31:32 +00:00
t := rType(bean)
return engine.autoMapType(t)
2013-05-13 11:56:38 +00:00
}
func (engine *Engine) newTable() *Table {
2013-12-18 03:31:32 +00:00
table := &Table{}
table.Indexes = make(map[string]*Index)
table.Columns = make(map[string]*Column)
table.ColumnsSeq = make([]string, 0)
table.Created = make(map[string]bool)
table.Cacher = engine.Cacher
return table
}
func (engine *Engine) mapType(t reflect.Type) *Table {
2013-12-18 03:31:32 +00:00
table := engine.newTable()
table.Name = engine.tableMapper.Obj2Table(t.Name())
table.Type = t
var idFieldColName string
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
ormTagStr := tag.Get(engine.TagIdentifier)
var col *Column
fieldType := t.Field(i).Type
if ormTagStr != "" {
col = &Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
IsAutoIncrement: false, MapType: TWOSIDES, Indexes: make(map[string]bool)}
tags := strings.Split(ormTagStr, " ")
if len(tags) > 0 {
if tags[0] == "-" {
continue
}
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)
2013-12-25 09:41:01 +00:00
table.Columns[strings.ToLower(name)] = col
2013-12-18 03:31:32 +00:00
table.ColumnsSeq = append(table.ColumnsSeq, name)
}
table.PrimaryKeys = parentTable.PrimaryKeys
2013-12-18 03:31:32 +00:00
continue
}
var indexType int
var indexName string
2014-01-16 15:03:56 +00:00
var preKey string
2013-12-18 03:31:32 +00:00
for j, key := range tags {
k := strings.ToUpper(key)
switch {
case k == "<-":
col.MapType = ONLYFROMDB
case k == "->":
col.MapType = ONLYTODB
case k == "PK":
col.IsPrimaryKey = true
col.Nullable = false
case k == "NULL":
col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT")
case k == "AUTOINCR":
col.IsAutoIncrement = true
case k == "DEFAULT":
col.Default = tags[j+1]
case k == "CREATED":
col.IsCreated = true
case k == "VERSION":
col.IsVersion = true
col.Default = "1"
case k == "UPDATED":
col.IsUpdated = true
case strings.HasPrefix(k, "INDEX(") && strings.HasSuffix(k, ")"):
indexType = IndexType
indexName = k[len("INDEX")+1 : len(k)-1]
case k == "INDEX":
indexType = IndexType
case strings.HasPrefix(k, "UNIQUE(") && strings.HasSuffix(k, ")"):
indexName = k[len("UNIQUE")+1 : len(k)-1]
indexType = UniqueType
case k == "UNIQUE":
indexType = UniqueType
case k == "NOTNULL":
col.Nullable = false
case k == "NOT":
default:
if strings.HasPrefix(k, "'") && strings.HasSuffix(k, "'") {
2014-01-16 15:03:56 +00:00
if preKey != "DEFAULT" {
2013-12-18 03:31:32 +00:00
col.Name = key[1 : len(key)-1]
}
} else if strings.Contains(k, "(") && strings.HasSuffix(k, ")") {
fs := strings.Split(k, "(")
if _, ok := sqlTypes[fs[0]]; !ok {
2014-01-16 15:03:56 +00:00
preKey = k
2013-12-18 03:31:32 +00:00
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}
2014-01-16 15:03:56 +00:00
} else if preKey != "DEFAULT" {
2013-12-18 03:31:32 +00:00
col.Name = key
}
}
engine.SqlType(col)
}
2014-01-16 15:03:56 +00:00
preKey = k
2013-12-18 03:31:32 +00:00
}
if col.SQLType.Name == "" {
col.SQLType = Type2SQLType(fieldType)
}
if col.Length == 0 {
col.Length = col.SQLType.DefaultLength
}
if col.Length2 == 0 {
col.Length2 = col.SQLType.DefaultLength2
}
if col.Name == "" {
col.Name = engine.columnMapper.Obj2Table(t.Field(i).Name)
}
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
}
}
}
} else {
sqlType := Type2SQLType(fieldType)
col = &Column{engine.columnMapper.Obj2Table(t.Field(i).Name), t.Field(i).Name, sqlType,
sqlType.DefaultLength, sqlType.DefaultLength2, true, "", make(map[string]bool), false, false,
TWOSIDES, false, false, false, false}
}
if col.IsAutoIncrement {
col.Nullable = false
}
table.AddColumn(col)
2013-12-20 08:31:26 +00:00
if fieldType.Kind() == reflect.Int64 && (col.FieldName == "Id" || strings.HasSuffix(col.FieldName, ".Id")) {
2013-12-18 03:31:32 +00:00
idFieldColName = col.Name
}
}
if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
2013-12-25 09:41:01 +00:00
col := table.Columns[strings.ToLower(idFieldColName)]
2013-12-18 03:31:32 +00:00
col.IsPrimaryKey = true
col.IsAutoIncrement = true
col.Nullable = false
table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
table.AutoIncrement = col.Name
2013-12-18 03:31:32 +00:00
}
return table
2013-05-03 07:26:51 +00:00
}
2013-09-30 07:08:34 +00:00
// Map a struct to a table
func (engine *Engine) mapping(beans ...interface{}) (e error) {
2013-12-18 03:31:32 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
engine.Tables[t] = engine.mapType(t)
}
return
2013-05-03 07:26:51 +00:00
}
// If a table has any reocrd
2013-09-30 07:08:34 +00:00
func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
2013-12-18 03:31:32 +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-12-18 03:31:32 +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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.CreateIndexes(bean)
2013-10-12 15:16:51 +00:00
}
// create uniques
func (engine *Engine) CreateUniques(bean interface{}) error {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.CreateUniques(bean)
2013-10-12 15:16:51 +00:00
}
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-12-18 03:31:32 +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 {
2013-12-18 03:31:32 +00:00
for _, bean := range beans {
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 {
2013-12-18 03:31:32 +00:00
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
}
}
/*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
}
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
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addColumn(col.Name)
if err != nil {
return err
}
}
}
for name, index := range table.Indexes {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
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
}
}
} 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
}
}
} else {
return errors.New("unknow index type")
}
}
}
}
return nil
}
func (engine *Engine) unMap(beans ...interface{}) (e error) {
2013-12-18 03:31:32 +00:00
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
}
}
return
2013-05-03 07:26:51 +00:00
}
2013-09-30 06:45:34 +00:00
// Drop all mapped table
func (engine *Engine) dropAll() error {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
2013-06-16 03:05:16 +00:00
2013-12-18 03:31:32 +00:00
err := session.Begin()
if err != nil {
return err
}
err = session.dropAll()
if err != nil {
session.Rollback()
return err
}
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
err := session.Begin()
defer session.Close()
if err != nil {
return err
}
for _, bean := range beans {
err = session.CreateTable(bean)
if err != nil {
session.Rollback()
return err
}
}
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
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()
2013-07-27 13:47:22 +00:00
}
func (engine *Engine) createAll() error {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Exec(sql, args...)
2013-05-08 13:42:22 +00:00
}
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Query(sql, paramStr...)
2013-05-08 13:42:22 +00:00
}
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Insert(beans...)
2013-05-03 07:26:51 +00:00
}
2013-11-22 06:11:07 +00:00
// Insert only one record
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
2013-12-18 03:31:32 +00:00
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:
2013-12-09 02:29:23 +00:00
// 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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Delete(bean)
2013-05-03 07:26:51 +00:00
}
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) {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Get(bean)
2013-05-03 07:26:51 +00:00
}
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
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 {
2013-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Iterate(bean, fun)
}
2013-12-26 06:53:20 +00:00
// 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 *Engine) Rows(bean interface{}) (*Rows, error) {
session := engine.NewSession()
return session.Rows(bean)
}
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-12-18 03:31:32 +00:00
session := engine.NewSession()
defer session.Close()
return session.Count(bean)
2013-05-03 07:26:51 +00:00
}
2013-12-04 10:39:22 +00:00
// Import SQL DDL file
func (engine *Engine) Import(ddlPath string) ([]sql.Result, error) {
2013-12-18 03:31:32 +00:00
file, err := os.Open(ddlPath)
if err != nil {
return nil, err
}
defer file.Close()
var results []sql.Result
var lastError error
scanner := bufio.NewScanner(file)
semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, ';'); i >= 0 {
return i + 1, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
scanner.Split(semiColSpliter)
session := engine.NewSession()
2013-12-26 10:31:04 +00:00
defer session.Close()
err = session.newDb()
if err != nil {
return results, err
}
2013-12-18 03:31:32 +00:00
for scanner.Scan() {
query := scanner.Text()
query = strings.Trim(query, " \t")
if len(query) > 0 {
2013-12-26 10:31:04 +00:00
result, err := session.Db.Exec(query)
2013-12-18 03:31:32 +00:00
results = append(results, result)
if err != nil {
lastError = err
}
}
}
return results, lastError
2013-12-04 10:39:22 +00:00
}