Skip to content

Commit f56c519

Browse files
committed
Boolean parameters transmitted as binary
Work towards #7.
1 parent ace9ffc commit f56c519

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/test.rs

+24
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,30 @@ fn test_nulls() {
6868
};
6969
}
7070
71+
#[test]
72+
fn test_binary_bool_params() {
73+
let conn = PostgresConnection::connect("postgres://[email protected]:5432");
74+
75+
do conn.in_transaction |trans| {
76+
trans.prepare("CREATE TABLE foo (
77+
id BIGINT PRIMARY KEY,
78+
b BOOL
79+
)").update([]);
80+
trans.prepare("INSERT INTO foo (id, b) VALUES
81+
($1, $2), ($3, $4), ($5, $6)")
82+
.update([&1 as &ToSql, &true as &ToSql,
83+
&2 as &ToSql, &false as &ToSql,
84+
&3 as &ToSql, &None::<bool> as &ToSql]);
85+
let stmt = trans.prepare("SELECT b FROM foo ORDER BY id");
86+
let result = stmt.query([]);
87+
88+
assert_eq!(~[Some(true), Some(false), None],
89+
result.iter().map(|row| { row[0] }).collect());
90+
91+
trans.set_rollback();
92+
}
93+
}
94+
7195
#[test]
7296
fn test_wrong_num_params() {
7397
let conn = PostgresConnection::connect("postgres://[email protected]:5432");

src/types.rs

+31
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ use std::str;
22

33
pub type Oid = i32;
44

5+
// Values from pg_type.h
6+
static BOOLOID: Oid = 16;
7+
58
pub enum Format {
69
Text = 0,
710
Binary = 1
@@ -39,6 +42,23 @@ macro_rules! from_option_impl(
3942
)
4043
)
4144

45+
impl FromSql for Option<bool> {
46+
fn from_sql(raw: &Option<~[u8]>) -> Option<bool> {
47+
match *raw {
48+
None => None,
49+
Some(ref buf) => {
50+
assert_eq!(1, buf.len());
51+
match buf[0] as char {
52+
't' => Some(true),
53+
'f' => Some(false),
54+
byte => fail!("Invalid byte: %?", byte)
55+
}
56+
}
57+
}
58+
}
59+
}
60+
from_option_impl!(bool)
61+
4262
from_str_impl!(int)
4363
from_option_impl!(int)
4464
from_str_impl!(i8)
@@ -102,6 +122,17 @@ macro_rules! to_option_impl(
102122
)
103123
)
104124

125+
impl ToSql for bool {
126+
fn to_sql(&self, ty: Oid) -> (Format, Option<~[u8]>) {
127+
if ty == BOOLOID {
128+
(Binary, Some(~[*self as u8]))
129+
} else {
130+
(Text, Some(self.to_str().into_bytes()))
131+
}
132+
}
133+
}
134+
to_option_impl!(bool)
135+
105136
to_str_impl!(int)
106137
to_option_impl!(int)
107138
to_str_impl!(i8)

0 commit comments

Comments
 (0)