1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
extern crate chrono;
extern crate chrono_tz;
extern crate core;
#[macro_use]
extern crate futures;
extern crate hostname;
#[macro_use]
extern crate log;
extern crate rand;
extern crate tokio;
use std::fmt;
use std::net::SocketAddr;
use futures::{Future, Stream};
use tokio::net::TcpStream;
use tokio::prelude::*;
pub use block::Block;
use block::BlockEx;
use io::ClickhouseTransport;
use io::IoFuture;
use types::query::QueryEx;
pub use types::ClickhouseError;
use types::{ClickhouseResult, Cmd, Context, Packet, Query};
mod binary;
mod block;
mod client_info;
mod column;
mod io;
mod types;
#[derive(Clone)]
pub struct Options {
addr: SocketAddr,
database: String,
username: String,
password: String,
}
pub struct Client {
_private: (),
}
pub struct ClientHandle {
inner: ClickhouseTransport,
context: Context,
}
impl Options {
pub fn new(addr: SocketAddr) -> Options {
Options {
addr,
database: "default".to_string(),
username: "default".to_string(),
password: "".to_string(),
}
}
pub fn database(self, database: &str) -> Options {
Options {
database: database.to_string(),
..self
}
}
pub fn username(self, username: &str) -> Options {
Options {
username: username.to_string(),
..self
}
}
pub fn password(self, password: &str) -> Options {
Options {
password: password.to_string(),
..self
}
}
}
impl fmt::Debug for ClientHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "ClientHandle({:?})", self.context.server_info)
}
}
impl Client {
pub fn connect(options: Options) -> IoFuture<ClientHandle> {
Box::new(
TcpStream::connect(&options.addr)
.and_then(|stream| {
stream.set_nodelay(true)?;
let transport = ClickhouseTransport::new(stream);
Ok(ClientHandle {
inner: transport,
context: Context::default(),
})
}).and_then(|client| client.hello()),
)
}
}
impl ClientHandle {
pub fn hello(self) -> IoFuture<ClientHandle> {
let context = self.context;
Box::new(
self.inner
.call(Cmd::Hello(context.clone()))
.fold(None, move |_, packet| match packet {
Packet::Hello(inner, server_info) => {
let context = Context {
server_info,
..context.clone()
};
let client = ClientHandle { inner, context };
future::ok::<_, std::io::Error>(Some(client))
}
Packet::Exception(e) => future::err(ClickhouseError::Internal(e).into()),
_ => future::err(ClickhouseError::UnexpectedPacket.into()),
}).map(Option::unwrap),
)
}
pub fn ping(self) -> IoFuture<ClientHandle> {
let context = self.context;
Box::new(
self.inner
.call(Cmd::Ping)
.fold(None, move |_, packet| match packet {
Packet::Pong(inner) => {
let client = ClientHandle {
inner,
context: context.clone(),
};
future::ok::<_, std::io::Error>(Some(client))
}
Packet::Exception(e) => future::err(ClickhouseError::Internal(e).into()),
_ => future::err(ClickhouseError::UnexpectedPacket.into()),
}).map(Option::unwrap),
)
}
pub fn query_all<Q>(self, sql: Q) -> IoFuture<(ClientHandle, Block)>
where
Query: From<Q>,
{
let context = self.context;
let query = Query::from(sql);
let init = (None, vec![]);
info!("[send query] {}", query.get_sql());
Box::new(
self.inner
.call(Cmd::SendQuery(query, context.clone()))
.fold(init, move |(h, mut bs), packet| match packet {
Packet::Block(b) => {
if !b.is_empty() {
bs.push(b);
}
future::ok::<_, std::io::Error>((h, bs))
}
Packet::Eof(inner) => {
let client = ClientHandle {
inner,
context: context.clone(),
};
future::ok((Some(client), bs))
}
Packet::ProfileInfo(_) | Packet::Progress(_) => future::ok((h, bs)),
Packet::Exception(e) => future::err(ClickhouseError::Internal(e).into()),
_ => future::err(ClickhouseError::UnexpectedPacket.into()),
}).map(|(client, blocks)| (client.unwrap(), Block::concat(&blocks[..]))),
)
}
pub fn execute<Q>(self, sql: Q) -> IoFuture<ClientHandle>
where
Query: From<Q>,
{
let context = self.context;
let query = Query::from(sql);
trace!("[send query] {}", query.get_sql());
Box::new(
self.inner
.call(Cmd::SendQuery(query, context.clone()))
.fold(None, move |acc, packet| match packet {
Packet::Eof(inner) => {
let client = ClientHandle {
inner,
context: context.clone(),
};
future::ok::<_, std::io::Error>(Some(client))
}
Packet::Block(_) | Packet::ProfileInfo(_) | Packet::Progress(_) => {
future::ok::<_, std::io::Error>(acc)
}
Packet::Exception(exception) => {
future::err(ClickhouseError::Internal(exception).into())
}
_ => future::err(ClickhouseError::UnexpectedPacket.into()),
}).map(Option::unwrap),
)
}
pub fn insert<Q>(self, table: Q, block: Block) -> IoFuture<ClientHandle>
where
Query: From<Q>,
{
let names: Vec<_> = block
.as_ref()
.columns()
.iter()
.map(|column| column.name().to_string())
.collect();
let fields = names.join(", ");
let query = Query::from(table)
.map_sql(|table| format!("INSERT INTO {} ({}) VALUES", table, fields));
let context = self.context;
let send_cmd = Cmd::Union(
Box::new(Cmd::SendData(block)),
Box::new(Cmd::SendData(Block::default())),
);
Box::new(
self.inner
.call(Cmd::SendQuery(query, context.clone()))
.read_block(context.clone())
.and_then(move |c| c.inner.call(send_cmd).read_block(context.clone())),
)
}
}