Add column name to index lookup

This commit is contained in:
Steven Fackler
2013-09-02 20:07:08 -04:00
parent 57146672ab
commit 8ab3c1d04b
2 changed files with 45 additions and 1 deletions

View File

@@ -565,6 +565,12 @@ impl<'self> PostgresStatement<'self> {
Ok(result)
}
pub fn find_col_named(&self, col: &str) -> Option<uint> {
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<T: FromSql>(&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)
}
}

View File

@@ -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");