diff --git a/src/lib.rs b/src/lib.rs index 9dc00d04..90436362 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -565,6 +565,12 @@ impl<'self> PostgresStatement<'self> { Ok(result) } + + pub fn find_col_named(&self, col: &str) -> Option { + do self.result_desc.iter().position |desc| { + desc.name.as_slice() == col + } + } } pub struct PostgresResult<'self> { @@ -660,4 +666,12 @@ impl<'self> PostgresRow<'self> { FromSql::from_sql(self.stmt.result_desc[idx].type_oid, &self.data[idx]) } + + pub fn get_named(&self, col: &str) -> T { + let idx = match self.stmt.find_col_named(col) { + Some(idx) => idx, + None => fail!("No column with name %s", col) + }; + self.get(idx) + } } diff --git a/src/test.rs b/src/test.rs index 98d7dd3b..00bf5b24 100644 --- a/src/test.rs +++ b/src/test.rs @@ -121,7 +121,7 @@ fn test_bool_params() { #[test] fn test_i8_params() { - test_type("\"char\"", [Some(0i8), Some(127i8), None]); + test_type("\"char\"", [Some(-100i8), Some(127i8), None]); } #[test] @@ -257,6 +257,36 @@ fn test_wrong_param_type() { } } +#[test] +fn test_find_col_named() { + do test_in_transaction |trans| { + trans.update("CREATE TABLE foo ( + id SERIAL PRIMARY KEY, + val BOOL + )", []); + let stmt = trans.prepare("SELECT id as my_id, val FROM foo"); + assert_eq!(Some(0), stmt.find_col_named("my_id")); + assert_eq!(Some(1), stmt.find_col_named("val")); + assert_eq!(None, stmt.find_col_named("asdf")); + } +} + +#[test] +fn test_find_get_named() { + do test_in_transaction |trans| { + trans.update("CREATE TABLE foo ( + id SERIAL PRIMARY KEY, + val INT + )", []); + trans.update("INSERT INTO foo (val) VALUES (10)", []); + let stmt = trans.prepare("SELECT id, val FROM foo"); + let result = stmt.query([]); + + assert_eq!(~[10i32], + result.map(|row| { row.get_named("val") }).collect()); + } +} + #[test] fn test_plaintext_pass() { PostgresConnection::connect("postgres://pass_user:password@127.0.0.1:5432");