ch-client 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. checksums.yaml +7 -0
  2. data/.codeclimate.yml +22 -0
  3. data/.gitignore +9 -0
  4. data/.travis.yml +3 -0
  5. data/CHANGELOG.md +58 -0
  6. data/Gemfile +3 -0
  7. data/MIT-LICENSE +20 -0
  8. data/README.md +262 -0
  9. data/Rakefile +15 -0
  10. data/VERSION +1 -0
  11. data/bin/clickhouse +9 -0
  12. data/clickhouse.gemspec +36 -0
  13. data/lib/clickhouse.rb +60 -0
  14. data/lib/clickhouse/cli.rb +46 -0
  15. data/lib/clickhouse/cli/client.rb +149 -0
  16. data/lib/clickhouse/cli/console.rb +73 -0
  17. data/lib/clickhouse/cli/server.rb +37 -0
  18. data/lib/clickhouse/cli/server/assets/css/clickhouse.css +177 -0
  19. data/lib/clickhouse/cli/server/assets/css/codemirror.css +341 -0
  20. data/lib/clickhouse/cli/server/assets/css/datatables.css +1 -0
  21. data/lib/clickhouse/cli/server/assets/css/normalize.css +427 -0
  22. data/lib/clickhouse/cli/server/assets/css/skeleton.css +418 -0
  23. data/lib/clickhouse/cli/server/assets/js/clickhouse.js +188 -0
  24. data/lib/clickhouse/cli/server/assets/js/codemirror.js +9096 -0
  25. data/lib/clickhouse/cli/server/assets/js/datatables.js +166 -0
  26. data/lib/clickhouse/cli/server/assets/js/disableswipeback.js +97 -0
  27. data/lib/clickhouse/cli/server/assets/js/jquery.js +11015 -0
  28. data/lib/clickhouse/cli/server/assets/js/sql.js +232 -0
  29. data/lib/clickhouse/cli/server/views/index.erb +46 -0
  30. data/lib/clickhouse/cluster.rb +43 -0
  31. data/lib/clickhouse/connection.rb +42 -0
  32. data/lib/clickhouse/connection/client.rb +135 -0
  33. data/lib/clickhouse/connection/logger.rb +12 -0
  34. data/lib/clickhouse/connection/query.rb +160 -0
  35. data/lib/clickhouse/connection/query/result_row.rb +36 -0
  36. data/lib/clickhouse/connection/query/result_set.rb +103 -0
  37. data/lib/clickhouse/connection/query/table.rb +50 -0
  38. data/lib/clickhouse/error.rb +18 -0
  39. data/lib/clickhouse/utils.rb +23 -0
  40. data/lib/clickhouse/version.rb +7 -0
  41. data/script/console +58 -0
  42. data/test/test_helper.rb +15 -0
  43. data/test/test_helper/coverage.rb +16 -0
  44. data/test/test_helper/minitest.rb +13 -0
  45. data/test/test_helper/simple_connection.rb +12 -0
  46. data/test/unit/connection/query/test_result_row.rb +36 -0
  47. data/test/unit/connection/query/test_result_set.rb +196 -0
  48. data/test/unit/connection/query/test_table.rb +39 -0
  49. data/test/unit/connection/test_client.rb +206 -0
  50. data/test/unit/connection/test_cluster.rb +81 -0
  51. data/test/unit/connection/test_logger.rb +35 -0
  52. data/test/unit/connection/test_query.rb +410 -0
  53. data/test/unit/test_clickhouse.rb +99 -0
  54. data/test/unit/test_connection.rb +55 -0
  55. data/test/unit/test_utils.rb +39 -0
  56. metadata +326 -0
@@ -0,0 +1,232 @@
1
+ CodeMirror.defineMode("sql", function(config, parserConfig) {
2
+ "use strict";
3
+
4
+ var client = parserConfig.client || {},
5
+ atoms = parserConfig.atoms || {"false": true, "true": true, "null": true},
6
+ builtin = parserConfig.builtin || {},
7
+ keywords = parserConfig.keywords,
8
+ operatorChars = /^[*+\-%<>!=&|~^]/,
9
+ hooks = parserConfig.hooks || {};
10
+
11
+ function tokenBase(stream, state) {
12
+ var ch = stream.next();
13
+
14
+ if (hooks[ch]) {
15
+ var result = hooks[ch](stream, state);
16
+ if (result !== false) return result;
17
+ }
18
+
19
+ if ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/))
20
+ || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/)) {
21
+ // hex
22
+ return "number";
23
+ } else if (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/))
24
+ || (ch == "0" && stream.match(/^b[01]+/))) {
25
+ // bitstring
26
+ return "number";
27
+ } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) {
28
+ // numbers
29
+ stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/);
30
+ return "number";
31
+ } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) {
32
+ // placeholders
33
+ return "variable-3";
34
+ } else if (ch == '"' || ch == "'") {
35
+ state.tokenize = tokenLiteral(ch);
36
+ return state.tokenize(stream, state);
37
+ } else if (/^[\(\),\.;\[\]]/.test(ch)) {
38
+ return null;
39
+ } else if (ch == "#" || (ch == "-" && stream.eat("-") && stream.eat(" "))) {
40
+ stream.skipToEnd();
41
+ return "comment";
42
+ } else if (ch == "/" && stream.eat("*")) {
43
+ state.tokenize = tokenComment;
44
+ return state.tokenize(stream, state);
45
+ } else if (operatorChars.test(ch)) {
46
+ stream.eatWhile(operatorChars);
47
+ return false;
48
+ } else {
49
+ stream.eatWhile(/^[_\w\d]/);
50
+ var word = stream.current().toLowerCase();
51
+ if (atoms.hasOwnProperty(word)) return "atom";
52
+ if (builtin.hasOwnProperty(word)) return "builtin";
53
+ if (keywords.hasOwnProperty(word)) return "keyword";
54
+ if (client.hasOwnProperty(word)) return "string-2";
55
+ return "variable";
56
+ }
57
+ }
58
+
59
+ function tokenLiteral(quote) {
60
+ return function(stream, state) {
61
+ var escaped = false, ch;
62
+ while ((ch = stream.next()) != null) {
63
+ if (ch == quote && !escaped) {
64
+ state.tokenize = tokenBase;
65
+ break;
66
+ }
67
+ escaped = !escaped && ch == "\\";
68
+ }
69
+ return "string";
70
+ };
71
+ }
72
+ function tokenComment(stream, state) {
73
+ while (true) {
74
+ if (stream.skipTo("*")) {
75
+ stream.next();
76
+ if (stream.eat("/")) {
77
+ state.tokenize = tokenBase;
78
+ break;
79
+ }
80
+ } else {
81
+ stream.skipToEnd();
82
+ break;
83
+ }
84
+ }
85
+ return "comment";
86
+ }
87
+
88
+ function pushContext(stream, state, type) {
89
+ state.context = {
90
+ prev: state.context,
91
+ indent: stream.indentation(),
92
+ col: stream.column(),
93
+ type: type
94
+ };
95
+ }
96
+
97
+ function popContext(state) {
98
+ state.indent = state.context.indent;
99
+ state.context = state.context.prev;
100
+ }
101
+
102
+ return {
103
+ startState: function() {
104
+ return {tokenize: tokenBase, context: null};
105
+ },
106
+
107
+ token: function(stream, state) {
108
+ if (stream.sol()) {
109
+ if (state.context && state.context.align == null)
110
+ state.context.align = false;
111
+ }
112
+ if (stream.eatSpace()) return null;
113
+
114
+ var style = state.tokenize(stream, state);
115
+ if (style == "comment") return style;
116
+
117
+ if (state.context && state.context.align == null)
118
+ state.context.align = true;
119
+
120
+ var tok = stream.current();
121
+ if (tok == "(")
122
+ pushContext(stream, state, ")");
123
+ else if (tok == "[")
124
+ pushContext(stream, state, "]");
125
+ else if (state.context && state.context.type == tok)
126
+ popContext(state);
127
+ return style;
128
+ },
129
+
130
+ indent: function(state, textAfter) {
131
+ var cx = state.context;
132
+ if (!cx) return CodeMirror.Pass;
133
+ if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1);
134
+ else return cx.indent + config.indentUnit;
135
+ }
136
+ };
137
+ });
138
+
139
+ (function() {
140
+ "use strict";
141
+
142
+ function hookIdentifier(stream) {
143
+ var escaped = false, ch;
144
+
145
+ while ((ch = stream.next()) != null) {
146
+ if (ch == "`" && !escaped) return "variable-2";
147
+ escaped = !escaped && ch == "`";
148
+ }
149
+ return false;
150
+ }
151
+
152
+ // variable token
153
+ function hookVar(stream) {
154
+ // variables
155
+ // @@ and prefix
156
+ if (stream.eat("@")) {
157
+ stream.match(/^session\./);
158
+ stream.match(/^local\./);
159
+ stream.match(/^global\./);
160
+ }
161
+
162
+ if (stream.eat("'")) {
163
+ stream.match(/^.*'/);
164
+ return "variable-2";
165
+ } else if (stream.eat('"')) {
166
+ stream.match(/^.*"/);
167
+ return "variable-2";
168
+ } else if (stream.eat("`")) {
169
+ stream.match(/^.*`/);
170
+ return "variable-2";
171
+ } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) {
172
+ return "variable-2";
173
+ }
174
+ return false;
175
+ };
176
+
177
+ // short client keyword token
178
+ function hookClient(stream) {
179
+ // \g, etc
180
+ return stream.match(/^[a-zA-Z]\b/) ? "variable-2" : false;
181
+ }
182
+
183
+ var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where ";
184
+
185
+ function set(str) {
186
+ var obj = {}, words = str.split(" ");
187
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
188
+ return obj;
189
+ }
190
+
191
+ CodeMirror.defineMIME("text/x-sql", {
192
+ name: "sql",
193
+ keywords: set(sqlKeywords + "begin"),
194
+ builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"),
195
+ atoms: set("false true null unknown")
196
+ });
197
+
198
+ CodeMirror.defineMIME("text/x-mysql", {
199
+ name: "sql",
200
+ client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
201
+ keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
202
+ builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed decimal numeric"),
203
+ atoms: set("false true null unknown"),
204
+ hooks: {
205
+ "@": hookVar,
206
+ "`": hookIdentifier,
207
+ "\\": hookClient
208
+ }
209
+ });
210
+
211
+ CodeMirror.defineMIME("text/x-mariadb", {
212
+ name: "sql",
213
+ client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
214
+ keywords: set(sqlKeywords + "accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
215
+ builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed decimal numeric"),
216
+ atoms: set("false true null unknown"),
217
+ hooks: {
218
+ "@": hookVar,
219
+ "`": hookIdentifier,
220
+ "\\": hookClient
221
+ }
222
+ });
223
+
224
+ // this is based on Peter Raganitsch's 'plsql' mode
225
+ CodeMirror.defineMIME("text/x-plsql", {
226
+ name: "sql",
227
+ client: set("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),
228
+ keywords: set("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),
229
+ functions: set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"),
230
+ builtin: set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2")
231
+ });
232
+ }());
@@ -0,0 +1,46 @@
1
+ <html>
2
+ <head>
3
+ <title>Clickhouse</title>
4
+ <link rel="stylesheet" href="/css/normalize.css">
5
+ <link rel="stylesheet" href="/css/skeleton.css">
6
+ <link rel="stylesheet" href="/css/codemirror.css">
7
+ <link rel="stylesheet" href="/css/datatables.css">
8
+ <link rel="stylesheet" href="/css/clickhouse.css">
9
+ <script charset="utf-8" src="/js/jquery.js"></script>
10
+ <script charset="utf-8" src="/js/codemirror.js"></script>
11
+ <script charset="utf-8" src="/js/datatables.js"></script>
12
+ <script charset="utf-8" src="/js/clickhouse.js"></script>
13
+ <script charset="utf-8" src="/js/sql.js"></script>
14
+ </head>
15
+ <body>
16
+ <h6 class="header">
17
+ Clickhouse Client
18
+ <small>&nbsp;/&nbsp; <span id="urls"></span></small>
19
+ </h6>
20
+ <div class="container">
21
+ <div class="row">
22
+ <!--
23
+ <div class="three columns">
24
+ Recent queries
25
+ </div>
26
+ -->
27
+ <div class="twelve columns">
28
+ <!-- <h6>Compose query</h6> -->
29
+ <form>
30
+ <textarea id="sql" name="sql"></textarea>
31
+ <input class="button" type="submit" value="Run query">
32
+ <a href="#" class="button download">Save as TSV</a>
33
+ <span id="stats"></span>
34
+ </form>
35
+ </div>
36
+ </div>
37
+ </div>
38
+ <script type="text/javascript">
39
+ Clickhouse.init(<%=
40
+ Readline::HISTORY.to_a.inspect
41
+ %>, <%=
42
+ Clickhouse.connection.pond.available.collect(&:url).inspect
43
+ %>);
44
+ </script>
45
+ </body>
46
+ </html>
@@ -0,0 +1,43 @@
1
+ module Clickhouse
2
+ class Cluster < BasicObject
3
+
4
+ attr_reader :pond
5
+
6
+ def initialize(config)
7
+ config = config.dup
8
+ urls = config.delete(:urls) || config.delete("urls")
9
+ urls.collect!{|url| ::Clickhouse::Utils.normalize_url(url)}
10
+
11
+ @pond = ::Pond.new :maximum_size => urls.size, :timeout => 5.0
12
+ block = ::Proc.new do
13
+ url = (urls - pond.available.collect(&:url)).first || urls.sample
14
+ ::Clickhouse::Connection.new(config.merge(:url => url))
15
+ end
16
+
17
+ pond.instance_variable_set :@block, block
18
+ pond.maximum_size.times do
19
+ pond.available << block.call
20
+ end
21
+
22
+ pond.detach_if = ::Proc.new do |connection|
23
+ begin
24
+ connection.ping!
25
+ false
26
+ rescue
27
+ true
28
+ end
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ def method_missing(*args, &block)
35
+ pond.checkout do |connection|
36
+ connection.send(*args, &block)
37
+ end
38
+ rescue ::Clickhouse::ConnectionError
39
+ retry if pond.available.any?
40
+ end
41
+
42
+ end
43
+ end
@@ -0,0 +1,42 @@
1
+ require "clickhouse/connection/client"
2
+ require "clickhouse/connection/logger"
3
+ require "clickhouse/connection/query"
4
+
5
+ module Clickhouse
6
+ class Connection
7
+
8
+ DEFAULT_CONFIG = {
9
+ :scheme => "http",
10
+ :host => "localhost",
11
+ :port => 8123
12
+ }
13
+
14
+ include Client
15
+ include Logger
16
+ include Query
17
+
18
+ def initialize(config = {})
19
+ @config = normalize_config(config)
20
+ end
21
+
22
+ private
23
+
24
+ def normalize_config(config)
25
+ config = config.inject({}) do |hash, (key, value)|
26
+ hash[key.to_sym] = value
27
+ hash
28
+ end
29
+
30
+ if config[:url]
31
+ uri = URI Clickhouse::Utils.normalize_url(config[:url])
32
+ config[:scheme] = uri.scheme
33
+ config[:host] = uri.host
34
+ config[:port] = uri.port
35
+ config.delete(:url)
36
+ end
37
+
38
+ DEFAULT_CONFIG.merge(config.reject{|_k, v| v.nil?})
39
+ end
40
+
41
+ end
42
+ end
@@ -0,0 +1,135 @@
1
+ module Clickhouse
2
+ class Connection
3
+ module Client
4
+ include ActiveSupport::NumberHelper
5
+
6
+ def connect!
7
+ ping! unless connected?
8
+ end
9
+
10
+ def ping!
11
+ ensure_authentication
12
+ status = client.get("/").status
13
+ if status != 200
14
+ raise ConnectionError, "Unexpected response status: #{status}"
15
+ end
16
+ true
17
+ rescue Faraday::Error => e
18
+ raise ConnectionError, e.message
19
+ end
20
+
21
+ def connected?
22
+ instance_variables.include?(:@client) && !!@client
23
+ end
24
+
25
+ def get(query)
26
+ request(:get, query)
27
+ end
28
+
29
+ def post(query, body = nil)
30
+ request(:post, query, body)
31
+ end
32
+
33
+ def url
34
+ "#{@config[:scheme]}://#{@config[:host]}:#{@config[:port]}"
35
+ end
36
+
37
+ private
38
+
39
+ def client
40
+ @client ||= Faraday.new(:url => url)
41
+ end
42
+
43
+ def ensure_authentication
44
+ username, password = @config.values_at(:username, :password)
45
+ client.basic_auth(username || "default", password) if username || password
46
+ end
47
+
48
+ def path(query)
49
+ params = @config.select{|k, _v| k == :database}
50
+ params[:query] = query
51
+ params[:output_format_write_statistics] = 1
52
+ query_string = params.collect{|k, v| "#{k}=#{CGI.escape(v.to_s)}"}.join("&")
53
+
54
+ "/?#{query_string}"
55
+ end
56
+
57
+ def request(method, query, body = nil)
58
+ connect!
59
+ query = query.strip
60
+ start = Time.now
61
+
62
+ response = client.send(method, path(query), body)
63
+ status = response.status
64
+ duration = Time.now - start
65
+ query, format = Utils.extract_format(query)
66
+ response = parse_body(format, response.body)
67
+ stats = parse_stats(response)
68
+
69
+ write_log duration, query, stats
70
+ raise QueryError, "Got status #{status} (expected 200): #{response}" unless status == 200
71
+ response
72
+
73
+ rescue Faraday::Error => e
74
+ raise ConnectionError, e.message
75
+ end
76
+
77
+ def parse_body(format, body)
78
+ case format
79
+ when "JSON", "JSONCompact"
80
+ body = JSON.parse(body) if body.strip[0] == "{"
81
+ end
82
+ body
83
+ end
84
+
85
+ def parse_stats(response)
86
+ return {} unless response.is_a?(Hash)
87
+
88
+ options = {:locale => :en, :precision => 2, :significant => false}
89
+ stats = response["statistics"].merge("rows" => response["rows"])
90
+ factor = 1 / stats["elapsed"]
91
+
92
+ stats["elapsed"] = number_to_human_duration(stats["elapsed"])
93
+ stats["rows_per_second"] = number_to_human(stats["rows_read"] * factor, options).downcase
94
+ stats["data_per_second"] = number_to_human_size(stats["bytes_read"] * factor, options)
95
+ stats["rows_read"] = number_to_human(stats["rows_read"], options).downcase
96
+ stats["data_read"] = number_to_human_size(stats["bytes_read"], options)
97
+
98
+ stats
99
+ end
100
+
101
+ def write_log(duration, query, stats)
102
+ duration = number_to_human_duration(duration)
103
+
104
+ rows,
105
+ elapsed,
106
+ rows_read,
107
+ data_read,
108
+ rows_per_second,
109
+ data_per_second = stats.values_at(*%w(
110
+ rows
111
+ elapsed
112
+ rows_read
113
+ data_read
114
+ rows_per_second
115
+ data_per_second
116
+ ))
117
+
118
+ line1 = "\n \e[1mSQL (#{duration})\e[0m #{query};"
119
+ line2 = "\n \e[1m#{rows} #{"row".pluralize(rows)} in set. Elapsed: #{elapsed}. Processed: #{rows_read} rows, #{data_read} (#{rows_per_second} rows/s, #{data_per_second}/s)\e[0m" if rows
120
+
121
+ log :debug, "#{line1}#{line2} "
122
+ end
123
+
124
+ def number_to_human_duration(number)
125
+ if (amount = number * 1000.0) < 1000
126
+ round = (amount < 1) ? 3 : 1
127
+ "#{amount.round(round)}ms"
128
+ else
129
+ "#{number.round(1)}s"
130
+ end
131
+ end
132
+
133
+ end
134
+ end
135
+ end