2016-11-04 03:46:01 +05:30
|
|
|
// Copyright 2015 The Xorm Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package xorm
|
|
|
|
|
|
|
|
import (
|
2019-06-23 20:52:43 +05:30
|
|
|
"context"
|
2020-06-16 02:16:01 +05:30
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
2016-11-04 03:46:01 +05:30
|
|
|
"database/sql"
|
2020-06-16 02:16:01 +05:30
|
|
|
"encoding/hex"
|
2016-11-04 03:46:01 +05:30
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"hash/crc32"
|
2020-06-16 02:16:01 +05:30
|
|
|
"io"
|
2016-11-04 03:46:01 +05:30
|
|
|
"reflect"
|
2021-08-13 04:41:42 +05:30
|
|
|
"strconv"
|
2016-11-04 03:46:01 +05:30
|
|
|
"strings"
|
|
|
|
|
2020-03-22 20:42:55 +05:30
|
|
|
"xorm.io/xorm/contexts"
|
|
|
|
"xorm.io/xorm/convert"
|
|
|
|
"xorm.io/xorm/core"
|
|
|
|
"xorm.io/xorm/internal/json"
|
|
|
|
"xorm.io/xorm/internal/statements"
|
2020-06-16 02:16:01 +05:30
|
|
|
"xorm.io/xorm/log"
|
2020-03-22 20:42:55 +05:30
|
|
|
"xorm.io/xorm/schemas"
|
2019-06-23 20:52:43 +05:30
|
|
|
)
|
|
|
|
|
2020-03-22 20:42:55 +05:30
|
|
|
// ErrFieldIsNotExist columns does not exist
|
|
|
|
type ErrFieldIsNotExist struct {
|
|
|
|
FieldName string
|
|
|
|
TableName string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrFieldIsNotExist) Error() string {
|
2021-08-13 04:41:42 +05:30
|
|
|
return fmt.Sprintf("field %s is not exist on table %s", e.FieldName, e.TableName)
|
2020-03-22 20:42:55 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// ErrFieldIsNotValid is not valid
|
|
|
|
type ErrFieldIsNotValid struct {
|
|
|
|
FieldName string
|
|
|
|
TableName string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrFieldIsNotValid) Error() string {
|
|
|
|
return fmt.Sprintf("field %s is not valid on table %s", e.FieldName, e.TableName)
|
|
|
|
}
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
type sessionType bool
|
2019-06-23 20:52:43 +05:30
|
|
|
|
|
|
|
const (
|
2020-06-16 02:16:01 +05:30
|
|
|
engineSession sessionType = false
|
|
|
|
groupSession sessionType = true
|
2016-11-04 03:46:01 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
// Session keep a pointer to sql.DB and provides all execution of all
|
|
|
|
// kind of database operations.
|
|
|
|
type Session struct {
|
2017-08-22 17:09:52 +05:30
|
|
|
engine *Engine
|
|
|
|
tx *core.Tx
|
2020-03-22 20:42:55 +05:30
|
|
|
statement *statements.Statement
|
2017-08-22 17:09:52 +05:30
|
|
|
isAutoCommit bool
|
|
|
|
isCommitedOrRollbacked bool
|
|
|
|
isAutoClose bool
|
2020-06-16 02:16:01 +05:30
|
|
|
isClosed bool
|
|
|
|
prepareStmt bool
|
2016-11-04 03:46:01 +05:30
|
|
|
// Automatically reset the statement after operations that execute a SQL
|
|
|
|
// query such as Count(), Find(), Get(), ...
|
2017-08-22 17:09:52 +05:30
|
|
|
autoResetStatement bool
|
2016-11-04 03:46:01 +05:30
|
|
|
|
|
|
|
// !nashtsai! storing these beans due to yet committed tx
|
|
|
|
afterInsertBeans map[interface{}]*[]func(interface{})
|
|
|
|
afterUpdateBeans map[interface{}]*[]func(interface{})
|
|
|
|
afterDeleteBeans map[interface{}]*[]func(interface{})
|
|
|
|
// --
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
beforeClosures []func(interface{})
|
|
|
|
afterClosures []func(interface{})
|
2017-10-01 22:22:35 +05:30
|
|
|
afterProcessors []executedProcessor
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr))
|
2016-11-04 03:46:01 +05:30
|
|
|
|
|
|
|
lastSQL string
|
|
|
|
lastSQLArgs []interface{}
|
2017-08-22 17:09:52 +05:30
|
|
|
|
2019-06-23 20:52:43 +05:30
|
|
|
ctx context.Context
|
|
|
|
sessionType sessionType
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
func newSessionID() string {
|
|
|
|
hash := sha256.New()
|
|
|
|
_, err := io.CopyN(hash, rand.Reader, 50)
|
|
|
|
if err != nil {
|
|
|
|
return "????????????????????"
|
|
|
|
}
|
|
|
|
md := hash.Sum(nil)
|
|
|
|
mdStr := hex.EncodeToString(md)
|
|
|
|
return mdStr[0:20]
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
func newSession(engine *Engine) *Session {
|
|
|
|
var ctx context.Context
|
|
|
|
if engine.logSessionID {
|
2020-09-03 07:28:04 +05:30
|
|
|
ctx = context.WithValue(engine.defaultContext, log.SessionIDKey, newSessionID())
|
2020-06-16 02:16:01 +05:30
|
|
|
} else {
|
|
|
|
ctx = engine.defaultContext
|
|
|
|
}
|
2019-06-23 20:52:43 +05:30
|
|
|
|
2020-07-21 17:58:27 +05:30
|
|
|
session := &Session{
|
2020-06-16 02:16:01 +05:30
|
|
|
ctx: ctx,
|
|
|
|
engine: engine,
|
|
|
|
tx: nil,
|
|
|
|
statement: statements.NewStatement(
|
|
|
|
engine.dialect,
|
|
|
|
engine.tagParser,
|
|
|
|
engine.DatabaseTZ,
|
|
|
|
),
|
|
|
|
isClosed: false,
|
|
|
|
isAutoCommit: true,
|
|
|
|
isCommitedOrRollbacked: false,
|
|
|
|
isAutoClose: false,
|
|
|
|
autoResetStatement: true,
|
|
|
|
prepareStmt: false,
|
|
|
|
|
|
|
|
afterInsertBeans: make(map[interface{}]*[]func(interface{}), 0),
|
|
|
|
afterUpdateBeans: make(map[interface{}]*[]func(interface{}), 0),
|
|
|
|
afterDeleteBeans: make(map[interface{}]*[]func(interface{}), 0),
|
|
|
|
beforeClosures: make([]func(interface{}), 0),
|
|
|
|
afterClosures: make([]func(interface{}), 0),
|
|
|
|
afterProcessors: make([]executedProcessor, 0),
|
|
|
|
stmtCache: make(map[uint32]*core.Stmt),
|
|
|
|
|
|
|
|
lastSQL: "",
|
|
|
|
lastSQLArgs: make([]interface{}, 0),
|
|
|
|
|
|
|
|
sessionType: engineSession,
|
|
|
|
}
|
2020-07-21 17:58:27 +05:30
|
|
|
if engine.logSessionID {
|
|
|
|
session.ctx = context.WithValue(session.ctx, log.SessionKey, session)
|
|
|
|
}
|
|
|
|
return session
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// Close release the connection from pool
|
2020-06-16 02:16:01 +05:30
|
|
|
func (session *Session) Close() error {
|
2016-11-04 03:46:01 +05:30
|
|
|
for _, v := range session.stmtCache {
|
2020-06-16 02:16:01 +05:30
|
|
|
if err := v.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
if !session.isClosed {
|
2016-11-04 03:46:01 +05:30
|
|
|
// When Close be called, if session is a transaction and do not call
|
|
|
|
// Commit or Rollback, then call Rollback.
|
2017-08-22 17:09:52 +05:30
|
|
|
if session.tx != nil && !session.isCommitedOrRollbacked {
|
2020-06-16 02:16:01 +05:30
|
|
|
if err := session.Rollback(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2017-08-22 17:09:52 +05:30
|
|
|
session.tx = nil
|
2016-11-04 03:46:01 +05:30
|
|
|
session.stmtCache = nil
|
2020-06-16 02:16:01 +05:30
|
|
|
session.isClosed = true
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2020-06-16 02:16:01 +05:30
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *Session) db() *core.DB {
|
|
|
|
return session.engine.db
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2021-05-15 00:47:06 +05:30
|
|
|
// Engine returns session Engine
|
2020-07-21 17:58:27 +05:30
|
|
|
func (session *Session) Engine() *Engine {
|
|
|
|
return session.engine
|
|
|
|
}
|
|
|
|
|
2020-03-25 20:02:23 +05:30
|
|
|
func (session *Session) getQueryer() core.Queryer {
|
|
|
|
if session.tx != nil {
|
|
|
|
return session.tx
|
|
|
|
}
|
2020-06-16 02:16:01 +05:30
|
|
|
return session.db()
|
2020-03-25 20:02:23 +05:30
|
|
|
}
|
|
|
|
|
2018-12-12 06:31:41 +05:30
|
|
|
// ContextCache enable context cache or not
|
2020-03-22 20:42:55 +05:30
|
|
|
func (session *Session) ContextCache(context contexts.ContextCache) *Session {
|
|
|
|
session.statement.SetContextCache(context)
|
2018-12-12 06:31:41 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2017-08-22 17:09:52 +05:30
|
|
|
// IsClosed returns if session is closed
|
|
|
|
func (session *Session) IsClosed() bool {
|
2020-06-16 02:16:01 +05:30
|
|
|
return session.isClosed
|
2017-08-22 17:09:52 +05:30
|
|
|
}
|
|
|
|
|
2016-11-04 03:46:01 +05:30
|
|
|
func (session *Session) resetStatement() {
|
2017-08-22 17:09:52 +05:30
|
|
|
if session.autoResetStatement {
|
2020-03-22 20:42:55 +05:30
|
|
|
session.statement.Reset()
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-23 14:41:18 +05:30
|
|
|
// Prepare set a flag to session that should be prepare statement before execute query
|
2016-11-04 03:46:01 +05:30
|
|
|
func (session *Session) Prepare() *Session {
|
|
|
|
session.prepareStmt = true
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Before Apply before Processor, affected bean is passed to closure arg
|
|
|
|
func (session *Session) Before(closures func(interface{})) *Session {
|
|
|
|
if closures != nil {
|
|
|
|
session.beforeClosures = append(session.beforeClosures, closures)
|
|
|
|
}
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// After Apply after Processor, affected bean is passed to closure arg
|
|
|
|
func (session *Session) After(closures func(interface{})) *Session {
|
|
|
|
if closures != nil {
|
|
|
|
session.afterClosures = append(session.afterClosures, closures)
|
|
|
|
}
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Table can input a string or pointer to struct for special a table to operate.
|
|
|
|
func (session *Session) Table(tableNameOrBean interface{}) *Session {
|
2020-03-22 20:42:55 +05:30
|
|
|
if err := session.statement.SetTable(tableNameOrBean); err != nil {
|
|
|
|
session.statement.LastError = err
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Alias set the table alias
|
|
|
|
func (session *Session) Alias(alias string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Alias(alias)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// NoCascade indicate that no cascade load child object
|
|
|
|
func (session *Session) NoCascade() *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.UseCascade = false
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// ForUpdate Set Read/Write locking for UPDATE
|
|
|
|
func (session *Session) ForUpdate() *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.IsForUpdate = true
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// NoAutoCondition disable generate SQL condition from beans
|
|
|
|
func (session *Session) NoAutoCondition(no ...bool) *Session {
|
2020-03-22 20:42:55 +05:30
|
|
|
session.statement.SetNoAutoCondition(no...)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Limit provide limit and offset query condition
|
|
|
|
func (session *Session) Limit(limit int, start ...int) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Limit(limit, start...)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// OrderBy provide order by query condition, the input parameter is the content
|
|
|
|
// after order by on a sql statement.
|
|
|
|
func (session *Session) OrderBy(order string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.OrderBy(order)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Desc provide desc order by query condition, the input parameters are columns.
|
|
|
|
func (session *Session) Desc(colNames ...string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Desc(colNames...)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Asc provide asc order by query condition, the input parameters are columns.
|
|
|
|
func (session *Session) Asc(colNames ...string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Asc(colNames...)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// StoreEngine is only avialble mysql dialect currently
|
|
|
|
func (session *Session) StoreEngine(storeEngine string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.StoreEngine = storeEngine
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Charset is only avialble mysql dialect currently
|
|
|
|
func (session *Session) Charset(charset string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Charset = charset
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cascade indicates if loading sub Struct
|
|
|
|
func (session *Session) Cascade(trueOrFalse ...bool) *Session {
|
|
|
|
if len(trueOrFalse) >= 1 {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.UseCascade = trueOrFalse[0]
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2019-12-18 18:37:36 +05:30
|
|
|
// MustLogSQL means record SQL or not and don't follow engine's setting
|
2020-06-16 02:16:01 +05:30
|
|
|
func (session *Session) MustLogSQL(logs ...bool) *Session {
|
2020-03-22 20:42:55 +05:30
|
|
|
var showSQL = true
|
2020-06-16 02:16:01 +05:30
|
|
|
if len(logs) > 0 {
|
|
|
|
showSQL = logs[0]
|
2019-12-18 18:37:36 +05:30
|
|
|
}
|
2020-06-16 02:16:01 +05:30
|
|
|
session.ctx = context.WithValue(session.ctx, log.SessionShowSQLKey, showSQL)
|
2019-12-18 18:37:36 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2016-11-04 03:46:01 +05:30
|
|
|
// NoCache ask this session do not retrieve data from cache system and
|
|
|
|
// get data from database directly.
|
|
|
|
func (session *Session) NoCache() *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.UseCache = false
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
|
|
|
|
func (session *Session) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Join(joinOperator, tablename, condition, args...)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// GroupBy Generate Group By statement
|
|
|
|
func (session *Session) GroupBy(keys string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.GroupBy(keys)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Having Generate Having statement
|
|
|
|
func (session *Session) Having(conditions string) *Session {
|
2017-08-22 17:09:52 +05:30
|
|
|
session.statement.Having(conditions)
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// DB db return the wrapper of sql.DB
|
|
|
|
func (session *Session) DB() *core.DB {
|
2020-06-16 02:16:01 +05:30
|
|
|
return session.db()
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2017-01-03 13:50:28 +05:30
|
|
|
func (session *Session) canCache() bool {
|
2017-08-22 17:09:52 +05:30
|
|
|
if session.statement.RefTable == nil ||
|
|
|
|
session.statement.JoinStr != "" ||
|
|
|
|
session.statement.RawSQL != "" ||
|
|
|
|
!session.statement.UseCache ||
|
|
|
|
session.statement.IsForUpdate ||
|
|
|
|
session.tx != nil ||
|
2020-03-22 20:42:55 +05:30
|
|
|
len(session.statement.SelectStr) > 0 {
|
2017-01-03 13:50:28 +05:30
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2018-01-27 20:50:59 +05:30
|
|
|
func (session *Session) doPrepare(db *core.DB, sqlStr string) (stmt *core.Stmt, err error) {
|
2017-01-03 13:50:28 +05:30
|
|
|
crc := crc32.ChecksumIEEE([]byte(sqlStr))
|
|
|
|
// TODO try hash(sqlStr+len(sqlStr))
|
|
|
|
var has bool
|
|
|
|
stmt, has = session.stmtCache[crc]
|
|
|
|
if !has {
|
2019-06-23 20:52:43 +05:30
|
|
|
stmt, err = db.PrepareContext(session.ctx, sqlStr)
|
2016-11-04 03:46:01 +05:30
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-03 13:50:28 +05:30
|
|
|
session.stmtCache[crc] = stmt
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2017-01-03 13:50:28 +05:30
|
|
|
return
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) getField(dataStruct *reflect.Value, table *schemas.Table, colName string, idx int) (*schemas.Column, *reflect.Value, error) {
|
|
|
|
var col = table.GetColumnIdx(colName, idx)
|
|
|
|
if col == nil {
|
|
|
|
return nil, nil, ErrFieldIsNotExist{colName, table.Name}
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2017-01-03 13:50:28 +05:30
|
|
|
fieldValue, err := col.ValueOfV(dataStruct)
|
|
|
|
if err != nil {
|
2021-08-13 04:41:42 +05:30
|
|
|
return nil, nil, err
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2021-07-04 18:40:46 +05:30
|
|
|
if fieldValue == nil {
|
2021-08-13 04:41:42 +05:30
|
|
|
return nil, nil, ErrFieldIsNotValid{colName, table.Name}
|
2021-07-04 18:40:46 +05:30
|
|
|
}
|
2017-01-03 13:50:28 +05:30
|
|
|
if !fieldValue.IsValid() || !fieldValue.CanSet() {
|
2021-08-13 04:41:42 +05:30
|
|
|
return nil, nil, ErrFieldIsNotValid{colName, table.Name}
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2018-07-20 07:40:17 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
return col, fieldValue, nil
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2017-01-03 13:50:28 +05:30
|
|
|
// Cell cell is a result of one column field
|
|
|
|
type Cell *interface{}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) rows2Beans(rows *core.Rows, fields []string, types []*sql.ColumnType,
|
2020-03-22 20:42:55 +05:30
|
|
|
table *schemas.Table, newElemFunc func([]string) reflect.Value,
|
|
|
|
sliceValueSetFunc func(*reflect.Value, schemas.PK) error) error {
|
2017-01-03 13:50:28 +05:30
|
|
|
for rows.Next() {
|
2017-04-07 07:17:25 +05:30
|
|
|
var newValue = newElemFunc(fields)
|
2017-01-03 13:50:28 +05:30
|
|
|
bean := newValue.Interface()
|
2017-10-01 22:22:35 +05:30
|
|
|
dataStruct := newValue.Elem()
|
2017-09-13 10:48:22 +05:30
|
|
|
|
2017-08-22 17:09:52 +05:30
|
|
|
// handle beforeClosures
|
2021-08-13 04:41:42 +05:30
|
|
|
scanResults, err := session.row2Slice(rows, fields, types, bean)
|
2017-08-22 17:09:52 +05:30
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-10-01 22:22:35 +05:30
|
|
|
pk, err := session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
|
2016-11-04 03:46:01 +05:30
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-10-01 22:22:35 +05:30
|
|
|
session.afterProcessors = append(session.afterProcessors, executedProcessor{
|
|
|
|
fun: func(*Session, interface{}) error {
|
|
|
|
return sliceValueSetFunc(&newValue, pk)
|
|
|
|
},
|
|
|
|
session: session,
|
|
|
|
bean: bean,
|
|
|
|
})
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
return rows.Err()
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) row2Slice(rows *core.Rows, fields []string, types []*sql.ColumnType, bean interface{}) ([]interface{}, error) {
|
2017-05-02 06:20:33 +05:30
|
|
|
for _, closure := range session.beforeClosures {
|
|
|
|
closure(bean)
|
|
|
|
}
|
|
|
|
|
2017-10-01 22:22:35 +05:30
|
|
|
scanResults := make([]interface{}, len(fields))
|
2017-01-03 13:50:28 +05:30
|
|
|
for i := 0; i < len(fields); i++ {
|
|
|
|
var cell interface{}
|
|
|
|
scanResults[i] = &cell
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
if err := session.engine.scan(rows, fields, types, scanResults...); err != nil {
|
2017-02-20 17:03:10 +05:30
|
|
|
return nil, err
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
|
2020-06-16 02:16:01 +05:30
|
|
|
executeBeforeSet(bean, fields, scanResults)
|
|
|
|
|
2017-08-22 17:09:52 +05:30
|
|
|
return scanResults, nil
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) setJSON(fieldValue *reflect.Value, fieldType reflect.Type, scanResult interface{}) error {
|
|
|
|
bs, ok := convert.AsBytes(scanResult)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("unsupported database data type: %#v", scanResult)
|
|
|
|
}
|
|
|
|
if len(bs) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2017-10-01 22:22:35 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if fieldType.Kind() == reflect.String {
|
|
|
|
fieldValue.SetString(string(bs))
|
|
|
|
return nil
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if fieldValue.CanAddr() {
|
|
|
|
err := json.DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
|
2018-07-20 07:40:17 +05:30
|
|
|
if err != nil {
|
2021-08-13 04:41:42 +05:30
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
} else {
|
|
|
|
x := reflect.New(fieldType)
|
|
|
|
err := json.DefaultJSONHandler.Unmarshal(bs, x.Interface())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
fieldValue.Set(x.Elem())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2017-01-03 13:50:28 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func asKind(vv reflect.Value, tp reflect.Type) (interface{}, error) {
|
|
|
|
switch tp.Kind() {
|
|
|
|
case reflect.Ptr:
|
|
|
|
return asKind(vv.Elem(), tp.Elem())
|
|
|
|
case reflect.Int64:
|
|
|
|
return vv.Int(), nil
|
|
|
|
case reflect.Int:
|
|
|
|
return int(vv.Int()), nil
|
|
|
|
case reflect.Int32:
|
|
|
|
return int32(vv.Int()), nil
|
|
|
|
case reflect.Int16:
|
|
|
|
return int16(vv.Int()), nil
|
|
|
|
case reflect.Int8:
|
|
|
|
return int8(vv.Int()), nil
|
|
|
|
case reflect.Uint64:
|
|
|
|
return vv.Uint(), nil
|
|
|
|
case reflect.Uint:
|
|
|
|
return uint(vv.Uint()), nil
|
|
|
|
case reflect.Uint32:
|
|
|
|
return uint32(vv.Uint()), nil
|
|
|
|
case reflect.Uint16:
|
|
|
|
return uint16(vv.Uint()), nil
|
|
|
|
case reflect.Uint8:
|
|
|
|
return uint8(vv.Uint()), nil
|
|
|
|
case reflect.String:
|
|
|
|
return vv.String(), nil
|
|
|
|
case reflect.Slice:
|
|
|
|
if tp.Elem().Kind() == reflect.Uint8 {
|
|
|
|
v, err := strconv.ParseInt(string(vv.Interface().([]byte)), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return v, nil
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("unsupported primary key type: %v, %v", tp, vv)
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) convertBeanField(col *schemas.Column, fieldValue *reflect.Value,
|
|
|
|
scanResult interface{}, table *schemas.Table) error {
|
|
|
|
v, ok := scanResult.(*interface{})
|
|
|
|
if ok {
|
|
|
|
scanResult = *v
|
|
|
|
}
|
|
|
|
if scanResult == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if fieldValue.CanAddr() {
|
|
|
|
if structConvert, ok := fieldValue.Addr().Interface().(convert.Conversion); ok {
|
|
|
|
data, ok := convert.AsBytes(scanResult)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("cannot convert %#v as bytes", scanResult)
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
return structConvert.FromDB(data)
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if structConvert, ok := fieldValue.Interface().(convert.Conversion); ok {
|
|
|
|
data, ok := convert.AsBytes(scanResult)
|
|
|
|
if !ok {
|
|
|
|
return fmt.Errorf("cannot convert %#v as bytes", scanResult)
|
|
|
|
}
|
|
|
|
if data == nil {
|
|
|
|
return nil
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
|
|
|
|
fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
|
|
|
|
return fieldValue.Interface().(convert.Conversion).FromDB(data)
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
return structConvert.FromDB(data)
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
vv := reflect.ValueOf(scanResult)
|
|
|
|
fieldType := fieldValue.Type()
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if col.IsJSON {
|
|
|
|
return session.setJSON(fieldValue, fieldType, scanResult)
|
|
|
|
}
|
|
|
|
|
|
|
|
switch fieldType.Kind() {
|
|
|
|
case reflect.Ptr:
|
|
|
|
var e reflect.Value
|
|
|
|
if fieldValue.IsNil() {
|
|
|
|
e = reflect.New(fieldType.Elem()).Elem()
|
|
|
|
} else {
|
|
|
|
e = fieldValue.Elem()
|
|
|
|
}
|
|
|
|
if err := session.convertBeanField(col, &e, scanResult, table); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if fieldValue.IsNil() {
|
|
|
|
fieldValue.Set(e.Addr())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
case reflect.Complex64, reflect.Complex128:
|
|
|
|
return session.setJSON(fieldValue, fieldType, scanResult)
|
|
|
|
case reflect.Slice, reflect.Array:
|
|
|
|
bs, ok := convert.AsBytes(scanResult)
|
|
|
|
if ok && fieldType.Elem().Kind() == reflect.Uint8 {
|
|
|
|
if col.SQLType.IsText() {
|
|
|
|
x := reflect.New(fieldType)
|
|
|
|
err := json.DefaultJSONHandler.Unmarshal(bs, x.Interface())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
fieldValue.Set(x.Elem())
|
|
|
|
} else {
|
|
|
|
if fieldValue.Len() > 0 {
|
|
|
|
for i := 0; i < fieldValue.Len(); i++ {
|
|
|
|
if i < vv.Len() {
|
|
|
|
fieldValue.Index(i).Set(vv.Index(i))
|
|
|
|
}
|
2018-01-27 20:50:59 +05:30
|
|
|
}
|
2018-07-20 07:40:17 +05:30
|
|
|
} else {
|
2021-08-13 04:41:42 +05:30
|
|
|
for i := 0; i < vv.Len(); i++ {
|
|
|
|
fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
|
2017-01-03 13:50:28 +05:30
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
return nil
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
case reflect.Struct:
|
|
|
|
if fieldType.ConvertibleTo(schemas.BigFloatType) {
|
|
|
|
v, err := convert.AsBigFloat(scanResult)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
fieldValue.Set(reflect.ValueOf(v).Elem().Convert(fieldType))
|
|
|
|
return nil
|
|
|
|
}
|
2018-07-20 07:40:17 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if fieldType.ConvertibleTo(schemas.TimeType) {
|
|
|
|
dbTZ := session.engine.DatabaseTZ
|
|
|
|
if col.TimeZone != nil {
|
|
|
|
dbTZ = col.TimeZone
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
|
|
|
|
t, err := convert.AsTime(scanResult, dbTZ, session.engine.TZLocation)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
|
|
|
|
fieldValue.Set(reflect.ValueOf(*t).Convert(fieldType))
|
|
|
|
return nil
|
|
|
|
} else if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
|
|
|
|
err := nulVal.Scan(scanResult)
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
session.engine.logger.Errorf("sql.Sanner error: %v", err)
|
|
|
|
} else if session.statement.UseCascade {
|
|
|
|
table, err := session.engine.tagParser.ParseWithCache(*fieldValue)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
|
|
|
|
if len(table.PrimaryKeys) != 1 {
|
|
|
|
return errors.New("unsupported non or composited primary key cascade")
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
var pk = make(schemas.PK, len(table.PrimaryKeys))
|
|
|
|
pk[0], err = asKind(vv, reflect.TypeOf(scanResult))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-20 07:40:17 +05:30
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if !pk.IsZero() {
|
|
|
|
// !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
|
|
|
|
// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
|
|
|
|
// property to be fetched lazily
|
|
|
|
structInter := reflect.New(fieldValue.Type())
|
|
|
|
has, err := session.ID(pk).NoCascade().get(structInter.Interface())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if has {
|
|
|
|
fieldValue.Set(structInter.Elem())
|
|
|
|
} else {
|
|
|
|
return errors.New("cascade obj is not exist")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
} // switch fieldType.Kind()
|
2017-04-07 07:17:25 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
return convert.AssignValue(fieldValue.Addr(), scanResult)
|
|
|
|
}
|
2016-11-04 03:46:01 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
func (session *Session) slice2Bean(scanResults []interface{}, fields []string, bean interface{}, dataStruct *reflect.Value, table *schemas.Table) (schemas.PK, error) {
|
|
|
|
defer func() {
|
|
|
|
executeAfterSet(bean, fields, scanResults)
|
|
|
|
}()
|
2017-04-07 07:17:25 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
buildAfterProcessors(session, bean)
|
2017-05-02 06:20:33 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
var tempMap = make(map[string]int)
|
|
|
|
var pk schemas.PK
|
|
|
|
for i, colName := range fields {
|
|
|
|
var idx int
|
|
|
|
var lKey = strings.ToLower(colName)
|
|
|
|
var ok bool
|
2018-07-20 07:40:17 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if idx, ok = tempMap[lKey]; !ok {
|
|
|
|
idx = 0
|
|
|
|
} else {
|
|
|
|
idx = idx + 1
|
|
|
|
}
|
|
|
|
tempMap[lKey] = idx
|
2018-07-20 07:40:17 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
col, fieldValue, err := session.getField(dataStruct, table, colName, idx)
|
|
|
|
if err != nil {
|
|
|
|
if _, ok := err.(ErrFieldIsNotExist); ok {
|
|
|
|
continue
|
|
|
|
} else {
|
2018-07-20 07:40:17 +05:30
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-13 04:41:42 +05:30
|
|
|
}
|
|
|
|
if fieldValue == nil {
|
|
|
|
continue
|
|
|
|
}
|
2018-07-20 07:40:17 +05:30
|
|
|
|
2021-08-13 04:41:42 +05:30
|
|
|
if err := session.convertBeanField(col, fieldValue, scanResults[i], table); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if col.IsPrimaryKey {
|
|
|
|
pk = append(pk, scanResults[i])
|
2016-11-04 03:46:01 +05:30
|
|
|
}
|
|
|
|
}
|
2017-02-20 17:03:10 +05:30
|
|
|
return pk, nil
|
2017-01-03 13:50:28 +05:30
|
|
|
}
|
|
|
|
|
2016-11-04 03:46:01 +05:30
|
|
|
// saveLastSQL stores executed query information
|
|
|
|
func (session *Session) saveLastSQL(sql string, args ...interface{}) {
|
|
|
|
session.lastSQL = sql
|
|
|
|
session.lastSQLArgs = args
|
|
|
|
}
|
|
|
|
|
|
|
|
// LastSQL returns last query information
|
|
|
|
func (session *Session) LastSQL() (string, []interface{}) {
|
|
|
|
return session.lastSQL, session.lastSQLArgs
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unscoped always disable struct tag "deleted"
|
|
|
|
func (session *Session) Unscoped() *Session {
|
2020-03-22 20:42:55 +05:30
|
|
|
session.statement.SetUnscoped()
|
2016-11-04 03:46:01 +05:30
|
|
|
return session
|
|
|
|
}
|
2018-12-12 06:31:41 +05:30
|
|
|
|
|
|
|
func (session *Session) incrVersionFieldValue(fieldValue *reflect.Value) {
|
|
|
|
switch fieldValue.Kind() {
|
|
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
|
|
fieldValue.SetInt(fieldValue.Int() + 1)
|
|
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
|
|
|
fieldValue.SetUint(fieldValue.Uint() + 1)
|
|
|
|
}
|
|
|
|
}
|
2020-03-22 20:42:55 +05:30
|
|
|
|
2021-05-15 00:47:06 +05:30
|
|
|
// Context sets the context on this session
|
2020-03-22 20:42:55 +05:30
|
|
|
func (session *Session) Context(ctx context.Context) *Session {
|
|
|
|
session.ctx = ctx
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// PingContext test if database is ok
|
|
|
|
func (session *Session) PingContext(ctx context.Context) error {
|
|
|
|
if session.isAutoClose {
|
|
|
|
defer session.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
session.engine.logger.Infof("PING DATABASE %v", session.engine.DriverName())
|
|
|
|
return session.DB().PingContext(ctx)
|
|
|
|
}
|