2016-11-03 18:16:01 -04:00
|
|
|
// 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 11:22:43 -04:00
|
|
|
"context"
|
2020-06-15 16:46:01 -04:00
|
|
|
"crypto/rand"
|
|
|
|
"crypto/sha256"
|
2016-11-03 18:16:01 -04:00
|
|
|
"database/sql"
|
2020-06-15 16:46:01 -04:00
|
|
|
"encoding/hex"
|
2016-11-03 18:16:01 -04:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"hash/crc32"
|
2020-06-15 16:46:01 -04:00
|
|
|
"io"
|
2016-11-03 18:16:01 -04:00
|
|
|
"reflect"
|
2021-08-12 19:11:42 -04:00
|
|
|
"strconv"
|
2016-11-03 18:16:01 -04:00
|
|
|
"strings"
|
|
|
|
|
2020-03-22 11:12:55 -04:00
|
|
|
"xorm.io/xorm/contexts"
|
|
|
|
"xorm.io/xorm/convert"
|
|
|
|
"xorm.io/xorm/core"
|
|
|
|
"xorm.io/xorm/internal/json"
|
|
|
|
"xorm.io/xorm/internal/statements"
|
2020-06-15 16:46:01 -04:00
|
|
|
"xorm.io/xorm/log"
|
2020-03-22 11:12:55 -04:00
|
|
|
"xorm.io/xorm/schemas"
|
2019-06-23 11:22:43 -04:00
|
|
|
)
|
|
|
|
|
2020-03-22 11:12:55 -04:00
|
|
|
// ErrFieldIsNotExist columns does not exist
|
|
|
|
type ErrFieldIsNotExist struct {
|
|
|
|
FieldName string
|
|
|
|
TableName string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ErrFieldIsNotExist) Error() string {
|
2021-08-12 19:11:42 -04:00
|
|
|
return fmt.Sprintf("field %s is not exist on table %s", e.FieldName, e.TableName)
|
2020-03-22 11:12:55 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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-15 16:46:01 -04:00
|
|
|
type sessionType bool
|
2019-06-23 11:22:43 -04:00
|
|
|
|
|
|
|
const (
|
2020-06-15 16:46:01 -04:00
|
|
|
engineSession sessionType = false
|
|
|
|
groupSession sessionType = true
|
2016-11-03 18:16:01 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// Session keep a pointer to sql.DB and provides all execution of all
|
|
|
|
// kind of database operations.
|
|
|
|
type Session struct {
|
2017-08-22 07:39:52 -04:00
|
|
|
engine *Engine
|
|
|
|
tx *core.Tx
|
2020-03-22 11:12:55 -04:00
|
|
|
statement *statements.Statement
|
2017-08-22 07:39:52 -04:00
|
|
|
isAutoCommit bool
|
|
|
|
isCommitedOrRollbacked bool
|
|
|
|
isAutoClose bool
|
2020-06-15 16:46:01 -04:00
|
|
|
isClosed bool
|
|
|
|
prepareStmt bool
|
2016-11-03 18:16:01 -04:00
|
|
|
// Automatically reset the statement after operations that execute a SQL
|
|
|
|
// query such as Count(), Find(), Get(), ...
|
2017-08-22 07:39:52 -04:00
|
|
|
autoResetStatement bool
|
2016-11-03 18:16:01 -04:00
|
|
|
|
|
|
|
// !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-15 16:46:01 -04:00
|
|
|
beforeClosures []func(interface{})
|
|
|
|
afterClosures []func(interface{})
|
2017-10-01 12:52:35 -04:00
|
|
|
afterProcessors []executedProcessor
|
|
|
|
|
2020-06-15 16:46:01 -04:00
|
|
|
stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr))
|
2016-11-03 18:16:01 -04:00
|
|
|
|
|
|
|
lastSQL string
|
|
|
|
lastSQLArgs []interface{}
|
2017-08-22 07:39:52 -04:00
|
|
|
|
2019-06-23 11:22:43 -04:00
|
|
|
ctx context.Context
|
|
|
|
sessionType sessionType
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2020-06-15 16:46:01 -04:00
|
|
|
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-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2020-06-15 16:46:01 -04:00
|
|
|
func newSession(engine *Engine) *Session {
|
|
|
|
var ctx context.Context
|
|
|
|
if engine.logSessionID {
|
2020-09-02 21:58:04 -04:00
|
|
|
ctx = context.WithValue(engine.defaultContext, log.SessionIDKey, newSessionID())
|
2020-06-15 16:46:01 -04:00
|
|
|
} else {
|
|
|
|
ctx = engine.defaultContext
|
|
|
|
}
|
2019-06-23 11:22:43 -04:00
|
|
|
|
2020-07-21 08:28:27 -04:00
|
|
|
session := &Session{
|
2020-06-15 16:46:01 -04:00
|
|
|
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 08:28:27 -04:00
|
|
|
if engine.logSessionID {
|
|
|
|
session.ctx = context.WithValue(session.ctx, log.SessionKey, session)
|
|
|
|
}
|
|
|
|
return session
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Close release the connection from pool
|
2020-06-15 16:46:01 -04:00
|
|
|
func (session *Session) Close() error {
|
2016-11-03 18:16:01 -04:00
|
|
|
for _, v := range session.stmtCache {
|
2020-06-15 16:46:01 -04:00
|
|
|
if err := v.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2020-06-15 16:46:01 -04:00
|
|
|
if !session.isClosed {
|
2016-11-03 18:16:01 -04:00
|
|
|
// When Close be called, if session is a transaction and do not call
|
|
|
|
// Commit or Rollback, then call Rollback.
|
2017-08-22 07:39:52 -04:00
|
|
|
if session.tx != nil && !session.isCommitedOrRollbacked {
|
2020-06-15 16:46:01 -04:00
|
|
|
if err := session.Rollback(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2017-08-22 07:39:52 -04:00
|
|
|
session.tx = nil
|
2016-11-03 18:16:01 -04:00
|
|
|
session.stmtCache = nil
|
2020-06-15 16:46:01 -04:00
|
|
|
session.isClosed = true
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2020-06-15 16:46:01 -04:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (session *Session) db() *core.DB {
|
|
|
|
return session.engine.db
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2021-05-14 15:17:06 -04:00
|
|
|
// Engine returns session Engine
|
2020-07-21 08:28:27 -04:00
|
|
|
func (session *Session) Engine() *Engine {
|
|
|
|
return session.engine
|
|
|
|
}
|
|
|
|
|
2021-09-16 13:53:28 -04:00
|
|
|
// Tx returns session tx
|
|
|
|
func (session *Session) Tx() *core.Tx {
|
|
|
|
return session.tx
|
|
|
|
}
|
|
|
|
|
2020-03-25 10:32:23 -04:00
|
|
|
func (session *Session) getQueryer() core.Queryer {
|
|
|
|
if session.tx != nil {
|
|
|
|
return session.tx
|
|
|
|
}
|
2020-06-15 16:46:01 -04:00
|
|
|
return session.db()
|
2020-03-25 10:32:23 -04:00
|
|
|
}
|
|
|
|
|
2018-12-11 20:01:41 -05:00
|
|
|
// ContextCache enable context cache or not
|
2020-03-22 11:12:55 -04:00
|
|
|
func (session *Session) ContextCache(context contexts.ContextCache) *Session {
|
|
|
|
session.statement.SetContextCache(context)
|
2018-12-11 20:01:41 -05:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2017-08-22 07:39:52 -04:00
|
|
|
// IsClosed returns if session is closed
|
|
|
|
func (session *Session) IsClosed() bool {
|
2020-06-15 16:46:01 -04:00
|
|
|
return session.isClosed
|
2017-08-22 07:39:52 -04:00
|
|
|
}
|
|
|
|
|
2016-11-03 18:16:01 -04:00
|
|
|
func (session *Session) resetStatement() {
|
2017-08-22 07:39:52 -04:00
|
|
|
if session.autoResetStatement {
|
2020-03-22 11:12:55 -04:00
|
|
|
session.statement.Reset()
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-23 04:11:18 -05:00
|
|
|
// Prepare set a flag to session that should be prepare statement before execute query
|
2016-11-03 18:16:01 -04:00
|
|
|
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 11:12:55 -04:00
|
|
|
if err := session.statement.SetTable(tableNameOrBean); err != nil {
|
|
|
|
session.statement.LastError = err
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Alias set the table alias
|
|
|
|
func (session *Session) Alias(alias string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Alias(alias)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// NoCascade indicate that no cascade load child object
|
|
|
|
func (session *Session) NoCascade() *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.UseCascade = false
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// ForUpdate Set Read/Write locking for UPDATE
|
|
|
|
func (session *Session) ForUpdate() *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.IsForUpdate = true
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// NoAutoCondition disable generate SQL condition from beans
|
|
|
|
func (session *Session) NoAutoCondition(no ...bool) *Session {
|
2020-03-22 11:12:55 -04:00
|
|
|
session.statement.SetNoAutoCondition(no...)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Limit provide limit and offset query condition
|
|
|
|
func (session *Session) Limit(limit int, start ...int) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Limit(limit, start...)
|
2016-11-03 18:16:01 -04:00
|
|
|
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 07:39:52 -04:00
|
|
|
session.statement.OrderBy(order)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Desc provide desc order by query condition, the input parameters are columns.
|
|
|
|
func (session *Session) Desc(colNames ...string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Desc(colNames...)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Asc provide asc order by query condition, the input parameters are columns.
|
|
|
|
func (session *Session) Asc(colNames ...string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Asc(colNames...)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// StoreEngine is only avialble mysql dialect currently
|
|
|
|
func (session *Session) StoreEngine(storeEngine string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.StoreEngine = storeEngine
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Charset is only avialble mysql dialect currently
|
|
|
|
func (session *Session) Charset(charset string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Charset = charset
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cascade indicates if loading sub Struct
|
|
|
|
func (session *Session) Cascade(trueOrFalse ...bool) *Session {
|
|
|
|
if len(trueOrFalse) >= 1 {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.UseCascade = trueOrFalse[0]
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2019-12-18 08:07:36 -05:00
|
|
|
// MustLogSQL means record SQL or not and don't follow engine's setting
|
2020-06-15 16:46:01 -04:00
|
|
|
func (session *Session) MustLogSQL(logs ...bool) *Session {
|
2020-03-22 11:12:55 -04:00
|
|
|
var showSQL = true
|
2020-06-15 16:46:01 -04:00
|
|
|
if len(logs) > 0 {
|
|
|
|
showSQL = logs[0]
|
2019-12-18 08:07:36 -05:00
|
|
|
}
|
2020-06-15 16:46:01 -04:00
|
|
|
session.ctx = context.WithValue(session.ctx, log.SessionShowSQLKey, showSQL)
|
2019-12-18 08:07:36 -05:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
2016-11-03 18:16:01 -04:00
|
|
|
// 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 07:39:52 -04:00
|
|
|
session.statement.UseCache = false
|
2016-11-03 18:16:01 -04:00
|
|
|
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 07:39:52 -04:00
|
|
|
session.statement.Join(joinOperator, tablename, condition, args...)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// GroupBy Generate Group By statement
|
|
|
|
func (session *Session) GroupBy(keys string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.GroupBy(keys)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// Having Generate Having statement
|
|
|
|
func (session *Session) Having(conditions string) *Session {
|
2017-08-22 07:39:52 -04:00
|
|
|
session.statement.Having(conditions)
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
|
|
|
|
|
|
|
// DB db return the wrapper of sql.DB
|
|
|
|
func (session *Session) DB() *core.DB {
|
2020-06-15 16:46:01 -04:00
|
|
|
return session.db()
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2017-01-03 03:20:28 -05:00
|
|
|
func (session *Session) canCache() bool {
|
2017-08-22 07:39:52 -04:00
|
|
|
if session.statement.RefTable == nil ||
|
|
|
|
session.statement.JoinStr != "" ||
|
|
|
|
session.statement.RawSQL != "" ||
|
|
|
|
!session.statement.UseCache ||
|
|
|
|
session.statement.IsForUpdate ||
|
|
|
|
session.tx != nil ||
|
2020-03-22 11:12:55 -04:00
|
|
|
len(session.statement.SelectStr) > 0 {
|
2017-01-03 03:20:28 -05:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2018-01-27 10:20:59 -05:00
|
|
|
func (session *Session) doPrepare(db *core.DB, sqlStr string) (stmt *core.Stmt, err error) {
|
2017-01-03 03:20:28 -05:00
|
|
|
crc := crc32.ChecksumIEEE([]byte(sqlStr))
|
|
|
|
// TODO try hash(sqlStr+len(sqlStr))
|
|
|
|
var has bool
|
|
|
|
stmt, has = session.stmtCache[crc]
|
|
|
|
if !has {
|
2019-06-23 11:22:43 -04:00
|
|
|
stmt, err = db.PrepareContext(session.ctx, sqlStr)
|
2016-11-03 18:16:01 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-01-03 03:20:28 -05:00
|
|
|
session.stmtCache[crc] = stmt
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2017-01-03 03:20:28 -05:00
|
|
|
return
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2017-01-03 03:20:28 -05:00
|
|
|
fieldValue, err := col.ValueOfV(dataStruct)
|
|
|
|
if err != nil {
|
2021-08-12 19:11:42 -04:00
|
|
|
return nil, nil, err
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2021-07-04 09:10:46 -04:00
|
|
|
if fieldValue == nil {
|
2021-08-12 19:11:42 -04:00
|
|
|
return nil, nil, ErrFieldIsNotValid{colName, table.Name}
|
2021-07-04 09:10:46 -04:00
|
|
|
}
|
2017-01-03 03:20:28 -05:00
|
|
|
if !fieldValue.IsValid() || !fieldValue.CanSet() {
|
2021-08-12 19:11:42 -04:00
|
|
|
return nil, nil, ErrFieldIsNotValid{colName, table.Name}
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2018-07-19 22:10:17 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
return col, fieldValue, nil
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2017-01-03 03:20:28 -05:00
|
|
|
// Cell cell is a result of one column field
|
|
|
|
type Cell *interface{}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
func (session *Session) rows2Beans(rows *core.Rows, fields []string, types []*sql.ColumnType,
|
2020-03-22 11:12:55 -04:00
|
|
|
table *schemas.Table, newElemFunc func([]string) reflect.Value,
|
|
|
|
sliceValueSetFunc func(*reflect.Value, schemas.PK) error) error {
|
2017-01-03 03:20:28 -05:00
|
|
|
for rows.Next() {
|
2017-04-06 21:47:25 -04:00
|
|
|
var newValue = newElemFunc(fields)
|
2017-01-03 03:20:28 -05:00
|
|
|
bean := newValue.Interface()
|
2017-10-01 12:52:35 -04:00
|
|
|
dataStruct := newValue.Elem()
|
2017-09-13 01:18:22 -04:00
|
|
|
|
2017-08-22 07:39:52 -04:00
|
|
|
// handle beforeClosures
|
2021-08-12 19:11:42 -04:00
|
|
|
scanResults, err := session.row2Slice(rows, fields, types, bean)
|
2017-08-22 07:39:52 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-10-01 12:52:35 -04:00
|
|
|
pk, err := session.slice2Bean(scanResults, fields, bean, &dataStruct, table)
|
2016-11-03 18:16:01 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-10-01 12:52:35 -04:00
|
|
|
session.afterProcessors = append(session.afterProcessors, executedProcessor{
|
|
|
|
fun: func(*Session, interface{}) error {
|
|
|
|
return sliceValueSetFunc(&newValue, pk)
|
|
|
|
},
|
|
|
|
session: session,
|
|
|
|
bean: bean,
|
|
|
|
})
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
return rows.Err()
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
func (session *Session) row2Slice(rows *core.Rows, fields []string, types []*sql.ColumnType, bean interface{}) ([]interface{}, error) {
|
2017-05-01 20:50:33 -04:00
|
|
|
for _, closure := range session.beforeClosures {
|
|
|
|
closure(bean)
|
|
|
|
}
|
|
|
|
|
2017-10-01 12:52:35 -04:00
|
|
|
scanResults := make([]interface{}, len(fields))
|
2017-01-03 03:20:28 -05:00
|
|
|
for i := 0; i < len(fields); i++ {
|
|
|
|
var cell interface{}
|
|
|
|
scanResults[i] = &cell
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
if err := session.engine.scan(rows, fields, types, scanResults...); err != nil {
|
2017-02-20 06:33:10 -05:00
|
|
|
return nil, err
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
|
2020-06-15 16:46:01 -04:00
|
|
|
executeBeforeSet(bean, fields, scanResults)
|
|
|
|
|
2017-08-22 07:39:52 -04:00
|
|
|
return scanResults, nil
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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 12:52:35 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if fieldType.Kind() == reflect.String {
|
|
|
|
fieldValue.SetString(string(bs))
|
|
|
|
return nil
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if fieldValue.CanAddr() {
|
|
|
|
err := json.DefaultJSONHandler.Unmarshal(bs, fieldValue.Addr().Interface())
|
2018-07-19 22:10:17 -04:00
|
|
|
if err != nil {
|
2021-08-12 19:11:42 -04:00
|
|
|
return err
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
} else {
|
|
|
|
x := reflect.New(fieldType)
|
|
|
|
err := json.DefaultJSONHandler.Unmarshal(bs, x.Interface())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
fieldValue.Set(x.Elem())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2017-01-03 03:20:28 -05:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("unsupported primary key type: %v, %v", tp, vv)
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-03 18:16:01 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
return structConvert.FromDB(data)
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-19 22:10:17 -04:00
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
|
|
|
|
fieldValue.Set(reflect.New(fieldValue.Type().Elem()))
|
|
|
|
return fieldValue.Interface().(convert.Conversion).FromDB(data)
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
return structConvert.FromDB(data)
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
vv := reflect.ValueOf(scanResult)
|
|
|
|
fieldType := fieldValue.Type()
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
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 10:20:59 -05:00
|
|
|
}
|
2018-07-19 22:10:17 -04:00
|
|
|
} else {
|
2021-08-12 19:11:42 -04:00
|
|
|
for i := 0; i < vv.Len(); i++ {
|
|
|
|
fieldValue.Set(reflect.Append(*fieldValue, vv.Index(i)))
|
2017-01-03 03:20:28 -05:00
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
return nil
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
case reflect.Struct:
|
|
|
|
if fieldType.ConvertibleTo(schemas.BigFloatType) {
|
|
|
|
v, err := convert.AsBigFloat(scanResult)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
fieldValue.Set(reflect.ValueOf(v).Elem().Convert(fieldType))
|
|
|
|
return nil
|
|
|
|
}
|
2018-07-19 22:10:17 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if fieldType.ConvertibleTo(schemas.TimeType) {
|
|
|
|
dbTZ := session.engine.DatabaseTZ
|
|
|
|
if col.TimeZone != nil {
|
|
|
|
dbTZ = col.TimeZone
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
|
|
|
|
t, err := convert.AsTime(scanResult, dbTZ, session.engine.TZLocation)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
|
|
|
|
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-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
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-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
|
|
|
|
if len(table.PrimaryKeys) != 1 {
|
|
|
|
return errors.New("unsupported non or composited primary key cascade")
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
var pk = make(schemas.PK, len(table.PrimaryKeys))
|
|
|
|
pk[0], err = asKind(vv, reflect.TypeOf(scanResult))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2018-07-19 22:10:17 -04:00
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-06 21:47:25 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
return convert.AssignValue(fieldValue.Addr(), scanResult)
|
|
|
|
}
|
2016-11-03 18:16:01 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-06 21:47:25 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
buildAfterProcessors(session, bean)
|
2017-05-01 20:50:33 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
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-19 22:10:17 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if idx, ok = tempMap[lKey]; !ok {
|
|
|
|
idx = 0
|
|
|
|
} else {
|
|
|
|
idx = idx + 1
|
|
|
|
}
|
|
|
|
tempMap[lKey] = idx
|
2018-07-19 22:10:17 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
col, fieldValue, err := session.getField(dataStruct, table, colName, idx)
|
|
|
|
if err != nil {
|
|
|
|
if _, ok := err.(ErrFieldIsNotExist); ok {
|
|
|
|
continue
|
|
|
|
} else {
|
2018-07-19 22:10:17 -04:00
|
|
|
return nil, err
|
|
|
|
}
|
2021-08-12 19:11:42 -04:00
|
|
|
}
|
|
|
|
if fieldValue == nil {
|
|
|
|
continue
|
|
|
|
}
|
2018-07-19 22:10:17 -04:00
|
|
|
|
2021-08-12 19:11:42 -04:00
|
|
|
if err := session.convertBeanField(col, fieldValue, scanResults[i], table); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if col.IsPrimaryKey {
|
|
|
|
pk = append(pk, scanResults[i])
|
2016-11-03 18:16:01 -04:00
|
|
|
}
|
|
|
|
}
|
2017-02-20 06:33:10 -05:00
|
|
|
return pk, nil
|
2017-01-03 03:20:28 -05:00
|
|
|
}
|
|
|
|
|
2016-11-03 18:16:01 -04:00
|
|
|
// 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 11:12:55 -04:00
|
|
|
session.statement.SetUnscoped()
|
2016-11-03 18:16:01 -04:00
|
|
|
return session
|
|
|
|
}
|
2018-12-11 20:01:41 -05:00
|
|
|
|
|
|
|
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 11:12:55 -04:00
|
|
|
|
2021-05-14 15:17:06 -04:00
|
|
|
// Context sets the context on this session
|
2020-03-22 11:12:55 -04:00
|
|
|
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)
|
|
|
|
}
|