helpers.go 8.9 KB

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