xorm/engine.go

501 lines
12 KiB
Go
Raw Normal View History

// Copyright 2013 The XORM Authors. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
// Package xorm provides is a simple and powerful ORM for Go. It makes your
// database operation simple.
2013-05-03 07:26:51 +00:00
package xorm
import (
"database/sql"
"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
)
type dialect interface {
SqlType(t *Column) string
SupportInsertMany() bool
QuoteStr() string
AutoIncrStr() string
SupportEngine() bool
SupportCharset() bool
}
2013-05-03 07:26:51 +00:00
type Engine struct {
Mapper IMapper
TagIdentifier string
DriverName string
DataSourceName string
Dialect dialect
Tables map[reflect.Type]*Table
mutex *sync.Mutex
ShowSQL bool
pool IConnectPool
CacheMapping bool
Filters []Filter
Logger io.Writer
}
func (engine *Engine) SupportInsertMany() bool {
return engine.Dialect.SupportInsertMany()
}
func (engine *Engine) QuoteStr() string {
return engine.Dialect.QuoteStr()
}
func (engine *Engine) Quote(sql string) string {
return engine.Dialect.QuoteStr() + sql + engine.Dialect.QuoteStr()
}
func (engine *Engine) SqlType(c *Column) string {
return engine.Dialect.SqlType(c)
}
func (engine *Engine) AutoIncrStr() string {
return engine.Dialect.AutoIncrStr()
}
func (engine *Engine) SetPool(pool IConnectPool) error {
engine.pool = pool
return engine.pool.Init(engine)
2013-05-06 08:01:17 +00:00
}
func Type(bean interface{}) reflect.Type {
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
return reflect.TypeOf(sliceValue.Interface())
2013-05-03 07:26:51 +00:00
}
2013-05-08 14:50:19 +00:00
func StructName(v reflect.Type) string {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
return v.Name()
}
2013-05-09 01:56:58 +00:00
func (e *Engine) OpenDB() (*sql.DB, error) {
return sql.Open(e.DriverName, e.DataSourceName)
2013-05-03 07:26:51 +00:00
}
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
}
func (engine *Engine) Close() error {
return engine.pool.Close(engine)
}
func (engine *Engine) Test() error {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
defer session.Close()
engine.LogSQL("PING DATABASE", engine.DriverName)
return session.Ping()
}
func (engine *Engine) LogSQL(contents ...interface{}) {
if engine.ShowSQL {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
}
}
func (engine *Engine) LogError(contents ...interface{}) {
io.WriteString(engine.Logger, fmt.Sprintln(contents...))
2013-06-16 03:05:16 +00:00
}
func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.Sql(querystring, args...)
}
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
session := engine.NewSession()
return session.Cascade(trueOrFalse...)
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) Where(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.Where(querystring, args...)
2013-05-06 08:01:17 +00:00
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) Id(id int64) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.Id(id)
2013-05-09 01:56:58 +00:00
}
func (engine *Engine) Charset(charset string) *Session {
session := engine.NewSession()
return session.Charset(charset)
}
func (engine *Engine) StoreEngine(storeEngine string) *Session {
session := engine.NewSession()
return session.StoreEngine(storeEngine)
}
func (engine *Engine) Cols(columns ...string) *Session {
session := engine.NewSession()
return session.Cols(columns...)
}
func (engine *Engine) Trans(t string) *Session {
session := engine.NewSession()
return session.Trans(t)
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) In(column string, args ...interface{}) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.In(column, args...)
2013-05-11 08:27:17 +00:00
}
func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
2013-06-16 03:05:16 +00:00
session := engine.NewSession()
return session.Table(tableNameOrBean)
2013-05-19 05:25:52 +00:00
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) Limit(limit int, start ...int) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.Limit(limit, start...)
2013-05-06 08:01:17 +00:00
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) OrderBy(order string) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.OrderBy(order)
2013-05-06 08:01:17 +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-07-17 17:26:14 +00:00
return session.Join(join_operator, tablename, condition)
2013-05-06 08:01:17 +00:00
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) GroupBy(keys string) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.GroupBy(keys)
2013-05-06 08:01:17 +00:00
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) Having(conditions string) *Session {
session := engine.NewSession()
2013-07-17 17:26:14 +00:00
return session.Having(conditions)
2013-05-06 08:01:17 +00:00
}
2013-06-16 03:05:16 +00:00
// some lock needed
2013-05-13 11:56:38 +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 {
t := Type(bean)
return engine.AutoMapType(t)
}
2013-06-16 03:05:16 +00:00
func (engine *Engine) MapType(t reflect.Type) *Table {
table := &Table{Name: engine.Mapper.Obj2Table(t.Name()), Type: t,
Indexes: map[string][]string{}, Uniques: map[string][]string{}}
2013-08-08 16:03:33 +00:00
table.Columns = make(map[string]*Column)
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,
IsAutoIncrement: false, MapType: TWOSIDES}
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-08-08 16:03:33 +00:00
table.PrimaryKey = parentTable.PrimaryKey
continue
}
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
table.PrimaryKey = col.Name
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-08-08 16:03:33 +00:00
case strings.HasPrefix(k, "INDEX"):
if k == "INDEX" {
col.IndexName = ""
col.IndexType = SINGLEINDEX
} else {
2013-08-08 16:03:33 +00:00
col.IndexName = k[len("INDEX")+1 : len(k)-1]
col.IndexType = UNIONINDEX
}
2013-08-08 16:03:33 +00:00
case strings.HasPrefix(k, "UNIQUE"):
if k == "UNIQUE" {
col.UniqueName = ""
col.UniqueType = SINGLEUNIQUE
} else {
2013-08-08 16:03:33 +00:00
col.UniqueName = k[len("UNIQUE")+1 : len(k)-1]
col.UniqueType = UNIONUNIQUE
}
2013-08-08 16:03:33 +00:00
case k == "NOT":
2013-05-03 07:26:51 +00:00
default:
2013-08-08 16:03:33 +00:00
if strings.Contains(k, "(") && strings.HasSuffix(k, ")") {
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}
} else if k != col.Default {
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)
}
if col.IndexType == SINGLEINDEX {
col.IndexName = col.Name
table.Indexes[col.IndexName] = []string{col.Name}
} else if col.IndexType == UNIONINDEX {
if unionIdxes, ok := table.Indexes[col.IndexName]; ok {
table.Indexes[col.IndexName] = append(unionIdxes, col.Name)
} else {
table.Indexes[col.IndexName] = []string{col.Name}
}
}
if col.UniqueType == SINGLEUNIQUE {
col.UniqueName = col.Name
table.Uniques[col.UniqueName] = []string{col.Name}
} else if col.UniqueType == UNIONUNIQUE {
if unionUniques, ok := table.Uniques[col.UniqueName]; ok {
table.Uniques[col.UniqueName] = append(unionUniques, col.Name)
} else {
table.Uniques[col.UniqueName] = []string{col.Name}
}
}
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,
sqlType.DefaultLength, sqlType.DefaultLength2, true, "", NONEUNIQUE, "", NONEINDEX, "", false, false, TWOSIDES}
2013-05-03 07:26:51 +00:00
2013-08-08 16:03:33 +00:00
}
if col.IsAutoIncrement {
col.Nullable = false
}
if col.IsPrimaryKey {
table.PrimaryKey = col.Name
2013-05-03 07:26:51 +00:00
}
table.Columns[col.Name] = 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-06-16 03:05:16 +00:00
// Map should use after all operation because it's not thread safe
2013-05-03 07:26:51 +00:00
func (engine *Engine) Map(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-05-08 14:50:19 +00:00
t := Type(bean)
engine.Tables[t] = engine.MapType(t)
2013-05-03 07:26:51 +00:00
}
return
}
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-05-08 14:50:19 +00:00
t := Type(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
2013-05-03 07:26:51 +00:00
}
}
return
}
func (e *Engine) DropAll() error {
2013-06-16 03:05:16 +00:00
session := e.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-06-16 03:05:16 +00:00
err = session.DropAll()
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
}
func (e *Engine) CreateTables(beans ...interface{}) error {
2013-06-16 03:05:16 +00:00
session := e.NewSession()
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-07-27 13:47:22 +00:00
func (e *Engine) DropTables(beans ...interface{}) error {
session := e.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-05-03 07:26:51 +00:00
func (e *Engine) CreateAll() error {
2013-06-16 03:05:16 +00:00
session := e.NewSession()
2013-05-03 07:26:51 +00:00
defer session.Close()
return session.CreateAll()
2013-05-03 07:26:51 +00:00
}
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...)
}
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-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...)
}
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.InsertOne(bean)
}
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
}
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-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-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
}
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)
}