gocql.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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:9042 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. opLAST byte = 0x0A // not a real opcode -- used to check for valid opcodes
  56. flagCompressed byte = 0x01
  57. keyVersion string = "CQL_VERSION"
  58. keyCompression string = "COMPRESSION"
  59. )
  60. var consistencyLevels = map[string]byte{"any": 0x00, "one": 0x01, "two": 0x02,
  61. "three": 0x03, "quorum": 0x04, "all": 0x05, "local_quorum": 0x06, "each_quorum": 0x07}
  62. var rnd = rand.New(rand.NewSource(0))
  63. type drv struct{}
  64. func (d drv) Open(name string) (driver.Conn, error) {
  65. return Open(name)
  66. }
  67. type connection struct {
  68. c net.Conn
  69. compression string
  70. consistency byte
  71. }
  72. func Open(name string) (*connection, error) {
  73. parts := strings.Split(name, " ")
  74. address := ""
  75. if len(parts) >= 1 {
  76. addresses := strings.Split(parts[0], ",")
  77. if len(addresses) > 0 {
  78. address = addresses[rnd.Intn(len(addresses))]
  79. }
  80. }
  81. c, err := net.Dial("tcp", address)
  82. if err != nil {
  83. return nil, err
  84. }
  85. version := "3.0.0"
  86. var (
  87. keyspace string
  88. compression string
  89. consistency byte = 0x01
  90. ok bool
  91. )
  92. for i := 1; i < len(parts); i++ {
  93. switch {
  94. case parts[i] == "":
  95. continue
  96. case strings.HasPrefix(parts[i], "keyspace="):
  97. keyspace = strings.TrimSpace(parts[i][9:])
  98. case strings.HasPrefix(parts[i], "compression="):
  99. compression = strings.TrimSpace(parts[i][12:])
  100. if compression != "snappy" {
  101. return nil, fmt.Errorf("unknown compression algorithm %q",
  102. compression)
  103. }
  104. case strings.HasPrefix(parts[i], "version="):
  105. version = strings.TrimSpace(parts[i][8:])
  106. case strings.HasPrefix(parts[i], "consistency="):
  107. cs := strings.TrimSpace(parts[i][12:])
  108. if consistency, ok = consistencyLevels[cs]; !ok {
  109. return nil, fmt.Errorf("unknown consistency level %q", cs)
  110. }
  111. default:
  112. return nil, fmt.Errorf("unsupported option %q", parts[i])
  113. }
  114. }
  115. cn := &connection{c: c, compression: compression, consistency: consistency}
  116. b := &bytes.Buffer{}
  117. if compression != "" {
  118. binary.Write(b, binary.BigEndian, uint16(2))
  119. } else {
  120. binary.Write(b, binary.BigEndian, uint16(1))
  121. }
  122. binary.Write(b, binary.BigEndian, uint16(len(keyVersion)))
  123. b.WriteString(keyVersion)
  124. binary.Write(b, binary.BigEndian, uint16(len(version)))
  125. b.WriteString(version)
  126. if compression != "" {
  127. binary.Write(b, binary.BigEndian, uint16(len(keyCompression)))
  128. b.WriteString(keyCompression)
  129. binary.Write(b, binary.BigEndian, uint16(len(compression)))
  130. b.WriteString(compression)
  131. }
  132. if err := cn.send(opStartup, b.Bytes()); err != nil {
  133. return nil, err
  134. }
  135. opcode, _, err := cn.recv()
  136. if err != nil {
  137. return nil, err
  138. }
  139. if opcode != opReady {
  140. return nil, fmt.Errorf("connection not ready")
  141. }
  142. if keyspace != "" {
  143. st, err := cn.Prepare(fmt.Sprintf("USE %s", keyspace))
  144. if err != nil {
  145. return nil, err
  146. }
  147. if _, err = st.Exec([]driver.Value{}); err != nil {
  148. return nil, err
  149. }
  150. }
  151. return cn, nil
  152. }
  153. // close a connection actively, typically used when there's an error and we want to ensure
  154. // we don't repeatedly try to use the broken connection
  155. func (cn *connection) close() {
  156. cn.c.Close()
  157. cn.c = nil // ensure we generate ErrBadConn when cn gets reused
  158. }
  159. func (cn *connection) send(opcode byte, body []byte) error {
  160. if cn.c == nil {
  161. return driver.ErrBadConn
  162. }
  163. frame := make([]byte, len(body)+8)
  164. frame[0] = protoRequest
  165. frame[1] = 0
  166. frame[2] = 0
  167. frame[3] = opcode
  168. binary.BigEndian.PutUint32(frame[4:8], uint32(len(body)))
  169. copy(frame[8:], body)
  170. if _, err := cn.c.Write(frame); err != nil {
  171. return err
  172. }
  173. return nil
  174. }
  175. func (cn *connection) recv() (byte, []byte, error) {
  176. if cn.c == nil {
  177. return 0, nil, driver.ErrBadConn
  178. }
  179. header := make([]byte, 8)
  180. if _, err := io.ReadFull(cn.c, header); err != nil {
  181. cn.close() // better assume that the connection is broken (may have read some bytes)
  182. return 0, nil, err
  183. }
  184. // verify that the frame starts with version==1 and req/resp flag==response
  185. // this may be overly conservative in that future versions may be backwards compatible
  186. // in that case simply amend the check...
  187. if header[0] != protoResponse {
  188. cn.close()
  189. return 0, nil, fmt.Errorf("unsupported frame version or not a response: 0x%x (header=%v)", header[0], header)
  190. }
  191. // verify that the flags field has only a single flag set, again, this may
  192. // be overly conservative if additional flags are backwards-compatible
  193. if header[1] > 1 {
  194. cn.close()
  195. return 0, nil, fmt.Errorf("unsupported frame flags: 0x%x (header=%v)", header[1], header)
  196. }
  197. opcode := header[3]
  198. if opcode > opLAST {
  199. cn.close()
  200. return 0, nil, fmt.Errorf("unknown opcode: 0x%x (header=%v)", opcode, header)
  201. }
  202. length := binary.BigEndian.Uint32(header[4:8])
  203. var body []byte
  204. if length > 0 {
  205. if length > 256*1024*1024 { // spec says 256MB is max
  206. cn.close()
  207. return 0, nil, fmt.Errorf("frame too large: %d (header=%v)", length, header)
  208. }
  209. body = make([]byte, length)
  210. if _, err := io.ReadFull(cn.c, body); err != nil {
  211. cn.close() // better assume that the connection is broken
  212. return 0, nil, err
  213. }
  214. }
  215. if header[1]&flagCompressed != 0 && cn.compression == "snappy" {
  216. var err error
  217. body, err = snappy.Decode(nil, body)
  218. if err != nil {
  219. cn.close()
  220. return 0, nil, err
  221. }
  222. }
  223. if opcode == opError {
  224. code := binary.BigEndian.Uint32(body[0:4])
  225. msglen := binary.BigEndian.Uint16(body[4:6])
  226. msg := string(body[6 : 6+msglen])
  227. return opcode, body, Error{Code: int(code), Msg: msg}
  228. }
  229. return opcode, body, nil
  230. }
  231. func (cn *connection) Begin() (driver.Tx, error) {
  232. if cn.c == nil {
  233. return nil, driver.ErrBadConn
  234. }
  235. return cn, nil
  236. }
  237. func (cn *connection) Commit() error {
  238. if cn.c == nil {
  239. return driver.ErrBadConn
  240. }
  241. return nil
  242. }
  243. func (cn *connection) Close() error {
  244. if cn.c == nil {
  245. return driver.ErrBadConn
  246. }
  247. cn.close()
  248. return nil
  249. }
  250. func (cn *connection) Rollback() error {
  251. if cn.c == nil {
  252. return driver.ErrBadConn
  253. }
  254. return nil
  255. }
  256. func (cn *connection) Prepare(query string) (driver.Stmt, error) {
  257. body := make([]byte, len(query)+4)
  258. binary.BigEndian.PutUint32(body[0:4], uint32(len(query)))
  259. copy(body[4:], []byte(query))
  260. if err := cn.send(opPrepare, body); err != nil {
  261. return nil, err
  262. }
  263. opcode, body, err := cn.recv()
  264. if err != nil {
  265. return nil, err
  266. }
  267. if opcode != opResult || binary.BigEndian.Uint32(body) != 4 {
  268. return nil, fmt.Errorf("expected prepared result")
  269. }
  270. n := int(binary.BigEndian.Uint16(body[4:]))
  271. prepared := body[6 : 6+n]
  272. columns, meta, _ := parseMeta(body[6+n:])
  273. return &statement{cn: cn, query: query,
  274. prepared: prepared, columns: columns, meta: meta}, nil
  275. }
  276. type statement struct {
  277. cn *connection
  278. query string
  279. prepared []byte
  280. columns []string
  281. meta []uint16
  282. }
  283. func (s *statement) Close() error {
  284. return nil
  285. }
  286. func (st *statement) ColumnConverter(idx int) driver.ValueConverter {
  287. return (&columnEncoder{st.meta}).ColumnConverter(idx)
  288. }
  289. func (st *statement) NumInput() int {
  290. return len(st.columns)
  291. }
  292. func parseMeta(body []byte) ([]string, []uint16, int) {
  293. flags := binary.BigEndian.Uint32(body)
  294. globalTableSpec := flags&1 == 1
  295. columnCount := int(binary.BigEndian.Uint32(body[4:]))
  296. i := 8
  297. if globalTableSpec {
  298. l := int(binary.BigEndian.Uint16(body[i:]))
  299. keyspace := string(body[i+2 : i+2+l])
  300. i += 2 + l
  301. l = int(binary.BigEndian.Uint16(body[i:]))
  302. tablename := string(body[i+2 : i+2+l])
  303. i += 2 + l
  304. _, _ = keyspace, tablename
  305. }
  306. columns := make([]string, columnCount)
  307. meta := make([]uint16, columnCount)
  308. for c := 0; c < columnCount; c++ {
  309. l := int(binary.BigEndian.Uint16(body[i:]))
  310. columns[c] = string(body[i+2 : i+2+l])
  311. i += 2 + l
  312. meta[c] = binary.BigEndian.Uint16(body[i:])
  313. i += 2
  314. }
  315. return columns, meta, i
  316. }
  317. func (st *statement) exec(v []driver.Value) error {
  318. sz := 6 + len(st.prepared)
  319. for i := range v {
  320. if b, ok := v[i].([]byte); ok {
  321. sz += len(b) + 4
  322. }
  323. }
  324. body, p := make([]byte, sz), 4+len(st.prepared)
  325. binary.BigEndian.PutUint16(body, uint16(len(st.prepared)))
  326. copy(body[2:], st.prepared)
  327. binary.BigEndian.PutUint16(body[p-2:], uint16(len(v)))
  328. for i := range v {
  329. b, ok := v[i].([]byte)
  330. if !ok {
  331. return fmt.Errorf("unsupported type %T at column %d", v[i], i)
  332. }
  333. binary.BigEndian.PutUint32(body[p:], uint32(len(b)))
  334. copy(body[p+4:], b)
  335. p += 4 + len(b)
  336. }
  337. binary.BigEndian.PutUint16(body[p:], uint16(st.cn.consistency))
  338. if err := st.cn.send(opExecute, body); err != nil {
  339. return err
  340. }
  341. return nil
  342. }
  343. func (st *statement) Exec(v []driver.Value) (driver.Result, error) {
  344. if err := st.exec(v); err != nil {
  345. return nil, err
  346. }
  347. opcode, body, err := st.cn.recv()
  348. if err != nil {
  349. return nil, err
  350. }
  351. _, _ = opcode, body
  352. return nil, nil
  353. }
  354. func (st *statement) Query(v []driver.Value) (driver.Rows, error) {
  355. if err := st.exec(v); err != nil {
  356. return nil, err
  357. }
  358. opcode, body, err := st.cn.recv()
  359. if err != nil {
  360. return nil, err
  361. }
  362. kind := binary.BigEndian.Uint32(body[0:4])
  363. if opcode != opResult || kind != 2 {
  364. return nil, fmt.Errorf("expected rows as result")
  365. }
  366. columns, meta, n := parseMeta(body[4:])
  367. i := n + 4
  368. rows := &rows{
  369. columns: columns,
  370. meta: meta,
  371. numRows: int(binary.BigEndian.Uint32(body[i:])),
  372. }
  373. i += 4
  374. rows.body = body[i:]
  375. return rows, nil
  376. }
  377. type rows struct {
  378. columns []string
  379. meta []uint16
  380. body []byte
  381. row int
  382. numRows int
  383. }
  384. func (r *rows) Close() error {
  385. return nil
  386. }
  387. func (r *rows) Columns() []string {
  388. return r.columns
  389. }
  390. func (r *rows) Next(values []driver.Value) error {
  391. if r.row >= r.numRows {
  392. return io.EOF
  393. }
  394. for column := 0; column < len(r.columns); column++ {
  395. n := int32(binary.BigEndian.Uint32(r.body))
  396. r.body = r.body[4:]
  397. if n >= 0 {
  398. values[column] = decode(r.body[:n], r.meta[column])
  399. r.body = r.body[n:]
  400. } else {
  401. values[column] = nil
  402. }
  403. }
  404. r.row++
  405. return nil
  406. }
  407. type Error struct {
  408. Code int
  409. Msg string
  410. }
  411. func (e Error) Error() string {
  412. return e.Msg
  413. }
  414. func init() {
  415. sql.Register("gocql", &drv{})
  416. }