rust-postgres/src/types/mod.rs

788 lines
24 KiB
Rust
Raw Normal View History

2013-10-20 21:34:50 +00:00
//! Traits dealing with Postgres data types
2014-03-29 21:33:11 +00:00
#![macro_escape]
2013-10-20 21:34:50 +00:00
2014-02-26 08:40:57 +00:00
use serialize::json;
2014-06-06 03:50:23 +00:00
use std::collections::HashMap;
2014-10-31 15:51:27 +00:00
use std::io::{AsRefReader, MemWriter, BufReader};
2013-12-15 20:42:07 +00:00
use std::io::util::LimitReader;
2014-02-24 06:32:14 +00:00
use time::Timespec;
2014-11-01 23:12:05 +00:00
use Result;
2014-11-17 06:54:57 +00:00
use error::{PgWrongType, PgWasNull, PgBadData};
use types::array::{Array, ArrayBase, DimensionInfo};
2014-03-28 05:43:10 +00:00
use types::range::{RangeBound, Inclusive, Exclusive, Range};
2014-11-17 17:43:10 +00:00
macro_rules! check_types(
($($expected:pat)|+, $actual:ident) => (
match $actual {
$(&$expected)|+ => {}
actual => return Err(PgWrongType(actual.clone()))
}
)
)
macro_rules! raw_from_impl(
($t:ty, $f:ident) => (
impl RawFromSql for $t {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<$t> {
Ok(try!(raw.$f()))
}
}
)
)
macro_rules! from_range_impl(
($t:ty) => (
impl RawFromSql for Range<$t> {
fn raw_from_sql<R: Reader>(rdr: &mut R) -> Result<Range<$t>> {
let t = try!(rdr.read_i8());
if t & RANGE_EMPTY != 0 {
Ok(Range::empty())
} else {
let lower = match t & RANGE_LOWER_UNBOUNDED {
0 => {
let type_ = match t & RANGE_LOWER_INCLUSIVE {
0 => Exclusive,
_ => Inclusive
};
let len = try!(rdr.read_be_i32()) as uint;
let mut limit = LimitReader::new(rdr.by_ref(), len);
let lower = try!(RawFromSql::raw_from_sql(&mut limit));
let lower = Some(RangeBound::new(lower, type_));
assert!(limit.limit() == 0);
lower
}
_ => None
};
let upper = match t & RANGE_UPPER_UNBOUNDED {
0 => {
let type_ = match t & RANGE_UPPER_INCLUSIVE {
0 => Exclusive,
_ => Inclusive
};
let len = try!(rdr.read_be_i32()) as uint;
let mut limit = LimitReader::new(rdr.by_ref(), len);
let upper = try!(RawFromSql::raw_from_sql(&mut limit));
let upper = Some(RangeBound::new(upper, type_));
assert!(limit.limit() == 0);
upper
}
_ => None
};
Ok(Range::new(lower, upper))
}
}
}
)
)
macro_rules! from_map_impl(
($($expected:pat)|+, $t:ty, $blk:expr $(, $a:meta)*) => (
$(#[$a])*
impl FromSql for Option<$t> {
fn from_sql(ty: &Type, raw: &Option<Vec<u8>>)
-> Result<Option<$t>> {
check_types!($($expected)|+, ty)
match *raw {
Some(ref buf) => ($blk)(buf).map(|ok| Some(ok)),
None => Ok(None)
}
}
}
$(#[$a])*
impl FromSql for $t {
fn from_sql(ty: &Type, raw: &Option<Vec<u8>>)
-> Result<$t> {
// FIXME when you can specify Self types properly
let ret: Result<Option<$t>> = FromSql::from_sql(ty, raw);
match ret {
Ok(Some(val)) => Ok(val),
Ok(None) => Err(PgWasNull),
Err(err) => Err(err)
}
}
}
)
)
macro_rules! from_raw_from_impl(
($($expected:pat)|+, $t:ty $(, $a:meta)*) => (
from_map_impl!($($expected)|+, $t, |buf: &Vec<u8>| {
let mut reader = BufReader::new(buf[]);
RawFromSql::raw_from_sql(&mut reader)
} $(, $a)*)
)
)
macro_rules! from_array_impl(
($($oid:pat)|+, $t:ty $(, $a:meta)*) => (
from_map_impl!($($oid)|+, ArrayBase<Option<$t>>, |buf: &Vec<u8>| {
let mut rdr = BufReader::new(buf[]);
let ndim = try!(rdr.read_be_i32()) as uint;
let _has_null = try!(rdr.read_be_i32()) == 1;
let _element_type: Oid = try!(rdr.read_be_u32());
let mut dim_info = Vec::with_capacity(ndim);
for _ in range(0, ndim) {
dim_info.push(DimensionInfo {
len: try!(rdr.read_be_i32()) as uint,
lower_bound: try!(rdr.read_be_i32()) as int
});
}
let nele = dim_info.iter().fold(1, |acc, info| acc * info.len);
let mut elements = Vec::with_capacity(nele);
for _ in range(0, nele) {
let len = try!(rdr.read_be_i32());
if len < 0 {
elements.push(None);
} else {
let mut limit = LimitReader::new(rdr.by_ref(), len as uint);
elements.push(Some(try!(RawFromSql::raw_from_sql(&mut limit))));
assert!(limit.limit() == 0);
}
}
Ok(ArrayBase::from_raw(elements, dim_info))
} $(, $a)*)
)
)
macro_rules! raw_to_impl(
($t:ty, $f:ident) => (
impl RawToSql for $t {
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
Ok(try!(w.$f(*self)))
}
}
)
)
macro_rules! to_range_impl(
($t:ty) => (
impl RawToSql for Range<$t> {
fn raw_to_sql<W: Writer>(&self, buf: &mut W) -> Result<()> {
let mut tag = 0;
if self.is_empty() {
tag |= RANGE_EMPTY;
} else {
match self.lower() {
None => tag |= RANGE_LOWER_UNBOUNDED,
Some(&RangeBound { type_: Inclusive, .. }) => tag |= RANGE_LOWER_INCLUSIVE,
_ => {}
}
match self.upper() {
None => tag |= RANGE_UPPER_UNBOUNDED,
Some(&RangeBound { type_: Inclusive, .. }) => tag |= RANGE_UPPER_INCLUSIVE,
_ => {}
}
}
try!(buf.write_i8(tag));
match self.lower() {
Some(bound) => {
let mut inner_buf = MemWriter::new();
try!(bound.value.raw_to_sql(&mut inner_buf));
let inner_buf = inner_buf.unwrap();
try!(buf.write_be_i32(inner_buf.len() as i32));
try!(buf.write(inner_buf[]));
}
None => {}
}
match self.upper() {
Some(bound) => {
let mut inner_buf = MemWriter::new();
try!(bound.value.raw_to_sql(&mut inner_buf));
let inner_buf = inner_buf.unwrap();
try!(buf.write_be_i32(inner_buf.len() as i32));
try!(buf.write(inner_buf[]));
}
None => {}
}
Ok(())
}
}
)
)
macro_rules! to_option_impl(
($($oid:pat)|+, $t:ty $(,$a:meta)*) => (
$(#[$a])*
impl ToSql for Option<$t> {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!($($oid)|+, ty)
match *self {
None => Ok(None),
Some(ref val) => val.to_sql(ty)
}
}
}
)
)
macro_rules! to_option_impl_lifetime(
($($oid:pat)|+, $t:ty) => (
impl<'a> ToSql for Option<$t> {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!($($oid)|+, ty)
match *self {
None => Ok(None),
Some(ref val) => val.to_sql(ty)
}
}
}
)
)
macro_rules! to_raw_to_impl(
($($oid:pat)|+, $t:ty $(, $a:meta)*) => (
$(#[$a])*
impl ToSql for $t {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!($($oid)|+, ty)
let mut writer = MemWriter::new();
try!(self.raw_to_sql(&mut writer));
Ok(Some(writer.unwrap()))
}
}
to_option_impl!($($oid)|+, $t $(, $a)*)
)
)
macro_rules! to_array_impl(
($($oid:pat)|+, $t:ty $(, $a:meta)*) => (
$(#[$a])*
impl ToSql for ArrayBase<Option<$t>> {
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!($($oid)|+, ty)
let mut buf = MemWriter::new();
try!(buf.write_be_i32(self.dimension_info().len() as i32));
try!(buf.write_be_i32(1));
try!(buf.write_be_u32(ty.member_type().to_oid()));
for info in self.dimension_info().iter() {
try!(buf.write_be_i32(info.len as i32));
try!(buf.write_be_i32(info.lower_bound as i32));
}
for v in self.values() {
match *v {
Some(ref val) => {
let mut inner_buf = MemWriter::new();
try!(val.raw_to_sql(&mut inner_buf));
let inner_buf = inner_buf.unwrap();
try!(buf.write_be_i32(inner_buf.len() as i32));
try!(buf.write(inner_buf[]));
}
None => try!(buf.write_be_i32(-1))
}
}
Ok(Some(buf.unwrap()))
}
}
to_option_impl!($($oid)|+, ArrayBase<Option<$t>> $(, $a)*)
)
)
pub mod array;
2013-10-29 05:35:52 +00:00
pub mod range;
2014-11-17 17:43:10 +00:00
#[cfg(feature = "uuid")]
mod uuid;
2013-10-29 05:35:52 +00:00
2013-09-30 02:47:30 +00:00
/// A Postgres OID
2014-01-03 07:10:26 +00:00
pub type Oid = u32;
// Values from pg_type.h
2014-10-10 04:50:40 +00:00
const BOOLOID: Oid = 16;
const BYTEAOID: Oid = 17;
const CHAROID: Oid = 18;
const NAMEOID: Oid = 19;
const INT8OID: Oid = 20;
const INT2OID: Oid = 21;
const INT4OID: Oid = 23;
const TEXTOID: Oid = 25;
const JSONOID: Oid = 114;
const JSONARRAYOID: Oid = 199;
const FLOAT4OID: Oid = 700;
const FLOAT8OID: Oid = 701;
const BOOLARRAYOID: Oid = 1000;
const BYTEAARRAYOID: Oid = 1001;
const CHARARRAYOID: Oid = 1002;
const NAMEARRAYOID: Oid = 1003;
const INT2ARRAYOID: Oid = 1005;
const INT4ARRAYOID: Oid = 1007;
const TEXTARRAYOID: Oid = 1009;
const BPCHARARRAYOID: Oid = 1014;
const VARCHARARRAYOID: Oid = 1015;
const INT8ARRAYOID: Oid = 1016;
const FLOAT4ARRAYOID: Oid = 1021;
const FLAOT8ARRAYOID: Oid = 1022;
const BPCHAROID: Oid = 1042;
const VARCHAROID: Oid = 1043;
const TIMESTAMPOID: Oid = 1114;
const TIMESTAMPARRAYOID: Oid = 1115;
const TIMESTAMPZOID: Oid = 1184;
const TIMESTAMPZARRAYOID: Oid = 1185;
2014-11-06 15:53:16 +00:00
const UUIDOID: Oid = 2950;
const UUIDARRAYOID: Oid = 2951;
2014-10-10 04:50:40 +00:00
const INT4RANGEOID: Oid = 3904;
const INT4RANGEARRAYOID: Oid = 3905;
const TSRANGEOID: Oid = 3908;
const TSRANGEARRAYOID: Oid = 3909;
const TSTZRANGEOID: Oid = 3910;
const TSTZRANGEARRAYOID: Oid = 3911;
const INT8RANGEOID: Oid = 3926;
const INT8RANGEARRAYOID: Oid = 3927;
2014-10-10 04:50:40 +00:00
const USEC_PER_SEC: i64 = 1_000_000;
const NSEC_PER_USEC: i64 = 1_000;
2013-09-08 20:27:15 +00:00
// Number of seconds from 1970-01-01 to 2000-01-01
2014-10-10 04:50:40 +00:00
const TIME_SEC_CONVERSION: i64 = 946684800;
2013-09-08 20:27:15 +00:00
2014-10-10 04:50:40 +00:00
const RANGE_UPPER_UNBOUNDED: i8 = 0b0001_0000;
const RANGE_LOWER_UNBOUNDED: i8 = 0b0000_1000;
const RANGE_UPPER_INCLUSIVE: i8 = 0b0000_0100;
const RANGE_LOWER_INCLUSIVE: i8 = 0b0000_0010;
const RANGE_EMPTY: i8 = 0b0000_0001;
2013-12-08 03:34:48 +00:00
macro_rules! make_postgres_type(
2014-03-29 21:33:11 +00:00
($(#[$doc:meta] $oid:ident => $variant:ident $(member $member:ident)*),+) => (
2013-12-08 03:34:48 +00:00
/// A Postgres type
2014-06-02 02:57:27 +00:00
#[deriving(PartialEq, Eq, Clone, Show)]
2014-11-04 05:29:16 +00:00
pub enum Type {
2013-12-08 03:34:48 +00:00
$(
2014-03-29 21:33:11 +00:00
#[$doc]
2013-12-08 03:34:48 +00:00
$variant,
)+
/// An unknown type
2014-11-04 05:29:16 +00:00
Unknown {
2013-12-08 03:34:48 +00:00
/// The name of the type
2014-11-17 16:56:25 +00:00
name: String,
2013-12-08 03:34:48 +00:00
/// The OID of the type
2014-11-17 16:56:25 +00:00
oid: Oid
2013-12-08 03:34:48 +00:00
}
}
2014-11-04 05:29:16 +00:00
impl Type {
2013-12-08 03:34:48 +00:00
#[doc(hidden)]
2014-11-04 05:29:16 +00:00
pub fn from_oid(oid: Oid) -> Type {
2013-12-08 03:34:48 +00:00
match oid {
2014-11-04 05:29:16 +00:00
$($oid => Type::$variant,)+
2013-12-08 03:34:48 +00:00
// We have to load an empty string now, it'll get filled in later
2014-11-04 05:29:16 +00:00
oid => Type::Unknown { name: String::new(), oid: oid }
2013-12-08 03:34:48 +00:00
}
}
2013-12-08 19:44:37 +00:00
#[doc(hidden)]
pub fn to_oid(&self) -> Oid {
match *self {
2014-11-04 05:29:16 +00:00
$(Type::$variant => $oid,)+
Type::Unknown { oid, .. } => oid
2013-12-08 19:44:37 +00:00
}
}
2014-11-04 05:29:16 +00:00
fn member_type(&self) -> Type {
2013-12-08 19:44:37 +00:00
match *self {
$(
2014-11-04 05:29:16 +00:00
$(Type::$variant => Type::$member,)*
2013-12-08 19:44:37 +00:00
)+
_ => unreachable!()
}
}
}
2013-12-08 03:34:48 +00:00
)
)
make_postgres_type!(
#[doc="BOOL"]
2014-11-04 05:29:16 +00:00
BOOLOID => Bool,
2013-12-08 03:34:48 +00:00
#[doc="BYTEA"]
2014-11-04 05:29:16 +00:00
BYTEAOID => ByteA,
2013-12-08 03:34:48 +00:00
#[doc="\"char\""]
2014-11-04 05:29:16 +00:00
CHAROID => Char,
#[doc="NAME"]
2014-11-04 05:29:16 +00:00
NAMEOID => Name,
2013-12-08 03:34:48 +00:00
#[doc="INT8/BIGINT"]
2014-11-04 05:29:16 +00:00
INT8OID => Int8,
2013-12-08 03:34:48 +00:00
#[doc="INT2/SMALLINT"]
2014-11-04 05:29:16 +00:00
INT2OID => Int2,
2013-12-08 03:34:48 +00:00
#[doc="INT4/INT"]
2014-11-04 05:29:16 +00:00
INT4OID => Int4,
2013-12-08 03:34:48 +00:00
#[doc="TEXT"]
2014-11-04 05:29:16 +00:00
TEXTOID => Text,
2013-12-08 03:34:48 +00:00
#[doc="JSON"]
2014-11-04 05:29:16 +00:00
JSONOID => Json,
2013-12-09 00:00:33 +00:00
#[doc="JSON[]"]
2014-11-04 05:29:16 +00:00
JSONARRAYOID => JsonArray member Json,
2013-12-08 03:34:48 +00:00
#[doc="FLOAT4/REAL"]
2014-11-04 05:29:16 +00:00
FLOAT4OID => Float4,
2013-12-08 03:34:48 +00:00
#[doc="FLOAT8/DOUBLE PRECISION"]
2014-11-04 05:29:16 +00:00
FLOAT8OID => Float8,
2013-12-08 03:34:48 +00:00
#[doc="BOOL[]"]
2014-11-04 05:29:16 +00:00
BOOLARRAYOID => BoolArray member Bool,
2013-12-08 03:34:48 +00:00
#[doc="BYTEA[]"]
2014-11-04 05:29:16 +00:00
BYTEAARRAYOID => ByteAArray member ByteA,
2013-12-08 03:34:48 +00:00
#[doc="\"char\"[]"]
2014-11-04 05:29:16 +00:00
CHARARRAYOID => CharArray member Char,
#[doc="NAME[]"]
2014-11-04 05:29:16 +00:00
NAMEARRAYOID => NameArray member Name,
2013-12-08 03:34:48 +00:00
#[doc="INT2[]"]
2014-11-04 05:29:16 +00:00
INT2ARRAYOID => Int2Array member Int2,
2013-12-08 03:34:48 +00:00
#[doc="INT4[]"]
2014-11-04 05:29:16 +00:00
INT4ARRAYOID => Int4Array member Int4,
2013-12-08 03:34:48 +00:00
#[doc="TEXT[]"]
2014-11-04 05:29:16 +00:00
TEXTARRAYOID => TextArray member Text,
2013-12-08 19:44:37 +00:00
#[doc="CHAR(n)[]"]
2014-11-04 05:29:16 +00:00
BPCHARARRAYOID => CharNArray member CharN,
2013-12-08 21:58:41 +00:00
#[doc="VARCHAR[]"]
2014-11-04 05:29:16 +00:00
VARCHARARRAYOID => VarcharArray member Varchar,
2013-12-08 03:34:48 +00:00
#[doc="INT8[]"]
2014-11-04 05:29:16 +00:00
INT8ARRAYOID => Int8Array member Int8,
2013-12-08 03:34:48 +00:00
#[doc="FLOAT4[]"]
2014-11-04 05:29:16 +00:00
FLOAT4ARRAYOID => Float4Array member Float4,
2013-12-08 03:34:48 +00:00
#[doc="FLOAT8[]"]
2014-11-04 05:29:16 +00:00
FLAOT8ARRAYOID => Float8Array member Float8,
2013-12-08 03:34:48 +00:00
#[doc="TIMESTAMP"]
2014-11-04 05:29:16 +00:00
TIMESTAMPOID => Timestamp,
2013-12-08 22:04:26 +00:00
#[doc="TIMESTAMP[]"]
2014-11-04 05:29:16 +00:00
TIMESTAMPARRAYOID => TimestampArray member Timestamp,
2013-12-08 03:34:48 +00:00
#[doc="TIMESTAMP WITH TIME ZONE"]
2014-11-04 05:29:16 +00:00
TIMESTAMPZOID => TimestampTZ,
2013-12-08 22:08:35 +00:00
#[doc="TIMESTAMP WITH TIME ZONE[]"]
2014-11-04 05:29:16 +00:00
TIMESTAMPZARRAYOID => TimestampTZArray member TimestampTZ,
2014-11-06 15:53:16 +00:00
#[doc="UUID"]
UUIDOID => Uuid,
#[doc="UUID[]"]
UUIDARRAYOID => UuidArray member Uuid,
2013-12-08 03:34:48 +00:00
#[doc="CHAR(n)/CHARACTER(n)"]
2014-11-04 05:29:16 +00:00
BPCHAROID => CharN,
2013-12-08 03:34:48 +00:00
#[doc="VARCHAR/CHARACTER VARYING"]
2014-11-04 05:29:16 +00:00
VARCHAROID => Varchar,
2013-12-08 03:34:48 +00:00
#[doc="INT4RANGE"]
2014-11-04 05:29:16 +00:00
INT4RANGEOID => Int4Range,
2013-12-08 22:37:31 +00:00
#[doc="INT4RANGE[]"]
2014-11-04 05:29:16 +00:00
INT4RANGEARRAYOID => Int4RangeArray member Int4Range,
2013-12-08 03:34:48 +00:00
#[doc="TSRANGE"]
2014-11-04 05:29:16 +00:00
TSRANGEOID => TsRange,
2013-12-08 23:02:38 +00:00
#[doc="TSRANGE[]"]
2014-11-04 05:29:16 +00:00
TSRANGEARRAYOID => TsRangeArray member TsRange,
2013-12-08 03:34:48 +00:00
#[doc="TSTZRANGE"]
2014-11-04 05:29:16 +00:00
TSTZRANGEOID => TstzRange,
2013-12-08 23:02:38 +00:00
#[doc="TSTZRANGE[]"]
2014-11-04 05:29:16 +00:00
TSTZRANGEARRAYOID => TstzRangeArray member TstzRange,
2013-12-08 23:07:11 +00:00
#[doc="INT8RANGE"]
2014-11-04 05:29:16 +00:00
INT8RANGEOID => Int8Range,
2013-12-08 23:07:11 +00:00
#[doc="INT8RANGE[]"]
2014-11-04 05:29:16 +00:00
INT8RANGEARRAYOID => Int8RangeArray member Int8Range
2013-12-08 03:34:48 +00:00
)
2013-09-30 05:22:10 +00:00
/// A trait for types that can be created from a Postgres value
pub trait FromSql {
2013-09-30 02:47:30 +00:00
/// Creates a new value of this type from a buffer of Postgres data.
///
/// If the value was `NULL`, the buffer will be `None`.
2014-11-04 05:29:16 +00:00
fn from_sql(ty: &Type, raw: &Option<Vec<u8>>) -> Result<Self>;
}
#[doc(hidden)]
2013-10-31 02:55:25 +00:00
trait RawFromSql {
2014-11-01 23:12:05 +00:00
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Self>;
2013-10-31 02:55:25 +00:00
}
2013-12-07 23:39:44 +00:00
impl RawFromSql for bool {
2014-11-01 23:12:05 +00:00
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<bool> {
2014-11-17 06:54:57 +00:00
Ok((try!(raw.read_u8())) != 0)
2013-12-07 23:39:44 +00:00
}
}
2014-04-08 03:02:05 +00:00
impl RawFromSql for Vec<u8> {
2014-11-17 17:43:10 +00:00
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<Vec<u8>> {
Ok(try!(raw.read_to_end()))
}
}
2013-12-08 22:37:31 +00:00
2014-11-17 17:43:10 +00:00
impl RawFromSql for String {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<String> {
String::from_utf8(try!(raw.read_to_end())).map_err(|_| PgBadData)
}
}
raw_from_impl!(i8, read_i8)
raw_from_impl!(i16, read_be_i16)
raw_from_impl!(i32, read_be_i32)
raw_from_impl!(i64, read_be_i64)
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> {
let t = try!(raw.read_be_i64());
let mut sec = t / USEC_PER_SEC + TIME_SEC_CONVERSION;
let mut usec = t % USEC_PER_SEC;
if usec < 0 {
sec -= 1;
usec = USEC_PER_SEC + usec;
2013-12-08 22:37:31 +00:00
}
2014-11-17 17:43:10 +00:00
Ok(Timespec::new(sec, (usec * NSEC_PER_USEC) as i32))
}
}
2013-12-08 22:37:31 +00:00
2014-04-23 06:02:56 +00:00
from_range_impl!(i32)
from_range_impl!(i64)
from_range_impl!(Timespec)
2013-12-08 22:37:31 +00:00
2014-11-04 05:29:16 +00:00
impl RawFromSql for json::Json {
fn raw_from_sql<R: Reader>(raw: &mut R) -> Result<json::Json> {
2014-07-07 04:34:27 +00:00
json::from_reader(raw).map_err(|_| PgBadData)
2013-12-09 00:00:33 +00:00
}
}
2014-11-04 05:29:16 +00:00
from_raw_from_impl!(Bool, bool)
from_raw_from_impl!(ByteA, Vec<u8>)
from_raw_from_impl!(Varchar | Text | CharN | Name, String)
from_raw_from_impl!(Char, i8)
from_raw_from_impl!(Int2, i16)
from_raw_from_impl!(Int4, i32)
from_raw_from_impl!(Int8, i64)
from_raw_from_impl!(Float4, f32)
from_raw_from_impl!(Float8, f64)
from_raw_from_impl!(Json, json::Json)
from_raw_from_impl!(Timestamp | TimestampTZ, Timespec)
from_raw_from_impl!(Int4Range, Range<i32>)
from_raw_from_impl!(Int8Range, Range<i64>)
from_raw_from_impl!(TsRange | TstzRange, Range<Timespec>)
2013-10-31 02:55:25 +00:00
2014-11-04 05:29:16 +00:00
from_array_impl!(BoolArray, bool)
from_array_impl!(ByteAArray, Vec<u8>)
from_array_impl!(CharArray, i8)
from_array_impl!(Int2Array, i16)
from_array_impl!(Int4Array, i32)
from_array_impl!(TextArray | CharNArray | VarcharArray | NameArray, String)
from_array_impl!(Int8Array, i64)
from_array_impl!(TimestampArray | TimestampTZArray, Timespec)
from_array_impl!(JsonArray, json::Json)
from_array_impl!(Float4Array, f32)
from_array_impl!(Float8Array, f64)
from_array_impl!(Int4RangeArray, Range<i32>)
from_array_impl!(TsRangeArray | TstzRangeArray, Range<Timespec>)
from_array_impl!(Int8RangeArray, Range<i64>)
2013-12-06 05:58:22 +00:00
2014-05-26 03:38:40 +00:00
impl FromSql for Option<HashMap<String, Option<String>>> {
2014-11-04 05:29:16 +00:00
fn from_sql(ty: &Type, raw: &Option<Vec<u8>>)
2014-11-01 23:12:05 +00:00
-> Result<Option<HashMap<String, Option<String>>>> {
2014-03-13 06:50:10 +00:00
match *ty {
2014-11-04 05:29:16 +00:00
Type::Unknown { ref name, .. } if "hstore" == name[] => {}
2014-03-28 05:43:10 +00:00
_ => return Err(PgWrongType(ty.clone()))
2014-03-13 06:50:10 +00:00
}
2014-03-28 05:43:10 +00:00
match *raw {
Some(ref buf) => {
2014-10-05 03:08:44 +00:00
let mut rdr = BufReader::new(buf[]);
2014-03-28 05:43:10 +00:00
let mut map = HashMap::new();
2013-12-05 05:20:48 +00:00
2014-11-17 06:54:57 +00:00
let count = try!(rdr.read_be_i32());
2013-12-05 05:20:48 +00:00
2014-03-28 05:43:10 +00:00
for _ in range(0, count) {
2014-11-17 06:54:57 +00:00
let key_len = try!(rdr.read_be_i32());
let key = try!(rdr.read_exact(key_len as uint));
2014-07-07 04:34:27 +00:00
let key = match String::from_utf8(key) {
Ok(key) => key,
Err(_) => return Err(PgBadData),
};
2014-03-13 06:50:10 +00:00
2014-11-17 06:54:57 +00:00
let val_len = try!(rdr.read_be_i32());
2014-03-28 05:43:10 +00:00
let val = if val_len < 0 {
None
} else {
2014-11-17 06:54:57 +00:00
let val = try!(rdr.read_exact(val_len as uint));
2014-07-07 04:34:27 +00:00
match String::from_utf8(val) {
Ok(val) => Some(val),
Err(_) => return Err(PgBadData),
}
2014-03-28 05:43:10 +00:00
};
2013-12-05 05:20:48 +00:00
2014-03-28 05:43:10 +00:00
map.insert(key, val);
}
Ok(Some(map))
2014-03-13 06:50:10 +00:00
}
2014-03-28 05:43:10 +00:00
None => Ok(None)
}
2013-12-05 05:20:48 +00:00
}
2014-03-13 06:50:10 +00:00
}
2013-12-05 05:20:48 +00:00
2014-05-26 03:38:40 +00:00
impl FromSql for HashMap<String, Option<String>> {
2014-11-04 05:29:16 +00:00
fn from_sql(ty: &Type, raw: &Option<Vec<u8>>)
2014-11-01 23:12:05 +00:00
-> Result<HashMap<String, Option<String>>> {
2014-03-13 06:50:10 +00:00
// FIXME when you can specify Self types properly
2014-11-01 23:12:05 +00:00
let ret: Result<Option<HashMap<String, Option<String>>>> =
2014-04-26 22:07:40 +00:00
FromSql::from_sql(ty, raw);
2014-03-30 02:01:23 +00:00
match ret {
Ok(Some(val)) => Ok(val),
Ok(None) => Err(PgWasNull),
Err(err) => Err(err)
}
2014-03-13 06:50:10 +00:00
}
}
2013-12-05 05:20:48 +00:00
2013-09-30 02:47:30 +00:00
/// A trait for types that can be converted into Postgres values
pub trait ToSql {
/// Converts the value of `self` into the binary format appropriate for the
/// Postgres backend.
2014-11-04 05:29:16 +00:00
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>>;
}
#[doc(hidden)]
trait RawToSql {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()>;
2013-10-31 02:55:25 +00:00
}
2013-12-07 23:39:44 +00:00
impl RawToSql for bool {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
2014-11-17 06:54:57 +00:00
Ok(try!(w.write_u8(*self as u8)))
2013-12-07 23:39:44 +00:00
}
}
2014-03-15 06:01:46 +00:00
impl RawToSql for Vec<u8> {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
2014-11-17 06:54:57 +00:00
Ok(try!(w.write(self[])))
2014-03-15 06:01:46 +00:00
}
}
2014-05-26 03:38:40 +00:00
impl RawToSql for String {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
2014-11-17 06:54:57 +00:00
Ok(try!(w.write(self.as_bytes())))
2013-12-08 03:13:21 +00:00
}
}
2013-12-08 02:49:55 +00:00
raw_to_impl!(i8, write_i8)
2013-12-08 02:58:40 +00:00
raw_to_impl!(i16, write_be_i16)
2013-10-31 02:55:25 +00:00
raw_to_impl!(i32, write_be_i32)
raw_to_impl!(i64, write_be_i64)
2013-12-06 05:51:09 +00:00
raw_to_impl!(f32, write_be_f32)
2013-12-06 05:58:22 +00:00
raw_to_impl!(f64, write_be_f64)
2013-10-31 02:55:25 +00:00
impl RawToSql for Timespec {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, w: &mut W) -> Result<()> {
2014-08-15 06:05:11 +00:00
let t = (self.sec - TIME_SEC_CONVERSION) * USEC_PER_SEC + self.nsec as i64 / NSEC_PER_USEC;
2014-11-17 06:54:57 +00:00
Ok(try!(w.write_be_i64(t)))
2013-10-31 02:55:25 +00:00
}
}
2014-04-23 06:02:56 +00:00
to_range_impl!(i32)
to_range_impl!(i64)
to_range_impl!(Timespec)
2013-12-08 22:37:31 +00:00
2014-11-04 05:29:16 +00:00
impl RawToSql for json::Json {
2014-11-01 23:12:05 +00:00
fn raw_to_sql<W: Writer>(&self, raw: &mut W) -> Result<()> {
2014-11-17 06:54:57 +00:00
Ok(try!(self.to_writer(raw as &mut Writer)))
2013-12-09 00:00:33 +00:00
}
}
2014-11-04 05:29:16 +00:00
to_raw_to_impl!(Bool, bool)
to_raw_to_impl!(ByteA, Vec<u8>)
to_raw_to_impl!(Varchar | Text | CharN | Name, String)
to_raw_to_impl!(Json, json::Json)
to_raw_to_impl!(Char, i8)
to_raw_to_impl!(Int2, i16)
to_raw_to_impl!(Int4, i32)
to_raw_to_impl!(Int8, i64)
to_raw_to_impl!(Float4, f32)
to_raw_to_impl!(Float8, f64)
to_raw_to_impl!(Int4Range, Range<i32>)
to_raw_to_impl!(Int8Range, Range<i64>)
to_raw_to_impl!(TsRange | TstzRange, Range<Timespec>)
2013-10-31 02:55:25 +00:00
impl<'a> ToSql for &'a str {
2014-11-04 05:29:16 +00:00
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!(Varchar | Text | CharN | Name, ty)
Ok(Some(self.as_bytes().to_vec()))
}
}
2014-11-04 05:29:16 +00:00
to_option_impl_lifetime!(Varchar | Text | CharN | Name, &'a str)
impl<'a> ToSql for &'a [u8] {
2014-11-04 05:29:16 +00:00
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
check_types!(ByteA, ty)
Ok(Some(self.to_vec()))
}
}
2014-11-04 05:29:16 +00:00
to_option_impl_lifetime!(ByteA, &'a [u8])
2014-11-04 05:29:16 +00:00
to_raw_to_impl!(Timestamp | TimestampTZ, Timespec)
2014-11-04 05:29:16 +00:00
to_array_impl!(BoolArray, bool)
to_array_impl!(ByteAArray, Vec<u8>)
to_array_impl!(CharArray, i8)
to_array_impl!(Int2Array, i16)
to_array_impl!(Int4Array, i32)
to_array_impl!(Int8Array, i64)
to_array_impl!(TextArray | CharNArray | VarcharArray | NameArray, String)
to_array_impl!(TimestampArray | TimestampTZArray, Timespec)
to_array_impl!(Float4Array, f32)
to_array_impl!(Float8Array, f64)
to_array_impl!(Int4RangeArray, Range<i32>)
to_array_impl!(TsRangeArray | TstzRangeArray, Range<Timespec>)
to_array_impl!(Int8RangeArray, Range<i64>)
to_array_impl!(JsonArray, json::Json)
2013-12-06 05:58:22 +00:00
2014-05-26 03:38:40 +00:00
impl ToSql for HashMap<String, Option<String>> {
2014-11-04 05:29:16 +00:00
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
2014-03-13 06:50:10 +00:00
match *ty {
2014-11-04 05:29:16 +00:00
Type::Unknown { ref name, .. } if "hstore" == name[] => {}
2014-03-28 05:43:10 +00:00
_ => return Err(PgWrongType(ty.clone()))
2014-03-13 06:50:10 +00:00
}
2013-12-05 05:20:48 +00:00
let mut buf = MemWriter::new();
2014-11-17 06:54:57 +00:00
try!(buf.write_be_i32(self.len() as i32));
2013-12-05 05:20:48 +00:00
for (key, val) in self.iter() {
2014-11-17 06:54:57 +00:00
try!(buf.write_be_i32(key.len() as i32));
try!(buf.write(key.as_bytes()));
2013-12-05 05:20:48 +00:00
match *val {
Some(ref val) => {
2014-11-17 06:54:57 +00:00
try!(buf.write_be_i32(val.len() as i32));
try!(buf.write(val.as_bytes()));
2013-12-05 05:20:48 +00:00
}
2014-11-17 06:54:57 +00:00
None => try!(buf.write_be_i32(-1))
2013-12-05 05:20:48 +00:00
}
}
Ok(Some(buf.unwrap()))
2013-12-05 05:20:48 +00:00
}
}
2014-03-13 06:50:10 +00:00
2014-05-26 03:38:40 +00:00
impl ToSql for Option<HashMap<String, Option<String>>> {
2014-11-04 05:29:16 +00:00
fn to_sql(&self, ty: &Type) -> Result<Option<Vec<u8>>> {
2014-03-13 06:50:10 +00:00
match *ty {
2014-11-04 05:29:16 +00:00
Type::Unknown { ref name, .. } if "hstore" == name[] => {}
2014-03-28 05:43:10 +00:00
_ => return Err(PgWrongType(ty.clone()))
2014-03-13 06:50:10 +00:00
}
match *self {
Some(ref inner) => inner.to_sql(ty),
None => Ok(None)
2014-03-13 06:50:10 +00:00
}
}
}