gocql.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. // The gocql package provides a database/sql driver for CQL, the Cassandra
  5. // query language.
  6. //
  7. // This package requires a recent version of Cassandra (≥ 1.2) that supports
  8. // CQL 3.0 and the new native protocol. The native protocol is still considered
  9. // beta and must be enabled manually in Cassandra 1.2 by setting
  10. // "start_native_transport" to true in conf/cassandra.yaml.
  11. //
  12. // Example Usage:
  13. //
  14. // db, err := sql.Open("gocql", "localhost:8000 keyspace=system")
  15. // // ...
  16. // rows, err := db.Query("SELECT keyspace_name FROM schema_keyspaces")
  17. // // ...
  18. // for rows.Next() {
  19. // var keyspace string
  20. // err = rows.Scan(&keyspace)
  21. // // ...
  22. // fmt.Println(keyspace)
  23. // }
  24. // if err := rows.Err(); err != nil {
  25. // // ...
  26. // }
  27. //
  28. package gocql
  29. import (
  30. "bytes"
  31. "code.google.com/p/snappy-go/snappy"
  32. "database/sql"
  33. "database/sql/driver"
  34. "encoding/binary"
  35. "fmt"
  36. "io"
  37. "math/rand"
  38. "net"
  39. "strings"
  40. )
  41. const (
  42. protoRequest byte = 0x01
  43. protoResponse byte = 0x81
  44. opError byte = 0x00
  45. opStartup byte = 0x01
  46. opReady byte = 0x02
  47. opAuthenticate byte = 0x03
  48. opCredentials byte = 0x04
  49. opOptions byte = 0x05
  50. opSupported byte = 0x06
  51. opQuery byte = 0x07
  52. opResult byte = 0x08
  53. opPrepare byte = 0x09
  54. opExecute byte = 0x0A
  55. flagCompressed byte = 0x01
  56. )
  57. var rnd = rand.New(rand.NewSource(0))
  58. type drv struct{}
  59. func (d drv) Open(name string) (driver.Conn, error) {
  60. return Open(name)
  61. }
  62. type connection struct {
  63. c net.Conn
  64. compression string
  65. }
  66. func Open(name string) (*connection, error) {
  67. parts := strings.Split(name, " ")
  68. address := ""
  69. if len(parts) >= 1 {
  70. addresses := strings.Split(parts[0], ",")
  71. if len(addresses) > 0 {
  72. address = addresses[rnd.Intn(len(addresses))]
  73. }
  74. }
  75. c, err := net.Dial("tcp", address)
  76. if err != nil {
  77. return nil, err
  78. }
  79. version := "3.0.0"
  80. keyspace := ""
  81. compression := ""
  82. for i := 1; i < len(parts); i++ {
  83. switch {
  84. case parts[i] == "":
  85. continue
  86. case strings.HasPrefix(parts[i], "keyspace="):
  87. keyspace = strings.TrimSpace(parts[i][9:])
  88. case strings.HasPrefix(parts[i], "compression="):
  89. compression = strings.TrimSpace(parts[i][12:])
  90. if compression != "snappy" {
  91. return nil, fmt.Errorf("unknown compression algorithm %q",
  92. compression)
  93. }
  94. case strings.HasPrefix(parts[i], "version="):
  95. compression = strings.TrimSpace(parts[i][8:])
  96. default:
  97. return nil, fmt.Errorf("unsupported option %q", parts[i])
  98. }
  99. }
  100. cn := &connection{c: c, compression: compression}
  101. b := &bytes.Buffer{}
  102. binary.Write(b, binary.BigEndian, uint16(len(version)))
  103. b.WriteString(version)
  104. if compression != "" {
  105. binary.Write(b, binary.BigEndian, uint16(1))
  106. binary.Write(b, binary.BigEndian, uint16(1))
  107. binary.Write(b, binary.BigEndian, uint16(len(compression)))
  108. b.WriteString(compression)
  109. } else {
  110. binary.Write(b, binary.BigEndian, uint16(0))
  111. }
  112. if err := cn.send(opStartup, b.Bytes()); err != nil {
  113. return nil, err
  114. }
  115. opcode, _, err := cn.recv()
  116. if err != nil {
  117. return nil, err
  118. }
  119. if opcode != opReady {
  120. return nil, fmt.Errorf("connection not ready")
  121. }
  122. if keyspace != "" {
  123. st, err := cn.Prepare(fmt.Sprintf("USE %s", keyspace))
  124. if err != nil {
  125. return nil, err
  126. }
  127. if _, err = st.Exec([]driver.Value{}); err != nil {
  128. return nil, err
  129. }
  130. }
  131. return cn, nil
  132. }
  133. func (cn *connection) send(opcode byte, body []byte) error {
  134. frame := make([]byte, len(body)+8)
  135. frame[0] = protoRequest
  136. frame[1] = 0
  137. frame[2] = 0
  138. frame[3] = opcode
  139. binary.BigEndian.PutUint32(frame[4:8], uint32(len(body)))
  140. copy(frame[8:], body)
  141. if _, err := cn.c.Write(frame); err != nil {
  142. return err
  143. }
  144. return nil
  145. }
  146. func (cn *connection) recv() (byte, []byte, error) {
  147. header := make([]byte, 8)
  148. if _, err := cn.c.Read(header); err != nil {
  149. return 0, nil, err
  150. }
  151. opcode := header[3]
  152. length := binary.BigEndian.Uint32(header[4:8])
  153. var body []byte
  154. if length > 0 {
  155. body = make([]byte, length)
  156. if _, err := cn.c.Read(body); err != nil {
  157. return 0, nil, err
  158. }
  159. }
  160. if header[1]&flagCompressed != 0 && cn.compression == "snappy" {
  161. var err error
  162. body, err = snappy.Decode(nil, body)
  163. if err != nil {
  164. return 0, nil, err
  165. }
  166. }
  167. if opcode == opError {
  168. code := binary.BigEndian.Uint32(body[0:4])
  169. msglen := binary.BigEndian.Uint16(body[4:6])
  170. msg := string(body[6 : 6+msglen])
  171. return opcode, body, Error{Code: int(code), Msg: msg}
  172. }
  173. return opcode, body, nil
  174. }
  175. func (cn *connection) Begin() (driver.Tx, error) {
  176. return cn, nil
  177. }
  178. func (cn *connection) Commit() error {
  179. return nil
  180. }
  181. func (cn *connection) Close() error {
  182. return cn.c.Close()
  183. }
  184. func (cn *connection) Rollback() error {
  185. return nil
  186. }
  187. func (cn *connection) Prepare(query string) (driver.Stmt, error) {
  188. body := make([]byte, len(query)+4)
  189. binary.BigEndian.PutUint32(body[0:4], uint32(len(query)))
  190. copy(body[4:], []byte(query))
  191. if err := cn.send(opPrepare, body); err != nil {
  192. return nil, err
  193. }
  194. opcode, body, err := cn.recv()
  195. if err != nil {
  196. return nil, err
  197. }
  198. if opcode != opResult || binary.BigEndian.Uint32(body) != 4 {
  199. return nil, fmt.Errorf("expected prepared result")
  200. }
  201. prepared := int(binary.BigEndian.Uint32(body[4:]))
  202. columns, meta, _ := parseMeta(body[8:])
  203. return &statement{cn: cn, query: query,
  204. prepared: prepared, columns: columns, meta: meta}, nil
  205. }
  206. type statement struct {
  207. cn *connection
  208. query string
  209. prepared int
  210. columns []string
  211. meta []uint16
  212. }
  213. func (s *statement) Close() error {
  214. return nil
  215. }
  216. func (st *statement) ColumnConverter(idx int) driver.ValueConverter {
  217. return (&columnEncoder{st.meta}).ColumnConverter(idx)
  218. }
  219. func (st *statement) NumInput() int {
  220. return len(st.columns)
  221. }
  222. func parseMeta(body []byte) ([]string, []uint16, int) {
  223. flags := binary.BigEndian.Uint32(body)
  224. globalTableSpec := flags&1 == 1
  225. columnCount := int(binary.BigEndian.Uint32(body[4:]))
  226. i := 8
  227. if globalTableSpec {
  228. l := int(binary.BigEndian.Uint16(body[i:]))
  229. keyspace := string(body[i+2 : i+2+l])
  230. i += 2 + l
  231. l = int(binary.BigEndian.Uint16(body[i:]))
  232. tablename := string(body[i+2 : i+2+l])
  233. i += 2 + l
  234. _, _ = keyspace, tablename
  235. }
  236. columns := make([]string, columnCount)
  237. meta := make([]uint16, columnCount)
  238. for c := 0; c < columnCount; c++ {
  239. l := int(binary.BigEndian.Uint16(body[i:]))
  240. columns[c] = string(body[i+2 : i+2+l])
  241. i += 2 + l
  242. meta[c] = binary.BigEndian.Uint16(body[i:])
  243. i += 2
  244. }
  245. return columns, meta, i
  246. }
  247. func (st *statement) exec(v []driver.Value) error {
  248. sz := 8
  249. for i := range v {
  250. if b, ok := v[i].([]byte); ok {
  251. sz += len(b) + 4
  252. }
  253. }
  254. body, p := make([]byte, sz), 6
  255. binary.BigEndian.PutUint32(body, uint32(st.prepared))
  256. binary.BigEndian.PutUint16(body[4:], uint16(len(v)))
  257. for i := range v {
  258. b, ok := v[i].([]byte)
  259. if !ok {
  260. return fmt.Errorf("unsupported type %T at column %d", v[i], i)
  261. }
  262. binary.BigEndian.PutUint32(body[p:], uint32(len(b)))
  263. copy(body[p+4:], b)
  264. p += 4 + len(b)
  265. }
  266. if err := st.cn.send(opExecute, body); err != nil {
  267. return err
  268. }
  269. return nil
  270. }
  271. func (st *statement) Exec(v []driver.Value) (driver.Result, error) {
  272. if err := st.exec(v); err != nil {
  273. return nil, err
  274. }
  275. opcode, body, err := st.cn.recv()
  276. if err != nil {
  277. return nil, err
  278. }
  279. _, _ = opcode, body
  280. return nil, nil
  281. }
  282. func (st *statement) Query(v []driver.Value) (driver.Rows, error) {
  283. if err := st.exec(v); err != nil {
  284. return nil, err
  285. }
  286. opcode, body, err := st.cn.recv()
  287. if err != nil {
  288. return nil, err
  289. }
  290. kind := binary.BigEndian.Uint32(body[0:4])
  291. if opcode != opResult || kind != 2 {
  292. return nil, fmt.Errorf("expected rows as result")
  293. }
  294. columns, meta, n := parseMeta(body[4:])
  295. i := n + 4
  296. rows := &rows{
  297. columns: columns,
  298. meta: meta,
  299. numRows: int(binary.BigEndian.Uint32(body[i:])),
  300. }
  301. i += 4
  302. rows.body = body[i:]
  303. return rows, nil
  304. }
  305. type rows struct {
  306. columns []string
  307. meta []uint16
  308. body []byte
  309. row int
  310. numRows int
  311. }
  312. func (r *rows) Close() error {
  313. return nil
  314. }
  315. func (r *rows) Columns() []string {
  316. return r.columns
  317. }
  318. func (r *rows) Next(values []driver.Value) error {
  319. if r.row >= r.numRows {
  320. return io.EOF
  321. }
  322. for column := 0; column < len(r.columns); column++ {
  323. n := int(binary.BigEndian.Uint32(r.body))
  324. r.body = r.body[4:]
  325. if n >= 0 {
  326. values[column] = decode(r.body[:n], r.meta[column])
  327. r.body = r.body[n:]
  328. } else {
  329. fmt.Println(column, n)
  330. values[column] = nil
  331. }
  332. }
  333. r.row++
  334. return nil
  335. }
  336. type Error struct {
  337. Code int
  338. Msg string
  339. }
  340. func (e Error) Error() string {
  341. return e.Msg
  342. }
  343. func init() {
  344. sql.Register("gocql", &drv{})
  345. }