gocql.go 9.4 KB

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