session_query.go 6.7 KB

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