session_query.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2017 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. "fmt"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/go-xorm/builder"
  12. "github.com/go-xorm/core"
  13. )
  14. func (session *Session) genQuerySQL(sqlorArgs ...interface{}) (string, []interface{}, error) {
  15. if len(sqlorArgs) > 0 {
  16. switch sqlorArgs[0].(type) {
  17. case string:
  18. return sqlorArgs[0].(string), sqlorArgs[1:], nil
  19. case *builder.Builder:
  20. return sqlorArgs[0].(*builder.Builder).ToSQL()
  21. case builder.Builder:
  22. bd := sqlorArgs[0].(builder.Builder)
  23. return bd.ToSQL()
  24. default:
  25. return "", nil, ErrUnSupportedType
  26. }
  27. }
  28. if session.statement.RawSQL != "" {
  29. return session.statement.RawSQL, session.statement.RawParams, nil
  30. }
  31. if len(session.statement.TableName()) <= 0 {
  32. return "", nil, ErrTableNotFound
  33. }
  34. var columnStr = session.statement.ColumnStr
  35. if len(session.statement.selectStr) > 0 {
  36. columnStr = session.statement.selectStr
  37. } else {
  38. if session.statement.JoinStr == "" {
  39. if columnStr == "" {
  40. if session.statement.GroupByStr != "" {
  41. columnStr = session.statement.Engine.Quote(strings.Replace(session.statement.GroupByStr, ",", session.engine.Quote(","), -1))
  42. } else {
  43. columnStr = session.statement.genColumnStr()
  44. }
  45. }
  46. } else {
  47. if columnStr == "" {
  48. if session.statement.GroupByStr != "" {
  49. columnStr = session.statement.Engine.Quote(strings.Replace(session.statement.GroupByStr, ",", session.engine.Quote(","), -1))
  50. } else {
  51. columnStr = "*"
  52. }
  53. }
  54. }
  55. if columnStr == "" {
  56. columnStr = "*"
  57. }
  58. }
  59. if err := session.statement.processIDParam(); err != nil {
  60. return "", nil, err
  61. }
  62. condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
  63. if err != nil {
  64. return "", nil, err
  65. }
  66. args := append(session.statement.joinArgs, condArgs...)
  67. sqlStr, err := session.statement.genSelectSQL(columnStr, condSQL, true, true)
  68. if err != nil {
  69. return "", nil, err
  70. }
  71. // for mssql and use limit
  72. qs := strings.Count(sqlStr, "?")
  73. if len(args)*2 == qs {
  74. args = append(args, args...)
  75. }
  76. return sqlStr, args, nil
  77. }
  78. // Query runs a raw sql and return records as []map[string][]byte
  79. func (session *Session) Query(sqlorArgs ...interface{}) ([]map[string][]byte, error) {
  80. if session.isAutoClose {
  81. defer session.Close()
  82. }
  83. sqlStr, args, err := session.genQuerySQL(sqlorArgs...)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return session.queryBytes(sqlStr, args...)
  88. }
  89. func value2String(rawValue *reflect.Value) (str string, err error) {
  90. aa := reflect.TypeOf((*rawValue).Interface())
  91. vv := reflect.ValueOf((*rawValue).Interface())
  92. switch aa.Kind() {
  93. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  94. str = strconv.FormatInt(vv.Int(), 10)
  95. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  96. str = strconv.FormatUint(vv.Uint(), 10)
  97. case reflect.Float32, reflect.Float64:
  98. str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
  99. case reflect.String:
  100. str = vv.String()
  101. case reflect.Array, reflect.Slice:
  102. switch aa.Elem().Kind() {
  103. case reflect.Uint8:
  104. data := rawValue.Interface().([]byte)
  105. str = string(data)
  106. if str == "\x00" {
  107. str = "0"
  108. }
  109. default:
  110. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  111. }
  112. // time type
  113. case reflect.Struct:
  114. if aa.ConvertibleTo(core.TimeType) {
  115. str = vv.Convert(core.TimeType).Interface().(time.Time).Format(time.RFC3339Nano)
  116. } else {
  117. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  118. }
  119. case reflect.Bool:
  120. str = strconv.FormatBool(vv.Bool())
  121. case reflect.Complex128, reflect.Complex64:
  122. str = fmt.Sprintf("%v", vv.Complex())
  123. /* TODO: unsupported types below
  124. case reflect.Map:
  125. case reflect.Ptr:
  126. case reflect.Uintptr:
  127. case reflect.UnsafePointer:
  128. case reflect.Chan, reflect.Func, reflect.Interface:
  129. */
  130. default:
  131. err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
  132. }
  133. return
  134. }
  135. func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string, err error) {
  136. result := make(map[string]string)
  137. scanResultContainers := make([]interface{}, len(fields))
  138. for i := 0; i < len(fields); i++ {
  139. var scanResultContainer interface{}
  140. scanResultContainers[i] = &scanResultContainer
  141. }
  142. if err := rows.Scan(scanResultContainers...); err != nil {
  143. return nil, err
  144. }
  145. for ii, key := range fields {
  146. rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
  147. // if row is null then as empty string
  148. if rawValue.Interface() == nil {
  149. result[key] = ""
  150. continue
  151. }
  152. if data, err := value2String(&rawValue); err == nil {
  153. result[key] = data
  154. } else {
  155. return nil, err
  156. }
  157. }
  158. return result, nil
  159. }
  160. func rows2Strings(rows *core.Rows) (resultsSlice []map[string]string, err error) {
  161. fields, err := rows.Columns()
  162. if err != nil {
  163. return nil, err
  164. }
  165. for rows.Next() {
  166. result, err := row2mapStr(rows, fields)
  167. if err != nil {
  168. return nil, err
  169. }
  170. resultsSlice = append(resultsSlice, result)
  171. }
  172. return resultsSlice, nil
  173. }
  174. // QueryString runs a raw sql and return records as []map[string]string
  175. func (session *Session) QueryString(sqlorArgs ...interface{}) ([]map[string]string, error) {
  176. if session.isAutoClose {
  177. defer session.Close()
  178. }
  179. sqlStr, args, err := session.genQuerySQL(sqlorArgs...)
  180. if err != nil {
  181. return nil, err
  182. }
  183. rows, err := session.queryRows(sqlStr, args...)
  184. if err != nil {
  185. return nil, err
  186. }
  187. defer rows.Close()
  188. return rows2Strings(rows)
  189. }
  190. func row2mapInterface(rows *core.Rows, fields []string) (resultsMap map[string]interface{}, err error) {
  191. resultsMap = make(map[string]interface{}, len(fields))
  192. scanResultContainers := make([]interface{}, len(fields))
  193. for i := 0; i < len(fields); i++ {
  194. var scanResultContainer interface{}
  195. scanResultContainers[i] = &scanResultContainer
  196. }
  197. if err := rows.Scan(scanResultContainers...); err != nil {
  198. return nil, err
  199. }
  200. for ii, key := range fields {
  201. resultsMap[key] = reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])).Interface()
  202. }
  203. return
  204. }
  205. func rows2Interfaces(rows *core.Rows) (resultsSlice []map[string]interface{}, err error) {
  206. fields, err := rows.Columns()
  207. if err != nil {
  208. return nil, err
  209. }
  210. for rows.Next() {
  211. result, err := row2mapInterface(rows, fields)
  212. if err != nil {
  213. return nil, err
  214. }
  215. resultsSlice = append(resultsSlice, result)
  216. }
  217. return resultsSlice, nil
  218. }
  219. // QueryInterface runs a raw sql and return records as []map[string]interface{}
  220. func (session *Session) QueryInterface(sqlorArgs ...interface{}) ([]map[string]interface{}, error) {
  221. if session.isAutoClose {
  222. defer session.Close()
  223. }
  224. sqlStr, args, err := session.genQuerySQL(sqlorArgs...)
  225. if err != nil {
  226. return nil, err
  227. }
  228. rows, err := session.queryRows(sqlStr, args...)
  229. if err != nil {
  230. return nil, err
  231. }
  232. defer rows.Close()
  233. return rows2Interfaces(rows)
  234. }