session_raw.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright 2016 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xorm
  5. import (
  6. "database/sql"
  7. "reflect"
  8. "time"
  9. "errors"
  10. "github.com/xormplus/builder"
  11. "github.com/xormplus/core"
  12. )
  13. func (session *Session) queryPreprocess(sqlStr *string, paramStr ...interface{}) {
  14. for _, filter := range session.engine.dialect.Filters() {
  15. *sqlStr = filter.Do(*sqlStr, session.engine.dialect, session.statement.RefTable)
  16. }
  17. session.lastSQL = *sqlStr
  18. session.lastSQLArgs = paramStr
  19. }
  20. func (session *Session) queryRows(sqlStr string, args ...interface{}) (*core.Rows, error) {
  21. defer session.resetStatement()
  22. session.queryPreprocess(&sqlStr, args...)
  23. if session.engine.showSQL {
  24. if session.engine.showExecTime {
  25. b4ExecTime := time.Now()
  26. defer func() {
  27. execDuration := time.Since(b4ExecTime)
  28. if len(args) > 0 {
  29. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr, args, execDuration)
  30. } else {
  31. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr, execDuration)
  32. }
  33. }()
  34. } else {
  35. if len(args) > 0 {
  36. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, args)
  37. } else {
  38. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr)
  39. }
  40. }
  41. }
  42. if session.isAutoCommit {
  43. var db *core.DB
  44. if session.sessionType == groupSession {
  45. db = session.engine.engineGroup.Slave().DB()
  46. } else {
  47. db = session.DB()
  48. }
  49. if session.prepareStmt {
  50. // don't clear stmt since session will cache them
  51. stmt, err := session.doPrepare(db, sqlStr)
  52. if err != nil {
  53. return nil, err
  54. }
  55. rows, err := stmt.QueryContext(session.ctx, args...)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return rows, nil
  60. }
  61. rows, err := db.QueryContext(session.ctx, sqlStr, args...)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return rows, nil
  66. }
  67. rows, err := session.tx.QueryContext(session.ctx, sqlStr, args...)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return rows, nil
  72. }
  73. func (session *Session) queryRow(sqlStr string, args ...interface{}) *core.Row {
  74. return core.NewRow(session.queryRows(sqlStr, args...))
  75. }
  76. func value2Bytes(rawValue *reflect.Value) ([]byte, error) {
  77. str, err := value2String(rawValue)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return []byte(str), nil
  82. }
  83. func value2Value(rawValue *reflect.Value) (Value, error) {
  84. str, err := value2String(rawValue)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return Value(str), nil
  89. }
  90. func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, err error) {
  91. result := make(map[string][]byte)
  92. scanResultContainers := make([]interface{}, len(fields))
  93. for i := 0; i < len(fields); i++ {
  94. var scanResultContainer interface{}
  95. scanResultContainers[i] = &scanResultContainer
  96. }
  97. if err := rows.Scan(scanResultContainers...); err != nil {
  98. return nil, err
  99. }
  100. for ii, key := range fields {
  101. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  102. //if row is null then ignore
  103. if rawValue.Interface() == nil {
  104. result[key] = []byte{}
  105. continue
  106. }
  107. if data, err := value2Bytes(&rawValue); err == nil {
  108. result[key] = data
  109. } else {
  110. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  111. }
  112. }
  113. return result, nil
  114. }
  115. func row2mapValue(rows *core.Rows, fields []string) (resultsMap map[string]Value, err error) {
  116. result := make(map[string]Value)
  117. scanResultContainers := make([]interface{}, len(fields))
  118. for i := 0; i < len(fields); i++ {
  119. var scanResultContainer interface{}
  120. scanResultContainers[i] = &scanResultContainer
  121. }
  122. if err := rows.Scan(scanResultContainers...); err != nil {
  123. return nil, err
  124. }
  125. for ii, key := range fields {
  126. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  127. if rawValue.Interface() == nil {
  128. result[key] = nil
  129. continue
  130. }
  131. if data, err := value2Value(&rawValue); err == nil {
  132. result[key] = data
  133. } else {
  134. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  135. }
  136. }
  137. return result, nil
  138. }
  139. func row2Record(rows *core.Rows, fields []string) (record Record, err error) {
  140. record = make(Record)
  141. scanResultContainers := make([]interface{}, len(fields))
  142. for i := 0; i < len(fields); i++ {
  143. var scanResultContainer interface{}
  144. scanResultContainers[i] = &scanResultContainer
  145. }
  146. if err := rows.Scan(scanResultContainers...); err != nil {
  147. return nil, err
  148. }
  149. for ii, key := range fields {
  150. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  151. if rawValue.Interface() == nil {
  152. record[key] = nil
  153. continue
  154. }
  155. if data, err := value2Value(&rawValue); err == nil {
  156. record[key] = data
  157. } else {
  158. return nil, err // !nashtsai! REVIEW, should return err or just error log?
  159. }
  160. }
  161. return record, nil
  162. }
  163. func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) {
  164. fields, err := rows.Columns()
  165. if err != nil {
  166. return nil, err
  167. }
  168. for rows.Next() {
  169. result, err := row2map(rows, fields)
  170. if err != nil {
  171. return nil, err
  172. }
  173. resultsSlice = append(resultsSlice, result)
  174. }
  175. return resultsSlice, nil
  176. }
  177. func rows2mapsValue(rows *core.Rows) (resultsSlice []map[string]Value, err error) {
  178. fields, err := rows.Columns()
  179. if err != nil {
  180. return nil, err
  181. }
  182. for rows.Next() {
  183. result, err := row2mapValue(rows, fields)
  184. if err != nil {
  185. return nil, err
  186. }
  187. resultsSlice = append(resultsSlice, result)
  188. }
  189. return resultsSlice, nil
  190. }
  191. func rows2Result(rows *core.Rows) (result Result, err error) {
  192. fields, err := rows.Columns()
  193. if err != nil {
  194. return nil, err
  195. }
  196. for rows.Next() {
  197. r, err := row2Record(rows, fields)
  198. if err != nil {
  199. return nil, err
  200. }
  201. result = append(result, r)
  202. }
  203. return result, nil
  204. }
  205. func (session *Session) queryBytes(sqlStr string, args ...interface{}) ([]map[string][]byte, error) {
  206. rows, err := session.queryRows(sqlStr, args...)
  207. if err != nil {
  208. return nil, err
  209. }
  210. defer rows.Close()
  211. return rows2maps(rows)
  212. }
  213. func (session *Session) queryValue(sqlStr string, args ...interface{}) ([]map[string]Value, error) {
  214. rows, err := session.queryRows(sqlStr, args...)
  215. if err != nil {
  216. return nil, err
  217. }
  218. defer rows.Close()
  219. return rows2mapsValue(rows)
  220. }
  221. func (session *Session) queryResult(sqlStr string, args ...interface{}) (Result, error) {
  222. rows, err := session.queryRows(sqlStr, args...)
  223. if err != nil {
  224. return nil, err
  225. }
  226. defer rows.Close()
  227. return rows2Result(rows)
  228. }
  229. var BeforeExecProcessor func(sqlStr string, args []interface{})
  230. func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, error) {
  231. defer session.resetStatement()
  232. session.queryPreprocess(&sqlStr, args...)
  233. if session.engine.showSQL {
  234. if session.engine.showExecTime {
  235. b4ExecTime := time.Now()
  236. defer func() {
  237. execDuration := time.Since(b4ExecTime)
  238. if len(args) > 0 {
  239. session.engine.logger.Infof("[SQL][%p] %s %#v - took: %v", session, sqlStr, args, execDuration)
  240. } else {
  241. session.engine.logger.Infof("[SQL][%p] %s - took: %v", session, sqlStr, execDuration)
  242. }
  243. }()
  244. } else {
  245. if len(args) > 0 {
  246. session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, args)
  247. } else {
  248. session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr)
  249. }
  250. }
  251. }
  252. if BeforeExecProcessor != nil {
  253. BeforeExecProcessor(sqlStr, args)
  254. }
  255. if !session.isAutoCommit {
  256. return session.tx.ExecContext(session.ctx, sqlStr, args...)
  257. }
  258. if session.prepareStmt {
  259. stmt, err := session.doPrepare(session.DB(), sqlStr)
  260. if err != nil {
  261. return nil, err
  262. }
  263. res, err := stmt.ExecContext(session.ctx, args...)
  264. if err != nil {
  265. return nil, err
  266. }
  267. return res, nil
  268. }
  269. return session.DB().ExecContext(session.ctx, sqlStr, args...)
  270. }
  271. func convertSQLOrArgs(sqlOrArgs ...interface{}) (string, []interface{}, error) {
  272. switch sqlOrArgs[0].(type) {
  273. case string:
  274. return sqlOrArgs[0].(string), sqlOrArgs[1:], nil
  275. case *builder.Builder:
  276. return sqlOrArgs[0].(*builder.Builder).ToSQL()
  277. case builder.Builder:
  278. bd := sqlOrArgs[0].(builder.Builder)
  279. return bd.ToSQL()
  280. }
  281. return "", nil, ErrUnSupportedType
  282. }
  283. // Exec raw sql
  284. func (session *Session) Exec(sqlOrArgs ...interface{}) (sql.Result, error) {
  285. if session.isAutoClose {
  286. defer session.Close()
  287. }
  288. if len(sqlOrArgs) == 0 {
  289. return nil, ErrUnSupportedType
  290. }
  291. sqlStr, args, err := convertSQLOrArgs(sqlOrArgs...)
  292. if err != nil {
  293. return nil, err
  294. }
  295. return session.exec(sqlStr, args...)
  296. }
  297. func (session *Session) ExecOne(sqlOrArgs ...interface{}) (lastInsertId int64, err error) {
  298. execRet, err := session.Exec(sqlOrArgs...)
  299. if err != nil {
  300. return 0, err
  301. }
  302. affected, err := execRet.RowsAffected()
  303. if affected != 1 {
  304. return 0, errors.New("affected rows not equal one")
  305. }
  306. return execRet.LastInsertId()
  307. }