rust-postgres/src/lib.rs

1358 lines
48 KiB
Rust
Raw Normal View History

2015-12-13 04:21:44 +00:00
//! A pure-Rust frontend for the popular PostgreSQL database.
2014-07-03 05:23:17 +00:00
//!
//! ```rust,no_run
//! extern crate postgres;
//!
//! use postgres::{Connection, TlsMode};
2014-07-03 05:23:17 +00:00
//!
//! struct Person {
//! id: i32,
//! name: String,
//! data: Option<Vec<u8>>
//! }
//!
//! fn main() {
//! let conn = Connection::connect("postgresql://postgres@localhost", TlsMode::None)
2014-11-01 23:38:52 +00:00
//! .unwrap();
2014-07-03 05:23:17 +00:00
//!
//! conn.execute("CREATE TABLE person (
//! id SERIAL PRIMARY KEY,
//! name VARCHAR NOT NULL,
//! data BYTEA
2014-11-25 20:59:31 +00:00
//! )", &[]).unwrap();
2014-07-03 05:23:17 +00:00
//! let me = Person {
//! id: 0,
//! name: "Steven".to_owned(),
2014-07-03 05:23:17 +00:00
//! data: None
//! };
2015-02-08 03:52:45 +00:00
//! conn.execute("INSERT INTO person (name, data) VALUES ($1, $2)",
//! &[&me.name, &me.data]).unwrap();
2014-07-03 05:23:17 +00:00
//!
2015-12-06 20:10:54 +00:00
//! for row in &conn.query("SELECT id, name, data FROM person", &[]).unwrap() {
2014-07-03 05:23:17 +00:00
//! let person = Person {
//! id: row.get(0),
//! name: row.get(1),
2015-02-08 03:52:45 +00:00
//! data: row.get(2)
2014-07-03 05:23:17 +00:00
//! };
//! println!("Found person {}", person.name);
//! }
//! }
//! ```
2016-08-29 08:26:54 +00:00
#![doc(html_root_url="https://sfackler.github.io/rust-postgres/doc/v0.11.11")]
2014-10-31 15:51:27 +00:00
#![warn(missing_docs)]
2016-02-20 23:05:48 +00:00
#![allow(unknown_lints, needless_lifetimes)] // for clippy
2013-10-08 04:11:54 +00:00
2015-05-05 18:40:14 +00:00
extern crate bufstream;
2015-02-05 04:39:30 +00:00
extern crate byteorder;
extern crate fallible_iterator;
extern crate hex;
2015-01-07 16:23:40 +00:00
#[macro_use]
2014-12-10 05:35:52 +00:00
extern crate log;
extern crate phf;
extern crate postgres_protocol;
2015-02-26 17:02:32 +00:00
2014-02-08 02:17:40 +00:00
use std::cell::{Cell, RefCell};
2015-02-20 21:56:03 +00:00
use std::collections::{VecDeque, HashMap};
2014-12-10 05:35:52 +00:00
use std::fmt;
2015-04-28 05:26:20 +00:00
use std::io as std_io;
2015-02-26 17:02:32 +00:00
use std::io::prelude::*;
2014-02-12 07:42:46 +00:00
use std::mem;
2014-11-01 23:12:05 +00:00
use std::result;
2016-01-03 05:02:54 +00:00
use std::sync::Arc;
use std::time::Duration;
2016-09-16 04:20:25 +00:00
use postgres_protocol::authentication;
2016-09-14 02:30:28 +00:00
use postgres_protocol::message::backend::{self, RowDescriptionEntry};
use postgres_protocol::message::frontend;
2013-08-04 02:17:32 +00:00
2015-05-26 05:47:25 +00:00
use error::{Error, ConnectError, SqlState, DbError};
2016-09-12 02:20:23 +00:00
use io::TlsHandshake;
use notification::{Notifications, Notification};
use params::{ConnectParams, IntoConnectParams, UserInfo};
2016-09-12 00:19:06 +00:00
use priv_io::MessageStream;
2015-05-30 05:54:10 +00:00
use rows::{Rows, LazyRows};
2015-09-19 03:21:13 +00:00
use stmt::{Statement, Column};
2016-03-04 05:48:25 +00:00
use transaction::{Transaction, IsolationLevel};
2016-09-12 00:19:06 +00:00
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, WrongType, ToSql, FromSql, Field};
2013-07-25 07:10:18 +00:00
2015-01-07 16:23:40 +00:00
#[macro_use]
2014-07-07 02:02:22 +00:00
mod macros;
mod feature_check;
2015-04-28 05:26:20 +00:00
mod priv_io;
mod url;
2015-08-16 04:39:46 +00:00
pub mod error;
pub mod io;
2016-02-24 07:43:28 +00:00
pub mod notification;
pub mod params;
2015-05-30 05:54:10 +00:00
pub mod rows;
2015-08-16 06:21:39 +00:00
pub mod stmt;
2016-02-24 07:43:28 +00:00
pub mod transaction;
2015-08-16 04:39:46 +00:00
pub mod types;
2016-02-16 07:11:01 +00:00
const TYPEINFO_QUERY: &'static str = "__typeinfo";
const TYPEINFO_ENUM_QUERY: &'static str = "__typeinfo_enum";
2016-02-20 23:21:24 +00:00
const TYPEINFO_COMPOSITE_QUERY: &'static str = "__typeinfo_composite";
2013-10-21 00:32:14 +00:00
/// A type alias of the result returned by many methods.
2014-11-04 06:24:11 +00:00
pub type Result<T> = result::Result<T, Error>;
2014-04-03 04:26:41 +00:00
2013-09-30 02:12:20 +00:00
/// Trait for types that can handle Postgres notice messages
///
/// It is implemented for all `Send + FnMut(DbError)` closures.
2015-02-22 23:05:19 +00:00
pub trait HandleNotice: Send {
2013-09-30 02:12:20 +00:00
/// Handle a Postgres notice message
2015-02-22 23:05:19 +00:00
fn handle_notice(&mut self, notice: DbError);
}
impl<F: Send + FnMut(DbError)> HandleNotice for F {
fn handle_notice(&mut self, notice: DbError) {
self(notice)
}
}
2013-09-30 05:22:10 +00:00
/// A notice handler which logs at the `info` level.
2013-09-30 02:12:20 +00:00
///
2014-11-01 23:21:47 +00:00
/// This is the default handler used by a `Connection`.
2015-04-03 15:46:02 +00:00
#[derive(Copy, Clone, Debug)]
2015-02-22 23:05:19 +00:00
pub struct LoggingNoticeHandler;
2015-02-22 23:05:19 +00:00
impl HandleNotice for LoggingNoticeHandler {
fn handle_notice(&mut self, notice: DbError) {
info!("{}: {}", notice.severity, notice.message);
}
}
2015-05-02 22:55:53 +00:00
/// Contains information necessary to cancel queries for a session.
2015-01-24 07:31:17 +00:00
#[derive(Copy, Clone, Debug)]
2014-11-01 23:19:02 +00:00
pub struct CancelData {
2015-05-02 22:55:53 +00:00
/// The process ID of the session.
2016-09-12 00:19:06 +00:00
pub process_id: i32,
2015-05-02 22:55:53 +00:00
/// The secret key for the session.
2016-09-12 00:19:06 +00:00
pub secret_key: i32,
2013-10-21 00:32:14 +00:00
}
/// 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.
///
2014-11-03 00:48:38 +00:00
/// A `CancelData` object can be created via `Connection::cancel_data`. The
/// object can cancel any query made on that connection.
2014-03-09 22:22:20 +00:00
///
2014-08-21 05:40:11 +00:00
/// Only the host and port of the connection info are used. See
2014-11-01 23:21:47 +00:00
/// `Connection::connect` for details of the `params` argument.
2014-03-31 02:21:51 +00:00
///
2015-11-29 05:05:13 +00:00
/// # Example
2014-03-09 22:22:20 +00:00
///
2014-03-10 17:06:40 +00:00
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
2015-03-26 02:11:40 +00:00
/// # use std::thread;
2014-03-09 22:22:20 +00:00
/// # let url = "";
/// let conn = Connection::connect(url, TlsMode::None).unwrap();
2014-03-09 22:22:20 +00:00
/// let cancel_data = conn.cancel_data();
2015-03-26 02:11:40 +00:00
/// thread::spawn(move || {
/// conn.execute("SOME EXPENSIVE QUERY", &[]).unwrap();
2015-01-09 19:20:43 +00:00
/// });
/// postgres::cancel_query(url, TlsMode::None, &cancel_data).unwrap();
2014-03-09 22:22:20 +00:00
/// ```
2015-11-16 03:51:04 +00:00
pub fn cancel_query<T>(params: T,
2016-07-01 19:26:13 +00:00
tls: TlsMode,
data: &CancelData)
2015-11-16 03:51:04 +00:00
-> result::Result<(), ConnectError>
where T: IntoConnectParams
{
let params = try!(params.into_connect_params().map_err(ConnectError::ConnectParams));
2016-07-01 19:26:13 +00:00
let mut socket = try!(priv_io::initialize_stream(&params, tls));
2013-10-21 00:32:14 +00:00
2016-09-11 23:29:28 +00:00
let mut buf = vec![];
2016-09-20 03:46:25 +00:00
frontend::cancel_request(data.process_id, data.secret_key, &mut buf);
2016-09-11 23:29:28 +00:00
try!(socket.write_all(&buf));
2014-11-17 06:54:57 +00:00
try!(socket.flush());
2013-10-21 00:32:14 +00:00
2013-12-06 07:20:50 +00:00
Ok(())
2013-10-21 00:32:14 +00:00
}
fn bad_response() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::InvalidInput,
"the server returned an unexpected response")
}
2015-05-26 06:27:12 +00:00
fn desynchronized() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::Other,
2015-11-16 03:51:04 +00:00
"communication with the server has desynchronized due to an earlier IO \
error")
2015-05-26 06:27:12 +00:00
}
/// Specifies the TLS support requested for a new connection.
#[derive(Debug)]
pub enum TlsMode<'a> {
2016-07-01 19:26:13 +00:00
/// The connection will not use TLS.
2015-04-28 05:26:20 +00:00
None,
2016-07-01 19:26:13 +00:00
/// The connection will use TLS if the backend supports it.
2016-07-01 19:18:56 +00:00
Prefer(&'a TlsHandshake),
2016-07-01 19:26:13 +00:00
/// The connection must use TLS.
2016-07-01 19:18:56 +00:00
Require(&'a TlsHandshake),
2015-04-28 05:26:20 +00:00
}
2016-01-03 05:02:54 +00:00
struct StatementInfo {
name: String,
param_types: Vec<Type>,
columns: Vec<Column>,
}
2014-11-01 23:21:47 +00:00
struct InnerConnection {
2016-09-12 00:19:06 +00:00
stream: MessageStream,
2015-02-22 23:05:19 +00:00
notice_handler: Box<HandleNotice>,
2015-02-20 21:56:03 +00:00
notifications: VecDeque<Notification>,
2014-11-01 23:19:02 +00:00
cancel_data: CancelData,
2016-01-03 04:07:33 +00:00
unknown_types: HashMap<Oid, Other>,
2016-01-03 05:02:54 +00:00
cached_statements: HashMap<String, Arc<StatementInfo>>,
2015-02-16 04:22:56 +00:00
parameters: HashMap<String, String>,
2015-01-29 04:35:17 +00:00
next_stmt_id: u32,
trans_depth: u32,
2015-01-29 04:35:17 +00:00
desynchronized: bool,
finished: bool,
2016-09-10 21:27:34 +00:00
has_typeinfo_query: bool,
has_typeinfo_enum_query: bool,
has_typeinfo_composite_query: bool,
2013-08-29 06:19:53 +00:00
}
2014-11-01 23:21:47 +00:00
impl Drop for InnerConnection {
2013-09-18 05:06:47 +00:00
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
2013-08-29 06:19:53 +00:00
}
}
2014-11-01 23:21:47 +00:00
impl InnerConnection {
2016-07-01 19:26:13 +00:00
fn connect<T>(params: T, tls: TlsMode) -> result::Result<InnerConnection, ConnectError>
2015-11-16 03:51:04 +00:00
where T: IntoConnectParams
{
let params = try!(params.into_connect_params().map_err(ConnectError::ConnectParams));
2016-07-01 19:26:13 +00:00
let stream = try!(priv_io::initialize_stream(&params, tls));
2014-12-02 05:28:58 +00:00
let ConnectParams { user, database, mut options, .. } = params;
let user = match user {
Some(user) => user,
None => {
2016-09-13 04:48:49 +00:00
return Err(ConnectError::ConnectParams("User missing from connection parameters"
.into()));
}
};
2014-11-01 23:21:47 +00:00
let mut conn = InnerConnection {
2016-09-12 00:19:06 +00:00
stream: MessageStream::new(stream),
2014-05-28 04:07:58 +00:00
next_stmt_id: 0,
2015-02-22 23:05:19 +00:00
notice_handler: Box::new(LoggingNoticeHandler),
2015-02-20 21:56:03 +00:00
notifications: VecDeque::new(),
2015-11-16 03:51:04 +00:00
cancel_data: CancelData {
process_id: 0,
secret_key: 0,
},
2014-05-28 04:07:58 +00:00
unknown_types: HashMap::new(),
cached_statements: HashMap::new(),
2015-02-16 04:22:56 +00:00
parameters: HashMap::new(),
2014-05-28 04:07:58 +00:00
desynchronized: false,
finished: false,
trans_depth: 0,
2016-09-10 21:27:34 +00:00
has_typeinfo_query: false,
has_typeinfo_enum_query: false,
has_typeinfo_composite_query: false,
2014-05-28 04:07:58 +00:00
};
2014-12-23 17:10:16 +00:00
options.push(("client_encoding".to_owned(), "UTF8".to_owned()));
2013-09-09 04:33:41 +00:00
// 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
2014-12-23 17:10:16 +00:00
options.push(("user".to_owned(), user.user.clone()));
2014-12-02 05:28:58 +00:00
if let Some(database) = database {
2014-12-23 17:10:16 +00:00
options.push(("database".to_owned(), database));
}
2016-09-20 16:54:51 +00:00
let options = options.iter().map(|&(ref a, ref b)| (&**a, &**b));
try!(conn.stream.write_message2(|buf| frontend::startup_message(options, buf)));
try!(conn.stream.flush());
try!(conn.handle_auth(user));
2013-08-04 02:17:32 +00:00
2013-08-22 05:52:15 +00:00
loop {
2014-11-17 06:54:57 +00:00
match try!(conn.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::BackendKeyData { process_id, secret_key } => {
conn.cancel_data.process_id = process_id;
conn.cancel_data.secret_key = secret_key;
2013-10-21 00:32:14 +00:00
}
2016-09-14 02:30:28 +00:00
backend::Message::ReadyForQuery { .. } => break,
backend::Message::ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::Io(bad_response())),
}
2013-08-05 00:48:48 +00:00
}
2013-08-23 05:24:14 +00:00
Ok(conn)
}
2016-09-14 02:30:28 +00:00
fn read_message_with_notification(&mut self) -> std_io::Result<backend::Message> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::NoticeResponse { fields } => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
2016-09-14 02:30:28 +00:00
backend::Message::ParameterStatus { parameter, value } => {
self.parameters.insert(parameter, value);
}
2015-11-16 03:51:04 +00:00
val => return Ok(val),
}
}
}
2015-11-16 03:51:04 +00:00
fn read_message_with_notification_timeout(&mut self,
timeout: Duration)
2016-09-14 02:30:28 +00:00
-> std::io::Result<Option<backend::Message>> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message_timeout(timeout)) {
2016-09-14 02:30:28 +00:00
Some(backend::Message::NoticeResponse { fields }) => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
2016-09-14 02:30:28 +00:00
Some(backend::Message::ParameterStatus { parameter, value }) => {
self.parameters.insert(parameter, value);
}
2015-11-16 03:51:04 +00:00
val => return Ok(val),
}
}
}
2016-09-16 03:51:26 +00:00
fn read_message_with_notification_nonblocking(&mut self)
-> std::io::Result<Option<backend::Message>> {
debug_assert!(!self.desynchronized);
loop {
match try_desync!(self, self.stream.read_message_nonblocking()) {
2016-09-14 02:30:28 +00:00
Some(backend::Message::NoticeResponse { fields }) => {
if let Ok(err) = DbError::new_raw(fields) {
self.notice_handler.handle_notice(err);
}
}
2016-09-14 02:30:28 +00:00
Some(backend::Message::ParameterStatus { parameter, value }) => {
self.parameters.insert(parameter, value);
}
val => return Ok(val),
}
}
}
2016-09-14 02:30:28 +00:00
fn read_message(&mut self) -> std_io::Result<backend::Message> {
loop {
match try!(self.read_message_with_notification()) {
2016-09-14 02:30:28 +00:00
backend::Message::NotificationResponse { process_id, channel, payload } => {
2014-11-07 16:54:10 +00:00
self.notifications.push_back(Notification {
process_id: process_id,
channel: channel,
2015-11-16 03:51:04 +00:00
payload: payload,
2014-08-16 02:50:11 +00:00
})
}
2015-11-16 03:51:04 +00:00
val => return Ok(val),
}
2013-08-04 05:21:16 +00:00
}
2013-08-22 06:41:26 +00:00
}
2014-11-04 06:24:11 +00:00
fn handle_auth(&mut self, user: UserInfo) -> result::Result<(), ConnectError> {
2014-11-17 06:54:57 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::AuthenticationOk => return Ok(()),
backend::Message::AuthenticationCleartextPassword => {
let pass = try!(user.password.ok_or_else(|| {
ConnectError::ConnectParams("a password was requested but not provided".into())
}));
2016-09-20 16:54:51 +00:00
try!(self.stream.write_message2(|buf| frontend::password_message(&pass, buf)));
try!(self.stream.flush());
}
2016-09-14 02:30:28 +00:00
backend::Message::AuthenticationMD5Password { salt } => {
let pass = try!(user.password.ok_or_else(|| {
ConnectError::ConnectParams("a password was requested but not provided".into())
}));
2016-09-16 04:20:25 +00:00
let output = authentication::md5_hash(user.user.as_bytes(), pass.as_bytes(), salt);
2016-09-20 16:54:51 +00:00
try!(self.stream.write_message2(|buf| frontend::password_message(&output, buf)));
try!(self.stream.flush());
}
2016-09-14 02:30:28 +00:00
backend::Message::AuthenticationKerberosV5 |
backend::Message::AuthenticationSCMCredential |
backend::Message::AuthenticationGSS |
backend::Message::AuthenticationSSPI => {
return Err(ConnectError::Io(std_io::Error::new(std_io::ErrorKind::Other,
"unsupported authentication")))
}
2016-09-14 02:30:28 +00:00
backend::Message::ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::Io(bad_response())),
}
2014-11-17 06:54:57 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::AuthenticationOk => Ok(()),
backend::Message::ErrorResponse { fields } => DbError::new_connect(fields),
2016-02-20 23:05:48 +00:00
_ => Err(ConnectError::Io(bad_response())),
}
}
2015-02-22 23:05:19 +00:00
fn set_notice_handler(&mut self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
2014-02-11 03:20:53 +00:00
mem::replace(&mut self.notice_handler, handler)
}
2015-05-18 04:04:44 +00:00
fn raw_prepare(&mut self, stmt_name: &str, query: &str) -> Result<(Vec<Type>, Vec<Column>)> {
2015-03-31 03:18:47 +00:00
debug!("preparing query with name `{}`: {}", stmt_name, query);
2016-09-20 16:54:51 +00:00
try!(self.stream.write_message2(|buf| frontend::parse(stmt_name, query, None, buf)));
2016-09-20 13:47:16 +00:00
try!(self.stream.write_message2(|buf| frontend::describe(b'S', stmt_name, buf)));
2016-09-20 20:33:26 +00:00
try!(self.stream.write_message2(|buf| Ok::<(), std_io::Error>(frontend::sync(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
2013-08-22 06:41:26 +00:00
2014-11-17 06:54:57 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::ParseComplete => {}
backend::Message::ErrorResponse { fields } => {
2014-02-22 07:18:39 +00:00
try!(self.wait_for_ready());
return DbError::new(fields);
}
2014-07-10 19:35:57 +00:00
_ => bad_response!(self),
}
2013-08-22 06:41:26 +00:00
2015-01-22 06:11:43 +00:00
let raw_param_types = match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::ParameterDescription { types } => types,
2014-07-10 19:35:57 +00:00
_ => bad_response!(self),
};
2013-08-22 06:41:26 +00:00
let raw_columns = match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::RowDescription { descriptions } => descriptions,
backend::Message::NoData => vec![],
2015-11-16 03:51:04 +00:00
_ => bad_response!(self),
};
2013-08-17 22:09:26 +00:00
2014-02-22 07:18:39 +00:00
try!(self.wait_for_ready());
2013-08-22 06:41:26 +00:00
2015-01-22 06:11:43 +00:00
let mut param_types = vec![];
2015-02-03 17:06:52 +00:00
for oid in raw_param_types {
2015-01-22 06:11:43 +00:00
param_types.push(try!(self.get_type(oid)));
}
let mut columns = vec![];
for RowDescriptionEntry { name, type_oid, .. } in raw_columns {
2015-08-16 04:39:46 +00:00
columns.push(Column::new(name, try!(self.get_type(type_oid))));
}
2013-12-04 08:18:28 +00:00
Ok((param_types, columns))
2014-12-02 05:28:58 +00:00
}
fn read_rows(&mut self, buf: &mut VecDeque<Vec<Option<Vec<u8>>>>) -> Result<bool> {
let more_rows;
loop {
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::EmptyQueryResponse |
backend::Message::CommandComplete { .. } => {
more_rows = false;
break;
}
2016-09-14 02:30:28 +00:00
backend::Message::PortalSuspended => {
more_rows = true;
break;
}
2016-09-14 02:30:28 +00:00
backend::Message::DataRow { row } => buf.push_back(row),
backend::Message::ErrorResponse { fields } => {
try!(self.wait_for_ready());
return DbError::new(fields);
}
2016-09-14 02:30:28 +00:00
backend::Message::CopyInResponse { .. } => {
2016-09-20 13:40:59 +00:00
try!(self.stream.write_message2(|buf| {
frontend::copy_fail("COPY queries cannot be directly executed", buf)
2016-09-11 23:13:57 +00:00
}));
2016-09-20 20:33:26 +00:00
try!(self.stream
.write_message2(|buf| Ok::<(), std_io::Error>(frontend::sync(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
}
2016-09-14 02:30:28 +00:00
backend::Message::CopyOutResponse { .. } => {
loop {
2016-09-14 02:30:28 +00:00
if let backend::Message::ReadyForQuery { .. } = try!(self.read_message()) {
2016-02-20 23:05:48 +00:00
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)
}
2016-02-16 06:25:52 +00:00
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());
2016-02-22 04:02:34 +00:00
debug!("executing statement {} with parameters: {:?}",
stmt_name,
params);
2016-09-20 03:46:25 +00:00
{
let info = SessionInfo::new(&self.parameters);
let r = self.stream.write_message2(|buf| {
frontend::bind(portal_name,
&stmt_name,
Some(1),
params.iter().zip(param_types),
|(param, ty), buf| {
match param.to_sql_checked(ty, buf, &info) {
Ok(IsNull::Yes) => Ok(postgres_protocol::IsNull::Yes),
Ok(IsNull::No) => Ok(postgres_protocol::IsNull::No),
Err(e) => Err(e),
}
},
Some(1),
buf)
});
match r {
Ok(()) => {}
Err(frontend::BindError::Conversion(e)) => return Err(Error::Conversion(e)),
Err(frontend::BindError::Serialization(e)) => return Err(Error::Io(e)),
2016-02-16 06:25:52 +00:00
}
}
2016-09-20 13:47:16 +00:00
try!(self.stream.write_message2(|buf| frontend::execute(portal_name, row_limit, buf)));
2016-09-20 20:33:26 +00:00
try!(self.stream.write_message2(|buf| Ok::<(), std_io::Error>(frontend::sync(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
2016-02-16 06:25:52 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::BindComplete => Ok(()),
backend::Message::ErrorResponse { fields } => {
2016-02-16 06:25:52 +00:00
try!(self.wait_for_ready());
DbError::new(fields)
}
_ => {
self.desynchronized = true;
Err(Error::Io(bad_response()))
}
}
}
2014-12-02 05:28:58 +00:00
fn make_stmt_name(&mut self) -> String {
let stmt_name = format!("s{}", self.next_stmt_id);
self.next_stmt_id += 1;
stmt_name
2014-09-30 05:56:43 +00:00
}
2014-11-03 00:48:38 +00:00
fn prepare<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
2014-12-02 05:28:58 +00:00
let stmt_name = self.make_stmt_name();
let (param_types, columns) = try!(self.raw_prepare(&stmt_name, query));
2016-01-03 05:02:54 +00:00
let info = Arc::new(StatementInfo {
name: stmt_name,
param_types: param_types,
columns: columns,
});
Ok(Statement::new(conn, info, Cell::new(0), false))
2013-08-22 06:41:26 +00:00
}
fn prepare_cached<'a>(&mut self, query: &str, conn: &'a Connection) -> Result<Statement<'a>> {
2016-01-03 05:02:54 +00:00
let info = self.cached_statements.get(query).cloned();
2016-01-03 05:02:54 +00:00
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));
2016-01-03 05:02:54 +00:00
let info = Arc::new(StatementInfo {
name: stmt_name,
param_types: param_types,
columns: columns,
2016-01-03 05:02:54 +00:00
});
self.cached_statements.insert(query.to_owned(), info.clone());
info
}
};
2016-01-03 05:02:54 +00:00
Ok(Statement::new(conn, info, Cell::new(0), true))
}
fn close_statement(&mut self, name: &str, type_: u8) -> Result<()> {
2016-09-20 03:46:25 +00:00
try!(self.stream.write_message2(|buf| frontend::close(type_, name, buf)));
2016-09-20 20:33:26 +00:00
try!(self.stream.write_message2(|buf| Ok::<(), std_io::Error>(frontend::sync(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
let resp = match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::CloseComplete => Ok(()),
backend::Message::ErrorResponse { fields } => DbError::new(fields),
2015-11-16 03:51:04 +00:00
_ => bad_response!(self),
};
try!(self.wait_for_ready());
resp
2014-09-30 05:56:43 +00:00
}
2015-01-22 06:11:43 +00:00
fn get_type(&mut self, oid: Oid) -> Result<Type> {
if let Some(ty) = Type::from_oid(oid) {
2015-01-22 06:11:43 +00:00
return Ok(ty);
2014-03-30 23:19:04 +00:00
}
2014-08-16 02:50:11 +00:00
2015-01-22 06:11:43 +00:00
if let Some(ty) = self.unknown_types.get(&oid) {
2016-01-03 04:07:33 +00:00
return Ok(Type::Other(ty.clone()));
2013-12-04 08:18:28 +00:00
}
2015-01-22 06:11:43 +00:00
2016-02-20 23:20:25 +00:00
let ty = try!(self.read_type(oid));
self.unknown_types.insert(oid, ty.clone());
Ok(Type::Other(ty))
}
fn setup_typeinfo_query(&mut self) -> Result<()> {
2016-09-10 21:27:34 +00:00
if self.has_typeinfo_query {
return Ok(());
}
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(..) => {}
// 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 => {
try!(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"));
}
Err(e) => return Err(e),
}
2016-09-10 21:27:34 +00:00
self.has_typeinfo_query = true;
Ok(())
}
#[allow(if_not_else)]
2016-02-20 23:20:25 +00:00
fn read_type(&mut self, oid: Oid) -> Result<Other> {
try!(self.setup_typeinfo_query());
2016-02-16 06:29:22 +00:00
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();
2016-02-16 07:11:01 +00:00
let (name, type_, elem_oid, rngsubtype, basetype, schema, relid) = {
2016-09-20 03:46:25 +00:00
let ctx = SessionInfo::new(&self.parameters);
let name = try!(String::from_sql(&Type::Name, &mut &**row[0].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
let type_ = try!(i8::from_sql(&Type::Char, &mut &**row[1].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
let elem_oid = try!(Oid::from_sql(&Type::Oid, &mut &**row[2].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
2016-02-16 06:29:22 +00:00
let rngsubtype = match row[3] {
Some(ref data) => {
try!(Option::<Oid>::from_sql(&Type::Oid, &mut &**data, &ctx)
.map_err(Error::Conversion))
2016-09-16 03:51:26 +00:00
}
None => {
2016-09-16 03:51:26 +00:00
try!(Option::<Oid>::from_sql_null(&Type::Oid, &ctx).map_err(Error::Conversion))
}
2016-02-16 06:29:22 +00:00
};
let basetype = try!(Oid::from_sql(&Type::Oid, &mut &**row[4].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
2016-09-16 03:51:26 +00:00
let schema =
try!(String::from_sql(&Type::Name, &mut &**row[5].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
let relid = try!(Oid::from_sql(&Type::Oid, &mut &**row[6].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
2016-02-16 07:11:01 +00:00
(name, type_, elem_oid, rngsubtype, basetype, schema, relid)
2015-11-15 01:05:31 +00:00
};
2015-01-22 06:11:43 +00:00
2016-02-14 05:51:37 +00:00
let kind = if type_ == b'e' as i8 {
2016-02-20 23:20:25 +00:00
Kind::Enum(try!(self.read_enum_variants(oid)))
2016-02-14 05:51:37 +00:00
} 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 {
2015-02-14 20:46:18 +00:00
Kind::Array(try!(self.get_type(elem_oid)))
2016-02-16 07:11:01 +00:00
} else if relid != 0 {
2016-02-20 23:20:25 +00:00
Kind::Composite(try!(self.read_composite_fields(relid)))
2015-01-22 06:11:43 +00:00
} else {
2015-02-14 20:46:18 +00:00
match rngsubtype {
Some(oid) => Kind::Range(try!(self.get_type(oid))),
2015-11-16 03:51:04 +00:00
None => Kind::Simple,
2015-02-14 20:46:18 +00:00
}
2015-01-22 06:11:43 +00:00
};
2015-02-14 20:46:18 +00:00
2016-02-20 23:20:25 +00:00
Ok(Other::new(name, oid, kind, schema))
}
fn setup_typeinfo_enum_query(&mut self) -> Result<()> {
2016-09-10 21:27:34 +00:00
if self.has_typeinfo_enum_query {
return Ok(());
}
match self.raw_prepare(TYPEINFO_ENUM_QUERY,
"SELECT enumlabel \
FROM pg_catalog.pg_enum \
WHERE enumtypid = $1 \
ORDER BY enumsortorder") {
Ok(..) => {}
// Postgres 9.0 doesn't have enumsortorder
Err(Error::Db(ref e)) if e.code == SqlState::UndefinedColumn => {
try!(self.raw_prepare(TYPEINFO_ENUM_QUERY,
"SELECT enumlabel \
FROM pg_catalog.pg_enum \
WHERE enumtypid = $1 \
ORDER BY oid"));
}
Err(e) => return Err(e),
}
2016-09-10 21:27:34 +00:00
self.has_typeinfo_enum_query = true;
Ok(())
}
2016-02-20 23:20:25 +00:00
fn read_enum_variants(&mut self, oid: Oid) -> Result<Vec<String>> {
try!(self.setup_typeinfo_enum_query());
2016-02-20 23:20:25 +00:00
try!(self.raw_execute(TYPEINFO_ENUM_QUERY, "", 0, &[Type::Oid], &[&oid]));
let mut rows = VecDeque::new();
try!(self.read_rows(&mut rows));
2016-09-20 03:46:25 +00:00
let ctx = SessionInfo::new(&self.parameters);
2016-02-20 23:20:25 +00:00
let mut variants = vec![];
for row in rows {
2016-09-16 03:51:26 +00:00
variants.push(try!(String::from_sql(&Type::Name, &mut &**row[0].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion)));
2016-02-20 23:20:25 +00:00
}
Ok(variants)
}
fn setup_typeinfo_composite_query(&mut self) -> Result<()> {
2016-09-10 21:27:34 +00:00
if self.has_typeinfo_composite_query {
return Ok(());
}
try!(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"));
2016-09-10 21:27:34 +00:00
self.has_typeinfo_composite_query = true;
Ok(())
}
2016-02-20 23:20:25 +00:00
fn read_composite_fields(&mut self, relid: Oid) -> Result<Vec<Field>> {
try!(self.setup_typeinfo_composite_query());
2016-02-20 23:21:24 +00:00
try!(self.raw_execute(TYPEINFO_COMPOSITE_QUERY, "", 0, &[Type::Oid], &[&relid]));
2016-02-20 23:20:25 +00:00
let mut rows = VecDeque::new();
try!(self.read_rows(&mut rows));
let mut fields = vec![];
for row in rows {
let (name, type_) = {
2016-09-20 03:46:25 +00:00
let ctx = SessionInfo::new(&self.parameters);
2016-09-16 03:51:26 +00:00
let name =
try!(String::from_sql(&Type::Name, &mut &**row[0].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
let type_ = try!(Oid::from_sql(&Type::Oid, &mut &**row[1].as_ref().unwrap(), &ctx)
.map_err(Error::Conversion));
2016-02-20 23:20:25 +00:00
(name, type_)
};
let type_ = try!(self.get_type(type_));
fields.push(Field::new(name, type_));
}
Ok(fields)
2013-12-04 08:18:28 +00:00
}
2014-03-30 23:19:04 +00:00
fn is_desynchronized(&self) -> bool {
self.desynchronized
}
2016-02-20 23:26:33 +00:00
#[allow(needless_return)]
2014-11-01 23:12:05 +00:00
fn wait_for_ready(&mut self) -> Result<()> {
2014-11-17 06:54:57 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::ReadyForQuery { .. } => Ok(()),
2015-11-16 03:51:04 +00:00
_ => bad_response!(self),
}
}
2013-12-04 07:48:46 +00:00
2014-11-01 23:12:05 +00:00
fn quick_query(&mut self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
check_desync!(self);
2015-03-31 03:18:47 +00:00
debug!("executing query: {}", query);
2016-09-20 16:54:51 +00:00
try!(self.stream.write_message2(|buf| frontend::query(query, buf)));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
2013-12-04 07:48:46 +00:00
2014-05-26 18:41:18 +00:00
let mut result = vec![];
2013-12-04 07:48:46 +00:00
loop {
2014-11-17 06:54:57 +00:00
match try!(self.read_message()) {
2016-09-14 02:30:28 +00:00
backend::Message::ReadyForQuery { .. } => break,
backend::Message::DataRow { row } => {
2015-11-16 03:51:04 +00:00
result.push(row.into_iter()
2016-09-13 04:48:49 +00:00
.map(|opt| opt.map(|b| String::from_utf8_lossy(&b).into_owned()))
.collect());
2014-04-26 21:46:38 +00:00
}
2016-09-14 02:30:28 +00:00
backend::Message::CopyInResponse { .. } => {
2016-09-20 13:40:59 +00:00
try!(self.stream.write_message2(|buf| {
frontend::copy_fail("COPY queries cannot be directly executed", buf)
2016-09-11 23:13:57 +00:00
}));
2016-09-20 20:33:26 +00:00
try!(self.stream
.write_message2(|buf| Ok::<(), std_io::Error>(frontend::sync(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
2014-10-06 00:31:25 +00:00
}
2016-09-14 02:30:28 +00:00
backend::Message::ErrorResponse { fields } => {
2014-02-22 07:18:39 +00:00
try!(self.wait_for_ready());
return DbError::new(fields);
}
2013-12-04 07:48:46 +00:00
_ => {}
}
}
Ok(result)
2013-12-04 07:48:46 +00:00
}
2014-11-01 23:12:05 +00:00
fn finish_inner(&mut self) -> Result<()> {
check_desync!(self);
2016-09-20 20:33:26 +00:00
try!(self.stream.write_message2(|buf| Ok::<(), std_io::Error>(frontend::terminate(buf))));
2016-09-11 23:13:57 +00:00
try!(self.stream.flush());
2014-04-26 06:14:55 +00:00
Ok(())
}
}
2015-07-22 14:41:40 +00:00
fn _ensure_send() {
fn _is_send<T: Send>() {}
2015-07-22 14:41:40 +00:00
_is_send::<Connection>();
}
2013-09-30 02:12:20 +00:00
/// A connection to a Postgres database.
2014-11-01 23:21:47 +00:00
pub struct Connection {
2015-11-16 03:51:04 +00:00
conn: RefCell<InnerConnection>,
}
2015-01-23 18:44:15 +00:00
impl fmt::Debug for Connection {
2015-01-10 04:48:47 +00:00
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let conn = self.conn.borrow();
2015-09-19 05:55:32 +00:00
fmt.debug_struct("Connection")
2016-09-13 04:48:49 +00:00
.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()
2015-01-10 04:48:47 +00:00
}
}
2014-11-01 23:21:47 +00:00
impl Connection {
/// Creates a new connection to a Postgres database.
2013-09-30 02:12:20 +00:00
///
/// Most applications can use a URL string in the normal format:
2013-09-30 02:12:20 +00:00
///
2014-03-09 06:01:24 +00:00
/// ```notrust
/// postgresql://user[:password]@host[:port][/database][?param1=val1[[&param2=val2]...]]
2013-09-30 02:12:20 +00:00
/// ```
///
/// 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.
2014-03-09 22:22:20 +00:00
///
2016-07-08 05:54:22 +00:00
/// 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 TLS
/// over Unix sockets.
///
2015-11-29 05:05:13 +00:00
/// # Examples
2014-03-09 22:22:20 +00:00
///
2014-03-10 17:06:40 +00:00
/// ```rust,no_run
/// use postgres::{Connection, TlsMode};
2015-11-30 04:00:25 +00:00
///
/// let url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let conn = Connection::connect(url, TlsMode::None).unwrap();
2014-03-09 22:22:20 +00:00
/// ```
///
2014-04-19 18:10:27 +00:00
/// ```rust,no_run
/// use postgres::{Connection, TlsMode};
2015-11-30 04:00:25 +00:00
///
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let conn = Connection::connect(url, TlsMode::None).unwrap();
/// ```
///
/// ```rust,no_run
/// use postgres::{Connection, TlsMode};
/// use postgres::params::{UserInfo, ConnectParams, ConnectTarget};
/// # use std::path::PathBuf;
2015-11-30 04:00:25 +00:00
///
2016-07-08 05:54:22 +00:00
/// # #[cfg(unix)]
2015-11-30 04:00:25 +00:00
/// # fn f() {
/// # let some_crazy_path = PathBuf::new();
2014-11-01 23:15:30 +00:00
/// let params = ConnectParams {
/// target: ConnectTarget::Unix(some_crazy_path),
/// port: None,
2014-11-01 23:14:08 +00:00
/// user: Some(UserInfo {
/// user: "postgres".to_owned(),
/// password: None
/// }),
/// database: None,
2014-05-26 18:41:18 +00:00
/// options: vec![],
/// };
/// let conn = Connection::connect(params, TlsMode::None).unwrap();
2015-11-30 04:00:25 +00:00
/// # }
/// ```
2016-07-01 19:26:13 +00:00
pub fn connect<T>(params: T, tls: TlsMode) -> result::Result<Connection, ConnectError>
2015-11-16 03:51:04 +00:00
where T: IntoConnectParams
{
2016-07-01 19:26:13 +00:00
InnerConnection::connect(params, tls).map(|conn| Connection { conn: RefCell::new(conn) })
}
/// Executes a statement, returning the number of rows modified.
///
/// A statement may contain parameters, specified by `$n` where `n` is the
/// index of the parameter in the list provided, 1-indexed.
///
/// If the statement does not modify any rows (e.g. SELECT), 0 is returned.
///
/// If the same statement will be repeatedly executed (perhaps with
/// different query parameters), consider using the `prepare` and
/// `prepare_cached` methods.
///
/// # Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// # Example
///
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
/// # let bar = 1i32;
/// # let baz = true;
/// let rows_updated = conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2", &[&bar, &baz])
/// .unwrap();
/// println!("{} rows updated", rows_updated);
/// ```
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
2016-01-03 05:02:54 +00:00
let info = Arc::new(StatementInfo {
name: String::new(),
param_types: param_types,
columns: columns,
});
let stmt = Statement::new(self, info, Cell::new(0), true);
stmt.execute(params)
}
/// Executes a statement, returning the resulting rows.
///
/// A statement may contain parameters, specified by `$n` where `n` is the
/// index of the parameter in the list provided, 1-indexed.
///
/// If the same statement will be repeatedly executed (perhaps with
/// different query parameters), consider using the `prepare` and
/// `prepare_cached` methods.
///
/// # Panics
///
/// Panics if the number of parameters provided does not match the number
/// expected.
///
/// # Example
///
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
/// # let baz = true;
/// for row in &conn.query("SELECT foo FROM bar WHERE baz = $1", &[&baz]).unwrap() {
/// let foo: i32 = row.get("foo");
/// println!("foo: {}", foo);
/// }
/// ```
pub fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>> {
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
2016-01-03 05:02:54 +00:00
let info = Arc::new(StatementInfo {
name: String::new(),
param_types: param_types,
columns: columns,
});
let stmt = Statement::new(self, info, Cell::new(0), true);
stmt.into_query(params)
}
/// 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.
///
/// # Panics
///
/// Panics if a transaction is already active.
///
/// # Example
///
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
/// let trans = conn.transaction().unwrap();
/// trans.execute("UPDATE foo SET bar = 10", &[]).unwrap();
/// // ...
///
/// trans.commit().unwrap();
/// ```
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
2016-02-25 06:29:09 +00:00
self.transaction_with(&transaction::Config::new())
}
/// Begins a new transaction with the specified configuration.
pub fn transaction_with<'a>(&'a self, config: &transaction::Config) -> Result<Transaction<'a>> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
assert!(conn.trans_depth == 0,
"`transaction` must be called on the active transaction");
2016-02-25 06:29:09 +00:00
let mut query = "BEGIN".to_owned();
config.build_command(&mut query);
try!(conn.quick_query(&query));
conn.trans_depth += 1;
2016-02-24 07:43:28 +00:00
Ok(Transaction::new(self, 1))
}
/// Creates a new prepared statement.
2013-09-30 02:12:20 +00:00
///
/// If the same statement will be executed repeatedly, explicitly preparing
/// it can improve performance.
2013-09-30 02:12:20 +00:00
///
/// The statement is associated with the connection that created it and may
/// not outlive that connection.
2014-03-09 22:22:20 +00:00
///
2015-11-29 05:05:13 +00:00
/// # Example
2014-03-09 22:22:20 +00:00
///
2014-03-10 17:06:40 +00:00
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
2015-11-30 04:00:25 +00:00
/// # let x = 10i32;
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
2015-12-13 04:21:44 +00:00
/// # let (a, b) = (0i32, 1i32);
/// # let updates = vec![(&a, &b)];
/// let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();
/// for (bar, baz) in updates {
/// stmt.execute(&[bar, baz]).unwrap();
2015-11-30 04:00:25 +00:00
/// }
/// ```
2014-11-01 23:24:24 +00:00
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare(query, self)
}
2015-11-01 20:06:38 +00:00
/// Creates a cached prepared statement.
///
2015-01-23 06:55:18 +00:00
/// Like `prepare`, except that the statement is only prepared once over
/// the lifetime of the connection and then cached. If the same statement
/// is going to be prepared frequently, caching it can improve performance
/// by reducing the number of round trips to the Postgres backend.
///
2015-11-29 05:05:13 +00:00
/// # Example
///
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode};
/// # let x = 10i32;
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
2015-12-13 04:21:44 +00:00
/// # let (a, b) = (0i32, 1i32);
/// # let updates = vec![(&a, &b)];
/// let stmt = conn.prepare_cached("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();
/// for (bar, baz) in updates {
/// stmt.execute(&[bar, baz]).unwrap();
/// }
/// ```
pub fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.conn.borrow_mut().prepare_cached(query, self)
}
2016-01-03 05:51:02 +00:00
/// Returns the isolation level which will be used for future transactions.
///
/// This is a simple wrapper around `SHOW TRANSACTION ISOLATION LEVEL`.
pub fn transaction_isolation(&self) -> Result<IsolationLevel> {
let mut conn = self.conn.borrow_mut();
check_desync!(conn);
let result = try!(conn.quick_query("SHOW TRANSACTION ISOLATION LEVEL"));
IsolationLevel::new(result[0][0].as_ref().unwrap())
2016-01-03 05:51:02 +00:00
}
2016-02-25 06:29:09 +00:00
/// Sets the configuration that will be used for future transactions.
2016-02-24 08:01:22 +00:00
pub fn set_transaction_config(&self, config: &transaction::Config) -> Result<()> {
let mut command = "SET SESSION CHARACTERISTICS AS TRANSACTION".to_owned();
config.build_command(&mut command);
self.batch_execute(&command)
}
2014-06-08 23:07:15 +00:00
/// 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.
///
2015-11-29 05:05:13 +00:00
/// # Warning
2014-06-08 23:07:15 +00:00
///
/// Prepared statements should be used for any SQL statement which contains
/// user-specified data, as it provides functionality to safely embed that
2015-01-24 18:46:01 +00:00
/// data in the statement. Do not form statements via string concatenation
2014-06-08 23:07:15 +00:00
/// and feed them into this method.
///
2015-11-29 05:05:13 +00:00
/// # Example
2014-06-08 23:07:15 +00:00
///
2014-06-08 23:12:27 +00:00
/// ```rust,no_run
/// # use postgres::{Connection, TlsMode, Result};
/// # let conn = Connection::connect("", TlsMode::None).unwrap();
2015-11-30 04:00:25 +00:00
/// conn.batch_execute("
/// CREATE TABLE person (
/// id SERIAL PRIMARY KEY,
/// name NOT NULL
/// );
2014-06-08 23:07:15 +00:00
///
2015-11-30 04:00:25 +00:00
/// CREATE TABLE purchase (
/// id SERIAL PRIMARY KEY,
/// person INT NOT NULL REFERENCES person (id),
/// time TIMESTAMPTZ NOT NULL,
/// );
2014-06-08 23:07:15 +00:00
///
2015-11-30 04:00:25 +00:00
/// CREATE INDEX ON purchase (time);
/// ").unwrap();
2014-06-08 23:07:15 +00:00
/// ```
2014-11-01 23:12:05 +00:00
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.borrow_mut().quick_query(query).map(|_| ())
2014-06-08 23:07:15 +00:00
}
/// Returns a structure providing access to asynchronous notifications.
///
/// Use the `LISTEN` command to register this connection for notifications.
pub fn notifications<'a>(&'a self) -> Notifications<'a> {
Notifications::new(self)
}
2013-10-21 00:32:14 +00:00
/// 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.
2014-11-01 23:19:02 +00:00
pub fn cancel_data(&self) -> CancelData {
2014-03-19 04:00:06 +00:00
self.conn.borrow().cancel_data
2013-10-21 00:32:14 +00:00
}
/// Returns the value of the specified Postgres backend parameter, such as
/// `timezone` or `server_version`.
2015-02-16 04:22:56 +00:00
pub fn parameter(&self, param: &str) -> Option<String> {
self.conn.borrow().parameters.get(param).cloned()
}
/// Sets the notice handler for the connection, returning the old handler.
pub fn set_notice_handler(&self, handler: Box<HandleNotice>) -> Box<HandleNotice> {
self.conn.borrow_mut().set_notice_handler(handler)
}
/// 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 {
2014-03-19 04:00:06 +00:00
self.conn.borrow().is_desynchronized()
}
/// Determines if the `Connection` is currently "active", that is, if there
/// are no active transactions.
///
/// The `transaction` method can only be called on the active `Connection`
/// or `Transaction`.
pub fn is_active(&self) -> bool {
self.conn.borrow().trans_depth == 0
}
/// Consumes the connection, closing it.
///
2014-11-03 00:48:38 +00:00
/// Functionally equivalent to the `Drop` implementation for `Connection`
/// except that it returns any error encountered to the caller.
2014-11-01 23:12:05 +00:00
pub fn finish(self) -> Result<()> {
2014-03-19 04:00:06 +00:00
let mut conn = self.conn.borrow_mut();
conn.finished = true;
conn.finish_inner()
}
2013-08-17 22:09:26 +00:00
}
/// A trait allowing abstraction over connections and transactions
pub trait GenericConnection {
2014-11-01 23:21:47 +00:00
/// Like `Connection::execute`.
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64>;
/// Like `Connection::query`.
fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>>;
2016-01-03 05:51:02 +00:00
/// Like `Connection::prepare`.
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
/// Like `Connection::prepare_cached`.
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>>;
2014-11-01 23:21:47 +00:00
/// Like `Connection::transaction`.
2014-11-01 23:25:11 +00:00
fn transaction<'a>(&'a self) -> Result<Transaction<'a>>;
2014-11-01 23:21:47 +00:00
/// Like `Connection::batch_execute`.
2014-11-01 23:12:05 +00:00
fn batch_execute(&self, query: &str) -> Result<()>;
/// Like `Connection::is_active`.
fn is_active(&self) -> bool;
}
2014-11-01 23:21:47 +00:00
impl GenericConnection for Connection {
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>> {
self.query(query, params)
}
2016-01-03 05:51:02 +00:00
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare(query)
}
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
self.prepare_cached(query)
}
2014-11-01 23:25:11 +00:00
fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
self.transaction()
}
2014-11-01 23:12:05 +00:00
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
2014-11-01 23:25:11 +00:00
impl<'a> GenericConnection for Transaction<'a> {
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.execute(query, params)
}
fn query<'b>(&'b self, query: &str, params: &[&ToSql]) -> Result<Rows<'b>> {
self.query(query, params)
}
2016-01-03 05:51:02 +00:00
fn prepare<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare(query)
}
fn prepare_cached<'b>(&'b self, query: &str) -> Result<Statement<'b>> {
self.prepare_cached(query)
}
fn transaction<'b>(&'b self) -> Result<Transaction<'b>> {
self.transaction()
}
2014-11-01 23:12:05 +00:00
fn batch_execute(&self, query: &str) -> Result<()> {
self.batch_execute(query)
}
fn is_active(&self) -> bool {
self.is_active()
}
}
trait OtherNew {
fn new(name: String, oid: Oid, kind: Kind, schema: String) -> Other;
}
trait DbErrorNew {
fn new_raw(fields: Vec<(u8, String)>) -> result::Result<DbError, ()>;
fn new_connect<T>(fields: Vec<(u8, String)>) -> result::Result<T, ConnectError>;
fn new<T>(fields: Vec<(u8, String)>) -> Result<T>;
}
2015-05-27 04:47:42 +00:00
2015-05-30 05:54:10 +00:00
trait RowsNew<'a> {
fn new(stmt: &'a Statement<'a>, data: Vec<Vec<Option<Vec<u8>>>>) -> Rows<'a>;
fn new_owned(stmt: Statement<'a>, data: Vec<Vec<Option<Vec<u8>>>>) -> Rows<'a>;
2015-05-30 05:54:10 +00:00
}
trait LazyRowsNew<'trans, 'stmt> {
fn new(stmt: &'stmt Statement<'stmt>,
data: VecDeque<Vec<Option<Vec<u8>>>>,
name: String,
row_limit: i32,
more_rows: bool,
finished: bool,
2015-11-16 03:51:04 +00:00
trans: &'trans Transaction<'trans>)
-> LazyRows<'trans, 'stmt>;
2015-05-30 05:54:10 +00:00
}
2015-06-02 05:39:04 +00:00
trait SessionInfoNew<'a> {
2016-09-20 03:46:25 +00:00
fn new(params: &'a HashMap<String, String>) -> SessionInfo<'a>;
2015-06-02 05:39:04 +00:00
}
2015-08-16 04:39:46 +00:00
trait StatementInternals<'conn> {
fn new(conn: &'conn Connection,
2016-01-03 05:02:54 +00:00
info: Arc<StatementInfo>,
2015-08-16 04:39:46 +00:00
next_portal_id: Cell<u32>,
2015-11-16 03:51:04 +00:00
finished: bool)
-> Statement<'conn>;
2015-08-16 04:39:46 +00:00
fn conn(&self) -> &'conn Connection;
fn into_query(self, params: &[&ToSql]) -> Result<Rows<'conn>>;
2015-08-16 04:39:46 +00:00
}
trait ColumnNew {
fn new(name: String, type_: Type) -> Column;
}
trait NotificationsNew<'conn> {
fn new(conn: &'conn Connection) -> Notifications<'conn>;
}
trait WrongTypeNew {
fn new(ty: Type) -> WrongType;
}
2016-02-16 07:11:01 +00:00
trait FieldNew {
fn new(name: String, type_: Type) -> Field;
}
2016-02-24 07:43:28 +00:00
trait TransactionInternals<'conn> {
fn new(conn: &'conn Connection, depth: u32) -> Transaction<'conn>;
fn conn(&self) -> &'conn Connection;
fn depth(&self) -> u32;
}
2016-02-24 08:01:22 +00:00
trait ConfigInternals {
fn build_command(&self, s: &mut String);
}
trait IsolationLevelNew {
fn new(level: &str) -> Result<IsolationLevel>;
}