helpers.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright (c) 2012 The gocql 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 gocql
  5. import (
  6. "fmt"
  7. "math/big"
  8. "reflect"
  9. "strings"
  10. "time"
  11. "gopkg.in/inf.v0"
  12. )
  13. type RowData struct {
  14. Columns []string
  15. Values []interface{}
  16. }
  17. func goType(t TypeInfo) reflect.Type {
  18. switch t.Type() {
  19. case TypeVarchar, TypeAscii, TypeInet, TypeText:
  20. return reflect.TypeOf(*new(string))
  21. case TypeBigInt, TypeCounter:
  22. return reflect.TypeOf(*new(int64))
  23. case TypeTimestamp:
  24. return reflect.TypeOf(*new(time.Time))
  25. case TypeBlob:
  26. return reflect.TypeOf(*new([]byte))
  27. case TypeBoolean:
  28. return reflect.TypeOf(*new(bool))
  29. case TypeFloat:
  30. return reflect.TypeOf(*new(float32))
  31. case TypeDouble:
  32. return reflect.TypeOf(*new(float64))
  33. case TypeInt:
  34. return reflect.TypeOf(*new(int))
  35. case TypeSmallInt:
  36. return reflect.TypeOf(*new(int16))
  37. case TypeTinyInt:
  38. return reflect.TypeOf(*new(int8))
  39. case TypeDecimal:
  40. return reflect.TypeOf(*new(*inf.Dec))
  41. case TypeUUID, TypeTimeUUID:
  42. return reflect.TypeOf(*new(UUID))
  43. case TypeList, TypeSet:
  44. return reflect.SliceOf(goType(t.(CollectionType).Elem))
  45. case TypeMap:
  46. return reflect.MapOf(goType(t.(CollectionType).Key), goType(t.(CollectionType).Elem))
  47. case TypeVarint:
  48. return reflect.TypeOf(*new(*big.Int))
  49. case TypeTuple:
  50. // what can we do here? all there is to do is to make a list of interface{}
  51. tuple := t.(TupleTypeInfo)
  52. return reflect.TypeOf(make([]interface{}, len(tuple.Elems)))
  53. case TypeUDT:
  54. return reflect.TypeOf(make(map[string]interface{}))
  55. case TypeDate:
  56. return reflect.TypeOf(*new(time.Time))
  57. default:
  58. return nil
  59. }
  60. }
  61. func dereference(i interface{}) interface{} {
  62. return reflect.Indirect(reflect.ValueOf(i)).Interface()
  63. }
  64. func getCassandraType(name string) Type {
  65. switch name {
  66. case "ascii":
  67. return TypeAscii
  68. case "bigint":
  69. return TypeBigInt
  70. case "blob":
  71. return TypeBlob
  72. case "boolean":
  73. return TypeBoolean
  74. case "counter":
  75. return TypeCounter
  76. case "decimal":
  77. return TypeDecimal
  78. case "double":
  79. return TypeDouble
  80. case "float":
  81. return TypeFloat
  82. case "int":
  83. return TypeInt
  84. case "timestamp":
  85. return TypeTimestamp
  86. case "uuid":
  87. return TypeUUID
  88. case "varchar", "text":
  89. return TypeVarchar
  90. case "varint":
  91. return TypeVarint
  92. case "timeuuid":
  93. return TypeTimeUUID
  94. case "inet":
  95. return TypeInet
  96. case "MapType":
  97. return TypeMap
  98. case "ListType":
  99. return TypeList
  100. case "SetType":
  101. return TypeSet
  102. case "TupleType":
  103. return TypeTuple
  104. default:
  105. if strings.HasPrefix(name, "set") {
  106. return TypeSet
  107. } else if strings.HasPrefix(name, "list") {
  108. return TypeList
  109. } else if strings.HasPrefix(name, "map") {
  110. return TypeMap
  111. } else if strings.HasPrefix(name, "tuple") {
  112. return TypeTuple
  113. }
  114. return TypeCustom
  115. }
  116. }
  117. func getApacheCassandraType(class string) Type {
  118. switch strings.TrimPrefix(class, apacheCassandraTypePrefix) {
  119. case "AsciiType":
  120. return TypeAscii
  121. case "LongType":
  122. return TypeBigInt
  123. case "BytesType":
  124. return TypeBlob
  125. case "BooleanType":
  126. return TypeBoolean
  127. case "CounterColumnType":
  128. return TypeCounter
  129. case "DecimalType":
  130. return TypeDecimal
  131. case "DoubleType":
  132. return TypeDouble
  133. case "FloatType":
  134. return TypeFloat
  135. case "Int32Type":
  136. return TypeInt
  137. case "ShortType":
  138. return TypeSmallInt
  139. case "ByteType":
  140. return TypeTinyInt
  141. case "DateType", "TimestampType":
  142. return TypeTimestamp
  143. case "UUIDType", "LexicalUUIDType":
  144. return TypeUUID
  145. case "UTF8Type":
  146. return TypeVarchar
  147. case "IntegerType":
  148. return TypeVarint
  149. case "TimeUUIDType":
  150. return TypeTimeUUID
  151. case "InetAddressType":
  152. return TypeInet
  153. case "MapType":
  154. return TypeMap
  155. case "ListType":
  156. return TypeList
  157. case "SetType":
  158. return TypeSet
  159. case "TupleType":
  160. return TypeTuple
  161. default:
  162. return TypeCustom
  163. }
  164. }
  165. func typeCanBeNull(typ TypeInfo) bool {
  166. switch typ.(type) {
  167. case CollectionType, UDTTypeInfo, TupleTypeInfo:
  168. return false
  169. }
  170. return true
  171. }
  172. func (r *RowData) rowMap(m map[string]interface{}) {
  173. for i, column := range r.Columns {
  174. val := dereference(r.Values[i])
  175. if valVal := reflect.ValueOf(val); valVal.Kind() == reflect.Slice {
  176. valCopy := reflect.MakeSlice(valVal.Type(), valVal.Len(), valVal.Cap())
  177. reflect.Copy(valCopy, valVal)
  178. m[column] = valCopy.Interface()
  179. } else {
  180. m[column] = val
  181. }
  182. }
  183. }
  184. // TupeColumnName will return the column name of a tuple value in a column named
  185. // c at index n. It should be used if a specific element within a tuple is needed
  186. // to be extracted from a map returned from SliceMap or MapScan.
  187. func TupleColumnName(c string, n int) string {
  188. return fmt.Sprintf("%s[%d]", c, n)
  189. }
  190. func (iter *Iter) RowData() (RowData, error) {
  191. if iter.err != nil {
  192. return RowData{}, iter.err
  193. }
  194. columns := make([]string, 0, len(iter.Columns()))
  195. values := make([]interface{}, 0, len(iter.Columns()))
  196. for _, column := range iter.Columns() {
  197. if c, ok := column.TypeInfo.(TupleTypeInfo); !ok {
  198. val := column.TypeInfo.New()
  199. columns = append(columns, column.Name)
  200. values = append(values, val)
  201. } else {
  202. for i, elem := range c.Elems {
  203. columns = append(columns, TupleColumnName(column.Name, i))
  204. values = append(values, elem.New())
  205. }
  206. }
  207. }
  208. rowData := RowData{
  209. Columns: columns,
  210. Values: values,
  211. }
  212. return rowData, nil
  213. }
  214. // TODO(zariel): is it worth exporting this?
  215. func (iter *Iter) rowMap() (map[string]interface{}, error) {
  216. if iter.err != nil {
  217. return nil, iter.err
  218. }
  219. rowData, _ := iter.RowData()
  220. iter.Scan(rowData.Values...)
  221. m := make(map[string]interface{}, len(rowData.Columns))
  222. rowData.rowMap(m)
  223. return m, nil
  224. }
  225. // SliceMap is a helper function to make the API easier to use
  226. // returns the data from the query in the form of []map[string]interface{}
  227. func (iter *Iter) SliceMap() ([]map[string]interface{}, error) {
  228. if iter.err != nil {
  229. return nil, iter.err
  230. }
  231. // Not checking for the error because we just did
  232. rowData, _ := iter.RowData()
  233. dataToReturn := make([]map[string]interface{}, 0)
  234. for iter.Scan(rowData.Values...) {
  235. m := make(map[string]interface{}, len(rowData.Columns))
  236. rowData.rowMap(m)
  237. dataToReturn = append(dataToReturn, m)
  238. }
  239. if iter.err != nil {
  240. return nil, iter.err
  241. }
  242. return dataToReturn, nil
  243. }
  244. // MapScan takes a map[string]interface{} and populates it with a row
  245. // that is returned from cassandra.
  246. //
  247. // Each call to MapScan() must be called with a new map object.
  248. // During the call to MapScan() any pointers in the existing map
  249. // are replaced with non pointer types before the call returns
  250. //
  251. // iter := session.Query(`SELECT * FROM mytable`).Iter()
  252. // for {
  253. // // New map each iteration
  254. // row = make(map[string]interface{})
  255. // if !iter.MapScan(row) {
  256. // break
  257. // }
  258. // // Do things with row
  259. // if fullname, ok := row["fullname"]; ok {
  260. // fmt.Printf("Full Name: %s\n", fullname)
  261. // }
  262. // }
  263. //
  264. // You can also pass pointers in the map before each call
  265. //
  266. // var fullName FullName // Implements gocql.Unmarshaler and gocql.Marshaler interfaces
  267. // var address net.IP
  268. // var age int
  269. // iter := session.Query(`SELECT * FROM scan_map_table`).Iter()
  270. // for {
  271. // // New map each iteration
  272. // row := map[string]interface{}{
  273. // "fullname": &fullName,
  274. // "age": &age,
  275. // "address": &address,
  276. // }
  277. // if !iter.MapScan(row) {
  278. // break
  279. // }
  280. // fmt.Printf("First: %s Age: %d Address: %q\n", fullName.FirstName, age, address)
  281. // }
  282. func (iter *Iter) MapScan(m map[string]interface{}) bool {
  283. if iter.err != nil {
  284. return false
  285. }
  286. // Not checking for the error because we just did
  287. rowData, _ := iter.RowData()
  288. for i, col := range rowData.Columns {
  289. if dest, ok := m[col]; ok {
  290. rowData.Values[i] = dest
  291. }
  292. }
  293. if iter.Scan(rowData.Values...) {
  294. rowData.rowMap(m)
  295. return true
  296. }
  297. return false
  298. }
  299. func copyBytes(p []byte) []byte {
  300. b := make([]byte, len(p))
  301. copy(b, p)
  302. return b
  303. }