Finish variant naming convention transition

This commit is contained in:
Steven Fackler 2014-11-20 21:47:13 -08:00
parent b21300e344
commit a46c524200
6 changed files with 133 additions and 143 deletions

View File

@ -12,9 +12,6 @@ use phf;
use Result; use Result;
use types::Type; use types::Type;
use self::ConnectError::*;
use self::Error::*;
macro_rules! make_errors( macro_rules! make_errors(
($($code:expr => $error:ident),+) => ( ($($code:expr => $error:ident),+) => (
/// SQLSTATE error codes /// SQLSTATE error codes
@ -368,7 +365,7 @@ pub enum ConnectError {
/// The URL was missing a user /// The URL was missing a user
MissingUser, MissingUser,
/// An error from the Postgres server itself /// An error from the Postgres server itself
PgConnectDbError(DbError), DbError(::error::DbError),
/// A password was required but not provided in the URL /// A password was required but not provided in the URL
MissingPassword, MissingPassword,
/// The Postgres server requested an authentication method not supported /// The Postgres server requested an authentication method not supported
@ -379,40 +376,40 @@ pub enum ConnectError {
/// There was an error initializing the SSL session /// There was an error initializing the SSL session
SslError(sslerror::SslError), SslError(sslerror::SslError),
/// There was an error communicating with the server /// There was an error communicating with the server
PgConnectStreamError(io::IoError), IoError(io::IoError),
/// The server sent an unexpected response /// The server sent an unexpected response
PgConnectBadResponse, BadResponse,
} }
impl error::Error for ConnectError { impl error::Error for ConnectError {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match *self {
InvalidUrl(_) => "Invalid URL", ConnectError::InvalidUrl(_) => "Invalid URL",
MissingUser => "User missing in URL", ConnectError::MissingUser => "User missing in URL",
PgConnectDbError(_) => "An error from the Postgres server itself", ConnectError::DbError(_) => "An error from the Postgres server itself",
MissingPassword => "The server requested a password but none was provided", ConnectError::MissingPassword => "The server requested a password but none was provided",
UnsupportedAuthentication => { ConnectError::UnsupportedAuthentication => {
"The server requested an unsupported authentication method" "The server requested an unsupported authentication method"
} }
NoSslSupport => "The server does not support SSL", ConnectError::NoSslSupport => "The server does not support SSL",
SslError(_) => "Error initiating SSL session", ConnectError::SslError(_) => "Error initiating SSL session",
PgConnectStreamError(_) => "Error communicating with server", ConnectError::IoError(_) => "Error communicating with server",
PgConnectBadResponse => "The server returned an unexpected response", ConnectError::BadResponse => "The server returned an unexpected response",
} }
} }
fn detail(&self) -> Option<String> { fn detail(&self) -> Option<String> {
match *self { match *self {
InvalidUrl(ref msg) => Some(msg.clone()), ConnectError::InvalidUrl(ref msg) => Some(msg.clone()),
_ => None, _ => None,
} }
} }
fn cause(&self) -> Option<&error::Error> { fn cause(&self) -> Option<&error::Error> {
match *self { match *self {
PgConnectDbError(ref err) => Some(err as &error::Error), ConnectError::DbError(ref err) => Some(err as &error::Error),
SslError(ref err) => Some(err as &error::Error), ConnectError::SslError(ref err) => Some(err as &error::Error),
PgConnectStreamError(ref err) => Some(err as &error::Error), ConnectError::IoError(ref err) => Some(err as &error::Error),
_ => None _ => None
} }
} }
@ -420,39 +417,39 @@ impl error::Error for ConnectError {
impl error::FromError<io::IoError> for ConnectError { impl error::FromError<io::IoError> for ConnectError {
fn from_error(err: io::IoError) -> ConnectError { fn from_error(err: io::IoError) -> ConnectError {
PgConnectStreamError(err) ConnectError::IoError(err)
} }
} }
impl error::FromError<DbError> for ConnectError { impl error::FromError<DbError> for ConnectError {
fn from_error(err: DbError) -> ConnectError { fn from_error(err: DbError) -> ConnectError {
PgConnectDbError(err) ConnectError::DbError(err)
} }
} }
impl error::FromError<sslerror::SslError> for ConnectError { impl error::FromError<sslerror::SslError> for ConnectError {
fn from_error(err: sslerror::SslError) -> ConnectError { fn from_error(err: sslerror::SslError) -> ConnectError {
SslError(err) ConnectError::SslError(err)
} }
} }
impl fmt::Show for ConnectError { impl fmt::Show for ConnectError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
InvalidUrl(ref err) => write!(fmt, "Invalid URL: {}", err), ConnectError::InvalidUrl(ref err) => write!(fmt, "Invalid URL: {}", err),
MissingUser => write!(fmt, "User missing in URL"), ConnectError::MissingUser => write!(fmt, "User missing in URL"),
PgConnectDbError(ref err) => err.fmt(fmt), ConnectError::DbError(ref err) => err.fmt(fmt),
MissingPassword => ConnectError::MissingPassword =>
write!(fmt, "The server requested a password but none was provided"), write!(fmt, "The server requested a password but none was provided"),
UnsupportedAuthentication => ConnectError::UnsupportedAuthentication =>
write!(fmt, "The server requested an unsupported authentication method"), write!(fmt, "The server requested an unsupported authentication method"),
NoSslSupport => ConnectError::NoSslSupport =>
write!(fmt, "The server does not support SSL"), write!(fmt, "The server does not support SSL"),
SslError(ref err) => ConnectError::SslError(ref err) =>
write!(fmt, "Error initiating SSL session: {}", err), write!(fmt, "Error initiating SSL session: {}", err),
PgConnectStreamError(ref err) => ConnectError::IoError(ref err) =>
write!(fmt, "Error communicating with server: {}", err), write!(fmt, "Error communicating with server: {}", err),
PgConnectBadResponse => ConnectError::BadResponse =>
write!(fmt, "The server returned an unexpected response"), write!(fmt, "The server returned an unexpected response"),
} }
} }
@ -563,16 +560,16 @@ impl DbError {
#[doc(hidden)] #[doc(hidden)]
pub fn new_connect<T>(fields: Vec<(u8, String)>) -> result::Result<T, ConnectError> { pub fn new_connect<T>(fields: Vec<(u8, String)>) -> result::Result<T, ConnectError> {
match DbError::new_raw(fields) { match DbError::new_raw(fields) {
Ok(err) => Err(PgConnectDbError(err)), Ok(err) => Err(ConnectError::DbError(err)),
Err(()) => Err(PgConnectBadResponse), Err(()) => Err(ConnectError::BadResponse),
} }
} }
#[doc(hidden)] #[doc(hidden)]
pub fn new<T>(fields: Vec<(u8, String)>) -> Result<T> { pub fn new<T>(fields: Vec<(u8, String)>) -> Result<T> {
match DbError::new_raw(fields) { match DbError::new_raw(fields) {
Ok(err) => Err(PgDbError(err)), Ok(err) => Err(Error::DbError(err)),
Err(()) => Err(PgBadData), Err(()) => Err(Error::BadData),
} }
} }
} }
@ -597,16 +594,16 @@ impl error::Error for DbError {
#[deriving(Clone, PartialEq, Eq)] #[deriving(Clone, PartialEq, Eq)]
pub enum Error { pub enum Error {
/// An error reported by the Postgres server /// An error reported by the Postgres server
PgDbError(DbError), DbError(::error::DbError),
/// An error communicating with the Postgres server /// An error communicating with the Postgres server
PgStreamError(io::IoError), IoError(io::IoError),
/// The communication channel with the Postgres server has desynchronized /// The communication channel with the Postgres server has desynchronized
/// due to an earlier communications error. /// due to an earlier communications error.
PgStreamDesynchronized, StreamDesynchronized,
/// A prepared statement was executed on a connection it does not belong to /// A prepared statement was executed on a connection it does not belong to
PgWrongConnection, WrongConnection,
/// An incorrect number of parameters were bound to a statement /// An incorrect number of parameters were bound to a statement
PgWrongParamCount { WrongParamCount {
/// The expected number of parameters /// The expected number of parameters
expected: uint, expected: uint,
/// The actual number of parameters /// The actual number of parameters
@ -614,41 +611,41 @@ pub enum Error {
}, },
/// An attempt was made to convert between incompatible Rust and Postgres /// An attempt was made to convert between incompatible Rust and Postgres
/// types /// types
PgWrongType(Type), WrongType(Type),
/// An attempt was made to read from a column that does not exist /// An attempt was made to read from a column that does not exist
PgInvalidColumn, InvalidColumn,
/// A value was NULL but converted to a non-nullable Rust type /// A value was NULL but converted to a non-nullable Rust type
PgWasNull, WasNull,
/// An attempt was made to prepare a statement or start a transaction on an /// An attempt was made to prepare a statement or start a transaction on an
/// object other than the active transaction /// object other than the active transaction
PgWrongTransaction, WrongTransaction,
/// The server returned an unexpected response /// The server returned an unexpected response
PgBadResponse, BadResponse,
/// The server provided data that the client could not parse /// The server provided data that the client could not parse
PgBadData, BadData,
} }
impl fmt::Show for Error { impl fmt::Show for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
PgDbError(ref err) => err.fmt(fmt), Error::DbError(ref err) => err.fmt(fmt),
PgStreamError(ref err) => err.fmt(fmt), Error::IoError(ref err) => err.fmt(fmt),
PgStreamDesynchronized => Error::StreamDesynchronized =>
write!(fmt, "Communication with the server has desynchronized due to an earlier \ write!(fmt, "Communication with the server has desynchronized due to an earlier \
IO error"), IO error"),
PgWrongConnection => Error::WrongConnection =>
write!(fmt, "A statement was executed with a connection it was not prepared with"), write!(fmt, "A statement was executed with a connection it was not prepared with"),
PgWrongParamCount { expected, actual } => Error::WrongParamCount { expected, actual } =>
write!(fmt, "Expected {} parameters but got {}", expected, actual), write!(fmt, "Expected {} parameters but got {}", expected, actual),
PgWrongType(ref ty) => write!(fmt, "Unexpected type {}", ty), Error::WrongType(ref ty) => write!(fmt, "Unexpected type {}", ty),
PgInvalidColumn => write!(fmt, "Invalid column"), Error::InvalidColumn => write!(fmt, "Invalid column"),
PgWasNull => write!(fmt, "The value was NULL"), Error::WasNull => write!(fmt, "The value was NULL"),
PgWrongTransaction => Error::WrongTransaction =>
write!(fmt, "An attempt was made to prepare a statement or start a transaction on \ write!(fmt, "An attempt was made to prepare a statement or start a transaction on \
an object other than the active transaction"), an object other than the active transaction"),
PgBadResponse => Error::BadResponse =>
write!(fmt, "The server returned an unexpected response"), write!(fmt, "The server returned an unexpected response"),
PgBadData => Error::BadData =>
write!(fmt, "The server provided data that the client could not parse"), write!(fmt, "The server provided data that the client could not parse"),
} }
} }
@ -657,40 +654,40 @@ impl fmt::Show for Error {
impl error::Error for Error { impl error::Error for Error {
fn description(&self) -> &str { fn description(&self) -> &str {
match *self { match *self {
PgDbError(_) => "An error reported by the Postgres server", Error::DbError(_) => "An error reported by the Postgres server",
PgStreamError(_) => "An error communicating with the Postgres server", Error::IoError(_) => "An error communicating with the Postgres server",
PgStreamDesynchronized => { Error::StreamDesynchronized => {
"Communication with the server has desynchronized due to an earlier IO error" "Communication with the server has desynchronized due to an earlier IO error"
} }
PgWrongConnection => { Error::WrongConnection => {
"A statement was executed with a connection with which it was not prepared" "A statement was executed with a connection with which it was not prepared"
} }
PgWrongParamCount { .. } => "Wrong number of parameters", Error::WrongParamCount { .. } => "Wrong number of parameters",
PgWrongType(_) => "Unexpected type", Error::WrongType(_) => "Unexpected type",
PgInvalidColumn => "Invalid column", Error::InvalidColumn => "Invalid column",
PgWasNull => "The value was NULL", Error::WasNull => "The value was NULL",
PgWrongTransaction => { Error::WrongTransaction => {
"An attempt was made to use an object other than the active transaction" "An attempt was made to use an object other than the active transaction"
} }
PgBadResponse => "The server returned an unexpected response", Error::BadResponse => "The server returned an unexpected response",
PgBadData => "The server provided data that the client could not parse", Error::BadData => "The server provided data that the client could not parse",
} }
} }
fn detail(&self) -> Option<String> { fn detail(&self) -> Option<String> {
match *self { match *self {
PgWrongParamCount { expected, actual } => { Error::WrongParamCount { expected, actual } => {
Some(format!("expected: {}, actual: {}", expected, actual)) Some(format!("expected: {}, actual: {}", expected, actual))
} }
PgWrongType(ref ty) => Some(format!("saw type {}", ty)), Error::WrongType(ref ty) => Some(format!("saw type {}", ty)),
_ => None _ => None
} }
} }
fn cause(&self) -> Option<&error::Error> { fn cause(&self) -> Option<&error::Error> {
match *self { match *self {
PgDbError(ref err) => Some(err as &error::Error), Error::DbError(ref err) => Some(err as &error::Error),
PgStreamError(ref err) => Some(err as &error::Error), Error::IoError(ref err) => Some(err as &error::Error),
_ => None _ => None
} }
} }
@ -698,12 +695,12 @@ impl error::Error for Error {
impl error::FromError<DbError> for Error { impl error::FromError<DbError> for Error {
fn from_error(err: DbError) -> Error { fn from_error(err: DbError) -> Error {
PgDbError(err) Error::DbError(err)
} }
} }
impl error::FromError<io::IoError> for Error { impl error::FromError<io::IoError> for Error {
fn from_error(err: io::IoError) -> Error { fn from_error(err: io::IoError) -> Error {
PgStreamError(err) Error::IoError(err)
} }
} }

View File

@ -361,7 +361,7 @@ impl InnerConnection {
} }
ReadyForQuery { .. } => break, ReadyForQuery { .. } => break,
ErrorResponse { fields } => return DbError::new_connect(fields), ErrorResponse { fields } => return DbError::new_connect(fields),
_ => return Err(ConnectError::PgConnectBadResponse), _ => return Err(ConnectError::BadResponse),
} }
} }
@ -430,7 +430,7 @@ impl InnerConnection {
ErrorResponse { fields } => return DbError::new_connect(fields), ErrorResponse { fields } => return DbError::new_connect(fields),
_ => { _ => {
self.desynchronized = true; self.desynchronized = true;
return Err(ConnectError::PgConnectBadResponse); return Err(ConnectError::BadResponse);
} }
} }
@ -439,7 +439,7 @@ impl InnerConnection {
ErrorResponse { fields } => return DbError::new_connect(fields), ErrorResponse { fields } => return DbError::new_connect(fields),
_ => { _ => {
self.desynchronized = true; self.desynchronized = true;
return Err(ConnectError::PgConnectBadResponse); return Err(ConnectError::BadResponse);
} }
} }
} }
@ -737,7 +737,7 @@ impl Connection {
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> { pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
let mut conn = self.conn.borrow_mut(); let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 { if conn.trans_depth != 0 {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.prepare(query, self) conn.prepare(query, self)
} }
@ -769,7 +769,7 @@ impl Connection {
-> Result<CopyInStatement<'a>> { -> Result<CopyInStatement<'a>> {
let mut conn = self.conn.borrow_mut(); let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 { if conn.trans_depth != 0 {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.prepare_copy_in(table, rows, self) conn.prepare_copy_in(table, rows, self)
} }
@ -802,7 +802,7 @@ impl Connection {
let mut conn = self.conn.borrow_mut(); let mut conn = self.conn.borrow_mut();
check_desync!(conn); check_desync!(conn);
if conn.trans_depth != 0 { if conn.trans_depth != 0 {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
try!(conn.quick_query("BEGIN")); try!(conn.quick_query("BEGIN"));
conn.trans_depth += 1; conn.trans_depth += 1;
@ -862,7 +862,7 @@ impl Connection {
pub fn batch_execute(&self, query: &str) -> Result<()> { pub fn batch_execute(&self, query: &str) -> Result<()> {
let mut conn = self.conn.borrow_mut(); let mut conn = self.conn.borrow_mut();
if conn.trans_depth != 0 { if conn.trans_depth != 0 {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.quick_query(query).map(|_| ()) conn.quick_query(query).map(|_| ())
} }
@ -950,7 +950,7 @@ impl<'conn> Transaction<'conn> {
pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> { pub fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>> {
let mut conn = self.conn.conn.borrow_mut(); let mut conn = self.conn.conn.borrow_mut();
if conn.trans_depth != self.depth { if conn.trans_depth != self.depth {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.prepare(query, self.conn) conn.prepare(query, self.conn)
} }
@ -960,7 +960,7 @@ impl<'conn> Transaction<'conn> {
-> Result<CopyInStatement<'a>> { -> Result<CopyInStatement<'a>> {
let mut conn = self.conn.conn.borrow_mut(); let mut conn = self.conn.conn.borrow_mut();
if conn.trans_depth != self.depth { if conn.trans_depth != self.depth {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.prepare_copy_in(table, cols, self.conn) conn.prepare_copy_in(table, cols, self.conn)
} }
@ -974,7 +974,7 @@ impl<'conn> Transaction<'conn> {
pub fn batch_execute(&self, query: &str) -> Result<()> { pub fn batch_execute(&self, query: &str) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut(); let mut conn = self.conn.conn.borrow_mut();
if conn.trans_depth != self.depth { if conn.trans_depth != self.depth {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
conn.quick_query(query).map(|_| ()) conn.quick_query(query).map(|_| ())
} }
@ -984,7 +984,7 @@ impl<'conn> Transaction<'conn> {
let mut conn = self.conn.conn.borrow_mut(); let mut conn = self.conn.conn.borrow_mut();
check_desync!(conn); check_desync!(conn);
if conn.trans_depth != self.depth { if conn.trans_depth != self.depth {
return Err(Error::PgWrongTransaction); return Err(Error::WrongTransaction);
} }
try!(conn.quick_query("SAVEPOINT sp")); try!(conn.quick_query("SAVEPOINT sp"));
conn.trans_depth += 1; conn.trans_depth += 1;
@ -1009,7 +1009,7 @@ impl<'conn> Transaction<'conn> {
row_limit: i32) row_limit: i32)
-> Result<LazyRows<'trans, 'stmt>> { -> Result<LazyRows<'trans, 'stmt>> {
if self.conn as *const _ != stmt.conn as *const _ { if self.conn as *const _ != stmt.conn as *const _ {
return Err(Error::PgWrongConnection); return Err(Error::WrongConnection);
} }
check_desync!(self.conn); check_desync!(self.conn);
stmt.lazy_query(row_limit, params).map(|result| { stmt.lazy_query(row_limit, params).map(|result| {
@ -1080,7 +1080,7 @@ impl<'conn> Statement<'conn> {
fn inner_execute(&self, portal_name: &str, row_limit: i32, params: &[&ToSql]) -> Result<()> { fn inner_execute(&self, portal_name: &str, row_limit: i32, params: &[&ToSql]) -> Result<()> {
let mut conn = self.conn.conn.borrow_mut(); let mut conn = self.conn.conn.borrow_mut();
if self.param_types.len() != params.len() { if self.param_types.len() != params.len() {
return Err(Error::PgWrongParamCount { return Err(Error::WrongParamCount {
expected: self.param_types.len(), expected: self.param_types.len(),
actual: params.len(), actual: params.len(),
}); });
@ -1112,7 +1112,7 @@ impl<'conn> Statement<'conn> {
} }
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
Err(Error::PgBadResponse) Err(Error::BadResponse)
} }
} }
} }
@ -1193,7 +1193,7 @@ impl<'conn> Statement<'conn> {
} }
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
return Err(Error::PgBadResponse); return Err(Error::BadResponse);
} }
} }
} }
@ -1315,7 +1315,7 @@ impl<'stmt> Rows<'stmt> {
} }
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
return Err(Error::PgBadResponse); return Err(Error::BadResponse);
} }
} }
} }
@ -1392,7 +1392,7 @@ impl<'stmt> Row<'stmt> {
/// Returns an `Error` value if the index does not reference a column or /// Returns an `Error` value if the index does not reference a column or
/// the return type is not compatible with the Postgres type. /// 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) -> Result<T> where I: RowIndex, T: FromSql {
let idx = try!(idx.idx(self.stmt).ok_or(Error::PgInvalidColumn)); let idx = try!(idx.idx(self.stmt).ok_or(Error::InvalidColumn));
FromSql::from_sql(&self.stmt.result_desc[idx].ty, &self.data[idx]) FromSql::from_sql(&self.stmt.result_desc[idx].ty, &self.data[idx])
} }
@ -1537,7 +1537,7 @@ impl<'a> CopyInStatement<'a> {
} }
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
return Err(Error::PgBadResponse); return Err(Error::BadResponse);
} }
} }
@ -1545,7 +1545,7 @@ impl<'a> CopyInStatement<'a> {
CopyInResponse { .. } => {} CopyInResponse { .. } => {}
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
return Err(Error::PgBadResponse); return Err(Error::BadResponse);
} }
} }
@ -1613,7 +1613,7 @@ impl<'a> CopyInStatement<'a> {
} }
_ => { _ => {
conn.desynchronized = true; conn.desynchronized = true;
return Err(Error::PgBadResponse); return Err(Error::BadResponse);
} }
}; };

View File

@ -16,7 +16,7 @@ macro_rules! check_desync(
panic!("Connection use after free. See mozilla/rust#13246."); panic!("Connection use after free. See mozilla/rust#13246.");
} }
if $e.is_desynchronized() { if $e.is_desynchronized() {
return Err(::Error::PgStreamDesynchronized); return Err(::Error::StreamDesynchronized);
} }
}) })
) )
@ -25,6 +25,6 @@ macro_rules! bad_response(
($s:expr) => ({ ($s:expr) => ({
debug!("Unexpected response"); debug!("Unexpected response");
$s.desynchronized = true; $s.desynchronized = true;
return Err(::Error::PgBadResponse); return Err(::Error::BadResponse);
}) })
) )

View File

@ -5,7 +5,7 @@ use std::io::{ByRefReader, BufReader};
use self::Type::*; use self::Type::*;
use Result; use Result;
use error::Error::{PgWrongType, PgWasNull, PgBadData}; use error::Error;
use types::range::Range; use types::range::Range;
use types::range::BoundType::{Inclusive, Exclusive}; use types::range::BoundType::{Inclusive, Exclusive};
@ -13,7 +13,7 @@ macro_rules! check_types(
($($expected:pat)|+, $actual:ident) => ( ($($expected:pat)|+, $actual:ident) => (
match $actual { match $actual {
$(&$expected)|+ => {} $(&$expected)|+ => {}
actual => return Err(::Error::PgWrongType(actual.clone())) actual => return Err(::Error::WrongType(actual.clone()))
} }
) )
) )
@ -104,7 +104,7 @@ macro_rules! from_map_impl(
let ret: Result<Option<$t>> = FromSql::from_sql(ty, raw); let ret: Result<Option<$t>> = FromSql::from_sql(ty, raw);
match ret { match ret {
Ok(Some(val)) => Ok(val), Ok(Some(val)) => Ok(val),
Ok(None) => Err(Error::PgWasNull), Ok(None) => Err(Error::WasNull),
Err(err) => Err(err) Err(err) => Err(err)
} }
} }
@ -532,7 +532,7 @@ impl RawFromSql for Vec<u8> {
impl RawFromSql for String { impl RawFromSql for String {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<String> { fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<String> {
String::from_utf8(try!(raw.read_to_end())).map_err(|_| PgBadData) String::from_utf8(try!(raw.read_to_end())).map_err(|_| Error::BadData)
} }
} }
@ -548,7 +548,7 @@ from_range_impl!(i64)
impl RawFromSql for json::Json { impl RawFromSql for json::Json {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<json::Json> { fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<json::Json> {
json::from_reader(raw).map_err(|_| PgBadData) json::from_reader(raw).map_err(|_| Error::BadData)
} }
} }
@ -584,7 +584,7 @@ impl FromSql for Option<HashMap<String, Option<String>>> {
-> Result<Option<HashMap<String, Option<String>>>> { -> Result<Option<HashMap<String, Option<String>>>> {
match *ty { match *ty {
Type::Unknown { ref name, .. } if "hstore" == name[] => {} Type::Unknown { ref name, .. } if "hstore" == name[] => {}
_ => return Err(PgWrongType(ty.clone())) _ => return Err(Error::WrongType(ty.clone()))
} }
match *raw { match *raw {
@ -599,7 +599,7 @@ impl FromSql for Option<HashMap<String, Option<String>>> {
let key = try!(rdr.read_exact(key_len as uint)); let key = try!(rdr.read_exact(key_len as uint));
let key = match String::from_utf8(key) { let key = match String::from_utf8(key) {
Ok(key) => key, Ok(key) => key,
Err(_) => return Err(PgBadData), Err(_) => return Err(Error::BadData),
}; };
let val_len = try!(rdr.read_be_i32()); let val_len = try!(rdr.read_be_i32());
@ -609,7 +609,7 @@ impl FromSql for Option<HashMap<String, Option<String>>> {
let val = try!(rdr.read_exact(val_len as uint)); let val = try!(rdr.read_exact(val_len as uint));
match String::from_utf8(val) { match String::from_utf8(val) {
Ok(val) => Some(val), Ok(val) => Some(val),
Err(_) => return Err(PgBadData), Err(_) => return Err(Error::BadData),
} }
}; };
@ -630,7 +630,7 @@ impl FromSql for HashMap<String, Option<String>> {
FromSql::from_sql(ty, raw); FromSql::from_sql(ty, raw);
match ret { match ret {
Ok(Some(val)) => Ok(val), Ok(Some(val)) => Ok(val),
Ok(None) => Err(PgWasNull), Ok(None) => Err(Error::WasNull),
Err(err) => Err(err) Err(err) => Err(err)
} }
} }
@ -730,7 +730,7 @@ impl ToSql for HashMap<String, Option<String>> {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> { fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
match *ty { match *ty {
Type::Unknown { ref name, .. } if "hstore" == name[] => {} Type::Unknown { ref name, .. } if "hstore" == name[] => {}
_ => return Err(PgWrongType(ty.clone())) _ => return Err(Error::WrongType(ty.clone()))
} }
let mut buf = vec![]; let mut buf = vec![];
@ -758,7 +758,7 @@ impl ToSql for Option<HashMap<String, Option<String>>> {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> { fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
match *ty { match *ty {
Type::Unknown { ref name, .. } if "hstore" == name[] => {} Type::Unknown { ref name, .. } if "hstore" == name[] => {}
_ => return Err(PgWrongType(ty.clone())) _ => return Err(Error::WrongType(ty.clone()))
} }
match *self { match *self {

View File

@ -2,14 +2,14 @@ extern crate uuid;
use self::uuid::Uuid; use self::uuid::Uuid;
use types::{RawFromSql, ToSql, RawToSql, Type}; use types::{RawFromSql, ToSql, RawToSql, Type};
use Error::{PgWasNull, PgBadData}; use Error;
use Result; use Result;
impl RawFromSql for Uuid { impl RawFromSql for Uuid {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Uuid> { fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Uuid> {
match Uuid::from_bytes(try!(raw.read_to_end())[]) { match Uuid::from_bytes(try!(raw.read_to_end())[]) {
Some(u) => Ok(u), Some(u) => Ok(u),
None => Err(PgBadData), None => Err(Error::BadData),
} }
} }
} }

View File

@ -18,16 +18,9 @@ use postgres::{NoticeHandler,
SslMode, SslMode,
Type, Type,
ToSql, ToSql,
Error,
ConnectError,
DbError}; DbError};
use postgres::ConnectError::{PgConnectDbError,
MissingPassword};
use postgres::Error::{PgDbError,
PgWrongConnection,
PgWrongParamCount,
PgWrongType,
PgInvalidColumn,
PgWasNull,
PgWrongTransaction};
use postgres::SqlState::{SyntaxError, use postgres::SqlState::{SyntaxError,
QueryCanceled, QueryCanceled,
UndefinedTable, UndefinedTable,
@ -61,7 +54,7 @@ fn test_url_terminating_slash() {
fn test_prepare_err() { fn test_prepare_err() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
match conn.prepare("invalid sql statment") { match conn.prepare("invalid sql statment") {
Err(PgDbError(DbError { code: SyntaxError, position: Some(Normal(1)), .. })) => (), Err(Error::DbError(DbError { code: SyntaxError, position: Some(Normal(1)), .. })) => (),
Err(e) => panic!("Unexpected result {}", e), Err(e) => panic!("Unexpected result {}", e),
_ => panic!("Unexpected result"), _ => panic!("Unexpected result"),
} }
@ -70,7 +63,7 @@ fn test_prepare_err() {
#[test] #[test]
fn test_unknown_database() { fn test_unknown_database() {
match Connection::connect("postgres://postgres@localhost/asdf", &SslMode::None) { match Connection::connect("postgres://postgres@localhost/asdf", &SslMode::None) {
Err(PgConnectDbError(DbError { code: InvalidCatalogName, .. })) => {} Err(ConnectError::DbError(DbError { code: InvalidCatalogName, .. })) => {}
Err(resp) => panic!("Unexpected result {}", resp), Err(resp) => panic!("Unexpected result {}", resp),
_ => panic!("Unexpected result"), _ => panic!("Unexpected result"),
} }
@ -288,12 +281,12 @@ fn test_conn_prepare_with_trans() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
let _trans = or_panic!(conn.transaction()); let _trans = or_panic!(conn.transaction());
match conn.prepare("") { match conn.prepare("") {
Err(PgWrongTransaction) => {} Err(Error::WrongTransaction) => {}
Err(r) => panic!("Unexpected error {}", r), Err(r) => panic!("Unexpected error {}", r),
Ok(_) => panic!("Unexpected success"), Ok(_) => panic!("Unexpected success"),
} }
match conn.transaction() { match conn.transaction() {
Err(PgWrongTransaction) => {} Err(Error::WrongTransaction) => {}
Err(r) => panic!("Unexpected error {}", r), Err(r) => panic!("Unexpected error {}", r),
Ok(_) => panic!("Unexpected success"), Ok(_) => panic!("Unexpected success"),
} }
@ -305,12 +298,12 @@ fn test_trans_prepare_with_nested_trans() {
let trans = or_panic!(conn.transaction()); let trans = or_panic!(conn.transaction());
let _trans2 = or_panic!(trans.transaction()); let _trans2 = or_panic!(trans.transaction());
match trans.prepare("") { match trans.prepare("") {
Err(PgWrongTransaction) => {} Err(Error::WrongTransaction) => {}
Err(r) => panic!("Unexpected error {}", r), Err(r) => panic!("Unexpected error {}", r),
Ok(_) => panic!("Unexpected success"), Ok(_) => panic!("Unexpected success"),
} }
match trans.transaction() { match trans.transaction() {
Err(PgWrongTransaction) => {} Err(Error::WrongTransaction) => {}
Err(r) => panic!("Unexpected error {}", r), Err(r) => panic!("Unexpected error {}", r),
Ok(_) => panic!("Unexpected success"), Ok(_) => panic!("Unexpected success"),
} }
@ -347,7 +340,7 @@ fn test_batch_execute_error() {
conn.batch_execute(query).unwrap_err(); conn.batch_execute(query).unwrap_err();
match conn.prepare("SELECT * from foo ORDER BY id") { match conn.prepare("SELECT * from foo ORDER BY id") {
Err(PgDbError(DbError { code: UndefinedTable, .. })) => {}, Err(Error::DbError(DbError { code: UndefinedTable, .. })) => {},
Err(e) => panic!("unexpected error {}", e), Err(e) => panic!("unexpected error {}", e),
_ => panic!("unexpected success"), _ => panic!("unexpected success"),
} }
@ -390,7 +383,7 @@ FROM (SELECT gs.i
ORDER BY gs.i ORDER BY gs.i
LIMIT 2) ss")); LIMIT 2) ss"));
match stmt.query(&[]) { match stmt.query(&[]) {
Err(PgDbError(DbError { code: CardinalityViolation, .. })) => {} Err(Error::DbError(DbError { code: CardinalityViolation, .. })) => {}
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
Ok(_) => panic!("Expected failure"), Ok(_) => panic!("Expected failure"),
} }
@ -429,7 +422,7 @@ fn test_lazy_query_wrong_conn() {
let trans = or_panic!(conn1.transaction()); let trans = or_panic!(conn1.transaction());
let stmt = or_panic!(conn2.prepare("SELECT 1::INT")); let stmt = or_panic!(conn2.prepare("SELECT 1::INT"));
match trans.lazy_query(&stmt, &[], 1) { match trans.lazy_query(&stmt, &[], 1) {
Err(PgWrongConnection) => {} Err(Error::WrongConnection) => {}
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
Ok(_) => panic!("Expected failure") Ok(_) => panic!("Expected failure")
} }
@ -468,7 +461,7 @@ fn test_execute_counts() {
fn test_wrong_param_type() { fn test_wrong_param_type() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
match conn.execute("SELECT $1::VARCHAR", &[&1i32]) { match conn.execute("SELECT $1::VARCHAR", &[&1i32]) {
Err(PgWrongType(_)) => {} Err(Error::WrongType(_)) => {}
res => panic!("unexpected result {}", res) res => panic!("unexpected result {}", res)
} }
} }
@ -477,7 +470,7 @@ fn test_wrong_param_type() {
fn test_too_few_params() { fn test_too_few_params() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
match conn.execute("SELECT $1::INT, $2::INT", &[&1i32]) { match conn.execute("SELECT $1::INT, $2::INT", &[&1i32]) {
Err(PgWrongParamCount { expected: 2, actual: 1 }) => {}, Err(Error::WrongParamCount { expected: 2, actual: 1 }) => {},
res => panic!("unexpected result {}", res) res => panic!("unexpected result {}", res)
} }
} }
@ -486,7 +479,7 @@ fn test_too_few_params() {
fn test_too_many_params() { fn test_too_many_params() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
match conn.execute("SELECT $1::INT, $2::INT", &[&1i32, &2i32, &3i32]) { match conn.execute("SELECT $1::INT, $2::INT", &[&1i32, &2i32, &3i32]) {
Err(PgWrongParamCount { expected: 2, actual: 3 }) => {}, Err(Error::WrongParamCount { expected: 2, actual: 3 }) => {},
res => panic!("unexpected result {}", res) res => panic!("unexpected result {}", res)
} }
} }
@ -517,7 +510,7 @@ fn test_get_named_err() {
let mut result = or_panic!(stmt.query(&[])); let mut result = or_panic!(stmt.query(&[]));
match result.next().unwrap().get_opt::<&str, i32>("asdf") { match result.next().unwrap().get_opt::<&str, i32>("asdf") {
Err(PgInvalidColumn) => {} Err(Error::InvalidColumn) => {}
res => panic!("unexpected result {}", res), res => panic!("unexpected result {}", res),
}; };
} }
@ -529,7 +522,7 @@ fn test_get_was_null() {
let mut result = or_panic!(stmt.query(&[])); let mut result = or_panic!(stmt.query(&[]));
match result.next().unwrap().get_opt::<uint, i32>(0) { match result.next().unwrap().get_opt::<uint, i32>(0) {
Err(PgWasNull) => {} Err(Error::WasNull) => {}
res => panic!("unexpected result {}", res), res => panic!("unexpected result {}", res),
}; };
} }
@ -619,7 +612,7 @@ fn test_cancel_query() {
}); });
match conn.execute("SELECT pg_sleep(10)", &[]) { match conn.execute("SELECT pg_sleep(10)", &[]) {
Err(PgDbError(DbError { code: QueryCanceled, .. })) => {} Err(Error::DbError(DbError { code: QueryCanceled, .. })) => {}
Err(res) => panic!("Unexpected result {}", res), Err(res) => panic!("Unexpected result {}", res),
_ => panic!("Unexpected result"), _ => panic!("Unexpected result"),
} }
@ -650,7 +643,7 @@ fn test_plaintext_pass() {
fn test_plaintext_pass_no_pass() { fn test_plaintext_pass_no_pass() {
let ret = Connection::connect("postgres://pass_user@localhost/postgres", &SslMode::None); let ret = Connection::connect("postgres://pass_user@localhost/postgres", &SslMode::None);
match ret { match ret {
Err(MissingPassword) => (), Err(ConnectError::MissingPassword) => (),
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
_ => panic!("Expected error") _ => panic!("Expected error")
} }
@ -660,7 +653,7 @@ fn test_plaintext_pass_no_pass() {
fn test_plaintext_pass_wrong_pass() { fn test_plaintext_pass_wrong_pass() {
let ret = Connection::connect("postgres://pass_user:asdf@localhost/postgres", &SslMode::None); let ret = Connection::connect("postgres://pass_user:asdf@localhost/postgres", &SslMode::None);
match ret { match ret {
Err(PgConnectDbError(DbError { code: InvalidPassword, .. })) => (), Err(ConnectError::DbError(DbError { code: InvalidPassword, .. })) => (),
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
_ => panic!("Expected error") _ => panic!("Expected error")
} }
@ -675,7 +668,7 @@ fn test_md5_pass() {
fn test_md5_pass_no_pass() { fn test_md5_pass_no_pass() {
let ret = Connection::connect("postgres://md5_user@localhost/postgres", &SslMode::None); let ret = Connection::connect("postgres://md5_user@localhost/postgres", &SslMode::None);
match ret { match ret {
Err(MissingPassword) => (), Err(ConnectError::MissingPassword) => (),
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
_ => panic!("Expected error") _ => panic!("Expected error")
} }
@ -685,7 +678,7 @@ fn test_md5_pass_no_pass() {
fn test_md5_pass_wrong_pass() { fn test_md5_pass_wrong_pass() {
let ret = Connection::connect("postgres://md5_user:asdf@localhost/postgres", &SslMode::None); let ret = Connection::connect("postgres://md5_user:asdf@localhost/postgres", &SslMode::None);
match ret { match ret {
Err(PgConnectDbError(DbError { code: InvalidPassword, .. })) => (), Err(ConnectError::DbError(DbError { code: InvalidPassword, .. })) => (),
Err(err) => panic!("Unexpected error {}", err), Err(err) => panic!("Unexpected error {}", err),
_ => panic!("Expected error") _ => panic!("Expected error")
} }
@ -697,12 +690,12 @@ fn test_execute_copy_from_err() {
or_panic!(conn.execute("CREATE TEMPORARY TABLE foo (id INT)", &[])); or_panic!(conn.execute("CREATE TEMPORARY TABLE foo (id INT)", &[]));
let stmt = or_panic!(conn.prepare("COPY foo (id) FROM STDIN")); let stmt = or_panic!(conn.prepare("COPY foo (id) FROM STDIN"));
match stmt.execute(&[]) { match stmt.execute(&[]) {
Err(PgDbError(ref err)) if err.message[].contains("COPY") => {} Err(Error::DbError(ref err)) if err.message[].contains("COPY") => {}
Err(err) => panic!("Unexptected error {}", err), Err(err) => panic!("Unexptected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }
match stmt.query(&[]) { match stmt.query(&[]) {
Err(PgDbError(ref err)) if err.message[].contains("COPY") => {} Err(Error::DbError(ref err)) if err.message[].contains("COPY") => {}
Err(err) => panic!("Unexptected error {}", err), Err(err) => panic!("Unexptected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }
@ -733,7 +726,7 @@ fn test_copy_in_bad_column_count() {
let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e))); let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e)));
match res { match res {
Err(PgDbError(ref err)) if err.message[].contains("Invalid column count") => {} Err(Error::DbError(ref err)) if err.message[].contains("Invalid column count") => {}
Err(err) => panic!("unexpected error {}", err), Err(err) => panic!("unexpected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }
@ -742,7 +735,7 @@ fn test_copy_in_bad_column_count() {
let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e))); let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e)));
match res { match res {
Err(PgDbError(ref err)) if err.message[].contains("Invalid column count") => {} Err(Error::DbError(ref err)) if err.message[].contains("Invalid column count") => {}
Err(err) => panic!("unexpected error {}", err), Err(err) => panic!("unexpected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }
@ -760,7 +753,7 @@ fn test_copy_in_bad_type() {
let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e))); let res = stmt.execute(data.iter().map(|r| r.iter().map(|&e| e)));
match res { match res {
Err(PgDbError(ref err)) if err.message[].contains("Unexpected type Varchar") => {} Err(Error::DbError(ref err)) if err.message[].contains("Unexpected type Varchar") => {}
Err(err) => panic!("unexpected error {}", err), Err(err) => panic!("unexpected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }
@ -773,7 +766,7 @@ fn test_batch_execute_copy_from_err() {
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None)); let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
or_panic!(conn.execute("CREATE TEMPORARY TABLE foo (id INT)", &[])); or_panic!(conn.execute("CREATE TEMPORARY TABLE foo (id INT)", &[]));
match conn.batch_execute("COPY foo (id) FROM STDIN") { match conn.batch_execute("COPY foo (id) FROM STDIN") {
Err(PgDbError(ref err)) if err.message[].contains("COPY") => {} Err(Error::DbError(ref err)) if err.message[].contains("COPY") => {}
Err(err) => panic!("Unexptected error {}", err), Err(err) => panic!("Unexptected error {}", err),
_ => panic!("Expected error"), _ => panic!("Expected error"),
} }