Skip to content

Commit 278ee1c

Browse files
committed
Drop WrongType variant
Following the tradition of WasNull
1 parent c87b938 commit 278ee1c

File tree

6 files changed

+58
-24
lines changed

6 files changed

+58
-24
lines changed

src/error.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use std::result;
1010
use std::collections::HashMap;
1111

1212
use {Result, DbErrorNew};
13-
use types::Type;
1413

1514
include!(concat!(env!("OUT_DIR"), "/sqlstate.rs"));
1615

@@ -275,9 +274,6 @@ pub enum Error {
275274
Db(Box<DbError>),
276275
/// An error communicating with the Postgres server.
277276
Io(io::Error),
278-
/// An attempt was made to convert between incompatible Rust and Postgres
279-
/// types.
280-
WrongType(Type),
281277
/// An error converting between Postgres and Rust types.
282278
Conversion(Box<error::Error + Sync + Send>),
283279
}
@@ -288,7 +284,6 @@ impl fmt::Display for Error {
288284
match *self {
289285
Error::Db(ref err) => write!(fmt, ": {}", err),
290286
Error::Io(ref err) => write!(fmt, ": {}", err),
291-
Error::WrongType(ref ty) => write!(fmt, ": saw type {:?}", ty),
292287
Error::Conversion(ref err) => write!(fmt, ": {}", err),
293288
}
294289
}
@@ -299,7 +294,6 @@ impl error::Error for Error {
299294
match *self {
300295
Error::Db(_) => "Error reported by Postgres",
301296
Error::Io(_) => "Error communicating with the server",
302-
Error::WrongType(_) => "Unexpected type",
303297
Error::Conversion(_) => "Error converting between Postgres and Rust types",
304298
}
305299
}
@@ -309,7 +303,6 @@ impl error::Error for Error {
309303
Error::Db(ref err) => Some(&**err),
310304
Error::Io(ref err) => Some(err),
311305
Error::Conversion(ref err) => Some(&**err),
312-
_ => None,
313306
}
314307
}
315308
}

src/lib.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,7 @@ use message::{WriteMessage, ReadMessage};
7878
use notification::{Notifications, Notification};
7979
use rows::{Rows, LazyRows};
8080
use stmt::{Statement, Column};
81-
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other};
82-
use types::{ToSql, FromSql};
81+
use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, WrongType, ToSql, FromSql};
8382
use url::Url;
8483

8584
#[macro_use]
@@ -1485,3 +1484,7 @@ trait ColumnNew {
14851484
trait NotificationsNew<'conn> {
14861485
fn new(conn: &'conn Connection) -> Notifications<'conn>;
14871486
}
1487+
1488+
trait WrongTypeNew {
1489+
fn new(ty: Type) -> WrongType;
1490+
}

src/rows.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ use std::ops::Deref;
88
use std::slice;
99

1010
use {Result, Transaction, read_rows, DbErrorNew, SessionInfoNew, RowsNew, LazyRowsNew,
11-
StatementInternals};
12-
use types::{FromSql, SessionInfo};
11+
StatementInternals, WrongTypeNew};
12+
use types::{FromSql, SessionInfo, WrongType};
1313
use stmt::{Statement, Column};
1414
use error::Error;
1515
use message::FrontendMessage::*;
@@ -222,7 +222,7 @@ impl<'a> Row<'a> {
222222

223223
let ty = self.stmt.columns()[idx].type_();
224224
if !<T as FromSql>::accepts(ty) {
225-
return Some(Err(Error::WrongType(ty.clone())));
225+
return Some(Err(Error::Conversion(Box::new(WrongType::new(ty.clone())))));
226226
}
227227
let conn = self.stmt.conn().conn.borrow();
228228
let value = match self.data[idx] {

src/types/mod.rs

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::io::prelude::*;
77
use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
88

99
pub use self::slice::Slice;
10-
use {Result, SessionInfoNew, InnerConnection, OtherNew};
10+
use {Result, SessionInfoNew, InnerConnection, OtherNew, WrongTypeNew};
1111
use error::Error;
1212
use util;
1313

@@ -31,17 +31,32 @@ macro_rules! accepts {
3131
#[macro_export]
3232
macro_rules! to_sql_checked {
3333
() => {
34-
fn to_sql_checked(&self, ty: &$crate::types::Type, out: &mut ::std::io::Write,
34+
fn to_sql_checked(&self,
35+
ty: &$crate::types::Type,
36+
out: &mut ::std::io::Write,
3537
ctx: &$crate::types::SessionInfo)
3638
-> $crate::Result<$crate::types::IsNull> {
37-
if !<Self as $crate::types::ToSql>::accepts(ty) {
38-
return Err($crate::error::Error::WrongType(ty.clone()));
39-
}
40-
$crate::types::ToSql::to_sql(self, ty, out, ctx)
39+
$crate::types::__to_sql_checked(self, ty, out, ctx)
4140
}
4241
}
4342
}
4443

44+
// WARNING: this function is not considered part of this crate's public API.
45+
// It is subject to change at any time.
46+
#[doc(hidden)]
47+
pub fn __to_sql_checked<T>(v: &T,
48+
ty: &Type,
49+
out: &mut Write,
50+
ctx: &SessionInfo)
51+
-> Result<IsNull>
52+
where T: ToSql
53+
{
54+
if !T::accepts(ty) {
55+
return Err(Error::Conversion(Box::new(WrongType(ty.clone()))));
56+
}
57+
v.to_sql(ty, out, ctx)
58+
}
59+
4560
#[cfg(feature = "bit-vec")]
4661
mod bit_vec;
4762
#[cfg(feature = "uuid")]
@@ -547,6 +562,29 @@ impl error::Error for WasNull {
547562
}
548563
}
549564

565+
/// An error indicating that a conversion was attempted between incompatible
566+
/// Rust and Postgres types.
567+
#[derive(Debug)]
568+
pub struct WrongType(Type);
569+
570+
impl fmt::Display for WrongType {
571+
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
572+
write!(fmt, "cannot convert to or from a Postgres value of type {:?}", self.0)
573+
}
574+
}
575+
576+
impl error::Error for WrongType {
577+
fn description(&self) -> &str {
578+
"cannot convert to or from a Postgres value"
579+
}
580+
}
581+
582+
impl WrongTypeNew for WrongType {
583+
fn new(ty: Type) -> WrongType {
584+
WrongType(ty)
585+
}
586+
}
587+
550588
/// A trait for types that can be created from a Postgres value.
551589
///
552590
/// # Types

tests/test.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use postgres::{HandleNotice,
1919
IntoConnectParams,
2020
IsolationLevel};
2121
use postgres::error::{Error, ConnectError, DbError};
22-
use postgres::types::{Oid, Type, Kind};
22+
use postgres::types::{Oid, Type, Kind, WrongType};
2323
use postgres::error::SqlState::{SyntaxError,
2424
QueryCanceled,
2525
UndefinedTable,
@@ -451,7 +451,7 @@ fn test_execute_counts() {
451451
fn test_wrong_param_type() {
452452
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", SslMode::None));
453453
match conn.execute("SELECT $1::VARCHAR", &[&1i32]) {
454-
Err(Error::WrongType(_)) => {}
454+
Err(Error::Conversion(ref e)) if e.is::<WrongType>() => {}
455455
res => panic!("unexpected result {:?}", res)
456456
}
457457
}
@@ -937,7 +937,7 @@ fn test_get_opt_wrong_type() {
937937
let res = stmt.query(&[]).unwrap();
938938
match res.iter().next().unwrap().get_opt::<_, String>(0) {
939939
Some(Ok(_)) => panic!("unexpected success"),
940-
Some(Err(Error::WrongType(Type::Int4))) => {}
940+
Some(Err(Error::Conversion(ref e))) if e.is::<WrongType>() => {}
941941
Some(Err(e)) => panic!("unexpected error {}", e),
942942
None => panic!("unexpected None"),
943943
}

tests/types/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::fmt;
55

66
use postgres::{Connection, SslMode};
77
use postgres::error::Error;
8-
use postgres::types::{ToSql, FromSql, Slice};
8+
use postgres::types::{ToSql, FromSql, Slice, WrongType};
99

1010
#[cfg(feature = "bit-vec")]
1111
mod bit_vec;
@@ -217,7 +217,7 @@ fn test_slice_wrong_type() {
217217
let stmt = conn.prepare("SELECT * FROM foo WHERE id = ANY($1)").unwrap();
218218
match stmt.query(&[&Slice(&["hi"])]) {
219219
Ok(_) => panic!("Unexpected success"),
220-
Err(Error::WrongType(..)) => {}
220+
Err(Error::Conversion(ref e)) if e.is::<WrongType>() => {}
221221
Err(e) => panic!("Unexpected error {:?}", e),
222222
};
223223
}
@@ -229,7 +229,7 @@ fn test_slice_range() {
229229
let stmt = conn.prepare("SELECT $1::INT8RANGE").unwrap();
230230
match stmt.query(&[&Slice(&[1i64])]) {
231231
Ok(_) => panic!("Unexpected success"),
232-
Err(Error::WrongType(..)) => {}
232+
Err(Error::Conversion(ref e)) if e.is::<WrongType>() => {}
233233
Err(e) => panic!("Unexpected error {:?}", e),
234234
};
235235
}

0 commit comments

Comments
 (0)