forked from rust-postgres/rust-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
628 lines (548 loc) · 16.7 KB
/
Copy pathlib.rs
File metadata and controls
628 lines (548 loc) · 16.7 KB
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
extern mod extra;
use extra::digest::Digest;
use extra::md5::Md5;
use extra::url::{UserInfo, Url};
use std::cell::Cell;
use std::rt::io::io_error;
use std::rt::io::net::ip::SocketAddr;
use std::rt::io::net::tcp::TcpStream;
use std::str;
use message::*;
mod message;
pub struct PostgresConnection {
priv stream: Cell<TcpStream>,
priv next_stmt_id: Cell<int>
}
impl Drop for PostgresConnection {
fn drop(&self) {
do io_error::cond.trap(|_| {}).inside {
self.write_message(&Terminate);
}
}
}
#[deriving(ToStr)]
pub enum PostgresConnectError {
InvalidUrl,
MissingUser,
DbError(PostgresDbError),
MissingPassword,
UnsupportedAuthentication
}
#[deriving(ToStr)]
// TODO this should have things in it
pub struct PostgresDbError;
impl PostgresConnection {
pub fn connect(url: &str) -> PostgresConnection {
match PostgresConnection::try_connect(url) {
Ok(conn) => conn,
Err(err) => fail!("Failed to connect: %s", err.to_str())
}
}
pub fn try_connect(url: &str) -> Result<PostgresConnection,
PostgresConnectError> {
let Url {
host,
port,
user,
path,
query: args,
_
}: Url = match FromStr::from_str(url) {
Some(url) => url,
None => return Err(InvalidUrl)
};
let user = match user {
Some(user) => user,
None => return Err(MissingUser)
};
let mut args = args;
// This seems silly
let socket_url = format!("{:s}:{:s}", host,
port.unwrap_or_default(~"5432"));
let addr: SocketAddr = match FromStr::from_str(socket_url) {
Some(addr) => addr,
None => return Err(InvalidUrl)
};
let conn = PostgresConnection {
// Need to figure out what to do about unwrap here
stream: Cell::new(TcpStream::connect(addr).unwrap()),
next_stmt_id: Cell::new(0)
};
// We have to clone here since we need the user again for auth
args.push((~"user", user.user.clone()));
if !path.is_empty() {
args.push((~"database", path));
}
conn.write_message(&StartupMessage(args.as_slice()));
match conn.handle_auth(user) {
Some(err) => return Err(err),
None => ()
}
loop {
match conn.read_message() {
ParameterStatus(param, value) =>
info!("Parameter %s = %s", param, value),
BackendKeyData(*) => (),
ReadyForQuery(*) => break,
resp => fail!("Bad response: %?", resp.to_str())
}
}
Ok(conn)
}
fn write_message(&self, message: &FrontendMessage) {
do self.stream.with_mut_ref |s| {
s.write_message(message);
}
}
fn read_message(&self) -> BackendMessage {
do self.stream.with_mut_ref |s| {
s.read_message()
}
}
fn handle_auth(&self, user: UserInfo) -> Option<PostgresConnectError> {
match self.read_message() {
AuthenticationOk => return None,
AuthenticationCleartextPassword => {
let pass = match user.pass {
Some(pass) => pass,
None => return Some(MissingPassword)
};
self.write_message(&PasswordMessage(pass));
}
AuthenticationMD5Password(salt) => {
let UserInfo { user, pass } = user;
let pass = match pass {
Some(pass) => pass,
None => return Some(MissingPassword)
};
let input = pass + user;
let mut md5 = Md5::new();
md5.input_str(input);
let output = md5.result_str();
md5.reset();
md5.input_str(output);
md5.input(salt);
let output = "md5" + md5.result_str();
self.write_message(&PasswordMessage(output.as_slice()));
}
resp => fail!("Bad response: %?", resp.to_str())
}
match self.read_message() {
AuthenticationOk => None,
ErrorResponse(*) => Some(DbError(PostgresDbError)),
resp => fail!("Bad response: %?", resp.to_str())
}
}
pub fn prepare<'a>(&'a self, query: &str) -> PostgresStatement<'a> {
match self.try_prepare(query) {
Ok(stmt) => stmt,
Err(err) => fail!("Error preparing \"%s\": %s", query,
err.to_str())
}
}
pub fn try_prepare<'a>(&'a self, query: &str)
-> Result<PostgresStatement<'a>, PostgresDbError> {
let id = self.next_stmt_id.take();
let stmt_name = format!("statement_{}", id);
self.next_stmt_id.put_back(id + 1);
let types = [];
self.write_message(&Parse(stmt_name, query, types));
self.write_message(&Sync);
match self.read_message() {
ParseComplete => (),
ErrorResponse(*) => return Err(PostgresDbError),
resp => fail!("Bad response: %?", resp.to_str())
}
self.wait_for_ready();
self.write_message(&Describe('S' as u8, stmt_name));
self.write_message(&Sync);
let num_params = match self.read_message() {
ParameterDescription(ref types) => types.len(),
resp => fail!("Bad response: %?", resp.to_str())
};
match self.read_message() {
RowDescription(*) | NoData => (),
resp => fail!("Bad response: %?", resp.to_str())
}
self.wait_for_ready();
Ok(PostgresStatement {
conn: self,
name: stmt_name,
num_params: num_params,
next_portal_id: Cell::new(0)
})
}
pub fn in_transaction<T>(&self, blk: &fn(&PostgresTransaction) -> T)
-> T {
self.quick_query("BEGIN");
let trans = PostgresTransaction {
conn: self,
commit: Cell::new(true)
};
// If this fails, Postgres will rollback when the connection closes
let ret = blk(&trans);
if trans.commit.take() {
self.quick_query("COMMIT");
} else {
self.quick_query("ROLLBACK");
}
ret
}
fn quick_query(&self, query: &str) {
self.write_message(&Query(query));
loop {
match self.read_message() {
ReadyForQuery(*) => break,
resp @ ErrorResponse(*) => fail!("Error: %?", resp.to_str()),
_ => ()
}
}
}
fn wait_for_ready(&self) {
loop {
match self.read_message() {
ReadyForQuery(*) => break,
resp => fail!("Bad response: %?", resp.to_str())
}
}
}
}
pub struct PostgresTransaction<'self> {
priv conn: &'self PostgresConnection,
priv commit: Cell<bool>
}
impl<'self> PostgresTransaction<'self> {
pub fn prepare<'a>(&'a self, query: &str) -> PostgresStatement<'a> {
self.conn.prepare(query)
}
pub fn try_prepare<'a>(&'a self, query: &str)
-> Result<PostgresStatement<'a>, PostgresDbError> {
self.conn.try_prepare(query)
}
pub fn will_commit(&self) -> bool {
let commit = self.commit.take();
self.commit.put_back(commit);
commit
}
pub fn set_commit(&self) {
self.commit.take();
self.commit.put_back(true);
}
pub fn set_rollback(&self) {
self.commit.take();
self.commit.put_back(false);
}
}
pub struct PostgresStatement<'self> {
priv conn: &'self PostgresConnection,
priv name: ~str,
priv num_params: uint,
priv next_portal_id: Cell<uint>
}
#[unsafe_destructor]
impl<'self> Drop for PostgresStatement<'self> {
fn drop(&self) {
do io_error::cond.trap(|_| {}).inside {
self.conn.write_message(&Close('S' as u8, self.name.as_slice()));
self.conn.write_message(&Sync);
loop {
match self.conn.read_message() {
ReadyForQuery(*) => break,
_ => ()
}
}
}
}
}
impl<'self> PostgresStatement<'self> {
pub fn num_params(&self) -> uint {
self.num_params
}
fn execute(&self, portal_name: &str, params: &[&ToSql])
-> Option<PostgresDbError> {
if self.num_params != params.len() {
fail!("Expected %u params but got %u", self.num_params,
params.len());
}
let formats = [];
let values: ~[Option<~[u8]>] = params.iter().map(|val| val.to_sql())
.collect();
let result_formats = [];
self.conn.write_message(&Bind(portal_name, self.name.as_slice(),
formats, values, result_formats));
self.conn.write_message(&Execute(portal_name.as_slice(), 0));
self.conn.write_message(&Sync);
match self.conn.read_message() {
BindComplete => None,
ErrorResponse(*) => Some(PostgresDbError),
resp => fail!("Bad response: %?", resp.to_str())
}
}
pub fn update(&self, params: &[&ToSql]) -> uint {
match self.try_update(params) {
Ok(count) => count,
Err(err) => fail!("Error running update: %s", err.to_str())
}
}
pub fn try_update(&self, params: &[&ToSql])
-> Result<uint, PostgresDbError> {
// The unnamed portal is automatically cleaned up at sync time
match self.execute("", params) {
Some(err) => {
self.conn.wait_for_ready();
return Err(err);
}
None => ()
}
let mut num = 0;
loop {
match self.conn.read_message() {
CommandComplete(ret) => {
let s = ret.split_iter(' ').last().unwrap();
match FromStr::from_str(s) {
None => (),
Some(n) => num = n
}
break;
}
DataRow(*) => (),
EmptyQueryResponse => break,
NoticeResponse(*) => (),
ErrorResponse(*) => {
self.conn.wait_for_ready();
return Err(PostgresDbError);
}
resp => fail!("Bad response: %?", resp.to_str())
}
}
self.conn.wait_for_ready();
Ok(num)
}
pub fn query<'a>(&'a self, params: &[&ToSql]) -> PostgresResult<'a> {
match self.try_query(params) {
Ok(result) => result,
Err(err) => fail!("Error running query: %s", err.to_str())
}
}
pub fn try_query<'a>(&'a self, params: &[&ToSql])
-> Result<PostgresResult<'a>, PostgresDbError> {
let id = self.next_portal_id.take();
let portal_name = format!("{:s}_portal_{}", self.name.as_slice(), id);
self.next_portal_id.put_back(id + 1);
match self.execute(portal_name, params) {
Some(err) => {
self.conn.wait_for_ready();
return Err(err);
}
None => ()
}
let mut data = ~[];
loop {
match self.conn.read_message() {
EmptyQueryResponse => break,
DataRow(row) => data.push(row),
CommandComplete(*) => break,
NoticeResponse(*) => (),
ErrorResponse(*) => {
self.conn.wait_for_ready();
return Err(PostgresDbError);
}
resp => fail!("Bad response: %?", resp.to_str())
}
}
self.conn.wait_for_ready();
Ok(PostgresResult {
stmt: self,
name: portal_name,
data: data
})
}
}
pub struct PostgresResult<'self> {
priv stmt: &'self PostgresStatement<'self>,
priv name: ~str,
priv data: ~[~[Option<~[u8]>]]
}
#[unsafe_destructor]
impl<'self> Drop for PostgresResult<'self> {
fn drop(&self) {
do io_error::cond.trap(|_| {}).inside {
self.stmt.conn.write_message(&Close('P' as u8,
self.name.as_slice()));
self.stmt.conn.write_message(&Sync);
loop {
match self.stmt.conn.read_message() {
ReadyForQuery(*) => break,
_ => ()
}
}
}
}
}
impl<'self> PostgresResult<'self> {
pub fn iter<'a>(&'a self) -> PostgresResultIterator<'a> {
PostgresResultIterator { result: self, next_row: 0 }
}
}
pub struct PostgresResultIterator<'self> {
priv result: &'self PostgresResult<'self>,
priv next_row: uint
}
impl<'self> Iterator<PostgresRow<'self>> for PostgresResultIterator<'self> {
fn next(&mut self) -> Option<PostgresRow<'self>> {
if self.next_row == self.result.data.len() {
return None;
}
let row = self.next_row;
self.next_row += 1;
Some(PostgresRow { result: self.result, row: row })
}
}
pub struct PostgresRow<'self> {
priv result: &'self PostgresResult<'self>,
priv row: uint
}
impl<'self> Container for PostgresRow<'self> {
fn len(&self) -> uint {
self.result.data[self.row].len()
}
}
impl<'self, T: FromSql> Index<uint, T> for PostgresRow<'self> {
fn index(&self, idx: &uint) -> T {
self.get(*idx)
}
}
impl<'self> PostgresRow<'self> {
pub fn get<T: FromSql>(&self, idx: uint) -> T {
FromSql::from_sql(&self.result.data[self.row][idx])
}
}
pub trait FromSql {
fn from_sql(raw: &Option<~[u8]>) -> Self;
}
macro_rules! from_str_impl(
($t:ty) => (
impl FromSql for Option<$t> {
fn from_sql(raw: &Option<~[u8]>) -> Option<$t> {
match *raw {
None => None,
Some(ref buf) => {
let s = str::from_bytes_slice(buf.as_slice());
Some(FromStr::from_str(s).unwrap())
}
}
}
}
)
)
macro_rules! from_option_impl(
($t:ty) => (
impl FromSql for $t {
fn from_sql(raw: &Option<~[u8]>) -> $t {
FromSql::from_sql::<Option<$t>>(raw).unwrap()
}
}
)
)
from_str_impl!(int)
from_option_impl!(int)
from_str_impl!(i8)
from_option_impl!(i8)
from_str_impl!(i16)
from_option_impl!(i16)
from_str_impl!(i32)
from_option_impl!(i32)
from_str_impl!(i64)
from_option_impl!(i64)
from_str_impl!(uint)
from_option_impl!(uint)
from_str_impl!(u8)
from_option_impl!(u8)
from_str_impl!(u16)
from_option_impl!(u16)
from_str_impl!(u32)
from_option_impl!(u32)
from_str_impl!(u64)
from_option_impl!(u64)
from_str_impl!(float)
from_option_impl!(float)
from_str_impl!(f32)
from_option_impl!(f32)
from_str_impl!(f64)
from_option_impl!(f64)
impl FromSql for Option<~str> {
fn from_sql(raw: &Option<~[u8]>) -> Option<~str> {
do raw.chain_ref |buf| {
Some(str::from_bytes(buf.as_slice()))
}
}
}
from_option_impl!(~str)
pub trait ToSql {
fn to_sql(&self) -> Option<~[u8]>;
}
macro_rules! to_str_impl(
($t:ty) => (
impl ToSql for $t {
fn to_sql(&self) -> Option<~[u8]> {
Some(self.to_str().into_bytes())
}
}
)
)
macro_rules! to_option_impl(
($t:ty) => (
impl ToSql for Option<$t> {
fn to_sql(&self) -> Option<~[u8]> {
do self.chain |val| {
val.to_sql()
}
}
}
)
)
to_str_impl!(int)
to_option_impl!(int)
to_str_impl!(i8)
to_option_impl!(i8)
to_str_impl!(i16)
to_option_impl!(i16)
to_str_impl!(i32)
to_option_impl!(i32)
to_str_impl!(i64)
to_option_impl!(i64)
to_str_impl!(uint)
to_option_impl!(uint)
to_str_impl!(u8)
to_option_impl!(u8)
to_str_impl!(u16)
to_option_impl!(u16)
to_str_impl!(u32)
to_option_impl!(u32)
to_str_impl!(u64)
to_option_impl!(u64)
to_str_impl!(float)
to_option_impl!(float)
to_str_impl!(f32)
to_option_impl!(f32)
to_str_impl!(f64)
to_option_impl!(f64)
impl<'self> ToSql for &'self str {
fn to_sql(&self) -> Option<~[u8]> {
Some(self.as_bytes().to_owned())
}
}
impl ToSql for Option<~str> {
fn to_sql(&self) -> Option<~[u8]> {
do self.chain_ref |val| {
val.to_sql()
}
}
}
impl<'self> ToSql for Option<&'self str> {
fn to_sql(&self) -> Option<~[u8]> {
do self.chain |val| {
val.to_sql()
}
}
}