Revert "Strip prefixes from types"

This reverts commit ccdb02f661.

I'm not sure this is the right way to go just yet
This commit is contained in:
Steven Fackler 2014-08-18 22:02:16 -07:00
parent ccdb02f661
commit 30a3210be0
8 changed files with 284 additions and 270 deletions

View File

@ -14,12 +14,12 @@ path = "tests/test.rs"
[dependencies.openssl]
git = "https://github.com/sfackler/rust-openssl"
rev = "182ec4a6e77a53381e8b5e161f5d9c8fb3d965ff"
rev = "39343df472b4b0c99055d371f42beceeef527bd6"
[dependencies.phf]
git = "https://github.com/sfackler/rust-phf"
rev = "9fd8d24f59b1af976526fc43baf6635a3714c71e"
rev = "b2220d9a428049fb9c52b51c16d8f6b15cd02487"
[dependencies.phf_mac]
git = "https://github.com/sfackler/rust-phf"
rev = "9fd8d24f59b1af976526fc43baf6635a3714c71e"
rev = "b2220d9a428049fb9c52b51c16d8f6b15cd02487"

View File

@ -15,7 +15,7 @@ extern crate time;
use time::Timespec;
use postgres::NoSsl;
use postgres::{PostgresConnection, NoSsl};
use postgres::types::ToSql;
struct Person {
@ -26,7 +26,7 @@ struct Person {
}
fn main() {
let conn = postgres::Connection::connect("postgres://postgres@localhost",
let conn = PostgresConnection::connect("postgres://postgres@localhost",
&NoSsl).unwrap();
conn.execute("CREATE TABLE person (

View File

@ -4,7 +4,7 @@ use std::io::net::tcp::TcpStream;
use std::io::net::unix::UnixStream;
use std::io::{Stream, IoResult};
use {ConnectParams,
use {PostgresConnectParams,
SslMode,
NoSsl,
PreferSsl,
@ -81,7 +81,8 @@ impl Writer for InternalStream {
}
}
fn open_socket(params: &ConnectParams) -> Result<InternalStream, PostgresConnectError> {
fn open_socket(params: &PostgresConnectParams)
-> Result<InternalStream, PostgresConnectError> {
let port = params.port.unwrap_or(DEFAULT_PORT);
let socket = match params.target {
TargetTcp(ref host) =>
@ -95,7 +96,7 @@ fn open_socket(params: &ConnectParams) -> Result<InternalStream, PostgresConnect
socket.map_err(|e| SocketError(e))
}
pub fn initialize_stream(params: &ConnectParams, ssl: &SslMode)
pub fn initialize_stream(params: &PostgresConnectParams, ssl: &SslMode)
-> Result<MaybeSslStream<InternalStream>, PostgresConnectError> {
let mut socket = try!(open_socket(params));

View File

@ -8,7 +8,7 @@
//!
//! use time::Timespec;
//!
//! use postgres::NoSsl;
//! use postgres::{PostgresConnection, NoSsl};
//!
//! struct Person {
//! id: i32,
@ -18,7 +18,7 @@
//! }
//!
//! fn main() {
//! let conn = postgres::Connection::connect("postgresql://postgres@localhost",
//! let conn = PostgresConnection::connect("postgresql://postgres@localhost",
//! &NoSsl).unwrap();
//!
//! conn.execute("CREATE TABLE person (
@ -66,18 +66,17 @@ extern crate url;
extern crate log;
use collections::{Deque, RingBuf};
use url::Url;
use url::{UserInfo, Url};
use openssl::crypto::hash::{MD5, Hasher};
use openssl::ssl::SslContext;
use serialize::hex::ToHex;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::from_str::FromStr;
use std::io::{BufferedStream, IoResult};
use std::io::net::ip::Port;
use std::mem;
use std::result;
use std::fmt;
use error::{InvalidUrl,
MissingPassword,
@ -149,11 +148,11 @@ pub mod types;
static CANARY: u32 = 0xdeadbeef;
/// A typedef of the result returned by many methods.
pub type Result<T> = result::Result<T, PostgresError>;
pub type PostgresResult<T> = Result<T, PostgresError>;
/// Specifies the target server to connect to.
#[deriving(Clone)]
pub enum ConnectTarget {
pub enum PostgresConnectTarget {
/// Connect via TCP to the specified host.
TargetTcp(String),
/// Connect via a Unix domain socket in the specified directory.
@ -162,7 +161,7 @@ pub enum ConnectTarget {
/// Authentication information
#[deriving(Clone)]
pub struct UserInfo {
pub struct PostgresUserInfo {
/// The username
pub user: String,
/// An optional password
@ -171,37 +170,39 @@ pub struct UserInfo {
/// Information necessary to open a new connection to a Postgres server.
#[deriving(Clone)]
pub struct ConnectParams {
pub struct PostgresConnectParams {
/// The target server
pub target: ConnectTarget,
pub target: PostgresConnectTarget,
/// 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>,
/// `PostgresConnection::connect` requires a user but `cancel_query` does
/// not.
pub user: Option<PostgresUserInfo>,
/// 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`.
/// A trait implemented by types that can be converted into a
/// `PostgresConnectParams`.
pub trait IntoConnectParams {
/// Converts the value of `self` into a `ConnectParams`.
fn into_connect_params(self) -> result::Result<ConnectParams, PostgresConnectError>;
/// Converts the value of `self` into a `PostgresConnectParams`.
fn into_connect_params(self) -> Result<PostgresConnectParams, PostgresConnectError>;
}
impl IntoConnectParams for ConnectParams {
fn into_connect_params(self) -> result::Result<ConnectParams, PostgresConnectError> {
impl IntoConnectParams for PostgresConnectParams {
fn into_connect_params(self) -> Result<PostgresConnectParams, PostgresConnectError> {
Ok(self)
}
}
impl<'a> IntoConnectParams for &'a str {
fn into_connect_params(self) -> result::Result<ConnectParams, PostgresConnectError> {
fn into_connect_params(self) -> Result<PostgresConnectParams, PostgresConnectError> {
match Url::parse(self) {
Ok(url) => url.into_connect_params(),
Err(err) => return Err(InvalidUrl(err)),
@ -210,7 +211,7 @@ impl<'a> IntoConnectParams for &'a str {
}
impl IntoConnectParams for Url {
fn into_connect_params(self) -> result::Result<ConnectParams, PostgresConnectError> {
fn into_connect_params(self) -> Result<PostgresConnectParams, PostgresConnectError> {
let Url {
host,
port,
@ -230,7 +231,8 @@ impl IntoConnectParams for Url {
};
let user = match user {
Some(url::UserInfo { user, pass }) => Some(UserInfo { user: user, password: pass }),
Some(UserInfo { user, pass }) =>
Some(PostgresUserInfo { user: user, password: pass }),
None => None,
};
@ -242,7 +244,7 @@ impl IntoConnectParams for Url {
None
};
Ok(ConnectParams {
Ok(PostgresConnectParams {
target: target,
port: port,
user: user,
@ -253,24 +255,24 @@ impl IntoConnectParams for Url {
}
/// Trait for types that can handle Postgres notice messages
pub trait NoticeHandler {
pub trait PostgresNoticeHandler {
/// Handle a Postgres notice message
fn handle(&mut self, notice: PostgresDbError);
}
/// A notice handler which logs at the `info` level.
///
/// This is the default handler used by a `Connection`.
/// This is the default handler used by a `PostgresConnection`.
pub struct DefaultNoticeHandler;
impl NoticeHandler for DefaultNoticeHandler {
impl PostgresNoticeHandler for DefaultNoticeHandler {
fn handle(&mut self, notice: PostgresDbError) {
info!("{}: {}", notice.severity, notice.message);
}
}
/// An asynchronous notification
pub struct Notification {
pub struct PostgresNotification {
/// The process ID of the notifying backend process
pub pid: u32,
/// The name of the channel that the notify has been raised on
@ -280,24 +282,24 @@ pub struct Notification {
}
/// An iterator over asynchronous notifications
pub struct Notifications<'conn> {
conn: &'conn Connection
pub struct PostgresNotifications<'conn> {
conn: &'conn PostgresConnection
}
impl<'conn> Iterator<Notification> for Notifications<'conn> {
impl<'conn> Iterator<PostgresNotification> for PostgresNotifications<'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> {
fn next(&mut self) -> Option<PostgresNotification> {
self.conn.conn.borrow_mut().notifications.pop_front()
}
}
/// Contains information necessary to cancel queries for a session
pub struct CancelData {
pub struct PostgresCancelData {
/// The process ID of the session
pub process_id: u32,
/// The secret key for the session
@ -310,18 +312,19 @@ pub struct CancelData {
/// 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.
/// A `PostgresCancelData` object can be created via
/// `PostgresConnection::cancel_data`. The object can cancel any query made on
/// that connection.
///
/// Only the host and port of the connetion info are used. See
/// `Connection::connect` for details of the `params` argument.
/// `PostgresConnection::connect` for details of the `params` argument.
///
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # use postgres::{PostgresConnection, NoSsl};
/// # let url = "";
/// let conn = postgres::Connection::connect(url, &NoSsl).unwrap();
/// let conn = PostgresConnection::connect(url, &NoSsl).unwrap();
/// let cancel_data = conn.cancel_data();
/// spawn(proc() {
/// conn.execute("SOME EXPENSIVE QUERY", []).unwrap();
@ -329,8 +332,8 @@ pub struct CancelData {
/// # let _ =
/// postgres::cancel_query(url, &NoSsl, cancel_data);
/// ```
pub fn cancel_query<T>(params: T, ssl: &SslMode, data: CancelData)
-> result::Result<(), PostgresConnectError> where T: IntoConnectParams {
pub fn cancel_query<T>(params: T, ssl: &SslMode, data: PostgresCancelData)
-> Result<(), PostgresConnectError> where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let mut socket = match io::initialize_stream(&params, ssl) {
@ -348,12 +351,12 @@ pub fn cancel_query<T>(params: T, ssl: &SslMode, data: CancelData)
Ok(())
}
struct InnerConnection {
struct InnerPostgresConnection {
stream: BufferedStream<MaybeSslStream<InternalStream>>,
next_stmt_id: uint,
notice_handler: Box<NoticeHandler+Send>,
notifications: RingBuf<Notification>,
cancel_data: CancelData,
notice_handler: Box<PostgresNoticeHandler+Send>,
notifications: RingBuf<PostgresNotification>,
cancel_data: PostgresCancelData,
unknown_types: HashMap<Oid, String>,
desynchronized: bool,
finished: bool,
@ -361,7 +364,7 @@ struct InnerConnection {
canary: u32,
}
impl Drop for InnerConnection {
impl Drop for InnerPostgresConnection {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
@ -369,14 +372,14 @@ impl Drop for InnerConnection {
}
}
impl InnerConnection {
impl InnerPostgresConnection {
fn connect<T>(params: T, ssl: &SslMode)
-> result::Result<InnerConnection, PostgresConnectError>
-> Result<InnerPostgresConnection, PostgresConnectError>
where T: IntoConnectParams {
let params = try!(params.into_connect_params());
let stream = try!(io::initialize_stream(&params, ssl));
let ConnectParams {
let PostgresConnectParams {
user,
database,
mut options,
@ -388,12 +391,12 @@ impl InnerConnection {
None => return Err(MissingUser),
};
let mut conn = InnerConnection {
let mut conn = InnerPostgresConnection {
stream: BufferedStream::new(stream),
next_stmt_id: 0,
notice_handler: box DefaultNoticeHandler,
notifications: RingBuf::new(),
cancel_data: CancelData { process_id: 0, secret_key: 0 },
cancel_data: PostgresCancelData { process_id: 0, secret_key: 0 },
unknown_types: HashMap::new(),
desynchronized: false,
finished: false,
@ -452,7 +455,7 @@ impl InnerConnection {
self.notice_handler.handle(PostgresDbError::new(fields))
}
NotificationResponse { pid, channel, payload } => {
self.notifications.push(Notification {
self.notifications.push(PostgresNotification {
pid: pid,
channel: channel,
payload: payload
@ -466,7 +469,7 @@ impl InnerConnection {
}
}
fn handle_auth(&mut self, user: UserInfo) -> result::Result<(), PostgresConnectError> {
fn handle_auth(&mut self, user: PostgresUserInfo) -> Result<(), PostgresConnectError> {
match try_pg_conn!(self.read_message()) {
AuthenticationOk => return Ok(()),
AuthenticationCleartextPassword => {
@ -517,13 +520,13 @@ impl InnerConnection {
}
}
fn set_notice_handler(&mut self, handler: Box<NoticeHandler+Send>)
-> Box<NoticeHandler+Send> {
fn set_notice_handler(&mut self, handler: Box<PostgresNoticeHandler+Send>)
-> Box<PostgresNoticeHandler+Send> {
mem::replace(&mut self.notice_handler, handler)
}
fn prepare<'a>(&mut self, query: &str, conn: &'a Connection)
-> Result<Statement<'a>> {
fn prepare<'a>(&mut self, query: &str, conn: &'a PostgresConnection)
-> PostgresResult<PostgresStatement<'a>> {
let stmt_name = format!("s{}", self.next_stmt_id);
self.next_stmt_id += 1;
@ -575,7 +578,7 @@ impl InnerConnection {
try!(self.set_type_names(param_types.mut_iter()));
try!(self.set_type_names(result_desc.mut_iter().map(|d| &mut d.ty)));
Ok(Statement {
Ok(PostgresStatement {
conn: conn,
name: stmt_name,
param_types: param_types,
@ -586,7 +589,7 @@ impl InnerConnection {
}
fn set_type_names<'a, I: Iterator<&'a mut PostgresType>>(&mut self, mut it: I)
-> Result<()> {
-> PostgresResult<()> {
for ty in it {
match *ty {
PgUnknownType { oid, ref mut name } => *name = try!(self.get_type_name(oid)),
@ -597,7 +600,7 @@ impl InnerConnection {
Ok(())
}
fn get_type_name(&mut self, oid: Oid) -> Result<String> {
fn get_type_name(&mut self, oid: Oid) -> PostgresResult<String> {
match self.unknown_types.find(&oid) {
Some(name) => return Ok(name.clone()),
None => {}
@ -617,7 +620,7 @@ impl InnerConnection {
self.canary
}
fn wait_for_ready(&mut self) -> Result<()> {
fn wait_for_ready(&mut self) -> PostgresResult<()> {
match try_pg!(self.read_message()) {
ReadyForQuery { .. } => Ok(()),
_ => bad_response!(self)
@ -625,7 +628,7 @@ impl InnerConnection {
}
fn quick_query(&mut self, query: &str)
-> Result<Vec<Vec<Option<String>>>> {
-> PostgresResult<Vec<Vec<Option<String>>>> {
check_desync!(self);
try_pg!(self.write_messages([Query { query: query }]));
@ -648,7 +651,7 @@ impl InnerConnection {
Ok(result)
}
fn finish_inner(&mut self) -> Result<()> {
fn finish_inner(&mut self) -> PostgresResult<()> {
check_desync!(self);
self.canary = 0;
try_pg!(self.write_messages([Terminate]));
@ -657,11 +660,11 @@ impl InnerConnection {
}
/// A connection to a Postgres database.
pub struct Connection {
conn: RefCell<InnerConnection>
pub struct PostgresConnection {
conn: RefCell<InnerPostgresConnection>
}
impl Connection {
impl PostgresConnection {
/// Creates a new connection to a Postgres database.
///
/// Most applications can use a URL string in the normal format:
@ -677,16 +680,16 @@ impl Connection {
/// 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.
/// path contains non-UTF 8 characters, a `PostgresConnectParams` struct
/// should be created manually and passed in. Note that Postgres does not
/// support SSL over Unix sockets.
///
/// ## Examples
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # use postgres::{PostgresConnection, NoSsl};
/// let url = "postgresql://postgres:hunter2@localhost:2994/foodb";
/// let maybe_conn = postgres::Connection::connect(url, &NoSsl);
/// let maybe_conn = PostgresConnection::connect(url, &NoSsl);
/// let conn = match maybe_conn {
/// Ok(conn) => conn,
/// Err(err) => fail!("Error connecting: {}", err)
@ -694,42 +697,46 @@ impl Connection {
/// ```
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # use postgres::{PostgresConnection, NoSsl};
/// let url = "postgresql://postgres@%2Frun%2Fpostgres";
/// let maybe_conn = postgres::Connection::connect(url, &NoSsl);
/// let maybe_conn = PostgresConnection::connect(url, &NoSsl);
/// ```
///
/// ```rust,no_run
/// # use postgres::{NoSsl, TargetUnix};
/// # use postgres::{PostgresConnection, PostgresUserInfo, PostgresConnectParams, NoSsl, TargetUnix};
/// # let some_crazy_path = Path::new("");
/// let params = postgres::ConnectParams {
/// let params = PostgresConnectParams {
/// target: TargetUnix(some_crazy_path),
/// port: None,
/// user: Some(postgres::UserInfo {
/// user: Some(PostgresUserInfo {
/// user: "postgres".to_string(),
/// password: None
/// }),
/// database: None,
/// options: vec![],
/// };
/// let maybe_conn = postgres::Connection::connect(params, &NoSsl);
/// let maybe_conn = PostgresConnection::connect(params, &NoSsl);
/// ```
pub fn connect<T>(params: T, ssl: &SslMode) -> result::Result<Connection, PostgresConnectError>
pub fn connect<T>(params: T, ssl: &SslMode) -> Result<PostgresConnection, PostgresConnectError>
where T: IntoConnectParams {
InnerConnection::connect(params, ssl).map(|conn| Connection { conn: RefCell::new(conn) })
InnerPostgresConnection::connect(params, ssl).map(|conn| {
PostgresConnection { 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> {
pub fn set_notice_handler(&self, handler: Box<PostgresNoticeHandler+Send>)
-> Box<PostgresNoticeHandler+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 }
pub fn notifications<'a>(&'a self) -> PostgresNotifications<'a> {
PostgresNotifications {
conn: self
}
}
/// Creates a new prepared statement.
@ -744,14 +751,14 @@ impl Connection {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # let conn = postgres::Connection::connect("", &NoSsl).unwrap();
/// # use postgres::{PostgresConnection, NoSsl};
/// # let conn = PostgresConnection::connect("", &NoSsl).unwrap();
/// let maybe_stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1");
/// let stmt = match maybe_stmt {
/// Ok(stmt) => stmt,
/// Err(err) => fail!("Error preparing statement: {}", err)
/// };
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
pub fn prepare<'a>(&'a self, query: &str) -> PostgresResult<PostgresStatement<'a>> {
let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 {
return Err(PgWrongTransaction);
@ -772,9 +779,9 @@ impl Connection {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # use postgres::{PostgresConnection, NoSsl};
/// # fn foo() -> Result<(), postgres::error::PostgresError> {
/// # let conn = postgres::Connection::connect("", &NoSsl).unwrap();
/// # let conn = PostgresConnection::connect("", &NoSsl).unwrap();
/// let trans = try!(conn.transaction());
/// try!(trans.execute("UPDATE foo SET bar = 10", []));
/// // ...
@ -784,7 +791,7 @@ impl Connection {
/// # Ok(())
/// # }
/// ```
pub fn transaction<'a>(&'a self) -> Result<PostgresTransaction<'a>> {
pub fn transaction<'a>(&'a self) -> PostgresResult<PostgresTransaction<'a>> {
check_desync!(self);
if self.conn.borrow().trans_depth != 0 {
return Err(PgWrongTransaction);
@ -805,7 +812,7 @@ impl Connection {
/// 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> {
pub fn execute(&self, query: &str, params: &[&ToSql]) -> PostgresResult<uint> {
self.prepare(query).and_then(|stmt| stmt.execute(params))
}
@ -826,8 +833,8 @@ impl Connection {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::Result;
/// fn init_db(conn: &postgres::Connection) -> Result<()> {
/// # use postgres::{PostgresConnection, PostgresResult};
/// fn init_db(conn: &PostgresConnection) -> PostgresResult<()> {
/// conn.batch_execute("
/// CREATE TABLE person (
/// id SERIAL PRIMARY KEY,
@ -844,7 +851,7 @@ impl Connection {
/// ")
/// }
/// ```
pub fn batch_execute(&self, query: &str) -> Result<()> {
pub fn batch_execute(&self, query: &str) -> PostgresResult<()> {
let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 {
return Err(PgWrongTransaction);
@ -856,7 +863,7 @@ impl Connection {
///
/// 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 {
pub fn cancel_data(&self) -> PostgresCancelData {
self.conn.borrow().cancel_data
}
@ -871,9 +878,10 @@ impl Connection {
/// 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<()> {
/// Functionally equivalent to the `Drop` implementation for
/// `PostgresConnection` except that it returns any error encountered to
/// the caller.
pub fn finish(self) -> PostgresResult<()> {
let mut conn = self.conn.borrow_mut();
conn.finished = true;
conn.finish_inner()
@ -883,11 +891,11 @@ impl Connection {
self.conn.borrow().canary()
}
fn quick_query(&self, query: &str) -> Result<Vec<Vec<Option<String>>>> {
fn quick_query(&self, query: &str) -> PostgresResult<Vec<Vec<Option<String>>>> {
self.conn.borrow_mut().quick_query(query)
}
fn wait_for_ready(&self) -> Result<()> {
fn wait_for_ready(&self) -> PostgresResult<()> {
self.conn.borrow_mut().wait_for_ready()
}
@ -914,7 +922,7 @@ pub enum SslMode {
///
/// The transaction will roll back by default.
pub struct PostgresTransaction<'conn> {
conn: &'conn Connection,
conn: &'conn PostgresConnection,
commit: Cell<bool>,
depth: u32,
finished: bool,
@ -930,7 +938,7 @@ impl<'conn> Drop for PostgresTransaction<'conn> {
}
impl<'conn> PostgresTransaction<'conn> {
fn finish_inner(&mut self) -> Result<()> {
fn finish_inner(&mut self) -> PostgresResult<()> {
debug_assert!(self.depth == self.conn.conn.borrow().trans_depth);
let query = match (self.commit.get(), self.depth != 1) {
(false, true) => "ROLLBACK TO sp",
@ -942,21 +950,21 @@ impl<'conn> PostgresTransaction<'conn> {
self.conn.quick_query(query).map(|_| ())
}
/// Like `Connection::prepare`.
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
/// Like `PostgresConnection::prepare`.
pub fn prepare<'a>(&'a self, query: &str) -> PostgresResult<PostgresStatement<'a>> {
if self.conn.conn.borrow().trans_depth != self.depth {
return Err(PgWrongTransaction);
}
self.conn.conn.borrow_mut().prepare(query, self.conn)
}
/// Like `Connection::execute`.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<uint> {
/// Like `PostgresConnection::execute`.
pub fn execute(&self, query: &str, params: &[&ToSql]) -> PostgresResult<uint> {
self.prepare(query).and_then(|s| s.execute(params))
}
/// Like `Connection::batch_execute`.
pub fn batch_execute(&self, query: &str) -> Result<()> {
/// Like `PostgresConnection::batch_execute`.
pub fn batch_execute(&self, query: &str) -> PostgresResult<()> {
let mut conn = self.conn.conn.borrow_mut();
if conn.trans_depth != self.depth {
return Err(PgWrongTransaction);
@ -964,8 +972,8 @@ impl<'conn> PostgresTransaction<'conn> {
conn.quick_query(query).map(|_| ())
}
/// Like `Connection::transaction`.
pub fn transaction<'a>(&'a self) -> Result<PostgresTransaction<'a>> {
/// Like `PostgresConnection::transaction`.
pub fn transaction<'a>(&'a self) -> PostgresResult<PostgresTransaction<'a>> {
check_desync!(self.conn);
if self.conn.conn.borrow().trans_depth != self.depth {
return Err(PgWrongTransaction);
@ -988,16 +996,16 @@ impl<'conn> PostgresTransaction<'conn> {
/// If `row_limit` is less than or equal to 0, `lazy_query` is equivalent
/// to `query`.
pub fn lazy_query<'trans, 'stmt>(&'trans self,
stmt: &'stmt Statement,
stmt: &'stmt PostgresStatement,
params: &[&ToSql],
row_limit: i32)
-> Result<LazyRows<'trans, 'stmt>> {
-> PostgresResult<PostgresLazyRows<'trans, 'stmt>> {
if self.conn as *const _ != stmt.conn as *const _ {
return Err(PgWrongConnection);
}
check_desync!(self.conn);
stmt.lazy_query(row_limit, params).map(|result| {
LazyRows {
PostgresLazyRows {
_trans: self,
result: result
}
@ -1020,7 +1028,7 @@ impl<'conn> PostgresTransaction<'conn> {
}
/// A convenience method which consumes and commits a transaction.
pub fn commit(self) -> Result<()> {
pub fn commit(self) -> PostgresResult<()> {
self.set_commit();
self.finish()
}
@ -1029,15 +1037,15 @@ impl<'conn> PostgresTransaction<'conn> {
///
/// Functionally equivalent to the `Drop` implementation of
/// `PostgresTransaction` except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
pub fn finish(mut self) -> PostgresResult<()> {
self.finished = true;
self.finish_inner()
}
}
/// A prepared statement
pub struct Statement<'conn> {
conn: &'conn Connection,
pub struct PostgresStatement<'conn> {
conn: &'conn PostgresConnection,
name: String,
param_types: Vec<PostgresType>,
result_desc: Vec<ResultDescription>,
@ -1046,7 +1054,7 @@ pub struct Statement<'conn> {
}
#[unsafe_destructor]
impl<'conn> Drop for Statement<'conn> {
impl<'conn> Drop for PostgresStatement<'conn> {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
@ -1054,8 +1062,8 @@ impl<'conn> Drop for Statement<'conn> {
}
}
impl<'conn> Statement<'conn> {
fn finish_inner(&mut self) -> Result<()> {
impl<'conn> PostgresStatement<'conn> {
fn finish_inner(&mut self) -> PostgresResult<()> {
check_desync!(self.conn);
try_pg!(self.conn.write_messages([
Close {
@ -1077,7 +1085,7 @@ impl<'conn> Statement<'conn> {
}
fn inner_execute(&self, portal_name: &str, row_limit: i32, params: &[&ToSql])
-> Result<()> {
-> PostgresResult<()> {
if self.param_types.len() != params.len() {
return Err(PgWrongParamCount {
expected: self.param_types.len(),
@ -1122,14 +1130,14 @@ impl<'conn> Statement<'conn> {
}
fn lazy_query<'a>(&'a self, row_limit: i32, params: &[&ToSql])
-> Result<Rows<'a>> {
-> PostgresResult<PostgresRows<'a>> {
let id = self.next_portal_id.get();
self.next_portal_id.set(id + 1);
let portal_name = format!("{}p{}", self.name, id);
try!(self.inner_execute(portal_name.as_slice(), row_limit, params));
let mut result = Rows {
let mut result = PostgresRows {
stmt: self,
name: portal_name,
data: RingBuf::new(),
@ -1159,8 +1167,8 @@ impl<'conn> Statement<'conn> {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # let conn = postgres::Connection::connect("", &NoSsl).unwrap();
/// # use postgres::{PostgresConnection, NoSsl};
/// # let conn = PostgresConnection::connect("", &NoSsl).unwrap();
/// # let bar = 1i32;
/// # let baz = true;
/// let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();
@ -1168,7 +1176,7 @@ impl<'conn> Statement<'conn> {
/// Ok(count) => println!("{} row(s) updated", count),
/// Err(err) => println!("Error executing query: {}", err)
/// }
pub fn execute(&self, params: &[&ToSql]) -> Result<uint> {
pub fn execute(&self, params: &[&ToSql]) -> PostgresResult<uint> {
check_desync!(self.conn);
try!(self.inner_execute("", 0, params));
@ -1206,8 +1214,8 @@ impl<'conn> Statement<'conn> {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # let conn = postgres::Connection::connect("", &NoSsl).unwrap();
/// # use postgres::{PostgresConnection, NoSsl};
/// # let conn = PostgresConnection::connect("", &NoSsl).unwrap();
/// let stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1").unwrap();
/// # let baz = true;
/// let mut rows = match stmt.query([&baz]) {
@ -1219,16 +1227,16 @@ impl<'conn> Statement<'conn> {
/// println!("foo: {}", foo);
/// }
/// ```
pub fn query<'a>(&'a self, params: &[&ToSql]) -> Result<Rows<'a>> {
pub fn query<'a>(&'a self, params: &[&ToSql]) -> PostgresResult<PostgresRows<'a>> {
check_desync!(self.conn);
self.lazy_query(0, params)
}
/// Consumes the statement, clearing it from the Postgres session.
///
/// Functionally identical to the `Drop` implementation of the `Statement`
/// except that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
/// Functionally identical to the `Drop` implementation of the
/// `PostgresStatement` except that it returns any error to the caller.
pub fn finish(mut self) -> PostgresResult<()> {
self.finished = true;
self.finish_inner()
}
@ -1244,8 +1252,8 @@ pub struct ResultDescription {
}
/// An iterator over the resulting rows of a query.
pub struct Rows<'stmt> {
stmt: &'stmt Statement<'stmt>,
pub struct PostgresRows<'stmt> {
stmt: &'stmt PostgresStatement<'stmt>,
name: String,
data: RingBuf<Vec<Option<Vec<u8>>>>,
row_limit: i32,
@ -1254,7 +1262,7 @@ pub struct Rows<'stmt> {
}
#[unsafe_destructor]
impl<'stmt> Drop for Rows<'stmt> {
impl<'stmt> Drop for PostgresRows<'stmt> {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
@ -1262,8 +1270,8 @@ impl<'stmt> Drop for Rows<'stmt> {
}
}
impl<'stmt> Rows<'stmt> {
fn finish_inner(&mut self) -> Result<()> {
impl<'stmt> PostgresRows<'stmt> {
fn finish_inner(&mut self) -> PostgresResult<()> {
check_desync!(self.stmt.conn);
try_pg!(self.stmt.conn.write_messages([
Close {
@ -1284,7 +1292,7 @@ impl<'stmt> Rows<'stmt> {
Ok(())
}
fn read_rows(&mut self) -> Result<()> {
fn read_rows(&mut self) -> PostgresResult<()> {
loop {
match try_pg!(self.stmt.conn.read_message()) {
EmptyQueryResponse | CommandComplete { .. } => {
@ -1309,7 +1317,7 @@ impl<'stmt> Rows<'stmt> {
self.stmt.conn.wait_for_ready()
}
fn execute(&mut self) -> Result<()> {
fn execute(&mut self) -> PostgresResult<()> {
try_pg!(self.stmt.conn.write_messages([
Execute {
portal: self.name.as_slice(),
@ -1319,16 +1327,16 @@ impl<'stmt> Rows<'stmt> {
self.read_rows()
}
/// Consumes the `Rows`, cleaning up associated state.
/// Consumes the `PostgresRows`, cleaning up associated state.
///
/// Functionally identical to the `Drop` implementation on `Rows` except
/// that it returns any error to the caller.
pub fn finish(mut self) -> Result<()> {
/// Functionally identical to the `Drop` implementation on `PostgresRows`
/// except that it returns any error to the caller.
pub fn finish(mut self) -> PostgresResult<()> {
self.finished = true;
self.finish_inner()
}
fn try_next(&mut self) -> Option<Result<Row<'stmt>>> {
fn try_next(&mut self) -> Option<PostgresResult<PostgresRow<'stmt>>> {
if self.data.is_empty() && self.more_rows {
match self.execute() {
Ok(()) => {}
@ -1337,7 +1345,7 @@ impl<'stmt> Rows<'stmt> {
}
self.data.pop_front().map(|row| {
Ok(Row {
Ok(PostgresRow {
stmt: self.stmt,
data: row
})
@ -1345,9 +1353,9 @@ impl<'stmt> Rows<'stmt> {
}
}
impl<'stmt> Iterator<Row<'stmt>> for Rows<'stmt> {
impl<'stmt> Iterator<PostgresRow<'stmt>> for PostgresRows<'stmt> {
#[inline]
fn next(&mut self) -> Option<Row<'stmt>> {
fn next(&mut self) -> Option<PostgresRow<'stmt>> {
// we'll never hit the network on a non-lazy result
self.try_next().map(|r| r.unwrap())
}
@ -1365,12 +1373,12 @@ impl<'stmt> Iterator<Row<'stmt>> for Rows<'stmt> {
}
/// A single result row of a query.
pub struct Row<'stmt> {
stmt: &'stmt Statement<'stmt>,
pub struct PostgresRow<'stmt> {
stmt: &'stmt PostgresStatement<'stmt>,
data: Vec<Option<Vec<u8>>>
}
impl<'stmt> Row<'stmt> {
impl<'stmt> PostgresRow<'stmt> {
/// Retrieves the contents of a field of the row.
///
/// A field can be accessed by the name or index of its column, though
@ -1378,7 +1386,7 @@ impl<'stmt> Row<'stmt> {
///
/// Returns an `Error` value if the index does not reference a column or
/// the return type is not compatible with the Postgres type.
pub fn get_opt<I, T>(&self, idx: I) -> Result<T> where I: RowIndex, T: FromSql {
pub fn get_opt<I, T>(&self, idx: I) -> PostgresResult<T> where I: RowIndex, T: FromSql {
let idx = match idx.idx(self.stmt) {
Some(idx) => idx,
None => return Err(PgInvalidColumn)
@ -1399,8 +1407,8 @@ impl<'stmt> Row<'stmt> {
/// ## Example
///
/// ```rust,no_run
/// # use postgres::NoSsl;
/// # let conn = postgres::Connection::connect("", &NoSsl).unwrap();
/// # use postgres::{PostgresConnection, NoSsl};
/// # let conn = PostgresConnection::connect("", &NoSsl).unwrap();
/// # let stmt = conn.prepare("").unwrap();
/// # let mut result = stmt.query([]).unwrap();
/// # let row = result.next().unwrap();
@ -1415,7 +1423,7 @@ impl<'stmt> Row<'stmt> {
}
}
impl<'stmt> Collection for Row<'stmt> {
impl<'stmt> Collection for PostgresRow<'stmt> {
#[inline]
fn len(&self) -> uint {
self.data.len()
@ -1426,12 +1434,12 @@ impl<'stmt> Collection for Row<'stmt> {
pub trait RowIndex {
/// Returns the index of the appropriate column, or `None` if no such
/// column exists.
fn idx(&self, stmt: &Statement) -> Option<uint>;
fn idx(&self, stmt: &PostgresStatement) -> Option<uint>;
}
impl RowIndex for uint {
#[inline]
fn idx(&self, stmt: &Statement) -> Option<uint> {
fn idx(&self, stmt: &PostgresStatement) -> Option<uint> {
if *self > stmt.result_desc.len() {
None
} else {
@ -1442,28 +1450,29 @@ impl RowIndex for uint {
impl<'a> RowIndex for &'a str {
#[inline]
fn idx(&self, stmt: &Statement) -> Option<uint> {
fn idx(&self, stmt: &PostgresStatement) -> Option<uint> {
stmt.result_descriptions().iter().position(|d| d.name.as_slice() == *self)
}
}
/// A lazily-loaded iterator over the resulting rows of a query
pub struct LazyRows<'trans, 'stmt> {
result: Rows<'stmt>,
pub struct PostgresLazyRows<'trans, 'stmt> {
result: PostgresRows<'stmt>,
_trans: &'trans PostgresTransaction<'trans>,
}
impl<'trans, 'stmt> LazyRows<'trans, 'stmt> {
/// Like `Rows::finish`.
impl<'trans, 'stmt> PostgresLazyRows<'trans, 'stmt> {
/// Like `PostgresRows::finish`.
#[inline]
pub fn finish(self) -> Result<()> {
pub fn finish(self) -> PostgresResult<()> {
self.result.finish()
}
}
impl<'trans, 'stmt> Iterator<Result<Row<'stmt>>> for LazyRows<'trans, 'stmt> {
impl<'trans, 'stmt> Iterator<PostgresResult<PostgresRow<'stmt>>>
for PostgresLazyRows<'trans, 'stmt> {
#[inline]
fn next(&mut self) -> Option<Result<Row<'stmt>>> {
fn next(&mut self) -> Option<PostgresResult<PostgresRow<'stmt>>> {
self.result.try_next()
}

View File

@ -4,18 +4,19 @@
use std::sync::{Arc, Mutex};
use {ConnectParams, IntoConnectParams, Connection, SslMode};
use {PostgresConnectParams, IntoConnectParams, PostgresConnection, SslMode};
use error::PostgresConnectError;
struct InnerConnectionPool {
params: ConnectParams,
params: PostgresConnectParams,
ssl: SslMode,
pool: Vec<Connection>,
pool: Vec<PostgresConnection>,
}
impl InnerConnectionPool {
fn add_connection(&mut self) -> Result<(), PostgresConnectError> {
Connection::connect(self.params.clone(), &self.ssl).map(|c| self.pool.push(c))
PostgresConnection::connect(self.params.clone(), &self.ssl)
.map(|c| self.pool.push(c))
}
}
@ -93,7 +94,7 @@ impl PostgresConnectionPool {
pub struct PooledPostgresConnection {
pool: PostgresConnectionPool,
// TODO remove the Option wrapper when drop takes self by value
conn: Option<Connection>
conn: Option<PostgresConnection>
}
impl Drop for PooledPostgresConnection {
@ -104,8 +105,8 @@ impl Drop for PooledPostgresConnection {
}
}
impl Deref<Connection> for PooledPostgresConnection {
fn deref<'a>(&'a self) -> &'a Connection {
impl Deref<PostgresConnection> for PooledPostgresConnection {
fn deref<'a>(&'a self) -> &'a PostgresConnection {
self.conn.get_ref()
}
}

View File

@ -8,7 +8,7 @@ use std::io::{MemWriter, BufReader};
use std::io::util::LimitReader;
use time::Timespec;
use Result;
use PostgresResult;
use error::{PgWrongType, PgStreamError, PgWasNull, PgBadData};
use types::array::{Array, ArrayBase, DimensionInfo};
use types::range::{RangeBound, Inclusive, Exclusive, Range};
@ -220,18 +220,18 @@ pub trait FromSql {
/// Creates a new value of this type from a buffer of Postgres data.
///
/// If the value was `NULL`, the buffer will be `None`.
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>) -> Result<Self>;
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>) -> PostgresResult<Self>;
}
#[doc(hidden)]
trait RawFromSql {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Self>;
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<Self>;
}
macro_rules! raw_from_impl(
($t:ty, $f:ident) => (
impl RawFromSql for $t {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<$t> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<$t> {
Ok(try_pg!(raw.$f()))
}
}
@ -239,19 +239,19 @@ macro_rules! raw_from_impl(
)
impl RawFromSql for bool {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<bool> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<bool> {
Ok((try_pg!(raw.read_u8())) != 0)
}
}
impl RawFromSql for Vec<u8> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Vec<u8>> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<Vec<u8>> {
Ok(try_pg!(raw.read_to_end()))
}
}
impl RawFromSql for String {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<String> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<String> {
String::from_utf8(try_pg!(raw.read_to_end())).map_err(|_| PgBadData)
}
}
@ -264,7 +264,7 @@ raw_from_impl!(f32, read_be_f32)
raw_from_impl!(f64, read_be_f64)
impl RawFromSql for Timespec {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Timespec> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<Timespec> {
let t = try_pg!(raw.read_be_i64());
let mut sec = t / USEC_PER_SEC + TIME_SEC_CONVERSION;
let mut usec = t % USEC_PER_SEC;
@ -281,7 +281,7 @@ impl RawFromSql for Timespec {
macro_rules! from_range_impl(
($t:ty) => (
impl RawFromSql for Range<$t> {
fn raw_from_sql<R: Reader>(rdr: &mut R) -> Result<Range<$t>> {
fn raw_from_sql<R: Reader>(rdr: &mut R) -> PostgresResult<Range<$t>> {
let t = try_pg!(rdr.read_i8());
if t & RANGE_EMPTY != 0 {
@ -330,7 +330,7 @@ from_range_impl!(i64)
from_range_impl!(Timespec)
impl RawFromSql for Json {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Json> {
fn raw_from_sql<R: Reader>(raw: &mut R) -> PostgresResult<Json> {
json::from_reader(raw).map_err(|_| PgBadData)
}
}
@ -339,7 +339,7 @@ macro_rules! from_map_impl(
($($expected:pat)|+, $t:ty, $blk:expr) => (
impl FromSql for Option<$t> {
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>)
-> Result<Option<$t>> {
-> PostgresResult<Option<$t>> {
check_types!($($expected)|+, ty)
match *raw {
Some(ref buf) => ($blk)(buf).map(|ok| Some(ok)),
@ -350,9 +350,9 @@ macro_rules! from_map_impl(
impl FromSql for $t {
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>)
-> Result<$t> {
-> PostgresResult<$t> {
// FIXME when you can specify Self types properly
let ret: Result<Option<$t>> = FromSql::from_sql(ty, raw);
let ret: PostgresResult<Option<$t>> = FromSql::from_sql(ty, raw);
match ret {
Ok(Some(val)) => Ok(val),
Ok(None) => Err(PgWasNull),
@ -440,7 +440,7 @@ from_array_impl!(PgInt8RangeArray, Range<i64>)
impl FromSql for Option<HashMap<String, Option<String>>> {
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>)
-> Result<Option<HashMap<String, Option<String>>>> {
-> PostgresResult<Option<HashMap<String, Option<String>>>> {
match *ty {
PgUnknownType { name: ref name, .. } if "hstore" == name.as_slice() => {}
_ => return Err(PgWrongType(ty.clone()))
@ -483,9 +483,9 @@ impl FromSql for Option<HashMap<String, Option<String>>> {
impl FromSql for HashMap<String, Option<String>> {
fn from_sql(ty: &PostgresType, raw: &Option<Vec<u8>>)
-> Result<HashMap<String, Option<String>>> {
-> PostgresResult<HashMap<String, Option<String>>> {
// FIXME when you can specify Self types properly
let ret: Result<Option<HashMap<String, Option<String>>>> =
let ret: PostgresResult<Option<HashMap<String, Option<String>>>> =
FromSql::from_sql(ty, raw);
match ret {
Ok(Some(val)) => Ok(val),
@ -500,18 +500,18 @@ pub trait ToSql {
/// Converts the value of `self` into a format appropriate for the Postgres
/// backend.
fn to_sql(&self, ty: &PostgresType)
-> Result<(Format, Option<Vec<u8>>)>;
-> PostgresResult<(Format, Option<Vec<u8>>)>;
}
#[doc(hidden)]
trait RawToSql {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()>;
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()>;
}
macro_rules! raw_to_impl(
($t:ty, $f:ident) => (
impl RawToSql for $t {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()> {
Ok(try_pg!(w.$f(*self)))
}
}
@ -519,19 +519,19 @@ macro_rules! raw_to_impl(
)
impl RawToSql for bool {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()> {
Ok(try_pg!(w.write_u8(*self as u8)))
}
}
impl RawToSql for Vec<u8> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()> {
Ok(try_pg!(w.write(self.as_slice())))
}
}
impl RawToSql for String {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()> {
Ok(try_pg!(w.write(self.as_bytes())))
}
}
@ -544,7 +544,7 @@ raw_to_impl!(f32, write_be_f32)
raw_to_impl!(f64, write_be_f64)
impl RawToSql for Timespec {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> PostgresResult<()> {
let t = (self.sec - TIME_SEC_CONVERSION) * USEC_PER_SEC + self.nsec as i64 / NSEC_PER_USEC;
Ok(try_pg!(w.write_be_i64(t)))
}
@ -553,7 +553,7 @@ impl RawToSql for Timespec {
macro_rules! to_range_impl(
($t:ty) => (
impl RawToSql for Range<$t> {
fn raw_to_sql<W: Writer>(&self, buf: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, buf: &mut W) -> PostgresResult<()> {
let mut tag = 0;
if self.is_empty() {
tag |= RANGE_EMPTY;
@ -604,7 +604,7 @@ to_range_impl!(i64)
to_range_impl!(Timespec)
impl RawToSql for Json {
fn raw_to_sql<W: Writer>(&self, raw: &mut W) -> Result<()> {
fn raw_to_sql<W: Writer>(&self, raw: &mut W) -> PostgresResult<()> {
Ok(try_pg!(self.to_writer(raw as &mut Writer)))
}
}
@ -612,7 +612,7 @@ impl RawToSql for Json {
macro_rules! to_option_impl(
($($oid:pat)|+, $t:ty) => (
impl ToSql for Option<$t> {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!($($oid)|+, ty)
match *self {
@ -627,7 +627,7 @@ macro_rules! to_option_impl(
macro_rules! to_option_impl_lifetime(
($($oid:pat)|+, $t:ty) => (
impl<'a> ToSql for Option<$t> {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!($($oid)|+, ty)
match *self {
@ -642,7 +642,7 @@ macro_rules! to_option_impl_lifetime(
macro_rules! to_raw_to_impl(
($($oid:ident)|+, $t:ty) => (
impl ToSql for $t {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!($($oid)|+, ty)
let mut writer = MemWriter::new();
@ -670,7 +670,7 @@ to_raw_to_impl!(PgInt8Range, Range<i64>)
to_raw_to_impl!(PgTsRange | PgTstzRange, Range<Timespec>)
impl<'a> ToSql for &'a str {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!(PgVarchar | PgText | PgCharN | PgName, ty)
Ok((Text, Some(Vec::from_slice(self.as_bytes()))))
}
@ -679,7 +679,7 @@ impl<'a> ToSql for &'a str {
to_option_impl_lifetime!(PgVarchar | PgText | PgCharN | PgName, &'a str)
impl<'a> ToSql for &'a [u8] {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!(PgByteA, ty)
Ok((Binary, Some(Vec::from_slice(*self))))
}
@ -692,7 +692,7 @@ to_raw_to_impl!(PgTimestamp | PgTimestampTZ, Timespec)
macro_rules! to_array_impl(
($($oid:ident)|+, $t:ty) => (
impl ToSql for ArrayBase<Option<$t>> {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
check_types!($($oid)|+, ty)
let mut buf = MemWriter::new();
@ -742,7 +742,7 @@ to_array_impl!(PgInt8RangeArray, Range<i64>)
to_array_impl!(PgJsonArray, Json)
impl ToSql for HashMap<String, Option<String>> {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
match *ty {
PgUnknownType { name: ref name, .. } if "hstore" == name.as_slice() => {}
_ => return Err(PgWrongType(ty.clone()))
@ -770,7 +770,7 @@ impl ToSql for HashMap<String, Option<String>> {
}
impl ToSql for Option<HashMap<String, Option<String>>> {
fn to_sql(&self, ty: &PostgresType) -> Result<(Format, Option<Vec<u8>>)> {
fn to_sql(&self, ty: &PostgresType) -> PostgresResult<(Format, Option<Vec<u8>>)> {
match *ty {
PgUnknownType { name: ref name, .. } if "hstore" == name.as_slice() => {}
_ => return Err(PgWrongType(ty.clone()))

View File

@ -11,7 +11,10 @@ use openssl::ssl::{SslContext, Sslv3};
use std::io::timer;
use std::time::Duration;
use postgres::{ResultDescription,
use postgres::{PostgresNoticeHandler,
PostgresNotification,
PostgresConnection,
ResultDescription,
RequireSsl,
PreferSsl,
NoSsl};
@ -48,17 +51,17 @@ mod pool;
#[test]
fn test_non_default_database() {
or_fail!(postgres::Connection::connect("postgres://postgres@localhost/postgres", &NoSsl));
or_fail!(PostgresConnection::connect("postgres://postgres@localhost/postgres", &NoSsl));
}
#[test]
fn test_url_terminating_slash() {
or_fail!(postgres::Connection::connect("postgres://postgres@localhost/", &NoSsl));
or_fail!(PostgresConnection::connect("postgres://postgres@localhost/", &NoSsl));
}
#[test]
fn test_prepare_err() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
match conn.prepare("invalid sql statment") {
Err(PgDbError(PostgresDbError { code: SyntaxError, position: Some(Position(1)), .. })) => (),
Err(e) => fail!("Unexpected result {}", e),
@ -68,7 +71,7 @@ fn test_prepare_err() {
#[test]
fn test_unknown_database() {
match postgres::Connection::connect("postgres://postgres@localhost/asdf", &NoSsl) {
match PostgresConnection::connect("postgres://postgres@localhost/asdf", &NoSsl) {
Err(PgConnectDbError(PostgresDbError { code: InvalidCatalogName, .. })) => {}
Err(resp) => fail!("Unexpected result {}", resp),
_ => fail!("Unexpected result"),
@ -77,13 +80,13 @@ fn test_unknown_database() {
#[test]
fn test_connection_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
assert!(conn.finish().is_ok());
}
#[test]
fn test_unix_connection() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SHOW unix_socket_directories"));
let result = or_fail!(stmt.query([]));
let unix_socket_directories: String = result.map(|row| row.get(0u)).next().unwrap();
@ -95,13 +98,13 @@ fn test_unix_connection() {
let unix_socket_directory = unix_socket_directories.as_slice() .split(',').next().unwrap();
let url = format!("postgres://postgres@{}", url::encode_component(unix_socket_directory));
let conn = or_fail!(postgres::Connection::connect(url.as_slice(), &NoSsl));
let conn = or_fail!(PostgresConnection::connect(url.as_slice(), &NoSsl));
assert!(conn.finish().is_ok());
}
#[test]
fn test_transaction_commit() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
let trans = or_fail!(conn.transaction());
@ -117,7 +120,7 @@ fn test_transaction_commit() {
#[test]
fn test_transaction_commit_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
let trans = or_fail!(conn.transaction());
@ -133,7 +136,7 @@ fn test_transaction_commit_finish() {
#[test]
fn test_transaction_commit_method() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
let trans = or_fail!(conn.transaction());
@ -148,7 +151,7 @@ fn test_transaction_commit_method() {
#[test]
fn test_transaction_rollback() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
or_fail!(conn.execute("INSERT INTO foo (id) VALUES ($1)", [&1i32]));
@ -165,7 +168,7 @@ fn test_transaction_rollback() {
#[test]
fn test_transaction_rollback_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
or_fail!(conn.execute("INSERT INTO foo (id) VALUES ($1)", [&1i32]));
@ -182,7 +185,7 @@ fn test_transaction_rollback_finish() {
#[test]
fn test_nested_transactions() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
or_fail!(conn.execute("INSERT INTO foo (id) VALUES (1)", []));
@ -228,7 +231,7 @@ fn test_nested_transactions() {
#[test]
fn test_nested_transactions_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
or_fail!(conn.execute("INSERT INTO foo (id) VALUES (1)", []));
@ -283,7 +286,7 @@ fn test_nested_transactions_finish() {
#[test]
fn test_conn_prepare_with_trans() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let _trans = or_fail!(conn.transaction());
match conn.prepare("") {
Err(PgWrongTransaction) => {}
@ -299,7 +302,7 @@ fn test_conn_prepare_with_trans() {
#[test]
fn test_trans_prepare_with_nested_trans() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let trans = or_fail!(conn.transaction());
let _trans2 = or_fail!(trans.transaction());
match trans.prepare("") {
@ -316,7 +319,7 @@ fn test_trans_prepare_with_nested_trans() {
#[test]
fn test_stmt_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY)", []));
let stmt = or_fail!(conn.prepare("SELECT * FROM foo"));
assert!(stmt.finish().is_ok());
@ -324,7 +327,7 @@ fn test_stmt_finish() {
#[test]
fn test_batch_execute() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let query = "CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY);
INSERT INTO foo (id) VALUES (10);";
or_fail!(conn.batch_execute(query));
@ -337,7 +340,7 @@ fn test_batch_execute() {
#[test]
fn test_batch_execute_error() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let query = "CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY);
INSERT INTO foo (id) VALUES (10);
asdfa;
@ -353,7 +356,7 @@ fn test_batch_execute_error() {
#[test]
fn test_transaction_batch_execute() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let trans = or_fail!(conn.transaction());
let query = "CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY);
INSERT INTO foo (id) VALUES (10);";
@ -367,7 +370,7 @@ fn test_transaction_batch_execute() {
#[test]
fn test_query() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY)", []));
or_fail!(conn.execute("INSERT INTO foo (id) VALUES ($1), ($2)",
[&1i64, &2i64]));
@ -379,7 +382,7 @@ fn test_query() {
#[test]
fn test_error_after_datarow() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("
SELECT
(SELECT generate_series(1, ss.i))
@ -396,7 +399,7 @@ FROM (SELECT gs.i
#[test]
fn test_result_finish() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (id BIGINT PRIMARY KEY)", []));
let stmt = or_fail!(conn.prepare("SELECT * FROM foo"));
let result = or_fail!(stmt.query([]));
@ -405,7 +408,7 @@ fn test_result_finish() {
#[test]
fn test_lazy_query() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let trans = or_fail!(conn.transaction());
or_fail!(trans.execute("CREATE TEMPORARY TABLE foo (id INT PRIMARY KEY)", []));
@ -421,8 +424,8 @@ fn test_lazy_query() {
#[test]
fn test_lazy_query_wrong_conn() {
let conn1 = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn2 = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn1 = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let conn2 = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let trans = or_fail!(conn1.transaction());
let stmt = or_fail!(conn2.prepare("SELECT 1::INT"));
@ -435,14 +438,14 @@ fn test_lazy_query_wrong_conn() {
#[test]
fn test_param_types() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT $1::INT, $2::VARCHAR"));
assert_eq!(stmt.param_types(), &[PgInt4, PgVarchar]);
}
#[test]
fn test_result_descriptions() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT 1::INT as a, 'hi'::VARCHAR as b"));
assert!(stmt.result_descriptions() ==
[ResultDescription { name: "a".to_string(), ty: PgInt4},
@ -451,7 +454,7 @@ fn test_result_descriptions() {
#[test]
fn test_execute_counts() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
assert_eq!(0, or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (
id SERIAL PRIMARY KEY,
b INT
@ -464,7 +467,7 @@ fn test_execute_counts() {
#[test]
fn test_wrong_param_type() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
match conn.execute("SELECT $1::VARCHAR", [&1i32]) {
Err(PgWrongType(_)) => {}
res => fail!("unexpected result {}", res)
@ -473,7 +476,7 @@ fn test_wrong_param_type() {
#[test]
fn test_too_few_params() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
match conn.execute("SELECT $1::INT, $2::INT", [&1i32]) {
Err(PgWrongParamCount { expected: 2, actual: 1 }) => {},
res => fail!("unexpected result {}", res)
@ -482,7 +485,7 @@ fn test_too_few_params() {
#[test]
fn test_too_many_params() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
match conn.execute("SELECT $1::INT, $2::INT", [&1i32, &2i32, &3i32]) {
Err(PgWrongParamCount { expected: 2, actual: 3 }) => {},
res => fail!("unexpected result {}", res)
@ -491,7 +494,7 @@ fn test_too_many_params() {
#[test]
fn test_index_named() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT 10::INT as val"));
let result = or_fail!(stmt.query([]));
@ -501,7 +504,7 @@ fn test_index_named() {
#[test]
#[should_fail]
fn test_index_named_fail() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT 10::INT as id"));
let mut result = or_fail!(stmt.query([]));
@ -510,7 +513,7 @@ fn test_index_named_fail() {
#[test]
fn test_get_named_err() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT 10::INT as id"));
let mut result = or_fail!(stmt.query([]));
@ -522,7 +525,7 @@ fn test_get_named_err() {
#[test]
fn test_get_was_null() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT NULL::INT as id"));
let mut result = or_fail!(stmt.query([]));
@ -537,14 +540,14 @@ fn test_custom_notice_handler() {
static mut count: uint = 0;
struct Handler;
impl postgres::NoticeHandler for Handler {
impl PostgresNoticeHandler for Handler {
fn handle(&mut self, notice: PostgresDbError) {
assert_eq!("note", notice.message.as_slice());
unsafe { count += 1; }
}
}
let conn = or_fail!(postgres::Connection::connect(
let conn = or_fail!(PostgresConnection::connect(
"postgres://postgres@localhost?client_min_messages=NOTICE", &NoSsl));
conn.set_notice_handler(box Handler);
or_fail!(conn.execute("CREATE FUNCTION pg_temp.note() RETURNS INT AS $$
@ -559,16 +562,16 @@ fn test_custom_notice_handler() {
#[test]
fn test_notification_iterator_none() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
assert!(conn.notifications().next().is_none());
}
#[test]
fn test_notification_iterator_some() {
fn check_notification(expected: postgres::Notification,
actual: Option<postgres::Notification>) {
fn check_notification(expected: PostgresNotification,
actual: Option<PostgresNotification>) {
match actual {
Some(postgres::Notification { channel, payload, .. }) => {
Some(PostgresNotification { channel, payload, .. }) => {
assert_eq!(&expected.channel, &channel);
assert_eq!(&expected.payload, &payload);
}
@ -576,19 +579,19 @@ fn test_notification_iterator_some() {
}
}
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let mut it = conn.notifications();
or_fail!(conn.execute("LISTEN test_notification_iterator_one_channel", []));
or_fail!(conn.execute("LISTEN test_notification_iterator_one_channel2", []));
or_fail!(conn.execute("NOTIFY test_notification_iterator_one_channel, 'hello'", []));
or_fail!(conn.execute("NOTIFY test_notification_iterator_one_channel2, 'world'", []));
check_notification(postgres::Notification {
check_notification(PostgresNotification {
pid: 0,
channel: "test_notification_iterator_one_channel".to_string(),
payload: "hello".to_string()
}, it.next());
check_notification(postgres::Notification {
check_notification(PostgresNotification {
pid: 0,
channel: "test_notification_iterator_one_channel2".to_string(),
payload: "world".to_string()
@ -596,7 +599,7 @@ fn test_notification_iterator_some() {
assert!(it.next().is_none());
or_fail!(conn.execute("NOTIFY test_notification_iterator_one_channel, '!'", []));
check_notification(postgres::Notification {
check_notification(PostgresNotification {
pid: 0,
channel: "test_notification_iterator_one_channel".to_string(),
payload: "!".to_string()
@ -607,7 +610,7 @@ fn test_notification_iterator_some() {
#[test]
// This test is pretty sad, but I don't think there's a better way :(
fn test_cancel_query() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let cancel_data = conn.cancel_data();
spawn(proc() {
@ -626,7 +629,7 @@ fn test_cancel_query() {
#[test]
fn test_require_ssl_conn() {
let ctx = SslContext::new(Sslv3);
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost",
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost",
&RequireSsl(ctx)));
or_fail!(conn.execute("SELECT 1::VARCHAR", []));
}
@ -634,19 +637,19 @@ fn test_require_ssl_conn() {
#[test]
fn test_prefer_ssl_conn() {
let ctx = SslContext::new(Sslv3);
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost",
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost",
&PreferSsl(ctx)));
or_fail!(conn.execute("SELECT 1::VARCHAR", []));
}
#[test]
fn test_plaintext_pass() {
or_fail!(postgres::Connection::connect("postgres://pass_user:password@localhost/postgres", &NoSsl));
or_fail!(PostgresConnection::connect("postgres://pass_user:password@localhost/postgres", &NoSsl));
}
#[test]
fn test_plaintext_pass_no_pass() {
let ret = postgres::Connection::connect("postgres://pass_user@localhost/postgres", &NoSsl);
let ret = PostgresConnection::connect("postgres://pass_user@localhost/postgres", &NoSsl);
match ret {
Err(MissingPassword) => (),
Err(err) => fail!("Unexpected error {}", err),
@ -656,7 +659,7 @@ fn test_plaintext_pass_no_pass() {
#[test]
fn test_plaintext_pass_wrong_pass() {
let ret = postgres::Connection::connect("postgres://pass_user:asdf@localhost/postgres", &NoSsl);
let ret = PostgresConnection::connect("postgres://pass_user:asdf@localhost/postgres", &NoSsl);
match ret {
Err(PgConnectDbError(PostgresDbError { code: InvalidPassword, .. })) => (),
Err(err) => fail!("Unexpected error {}", err),
@ -666,12 +669,12 @@ fn test_plaintext_pass_wrong_pass() {
#[test]
fn test_md5_pass() {
or_fail!(postgres::Connection::connect("postgres://md5_user:password@localhost/postgres", &NoSsl));
or_fail!(PostgresConnection::connect("postgres://md5_user:password@localhost/postgres", &NoSsl));
}
#[test]
fn test_md5_pass_no_pass() {
let ret = postgres::Connection::connect("postgres://md5_user@localhost/postgres", &NoSsl);
let ret = PostgresConnection::connect("postgres://md5_user@localhost/postgres", &NoSsl);
match ret {
Err(MissingPassword) => (),
Err(err) => fail!("Unexpected error {}", err),
@ -681,7 +684,7 @@ fn test_md5_pass_no_pass() {
#[test]
fn test_md5_pass_wrong_pass() {
let ret = postgres::Connection::connect("postgres://md5_user:asdf@localhost/postgres", &NoSsl);
let ret = PostgresConnection::connect("postgres://md5_user:asdf@localhost/postgres", &NoSsl);
match ret {
Err(PgConnectDbError(PostgresDbError { code: InvalidPassword, .. })) => (),
Err(err) => fail!("Unexpected error {}", err),

View File

@ -5,7 +5,7 @@ use std::f64;
use time;
use time::Timespec;
use postgres::{mod, NoSsl};
use postgres::{PostgresConnection, NoSsl};
use postgres::types::array::ArrayBase;
use postgres::types::{ToSql, FromSql};
@ -13,7 +13,7 @@ mod array;
mod range;
fn test_type<T: PartialEq+FromSql+ToSql, S: Str>(sql_type: &str, checks: &[(T, S)]) {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
for &(ref val, ref repr) in checks.iter() {
let stmt = or_fail!(conn.prepare(format!("SELECT {:s}::{}", *repr, sql_type).as_slice()));
let result = or_fail!(stmt.query([])).next().unwrap().get(0u);
@ -93,7 +93,7 @@ fn test_text_params() {
#[test]
fn test_bpchar_params() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
or_fail!(conn.execute("CREATE TEMPORARY TABLE foo (
id SERIAL PRIMARY KEY,
b CHAR(5)
@ -335,7 +335,7 @@ fn test_hstore_params() {
}
fn test_nan_param<T: Float+ToSql+FromSql>(sql_type: &str) {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare(format!("SELECT 'NaN'::{}", sql_type).as_slice()));
let mut result = or_fail!(stmt.query([]));
let val: T = result.next().unwrap().get(0u);
@ -371,7 +371,7 @@ fn test_jsonarray_params() {
#[test]
fn test_pg_database_datname() {
let conn = or_fail!(postgres::Connection::connect("postgres://postgres@localhost", &NoSsl));
let conn = or_fail!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));
let stmt = or_fail!(conn.prepare("SELECT datname FROM pg_database"));
let mut result = or_fail!(stmt.query([]));