-
-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathlib.rs
1781 lines (1605 loc) · 56.9 KB
/
lib.rs
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Rust-Postgres is a pure-Rust frontend for the popular PostgreSQL database. It
//! exposes a high level interface in the vein of JDBC or Go's `database/sql`
//! package.
//!
//! ```rust,no_run
//! extern crate postgres;
//! # #[cfg(feature = "time")]
//! extern crate time;
//!
//! # #[cfg(not(feature = "time"))] fn main() {}
//! # #[cfg(feature = "time")] fn main() {
//! use time::Timespec;
//!
//! use postgres::{Connection, SslMode};
//!
//! struct Person {
//! id: i32,
//! name: String,
//! time_created: Timespec,
//! data: Option<Vec<u8>>
//! }
//!
//! fn main() {
//! let conn = Connection::connect("postgresql://postgres@localhost", &SslMode::None)
//! .unwrap();
//!
//! conn.execute("CREATE TABLE person (
//! id SERIAL PRIMARY KEY,
//! name VARCHAR NOT NULL,
//! time_created TIMESTAMP NOT NULL,
//! data BYTEA
//! )", &[]).unwrap();
//! let me = Person {
//! id: 0,
//! name: "Steven".into_string(),
//! time_created: time::get_time(),
//! data: None
//! };
//! conn.execute("INSERT INTO person (name, time_created, data)
//! VALUES ($1, $2, $3)",
//! &[&me.name, &me.time_created, &me.data]).unwrap();
//!
//! let stmt = conn.prepare("SELECT id, name, time_created, data FROM person")
//! .unwrap();
//! for row in stmt.query(&[]).unwrap() {
//! let person = Person {
//! id: row.get(0),
//! name: row.get(1),
//! time_created: row.get(2),
//! data: row.get(3)
//! };
//! println!("Found person {}", person.name);
//! }
//! }
//! # }
//! ```
#![doc(html_root_url="https://sfackler.github.io/doc")]
#![feature(globs, macro_rules, phase, unsafe_destructor, slicing_syntax, default_type_params)]
#![warn(missing_docs)]
extern crate openssl;
extern crate serialize;
extern crate phf;
#[phase(plugin)]
extern crate phf_mac;
#[phase(plugin, link)]
extern crate log;
extern crate time;
use url::Url;
use openssl::crypto::hash::{HashType, Hasher};
use openssl::ssl::{SslContext, MaybeSslStream};
use serialize::hex::ToHex;
use std::cell::{Cell, RefCell};
use std::cmp::max;
use std::collections::{RingBuf, HashMap};
use std::io::{BufferedStream, IoResult, IoError, IoErrorKind};
use std::io::net::ip::Port;
use std::iter::IteratorCloneExt;
use std::time::Duration;
use std::mem;
use std::fmt;
use std::result;
use io::{InternalStream, Timeout};
use message::{FrontendMessage, BackendMessage, RowDescriptionEntry};
use message::FrontendMessage::*;
use message::BackendMessage::*;
use message::{WriteMessage, ReadMessage};
#[doc(inline)]
pub use types::{Oid, Type, ToSql, FromSql};
pub use error::{Error, ConnectError, SqlState, DbError, ErrorPosition};
#[macro_escape]
mod macros;
mod io;
mod message;
mod url;
mod util;
mod error;
pub mod types;
const CANARY: u32 = 0xdeadbeef;
/// A typedef of the result returned by many methods.
pub type Result<T> = result::Result<T, Error>;
/// Specifies the target server to connect to.
#[deriving(Clone)]
pub enum ConnectTarget {
/// Connect via TCP to the specified host.
Tcp(String),
/// Connect via a Unix domain socket in the specified directory.
Unix(Path)
}
/// Authentication information
#[deriving(Clone)]
pub struct UserInfo {
/// The username
pub user: String,
/// An optional password
pub password: Option<String>,
}
/// Information necessary to open a new connection to a Postgres server.
#[deriving(Clone)]
pub struct ConnectParams {
/// The target server
pub target: ConnectTarget,
/// The target port.
///
/// Defaults to 5432 if not specified.
pub port: Option<Port>,
/// The user to login as.
///
/// `Connection::connect` requires a user but `cancel_query` does not.
pub user: Option<UserInfo>,
/// The database to connect to. Defaults the value of `user`.
pub database: Option<String>,
/// Runtime parameters to be passed to the Postgres backend.
pub options: Vec<(String, String)>,
}
/// A trait implemented by types that can be converted into a `ConnectParams`.
pub trait IntoConnectParams {
/// Converts the value of `self` into a `ConnectParams`.
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => return Err(ConnectError::InvalidUrl(err)),
}
}
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> result::Result<ConnectParams, ConnectError> {
let Url {
host,
port,
user,
path: url::Path { path, query: options, .. },
..
} = self;
let maybe_path = try!(url::decode_component(&*host).map_err(ConnectError::InvalidUrl));
let target = if maybe_path.starts_with("/") {
ConnectTarget::Unix(Path::new(maybe_path))
} else {
ConnectTarget::Tcp(host)
};
let user = user.map(|url::UserInfo { user, pass }| {
UserInfo { user: user, password: pass }
});
// path contains the leading /
let database = path.slice_shift_char().map(|(_, path)| path.into_string());
Ok(ConnectParams {
target: target,
port: port,
user: user,
database: database,
options: options,
})
}
}
/// Trait for types that can handle Postgres notice messages
pub trait NoticeHandler {
/// Handle a Postgres notice message
fn handle(&mut self, notice: DbError);
}
/// A notice handler which logs at the `info` level.
///
/// This is the default handler used by a `Connection`.
pub struct DefaultNoticeHandler;
impl NoticeHandler for DefaultNoticeHandler {
fn handle(&mut self, notice: DbError) {
info!("{}: {}", notice.severity, notice.message);
}
}
/// An asynchronous notification
pub struct Notification {
/// The process ID of the notifying backend process
pub pid: u32,
/// The name of the channel that the notify has been raised on
pub channel: String,
/// The "payload" string passed from the notifying process
pub payload: String,
}
/// An iterator over asynchronous notifications
pub struct Notifications<'conn> {
conn: &'conn Connection
}
impl<'conn> Iterator<Notification> for Notifications<'conn> {
/// Returns the oldest pending notification or `None` if there are none.
///
/// ## Note
///
/// `next` may return `Some` notification after returning `None` if a new
/// notification was received.
fn next(&mut self) -> Option<Notification> {
self.conn.conn.borrow_mut().notifications.pop_front()
}
}
impl<'conn> Notifications<'conn> {
/// Returns the oldest pending notification.
///
/// If no notifications are pending, blocks until one arrives.
pub fn next_block(&mut self) -> Result<Notification> {
if let Some(notification) = self.next() {
return Ok(notification);
}
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
match try!(conn.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
Ok(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
_ => unreachable!()
}
}
/// Returns the oldest pending notification
///
/// If no notifications are pending, blocks for up to `timeout` time, after
/// which an `IoError` with the `TimedOut` kind is returned.
///
/// ## Example
///
/// ```rust,no_run
/// use std::io::{IoError, IoErrorKind};
/// use std::time::Duration;
///
/// use postgres::Error;
///
/// # let conn = postgres::Connection::connect("", &postgres::SslMode::None).unwrap();
/// match conn.notifications().next_block_for(Duration::seconds(2)) {
/// Ok(notification) => println!("notification: {}", notification.payload),
/// Err(Error::IoError(IoError { kind: IoErrorKind::TimedOut, .. })) => {
/// println!("Wait for notification timed out");
/// }
/// Err(e) => println!("Other error: {}", e),
/// }
/// ```
pub fn next_block_for(&mut self, timeout: Duration) -> Result<Notification> {
fn now() -> i64 {
(time::precise_time_ns() / 100_000) as i64
}
if let Some(notification) = self.next() {
return Ok(notification);
}
let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn);
let end = now() + timeout.num_milliseconds();
loop {
let timeout = max(0, end - now()) as u64;
conn.stream.set_read_timeout(Some(timeout));
match conn.read_one_message() {
Ok(Some(NotificationResponse { pid, channel, payload })) => {
return Ok(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
Ok(Some(_)) => unreachable!(),
Ok(None) => {}
Err(e @ IoError { kind: IoErrorKind::TimedOut, .. }) => {
conn.desynchronized = false;
return Err(Error::IoError(e));
}
Err(e) => return Err(Error::IoError(e)),
}
}
}
}
/// Contains information necessary to cancel queries for a session
pub struct CancelData {
/// The process ID of the session
pub process_id: u32,
/// The secret key for the session
pub secret_key: u32,
}
/// Attempts to cancel an in-progress query.
///
/// The backend provides no information about whether a cancellation attempt
/// was successful or not. An error will only be returned if the driver was
/// unable to connect to the database.
///
/// A `CancelData` object can be created via `Connection::cancel_data`. The
/// object can cancel any query made on that connection.
///
/// Only the host and port of the connection info are used. See
/// `Connection::connect` for details of the `params` argument.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let url = "";
/// let conn = Connection::connect(url, &SslMode::None).unwrap();
/// let cancel_data = conn.cancel_data();
/// spawn(proc() {
/// conn.execute("SOME EXPENSIVE QUERY", &[]).unwrap();
/// });
/// # let _ =
/// postgres::cancel_query(url, &SslMode::None, cancel_data);
/// ```
pub fn cancel_query<T>(params: T, ssl: &SslMode, data: CancelData)
-> result::Result<(), ConnectError> where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let mut socket = try!(io::initialize_stream(¶ms, ssl));
try!(socket.write_message(&CancelRequest {
code: message::CANCEL_CODE,
process_id: data.process_id,
secret_key: data.secret_key
}));
try!(socket.flush());
Ok(())
}
struct InnerConnection {
stream: BufferedStream<MaybeSslStream<InternalStream>>,
next_stmt_id: uint,
notice_handler: Box<NoticeHandler+Send>,
notifications: RingBuf<Notification>,
cancel_data: CancelData,
unknown_types: HashMap<Oid, String>,
desynchronized: bool,
finished: bool,
trans_depth: u32,
canary: u32,
}
impl Drop for InnerConnection {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl InnerConnection {
fn connect<T>(params: T, ssl: &SslMode) -> result::Result<InnerConnection, ConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let stream = try!(io::initialize_stream(¶ms, ssl));
let ConnectParams { user, database, mut options, .. } = params;
let user = try!(user.ok_or(ConnectError::MissingUser));
let mut conn = InnerConnection {
stream: BufferedStream::new(stream),
next_stmt_id: 0,
notice_handler: box DefaultNoticeHandler,
notifications: RingBuf::new(),
cancel_data: CancelData { process_id: 0, secret_key: 0 },
unknown_types: HashMap::new(),
desynchronized: false,
finished: false,
trans_depth: 0,
canary: CANARY,
};
options.push(("client_encoding".into_string(), "UTF8".into_string()));
// Postgres uses the value of TimeZone as the time zone for TIMESTAMP
// WITH TIME ZONE values. Timespec converts to GMT internally.
options.push(("TimeZone".into_string(), "GMT".into_string()));
// We have to clone here since we need the user again for auth
options.push(("user".into_string(), user.user.clone()));
if let Some(database) = database {
options.push(("database".into_string(), database));
}
try!(conn.write_messages(&[StartupMessage {
version: message::PROTOCOL_VERSION,
parameters: &*options
}]));
try!(conn.handle_auth(user));
loop {
match try!(conn.read_message()) {
BackendKeyData { process_id, secret_key } => {
conn.cancel_data.process_id = process_id;
conn.cancel_data.secret_key = secret_key;
}
ReadyForQuery { .. } => break,
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::BadResponse),
}
}
Ok(conn)
}
fn write_messages(&mut self, messages: &[FrontendMessage]) -> IoResult<()> {
debug_assert!(!self.desynchronized);
for message in messages.iter() {
try_desync!(self, self.stream.write_message(message));
}
Ok(try_desync!(self, self.stream.flush()))
}
fn read_one_message(&mut self) -> IoResult<Option<BackendMessage>> {
debug_assert!(!self.desynchronized);
match try_desync!(self, self.stream.read_message()) {
NoticeResponse { fields } => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle(err);
}
Ok(None)
}
ParameterStatus { parameter, value } => {
debug!("Parameter {} = {}", parameter, value);
Ok(None)
}
val => Ok(Some(val))
}
}
fn read_message_with_notification(&mut self) -> IoResult<BackendMessage> {
loop {
if let Some(msg) = try!(self.read_one_message()) {
return Ok(msg);
}
}
}
fn read_message(&mut self) -> IoResult<BackendMessage> {
loop {
match try!(self.read_message_with_notification()) {
NotificationResponse { pid, channel, payload } => {
self.notifications.push_back(Notification {
pid: pid,
channel: channel,
payload: payload
})
}
val => return Ok(val)
}
}
}
fn handle_auth(&mut self, user: UserInfo) -> result::Result<(), ConnectError> {
match try!(self.read_message()) {
AuthenticationOk => return Ok(()),
AuthenticationCleartextPassword => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
try!(self.write_messages(&[PasswordMessage {
password: &*pass,
}]));
}
AuthenticationMD5Password { salt } => {
let pass = try!(user.password.ok_or(ConnectError::MissingPassword));
let mut hasher = Hasher::new(HashType::MD5);
hasher.update(pass.as_bytes());
hasher.update(user.user.as_bytes());
let output = hasher.finalize().to_hex();
let mut hasher = Hasher::new(HashType::MD5);
hasher.update(output.as_bytes());
hasher.update(&salt);
let output = format!("md5{}", hasher.finalize().to_hex());
try!(self.write_messages(&[PasswordMessage {
password: &*output
}]));
}
AuthenticationKerberosV5
| AuthenticationSCMCredential
| AuthenticationGSS
| AuthenticationSSPI => return Err(ConnectError::UnsupportedAuthentication),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::BadResponse)
}
match try!(self.read_message()) {
AuthenticationOk => Ok(()),
ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::BadResponse)
}
}
fn set_notice_handler(&mut self, handler: Box<NoticeHandler+Send>) -> Box<NoticeHandler+Send> {
mem::replace(&mut self.notice_handler, handler)
}
fn raw_prepare(&mut self, stmt_name: &str, query: &str)
-> Result<(Vec<Type>, Vec<ResultDescription>)> {
try!(self.write_messages(&[
Parse {
name: stmt_name,
query: query,
param_types: &[]
},
Describe {
variant: b'S',
name: stmt_name,
},
Sync]));
match try!(self.read_message()) {
ParseComplete => {}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self),
}
let mut param_types: Vec<_> = match try!(self.read_message()) {
ParameterDescription { types } => {
types.into_iter().map(Type::from_oid).collect()
}
_ => bad_response!(self),
};
let mut result_desc: Vec<_> = match try!(self.read_message()) {
RowDescription { descriptions } => {
descriptions.into_iter().map(|RowDescriptionEntry { name, type_oid, .. }| {
ResultDescription {
name: name,
ty: Type::from_oid(type_oid)
}
}).collect()
}
NoData => vec![],
_ => bad_response!(self)
};
try!(self.wait_for_ready());
// now that the connection is ready again, get unknown type names,
// but not if stmt_name is "" since that'll blow away the statement
// and we don't care about result values anyway
if stmt_name != "" {
try!(self.set_type_names(param_types.iter_mut()));
try!(self.set_type_names(result_desc.iter_mut().map(|d| &mut d.ty)));
}
Ok((param_types, result_desc))
}
fn make_stmt_name(&mut self) -> String {
let stmt_name = format!("s{}", self.next_stmt_id);
self.next_stmt_id += 1;
stmt_name
}
fn prepare<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let stmt_name = self.make_stmt_name();
let (param_types, result_desc) = try!(self.raw_prepare(&*stmt_name, query));
Ok(Statement {
conn: conn,
name: stmt_name,
param_types: param_types,
result_desc: result_desc,
next_portal_id: Cell::new(0),
finished: false,
})
}
fn prepare_copy_in<'a>(&mut self, table: &str, rows: &[&str], conn: &'a Connection)
-> Result<CopyInStatement<'a>> {
let mut query = vec![];
let _ = write!(&mut query, "SELECT ");
let _ = util::comma_join(&mut query, rows.iter().cloned());
let _ = write!(&mut query, " FROM {}", table);
let query = String::from_utf8(query).unwrap();
let (_, result_desc) = try!(self.raw_prepare("", &*query));
let column_types = result_desc.into_iter().map(|desc| desc.ty).collect();
let mut query = vec![];
let _ = write!(&mut query, "COPY {} (", table);
let _ = util::comma_join(&mut query, rows.iter().cloned());
let _ = write!(&mut query, ") FROM STDIN WITH (FORMAT binary)");
let query = String::from_utf8(query).unwrap();
let stmt_name = self.make_stmt_name();
try!(self.raw_prepare(&*stmt_name, &*query));
Ok(CopyInStatement {
conn: conn,
name: stmt_name,
column_types: column_types,
finished: false,
})
}
fn close_statement(&mut self, name: &str, type_: u8) -> Result<()> {
try!(self.write_messages(&[
Close {
variant: type_,
name: name,
},
Sync]));
let resp = match try!(self.read_message()) {
CloseComplete => Ok(()),
ErrorResponse { fields } => DbError::new(fields),
_ => bad_response!(self)
};
try!(self.wait_for_ready());
resp
}
fn set_type_names<'a, I>(&mut self, mut it: I) -> Result<()> where I: Iterator<&'a mut Type> {
for ty in it {
if let &Type::Unknown { oid, ref mut name } = ty {
*name = try!(self.get_type_name(oid));
}
}
Ok(())
}
fn get_type_name(&mut self, oid: Oid) -> Result<String> {
if let Some(name) = self.unknown_types.get(&oid) {
return Ok(name.clone());
}
let name = try!(self.quick_query(&*format!("SELECT typname FROM pg_type \
WHERE oid={}", oid)))
.into_iter().next().unwrap().into_iter().next().unwrap().unwrap();
self.unknown_types.insert(oid, name.clone());
Ok(name)
}
fn is_desynchronized(&self) -> bool {
self.desynchronized
}
fn canary(&self) -> u32 {
self.canary
}
fn wait_for_ready(&mut self) -> Result<()> {
match try!(self.read_message()) {
ReadyForQuery { .. } => Ok(()),
_ => bad_response!(self)
}
}
fn quick_query(&mut self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
check_desync!(self);
try!(self.write_messages(&[Query { query: query }]));
let mut result = vec![];
loop {
match try!(self.read_message()) {
ReadyForQuery { .. } => break,
DataRow { row } => {
result.push(row.into_iter().map(|opt| {
opt.map(|b| String::from_utf8_lossy(&*b).into_string())
}).collect());
}
CopyInResponse { .. } => {
try!(self.write_messages(&[
CopyFail {
message: "COPY queries cannot be directly executed",
},
Sync]));
}
ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => {}
}
}
Ok(result)
}
fn finish_inner(&mut self) -> Result<()> {
check_desync!(self);
self.canary = 0;
try!(self.write_messages(&[Terminate]));
Ok(())
}
}
/// A connection to a Postgres database.
pub struct Connection {
conn: RefCell<InnerConnection>
}
impl Connection {
/// Creates a new connection to a Postgres database.
///
/// Most applications can use a URL string in the normal format:
///
/// ```notrust
/// postgresql://user[:password]@host[:port][/database][?param1=val1[[¶m2=val2]...]]
/// ```
///
/// The password may be omitted if not required. The default Postgres port
/// (5432) is used if none is specified. The database name defaults to the
/// username if not specified.
///
/// To connect to the server via Unix sockets, `host` should be set to the
/// absolute path of the directory containing the socket file. Since `/` is
/// a reserved character in URLs, the path should be URL encoded. If the
/// path contains non-UTF 8 characters, a `ConnectParams` struct
/// should be created manually and passed in. Note that Postgres does not
/// support SSL over Unix sockets.
///
/// ## Examples
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let _ = || {
/// let url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let _ = || {
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let conn = try!(Connection::connect(url, &SslMode::None));
/// # Ok(()) };
/// ```
///
/// ```rust,no_run
/// # use postgres::{Connection, UserInfo, ConnectParams, SslMode, ConnectTarget};
/// # let _ = || {
/// # let some_crazy_path = Path::new("");
/// let params = ConnectParams {
/// target: ConnectTarget::Unix(some_crazy_path),
/// port: None,
/// user: Some(UserInfo {
/// user: "postgres".into_string(),
/// password: None
/// }),
/// database: None,
/// options: vec![],
/// };
/// let conn = try!(Connection::connect(params, &SslMode::None));
/// # Ok(()) };
/// ```
pub fn connect<T>(params: T, ssl: &SslMode) -> result::Result<Connection, ConnectError>
where T: IntoConnectParams {
InnerConnection::connect(params, ssl).map(|conn| {
Connection { conn: RefCell::new(conn) }
})
}
/// Sets the notice handler for the connection, returning the old handler.
pub fn set_notice_handler(&self, handler: Box<NoticeHandler+Send>) -> Box<NoticeHandler+Send> {
self.conn.borrow_mut().set_notice_handler(handler)
}
/// Returns an iterator over asynchronous notification messages.
///
/// Use the `LISTEN` command to register this connection for notifications.
pub fn notifications<'a>(&'a self) -> Notifications<'a> {
Notifications { conn: self }
}
/// Creates a new prepared statement.
///
/// A statement may contain parameters, specified by `$n` where `n` is the
/// index of the parameter in the list provided at execution time,
/// 1-indexed.
///
/// The statement is associated with the connection that created it and may
/// not outlive that connection.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let maybe_stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1");
/// let stmt = match maybe_stmt {
/// Ok(stmt) => stmt,
/// Err(err) => panic!("Error preparing statement: {}", err)
/// };
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 {
return Err(Error::WrongTransaction);
}
conn.prepare(query, self)
}
/// Creates a new COPY FROM STDIN prepared statement.
///
/// These statements provide a method to efficiently bulk-upload data to
/// the database.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # use postgres::types::ToSql;
/// # let _ = || {
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// try!(conn.execute("CREATE TABLE foo (
/// bar INT PRIMARY KEY,
/// baz VARCHAR
/// )", &[]));
///
/// let stmt = try!(conn.prepare_copy_in("foo", &["bar", "baz"]));
/// let data: &[&[&ToSql]] = &[&[&0i32, &"blah".into_string()],
/// &[&1i32, &None::<String>]];
/// try!(stmt.execute(data.iter().map(|r| r.iter().map(|&e| e))));
/// # Ok(()) };
/// ```
pub fn prepare_copy_in<'a>(&'a self, table: &str, rows: &[&str])
-> Result<CopyInStatement<'a>> {
let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 {
return Err(Error::WrongTransaction);
}
conn.prepare_copy_in(table, rows, self)
}
/// Begins a new transaction.
///
/// Returns a `Transaction` object which should be used instead of
/// the connection for the duration of the transaction. The transaction
/// is active until the `Transaction` object falls out of scope.
///
/// ## Note
/// A transaction will roll back by default. The `set_commit`,
/// `set_rollback`, and `commit` methods alter this behavior.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, SslMode};
/// # fn foo() -> Result<(), postgres::Error> {
/// # let conn = Connection::connect("", &SslMode::None).unwrap();
/// let trans = try!(conn.transaction());
/// try!(trans.execute("UPDATE foo SET bar = 10", &[]));
/// // ...
///
/// try!(trans.commit());
/// # Ok(())
/// # }
/// ```
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
if conn.trans_depth != 0 {
return Err(Error::WrongTransaction);
}
try!(conn.quick_query("BEGIN"));
conn.trans_depth += 1;
Ok(Transaction {
conn: self,
commit: Cell::new(false),
depth: 1,
finished: false,
})
}
/// A convenience function for queries that are only run once.
///
/// If an error is returned, it could have come from either the preparation
/// or execution of the statement.
///
/// On success, returns the number of rows modified or 0 if not applicable.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<uint> {
let (param_types, result_desc) = try!(self.conn.borrow_mut().raw_prepare("", query));
let stmt = Statement {
conn: self,
name: "".into_string(),
param_types: param_types,
result_desc: result_desc,
next_portal_id: Cell::new(0),
finished: true, // << !!
};
stmt.execute(params)
}
/// Execute a sequence of SQL statements.
///
/// Statements should be separated by `;` characters. If an error occurs,
/// execution of the sequence will stop at that point. This is intended for
/// execution of batches of non-dynamic statements - for example, creation
/// of a schema for a fresh database.
///
/// ## Warning
///
/// Prepared statements should be used for any SQL statement which contains
/// user-specified data, as it provides functionality to safely embed that
/// data in the statment. Do not form statements via string concatenation
/// and feed them into this method.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::{Connection, Result};
/// fn init_db(conn: &Connection) -> Result<()> {
/// conn.batch_execute("
/// CREATE TABLE person (
/// id SERIAL PRIMARY KEY,
/// name NOT NULL
/// );
///
/// CREATE TABLE purchase (
/// id SERIAL PRIMARY KEY,
/// person INT NOT NULL REFERENCES person (id),
/// time TIMESTAMPTZ NOT NULL,
/// );
///
/// CREATE INDEX ON purchase (time);
/// ")
/// }
/// ```
pub fn batch_execute(&self, query: &str) -> Result<()> {
let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 {
return Err(Error::WrongTransaction);
}
conn.quick_query(query).map(|_| ())
}
/// Returns information used to cancel pending queries.
///
/// Used with the `cancel_query` function. The object returned can be used
/// to cancel any query executed by the connection it was created from.
pub fn cancel_data(&self) -> CancelData {
self.conn.borrow().cancel_data
}
/// Returns whether or not the stream has been desynchronized due to an
/// error in the communication channel with the server.
///
/// If this has occurred, all further queries will immediately return an
/// error.
pub fn is_desynchronized(&self) -> bool {
self.conn.borrow().is_desynchronized()
}
/// Consumes the connection, closing it.
///
/// Functionally equivalent to the `Drop` implementation for `Connection`
/// except that it returns any error encountered to the caller.
pub fn finish(self) -> Result<()> {
let mut conn = self.conn.borrow_mut();
conn.finished = true;
conn.finish_inner()
}
fn canary(&self) -> u32 {
self.conn.borrow().canary()