helpers.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 getCassandraBaseType(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":
  89. return TypeVarchar
  90. case "text":
  91. return TypeText
  92. case "varint":
  93. return TypeVarint
  94. case "timeuuid":
  95. return TypeTimeUUID
  96. case "inet":
  97. return TypeInet
  98. case "MapType":
  99. return TypeMap
  100. case "ListType":
  101. return TypeList
  102. case "SetType":
  103. return TypeSet
  104. case "TupleType":
  105. return TypeTuple
  106. default:
  107. return TypeCustom
  108. }
  109. }
  110. func getCassandraType(name string) TypeInfo {
  111. if strings.HasPrefix(name, "frozen<") {
  112. return getCassandraType(strings.TrimPrefix(name[:len(name)-1], "frozen<"))
  113. } else if strings.HasPrefix(name, "set<") {
  114. return CollectionType{
  115. NativeType: NativeType{typ: TypeSet},
  116. Elem: getCassandraType(strings.TrimPrefix(name[:len(name)-1], "set<")),
  117. }
  118. } else if strings.HasPrefix(name, "list<") {
  119. return CollectionType{
  120. NativeType: NativeType{typ: TypeList},
  121. Elem: getCassandraType(strings.TrimPrefix(name[:len(name)-1], "list<")),
  122. }
  123. } else if strings.HasPrefix(name, "map<") {
  124. names := strings.Split(strings.TrimPrefix(name[:len(name)-1], "map<"), ", ")
  125. if len(names) != 2 {
  126. panic(fmt.Sprintf("invalid map type: %v", name))
  127. }
  128. return CollectionType{
  129. NativeType: NativeType{typ: TypeMap},
  130. Key: getCassandraType(names[0]),
  131. Elem: getCassandraType(names[1]),
  132. }
  133. } else if strings.HasPrefix(name, "tuple<") {
  134. names := strings.Split(strings.TrimPrefix(name[:len(name)-1], "tuple<"), ", ")
  135. types := make([]TypeInfo, len(names))
  136. for i, name := range names {
  137. types[i] = getCassandraType(name)
  138. }
  139. return TupleTypeInfo{
  140. NativeType: NativeType{typ: TypeTuple},
  141. Elems: types,
  142. }
  143. } else {
  144. return NativeType{
  145. typ: getCassandraBaseType(name),
  146. }
  147. }
  148. }
  149. func getApacheCassandraType(class string) Type {
  150. switch strings.TrimPrefix(class, apacheCassandraTypePrefix) {
  151. case "AsciiType":
  152. return TypeAscii
  153. case "LongType":
  154. return TypeBigInt
  155. case "BytesType":
  156. return TypeBlob
  157. case "BooleanType":
  158. return TypeBoolean
  159. case "CounterColumnType":
  160. return TypeCounter
  161. case "DecimalType":
  162. return TypeDecimal
  163. case "DoubleType":
  164. return TypeDouble
  165. case "FloatType":
  166. return TypeFloat
  167. case "Int32Type":
  168. return TypeInt
  169. case "ShortType":
  170. return TypeSmallInt
  171. case "ByteType":
  172. return TypeTinyInt
  173. case "DateType", "TimestampType":
  174. return TypeTimestamp
  175. case "UUIDType", "LexicalUUIDType":
  176. return TypeUUID
  177. case "UTF8Type":
  178. return TypeVarchar
  179. case "IntegerType":
  180. return TypeVarint
  181. case "TimeUUIDType":
  182. return TypeTimeUUID
  183. case "InetAddressType":
  184. return TypeInet
  185. case "MapType":
  186. return TypeMap
  187. case "ListType":
  188. return TypeList
  189. case "SetType":
  190. return TypeSet
  191. case "TupleType":
  192. return TypeTuple
  193. default:
  194. return TypeCustom
  195. }
  196. }
  197. func typeCanBeNull(typ TypeInfo) bool {
  198. switch typ.(type) {
  199. case CollectionType, UDTTypeInfo, TupleTypeInfo:
  200. return false
  201. }
  202. return true
  203. }
  204. func (r *RowData) rowMap(m map[string]interface{}) {
  205. for i, column := range r.Columns {
  206. val := dereference(r.Values[i])
  207. if valVal := reflect.ValueOf(val); valVal.Kind() == reflect.Slice {
  208. valCopy := reflect.MakeSlice(valVal.Type(), valVal.Len(), valVal.Cap())
  209. reflect.Copy(valCopy, valVal)
  210. m[column] = valCopy.Interface()
  211. } else {
  212. m[column] = val
  213. }
  214. }
  215. }
  216. // TupeColumnName will return the column name of a tuple value in a column named
  217. // c at index n. It should be used if a specific element within a tuple is needed
  218. // to be extracted from a map returned from SliceMap or MapScan.
  219. func TupleColumnName(c string, n int) string {
  220. return fmt.Sprintf("%s[%d]", c, n)
  221. }
  222. func (iter *Iter) RowData() (RowData, error) {
  223. if iter.err != nil {
  224. return RowData{}, iter.err
  225. }
  226. columns := make([]string, 0, len(iter.Columns()))
  227. values := make([]interface{}, 0, len(iter.Columns()))
  228. for _, column := range iter.Columns() {
  229. if c, ok := column.TypeInfo.(TupleTypeInfo); !ok {
  230. val := column.TypeInfo.New()
  231. columns = append(columns, column.Name)
  232. values = append(values, val)
  233. } else {
  234. for i, elem := range c.Elems {
  235. columns = append(columns, TupleColumnName(column.Name, i))
  236. values = append(values, elem.New())
  237. }
  238. }
  239. }
  240. rowData := RowData{
  241. Columns: columns,
  242. Values: values,
  243. }
  244. return rowData, nil
  245. }
  246. // TODO(zariel): is it worth exporting this?
  247. func (iter *Iter) rowMap() (map[string]interface{}, error) {
  248. if iter.err != nil {
  249. return nil, iter.err
  250. }
  251. rowData, _ := iter.RowData()
  252. iter.Scan(rowData.Values...)
  253. m := make(map[string]interface{}, len(rowData.Columns))
  254. rowData.rowMap(m)
  255. return m, nil
  256. }
  257. // SliceMap is a helper function to make the API easier to use
  258. // returns the data from the query in the form of []map[string]interface{}
  259. func (iter *Iter) SliceMap() ([]map[string]interface{}, error) {
  260. if iter.err != nil {
  261. return nil, iter.err
  262. }
  263. // Not checking for the error because we just did
  264. rowData, _ := iter.RowData()
  265. dataToReturn := make([]map[string]interface{}, 0)
  266. for iter.Scan(rowData.Values...) {
  267. m := make(map[string]interface{}, len(rowData.Columns))
  268. rowData.rowMap(m)
  269. dataToReturn = append(dataToReturn, m)
  270. }
  271. if iter.err != nil {
  272. return nil, iter.err
  273. }
  274. return dataToReturn, nil
  275. }
  276. // MapScan takes a map[string]interface{} and populates it with a row
  277. // that is returned from cassandra.
  278. //
  279. // Each call to MapScan() must be called with a new map object.
  280. // During the call to MapScan() any pointers in the existing map
  281. // are replaced with non pointer types before the call returns
  282. //
  283. // iter := session.Query(`SELECT * FROM mytable`).Iter()
  284. // for {
  285. // // New map each iteration
  286. // row = make(map[string]interface{})
  287. // if !iter.MapScan(row) {
  288. // break
  289. // }
  290. // // Do things with row
  291. // if fullname, ok := row["fullname"]; ok {
  292. // fmt.Printf("Full Name: %s\n", fullname)
  293. // }
  294. // }
  295. //
  296. // You can also pass pointers in the map before each call
  297. //
  298. // var fullName FullName // Implements gocql.Unmarshaler and gocql.Marshaler interfaces
  299. // var address net.IP
  300. // var age int
  301. // iter := session.Query(`SELECT * FROM scan_map_table`).Iter()
  302. // for {
  303. // // New map each iteration
  304. // row := map[string]interface{}{
  305. // "fullname": &fullName,
  306. // "age": &age,
  307. // "address": &address,
  308. // }
  309. // if !iter.MapScan(row) {
  310. // break
  311. // }
  312. // fmt.Printf("First: %s Age: %d Address: %q\n", fullName.FirstName, age, address)
  313. // }
  314. func (iter *Iter) MapScan(m map[string]interface{}) bool {
  315. if iter.err != nil {
  316. return false
  317. }
  318. // Not checking for the error because we just did
  319. rowData, _ := iter.RowData()
  320. for i, col := range rowData.Columns {
  321. if dest, ok := m[col]; ok {
  322. rowData.Values[i] = dest
  323. }
  324. }
  325. if iter.Scan(rowData.Values...) {
  326. rowData.rowMap(m)
  327. return true
  328. }
  329. return false
  330. }
  331. func copyBytes(p []byte) []byte {
  332. b := make([]byte, len(p))
  333. copy(b, p)
  334. return b
  335. }