Skip to content

Commit 8ab3c1d

Browse files
committed
Add column name to index lookup
1 parent 5714667 commit 8ab3c1d

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

src/lib.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,12 @@ impl<'self> PostgresStatement<'self> {
565565
566566
Ok(result)
567567
}
568+
569+
pub fn find_col_named(&self, col: &str) -> Option<uint> {
570+
do self.result_desc.iter().position |desc| {
571+
desc.name.as_slice() == col
572+
}
573+
}
568574
}
569575
570576
pub struct PostgresResult<'self> {
@@ -660,4 +666,12 @@ impl<'self> PostgresRow<'self> {
660666
FromSql::from_sql(self.stmt.result_desc[idx].type_oid,
661667
&self.data[idx])
662668
}
669+
670+
pub fn get_named<T: FromSql>(&self, col: &str) -> T {
671+
let idx = match self.stmt.find_col_named(col) {
672+
Some(idx) => idx,
673+
None => fail!("No column with name %s", col)
674+
};
675+
self.get(idx)
676+
}
663677
}

src/test.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ fn test_bool_params() {
121121
122122
#[test]
123123
fn test_i8_params() {
124-
test_type("\"char\"", [Some(0i8), Some(127i8), None]);
124+
test_type("\"char\"", [Some(-100i8), Some(127i8), None]);
125125
}
126126

127127
#[test]
@@ -257,6 +257,36 @@ fn test_wrong_param_type() {
257257
}
258258
}
259259
260+
#[test]
261+
fn test_find_col_named() {
262+
do test_in_transaction |trans| {
263+
trans.update("CREATE TABLE foo (
264+
id SERIAL PRIMARY KEY,
265+
val BOOL
266+
)", []);
267+
let stmt = trans.prepare("SELECT id as my_id, val FROM foo");
268+
assert_eq!(Some(0), stmt.find_col_named("my_id"));
269+
assert_eq!(Some(1), stmt.find_col_named("val"));
270+
assert_eq!(None, stmt.find_col_named("asdf"));
271+
}
272+
}
273+
274+
#[test]
275+
fn test_find_get_named() {
276+
do test_in_transaction |trans| {
277+
trans.update("CREATE TABLE foo (
278+
id SERIAL PRIMARY KEY,
279+
val INT
280+
)", []);
281+
trans.update("INSERT INTO foo (val) VALUES (10)", []);
282+
let stmt = trans.prepare("SELECT id, val FROM foo");
283+
let result = stmt.query([]);
284+
285+
assert_eq!(~[10i32],
286+
result.map(|row| { row.get_named("val") }).collect());
287+
}
288+
}
289+
260290
#[test]
261291
fn test_plaintext_pass() {
262292
PostgresConnection::connect("postgres://pass_user:password@127.0.0.1:5432");

0 commit comments

Comments
 (0)