-
-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathlib.rs
1463 lines (1311 loc) · 51.7 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
//! A pure-Rust frontend for the popular PostgreSQL database.
//!
//! ```rust,no_run
//! extern crate postgres;
//!
//! use postgres::{Connection, SslMode};
//!
//! struct Person {
//! id: i32,
//! name: String,
//! 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,
//! data BYTEA
//! )", &[]).unwrap();
//! let me = Person {
//! id: 0,
//! name: "Steven".to_owned(),
//! data: None
//! };
//! conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
//! &[&me.name, &me.data]).unwrap();
//!
//! for row in &conn.query("SELECT id, name, data FROM person", &[]).unwrap() {
//! let person = Person {
//! id: row.get(0),
//! name: row.get(1),
//! data: row.get(2)
//! };
//! println!("Found person {}", person.name);
//! }
//! }
//! ```
#![doc(html_root_url="https://sfackler.github.io/rust-postgres/doc/v0.11.9")]
#![warn(missing_docs)]
#![allow(unknown_lints, needless_lifetimes)] // for clippy
#![cfg_attr(all(unix, feature = "nightly"), feature(unix_socket))]
extern crate bufstream;
extern crate byteorder;
extern crate hex;
#[macro_use]
extern crate log;
extern crate phf;
#[cfg(feature = "unix_socket")]
extern crate unix_socket;
use bufstream::BufStream;
use md5::Md5;
use std::cell::{Cell, RefCell};
use std::collections::{VecDeque, HashMap};
use std::error::Error as StdError;
use std::fmt;
use std::io as std_io;
use std::io::prelude::*;
use std::mem;
use std::result;
use std::sync::Arc;
use std::time::Duration;
#[cfg(any(feature = "unix_socket", all(unix, feature = "nightly")))]
use std::path::PathBuf;
// FIXME remove in 0.12
pub use transaction::{Transaction, IsolationLevel};
use error::{Error, ConnectError, SqlState, DbError};
use io::{StreamWrapper, NegotiateSsl};
use message::{Frontend, Backend, RowDescriptionEntry};
use message::{WriteMessage, ReadMessage};
use notification::{Notifications, Notification};
use rows::{Rows, LazyRows};
use stmt::{Statement, Column};
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, WrongType, ToSql, FromSql, Field};
use url::Url;
#[macro_use]
mod macros;
mod md5;
mod message;
mod priv_io;
mod url;
pub mod error;
pub mod io;
pub mod notification;
pub mod rows;
pub mod stmt;
pub mod transaction;
pub mod types;
const TYPEINFO_QUERY: &'static str = "__typeinfo";
const TYPEINFO_ENUM_QUERY: &'static str = "__typeinfo_enum";
const TYPEINFO_COMPOSITE_QUERY: &'static str = "__typeinfo_composite";
/// A type alias of the result returned by many methods.
pub type Result<T> = result::Result<T, Error>;
/// Specifies the target server to connect to.
#[derive(Clone, Debug)]
pub enum ConnectTarget {
/// Connect via TCP to the specified host.
Tcp(String),
/// Connect via a Unix domain socket in the specified directory.
///
/// Requires the `unix_socket` or `nightly` feature.
#[cfg(any(feature = "unix_socket", all(unix, feature = "nightly")))]
Unix(PathBuf),
}
/// Authentication information.
#[derive(Clone, Debug)]
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.
#[derive(Clone, Debug)]
pub struct ConnectParams {
/// The target server.
pub target: ConnectTarget,
/// The target port.
///
/// Defaults to 5432 if not specified.
pub port: Option<u16>,
/// 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, Box<StdError + Sync + Send>>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> result::Result<ConnectParams, Box<StdError + Sync + Send>> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> result::Result<ConnectParams, Box<StdError + Sync + Send>> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => Err(err.into()),
}
}
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> result::Result<ConnectParams, Box<StdError + Sync + Send>> {
#[cfg(any(feature = "unix_socket", all(unix, feature = "nightly")))]
fn make_unix(maybe_path: String)
-> result::Result<ConnectTarget, Box<StdError + Sync + Send>> {
Ok(ConnectTarget::Unix(PathBuf::from(maybe_path)))
}
#[cfg(not(any(feature = "unix_socket", all(unix, feature = "nightly"))))]
fn make_unix(_: String) -> result::Result<ConnectTarget, Box<StdError + Sync + Send>> {
Err("unix socket support requires the `unix_socket` or `nightly` features".into())
}
let Url { host, port, user, path: url::Path { mut path, query: options, .. }, .. } = self;
let maybe_path = try!(url::decode_component(&host));
let target = if maybe_path.starts_with('/') {
try!(make_unix(maybe_path))
} else {
ConnectTarget::Tcp(host)
};
let user = user.map(|url::UserInfo { user, pass }| {
UserInfo {
user: user,
password: pass,
}
});
let database = if path.is_empty() {
None
} else {
// path contains the leading /
path.remove(0);
Some(path)
};
Ok(ConnectParams {
target: target,
port: port,
user: user,
database: database,
options: options,
})
}
}
/// Trait for types that can handle Postgres notice messages
///
/// It is implemented for all `Send + FnMut(DbError)` closures.
pub trait HandleNotice: Send {
/// Handle a Postgres notice message
fn handle_notice(&mut self, notice: DbError);
}
impl<F: Send + FnMut(DbError)> HandleNotice for F {
fn handle_notice(&mut self, notice: DbError) {
self(notice)
}
}
/// A notice handler which logs at the `info` level.
///
/// This is the default handler used by a `Connection`.
#[derive(Copy, Clone, Debug)]
pub struct LoggingNoticeHandler;
impl HandleNotice for LoggingNoticeHandler {
fn handle_notice(&mut self, notice: DbError) {
info!("{}: {}", notice.severity, notice.message);
}
}
/// Contains information necessary to cancel queries for a session.
#[derive(Copy, Clone, Debug)]
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};
/// # use std::thread;
/// # let url = "";
/// let conn = Connection::connect(url, SslMode::None).unwrap();
/// let cancel_data = conn.cancel_data();
/// thread::spawn(move || {
/// conn.execute("SOME EXPENSIVE QUERY", &[]).unwrap();
/// });
/// postgres::cancel_query(url, SslMode::None, &cancel_data).unwrap();
/// ```
pub fn cancel_query<T>(params: T,
ssl: SslMode,
data: &CancelData)
-> result::Result<(), ConnectError>
where T: IntoConnectParams
{
let params = try!(params.into_connect_params().map_err(ConnectError::ConnectParams));
let mut socket = try!(priv_io::initialize_stream(¶ms, ssl));
try!(socket.write_message(&Frontend::CancelRequest {
code: message::CANCEL_CODE,
process_id: data.process_id,
secret_key: data.secret_key,
}));
try!(socket.flush());
Ok(())
}
fn bad_response() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::InvalidInput,
"the server returned an unexpected response")
}
fn desynchronized() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::Other,
"communication with the server has desynchronized due to an earlier IO \
error")
}
/// Specifies the SSL support requested for a new connection.
#[derive(Debug)]
pub enum SslMode<'a> {
/// The connection will not use SSL.
None,
/// The connection will use SSL if the backend supports it.
Prefer(&'a NegotiateSsl),
/// The connection must use SSL.
Require(&'a NegotiateSsl),
}
struct StatementInfo {
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
}
struct InnerConnection {
stream: BufStream<Box<StreamWrapper>>,
notice_handler: Box<HandleNotice>,
notifications: VecDeque<Notification>,
cancel_data: CancelData,
unknown_types: HashMap<Oid, Other>,
cached_statements: HashMap<String, Arc<StatementInfo>>,
parameters: HashMap<String, String>,
next_stmt_id: u32,
trans_depth: u32,
desynchronized: bool,
finished: bool,
}
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().map_err(ConnectError::ConnectParams));
let stream = try!(priv_io::initialize_stream(¶ms, ssl));
let ConnectParams { user, database, mut options, .. } = params;
let user = match user {
Some(user) => user,
None => {
return Err(ConnectError::ConnectParams("User missing from connection parameters".into()));
}
};
let mut conn = InnerConnection {
stream: BufStream::new(stream),
next_stmt_id: 0,
notice_handler: Box::new(LoggingNoticeHandler),
notifications: VecDeque::new(),
cancel_data: CancelData {
process_id: 0,
secret_key: 0,
},
unknown_types: HashMap::new(),
cached_statements: HashMap::new(),
parameters: HashMap::new(),
desynchronized: false,
finished: false,
trans_depth: 0,
};
options.push(("client_encoding".to_owned(), "UTF8".to_owned()));
// Postgres uses the value of TimeZone as the time zone for TIMESTAMP
// WITH TIME ZONE values. Timespec converts to GMT internally.
options.push(("timezone".to_owned(), "GMT".to_owned()));
// We have to clone here since we need the user again for auth
options.push(("user".to_owned(), user.user.clone()));
if let Some(database) = database {
options.push(("database".to_owned(), database));
}
try!(conn.write_messages(&[Frontend::StartupMessage {
version: message::PROTOCOL_VERSION,
parameters: &options,
}]));
try!(conn.handle_auth(user));
loop {
match try!(conn.read_message()) {
Backend::BackendKeyData { process_id, secret_key } => {
conn.cancel_data.process_id = process_id;
conn.cancel_data.secret_key = secret_key;
}
Backend::ReadyForQuery { .. } => break,
Backend::ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::Io(bad_response())),
}
}
try!(conn.setup_typeinfo_query());
Ok(conn)
}
#[cfg_attr(rustfmt, rustfmt_skip)]
fn setup_typeinfo_query(&mut self) -> result::Result<(), ConnectError> {
match self.raw_prepare(TYPEINFO_ENUM_QUERY,
"SELECT enumlabel \
FROM pg_catalog.pg_enum \
WHERE enumtypid = $1 \
ORDER BY enumsortorder") {
Ok(..) => {}
Err(Error::Io(e)) => return Err(ConnectError::Io(e)),
// Old versions of Postgres and things like Redshift don't support enums
Err(Error::Db(ref e)) if e.code == SqlState::UndefinedTable => {}
// Some Postgres-like databases are missing a pg_catalog (e.g. Cockroach)
Err(Error::Db(ref e)) if e.code == SqlState::InvalidCatalogName => return Ok(()),
Err(Error::Db(e)) => return Err(ConnectError::Db(e)),
Err(Error::Conversion(_)) => unreachable!(),
}
match self.raw_prepare(TYPEINFO_COMPOSITE_QUERY,
"SELECT attname, atttypid \
FROM pg_catalog.pg_attribute \
WHERE attrelid = $1 \
AND NOT attisdropped \
AND attnum > 0 \
ORDER BY attnum") {
Ok(..) => {}
Err(Error::Io(e)) => return Err(ConnectError::Io(e)),
// Old versions of Postgres and things like Redshift don't support composites
Err(Error::Db(ref e)) if e.code == SqlState::UndefinedTable => {}
Err(Error::Db(e)) => return Err(ConnectError::Db(e)),
Err(Error::Conversion(_)) => unreachable!(),
}
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT t.typname, t.typtype, t.typelem, r.rngsubtype, \
t.typbasetype, n.nspname, t.typrelid \
FROM pg_catalog.pg_type t \
LEFT OUTER JOIN pg_catalog.pg_range r ON \
r.rngtypid = t.oid \
INNER JOIN pg_catalog.pg_namespace n ON \
t.typnamespace = n.oid \
WHERE t.oid = $1") {
Ok(..) => return Ok(()),
Err(Error::Io(e)) => return Err(ConnectError::Io(e)),
// Range types weren't added until Postgres 9.2, so pg_range may not exist
Err(Error::Db(ref e)) if e.code == SqlState::UndefinedTable => {}
Err(Error::Db(e)) => return Err(ConnectError::Db(e)),
Err(Error::Conversion(_)) => unreachable!(),
}
match self.raw_prepare(TYPEINFO_QUERY,
"SELECT t.typname, t.typtype, t.typelem, NULL::OID, t.typbasetype, \
n.nspname, t.typrelid \
FROM pg_catalog.pg_type t \
INNER JOIN pg_catalog.pg_namespace n \
ON t.typnamespace = n.oid \
WHERE t.oid = $1") {
Ok(..) => Ok(()),
Err(Error::Io(e)) => Err(ConnectError::Io(e)),
Err(Error::Db(e)) => Err(ConnectError::Db(e)),
Err(Error::Conversion(_)) => unreachable!(),
}
}
fn write_messages(&mut self, messages: &[Frontend]) -> std_io::Result<()> {
debug_assert!(!self.desynchronized);
for message in messages {
try_desync!(self, self.stream.write_message(message));
}
Ok(try_desync!(self, self.stream.flush()))
}
fn read_message_with_notification(&mut self) -> std_io::Result<Backend> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message()) {
Backend::NoticeResponse { fields } => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
Backend::ParameterStatus { parameter, value } => {
self.parameters.insert(parameter, value);
}
val => return Ok(val),
}
}
}
fn read_message_with_notification_timeout(&mut self,
timeout: Duration)
-> std::io::Result<Option<Backend>> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message_timeout(timeout)) {
Some(Backend::NoticeResponse { fields }) => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
Some(Backend::ParameterStatus { parameter, value }) => {
self.parameters.insert(parameter, value);
}
val => return Ok(val),
}
}
}
fn read_message_with_notification_nonblocking(&mut self)
-> std::io::Result<Option<Backend>> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message_nonblocking()) {
Some(Backend::NoticeResponse { fields }) => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
Some(Backend::ParameterStatus { parameter, value }) => {
self.parameters.insert(parameter, value);
}
val => return Ok(val),
}
}
}
fn read_message(&mut self) -> std_io::Result<Backend> {
loop {
match try!(self.read_message_with_notification()) {
Backend::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()) {
Backend::AuthenticationOk => return Ok(()),
Backend::AuthenticationCleartextPassword => {
let pass = try!(user.password.ok_or_else(|| {
ConnectError::ConnectParams("a password was requested but not provided".into())
}));
try!(self.write_messages(&[Frontend::PasswordMessage { password: &pass }]));
}
Backend::AuthenticationMD5Password { salt } => {
let pass = try!(user.password.ok_or_else(|| {
ConnectError::ConnectParams("a password was requested but not provided".into())
}));
let mut hasher = Md5::new();
hasher.input(pass.as_bytes());
hasher.input(user.user.as_bytes());
let output = hasher.result_str();
hasher.reset();
hasher.input(output.as_bytes());
hasher.input(&salt);
let output = format!("md5{}", hasher.result_str());
try!(self.write_messages(&[Frontend::PasswordMessage { password: &output }]));
}
Backend::AuthenticationKerberosV5 |
Backend::AuthenticationSCMCredential |
Backend::AuthenticationGSS |
Backend::AuthenticationSSPI => {
return Err(ConnectError::Io(std_io::Error::new(std_io::ErrorKind::Other,
"unsupported authentication")))
}
Backend::ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::Io(bad_response())),
}
match try!(self.read_message()) {
Backend::AuthenticationOk => Ok(()),
Backend::ErrorResponse { fields } => DbError::new_connect(fields),
_ => Err(ConnectError::Io(bad_response())),
}
}
fn set_notice_handler(&mut self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
mem::replace(&mut self.notice_handler, handler)
}
fn raw_prepare(&mut self, stmt_name: &str, query: &str) -> Result<(Vec<Type>, Vec<Column>)> {
debug!("preparing query with name `{}`: {}", stmt_name, query);
try!(self.write_messages(&[Frontend::Parse {
name: stmt_name,
query: query,
param_types: &[],
},
Frontend::Describe {
variant: b'S',
name: stmt_name,
},
Frontend::Sync]));
match try!(self.read_message()) {
Backend::ParseComplete => {}
Backend::ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => bad_response!(self),
}
let raw_param_types = match try!(self.read_message()) {
Backend::ParameterDescription { types } => types,
_ => bad_response!(self),
};
let raw_columns = match try!(self.read_message()) {
Backend::RowDescription { descriptions } => descriptions,
Backend::NoData => vec![],
_ => bad_response!(self),
};
try!(self.wait_for_ready());
let mut param_types = vec![];
for oid in raw_param_types {
param_types.push(try!(self.get_type(oid)));
}
let mut columns = vec![];
for RowDescriptionEntry { name, type_oid, .. } in raw_columns {
columns.push(Column::new(name, try!(self.get_type(type_oid))));
}
Ok((param_types, columns))
}
fn read_rows(&mut self, buf: &mut VecDeque<Vec<Option<Vec<u8>>>>) -> Result<bool> {
let more_rows;
loop {
match try!(self.read_message()) {
Backend::EmptyQueryResponse | Backend::CommandComplete { .. } => {
more_rows = false;
break;
}
Backend::PortalSuspended => {
more_rows = true;
break;
}
Backend::DataRow { row } => buf.push_back(row),
Backend::ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
Backend::CopyInResponse { .. } => {
try!(self.write_messages(&[Frontend::CopyFail {
message: "COPY queries cannot be directly \
executed",
},
Frontend::Sync]));
}
Backend::CopyOutResponse { .. } => {
loop {
if let Backend::ReadyForQuery { .. } = try!(self.read_message()) {
break;
}
}
return Err(Error::Io(std_io::Error::new(std_io::ErrorKind::InvalidInput,
"COPY queries cannot be directly \
executed")));
}
_ => {
self.desynchronized = true;
return Err(Error::Io(bad_response()));
}
}
}
try!(self.wait_for_ready());
Ok(more_rows)
}
fn raw_execute(&mut self,
stmt_name: &str,
portal_name: &str,
row_limit: i32,
param_types: &[Type],
params: &[&ToSql])
-> Result<()> {
assert!(param_types.len() == params.len(),
"expected {} parameters but got {}",
param_types.len(),
params.len());
debug!("executing statement {} with parameters: {:?}",
stmt_name,
params);
let mut values = vec![];
for (param, ty) in params.iter().zip(param_types) {
let mut buf = vec![];
match try!(param.to_sql_checked(ty, &mut buf, &SessionInfo::new(self))) {
IsNull::Yes => values.push(None),
IsNull::No => values.push(Some(buf)),
}
}
try!(self.write_messages(&[Frontend::Bind {
portal: portal_name,
statement: &stmt_name,
formats: &[1],
values: &values,
result_formats: &[1],
},
Frontend::Execute {
portal: portal_name,
max_rows: row_limit,
},
Frontend::Sync]));
match try!(self.read_message()) {
Backend::BindComplete => Ok(()),
Backend::ErrorResponse { fields } => {
try!(self.wait_for_ready());
DbError::new(fields)
}
_ => {
self.desynchronized = true;
Err(Error::Io(bad_response()))
}
}
}
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, columns) = try!(self.raw_prepare(&stmt_name, query));
let info = Arc::new(StatementInfo {
name: stmt_name,
param_types: param_types,
columns: columns,
});
Ok(Statement::new(conn, info, Cell::new(0), false))
}
fn prepare_cached<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
let info = self.cached_statements.get(query).cloned();
let info = match info {
Some(info) => info,
None => {
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
let info = Arc::new(StatementInfo {
name: stmt_name,
param_types: param_types,
columns: columns,
});
self.cached_statements.insert(query.to_owned(), info.clone());
info
}
};
Ok(Statement::new(conn, info, Cell::new(0), true))
}
fn close_statement(&mut self, name: &str, type_: u8) -> Result<()> {
try!(self.write_messages(&[Frontend::Close {
variant: type_,
name: name,
},
Frontend::Sync]));
let resp = match try!(self.read_message()) {
Backend::CloseComplete => Ok(()),
Backend::ErrorResponse { fields } => DbError::new(fields),
_ => bad_response!(self),
};
try!(self.wait_for_ready());
resp
}
fn get_type(&mut self, oid: Oid) -> Result<Type> {
if let Some(ty) = Type::from_oid(oid) {
return Ok(ty);
}
if let Some(ty) = self.unknown_types.get(&oid) {
return Ok(Type::Other(ty.clone()));
}
let ty = try!(self.read_type(oid));
self.unknown_types.insert(oid, ty.clone());
Ok(Type::Other(ty))
}
#[allow(if_not_else)]
fn read_type(&mut self, oid: Oid) -> Result<Other> {
try!(self.raw_execute(TYPEINFO_QUERY, "", 0, &[Type::Oid], &[&oid]));
let mut rows = VecDeque::new();
try!(self.read_rows(&mut rows));
let row = rows.pop_front().unwrap();
let (name, type_, elem_oid, rngsubtype, basetype, schema, relid) = {
let ctx = SessionInfo::new(self);
let name = try!(String::from_sql(&Type::Name, &mut &**row[0].as_ref().unwrap(), &ctx));
let type_ = try!(i8::from_sql(&Type::Char, &mut &**row[1].as_ref().unwrap(), &ctx));
let elem_oid = try!(Oid::from_sql(&Type::Oid, &mut &**row[2].as_ref().unwrap(), &ctx));
let rngsubtype = match row[3] {
Some(ref data) => try!(Option::<Oid>::from_sql(&Type::Oid, &mut &**data, &ctx)),
None => try!(Option::<Oid>::from_sql_null(&Type::Oid, &ctx)),
};
let basetype = try!(Oid::from_sql(&Type::Oid, &mut &**row[4].as_ref().unwrap(), &ctx));
let schema = try!(String::from_sql(&Type::Name,
&mut &**row[5].as_ref().unwrap(),
&ctx));
let relid = try!(Oid::from_sql(&Type::Oid, &mut &**row[6].as_ref().unwrap(), &ctx));
(name, type_, elem_oid, rngsubtype, basetype, schema, relid)
};
let kind = if type_ == b'e' as i8 {
Kind::Enum(try!(self.read_enum_variants(oid)))
} else if type_ == b'p' as i8 {
Kind::Pseudo
} else if basetype != 0 {
Kind::Domain(try!(self.get_type(basetype)))
} else if elem_oid != 0 {
Kind::Array(try!(self.get_type(elem_oid)))
} else if relid != 0 {
Kind::Composite(try!(self.read_composite_fields(relid)))
} else {
match rngsubtype {
Some(oid) => Kind::Range(try!(self.get_type(oid))),
None => Kind::Simple,
}
};
Ok(Other::new(name, oid, kind, schema))
}
fn read_enum_variants(&mut self, oid: Oid) -> Result<Vec<String>> {
try!(self.raw_execute(TYPEINFO_ENUM_QUERY, "", 0, &[Type::Oid], &[&oid]));
let mut rows = VecDeque::new();
try!(self.read_rows(&mut rows));
let ctx = SessionInfo::new(self);
let mut variants = vec![];
for row in rows {
variants.push(try!(String::from_sql(&Type::Name,
&mut &**row[0].as_ref().unwrap(),
&ctx)));
}
Ok(variants)
}
fn read_composite_fields(&mut self, relid: Oid) -> Result<Vec<Field>> {
try!(self.raw_execute(TYPEINFO_COMPOSITE_QUERY, "", 0, &[Type::Oid], &[&relid]));
let mut rows = VecDeque::new();
try!(self.read_rows(&mut rows));
let mut fields = vec![];
for row in rows {
let (name, type_) = {
let ctx = SessionInfo::new(self);
let name = try!(String::from_sql(&Type::Name,
&mut &**row[0].as_ref().unwrap(),
&ctx));
let type_ = try!(Oid::from_sql(&Type::Oid, &mut &**row[1].as_ref().unwrap(), &ctx));
(name, type_)
};
let type_ = try!(self.get_type(type_));
fields.push(Field::new(name, type_));
}
Ok(fields)
}
fn is_desynchronized(&self) -> bool {
self.desynchronized
}
#[allow(needless_return)]
fn wait_for_ready(&mut self) -> Result<()> {
match try!(self.read_message()) {
Backend::ReadyForQuery { .. } => Ok(()),
_ => bad_response!(self),
}
}
fn quick_query(&mut self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
check_desync!(self);
debug!("executing query: {}", query);
try!(self.write_messages(&[Frontend::Query { query: query }]));
let mut result = vec![];
loop {
match try!(self.read_message()) {
Backend::ReadyForQuery { .. } => break,
Backend::DataRow { row } => {
result.push(row.into_iter()
.map(|opt| {
opt.map(|b| String::from_utf8_lossy(&b).into_owned())
})
.collect());
}
Backend::CopyInResponse { .. } => {
try!(self.write_messages(&[Frontend::CopyFail {
message: "COPY queries cannot be directly \
executed",
},
Frontend::Sync]));
}
Backend::ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
_ => {}
}
}
Ok(result)
}
fn finish_inner(&mut self) -> Result<()> {
check_desync!(self);
try!(self.write_messages(&[Frontend::Terminate]));
Ok(())
}
}
fn _ensure_send() {
fn _is_send<T: Send>() {}
_is_send::<Connection>();
}
/// A connection to a Postgres database.
pub struct Connection {
conn: RefCell<InnerConnection>,
}
impl fmt::Debug for Connection {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let conn = self.conn.borrow();
fmt.debug_struct("Connection")
.field("stream", &conn.stream.get_ref())
.field("cancel_data", &conn.cancel_data)
.field("notifications", &conn.notifications.len())
.field("transaction_depth", &conn.trans_depth)
.field("desynchronized", &conn.desynchronized)
.field("cached_statements", &conn.cached_statements.len())
.finish()
}
}
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.
///
/// Connection via Unix sockets is supported with either the `unix_socket`
/// or `nightly` features. 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 url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let conn = Connection::connect(url, SslMode::None).unwrap();
/// ```
///
/// ```rust,no_run
/// use postgres::{Connection, SslMode};
///
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let conn = Connection::connect(url, SslMode::None).unwrap();
/// ```
///
/// ```rust,no_run
/// use postgres::{Connection, UserInfo, ConnectParams, SslMode, ConnectTarget};