Add a Row struct

This commit is contained in:
Steven Fackler
2016-12-22 15:30:03 -05:00
parent 361c7bf395
commit 8b1034ad4e
2 changed files with 110 additions and 44 deletions

View File

@@ -6,8 +6,11 @@ extern crate phf;
extern crate postgres_protocol;
use fallible_iterator::{FallibleIterator, FromFallibleIterator};
use std::ascii::AsciiExt;
use std::ops::Range;
use types::Type;
pub mod error;
pub mod params;
pub mod types;
@@ -54,3 +57,67 @@ impl RowData {
}
}
}
pub struct Column {
name: String,
type_: Type,
}
impl Column {
#[doc(hidden)]
pub fn new(name: String, type_: Type) -> Column {
Column {
name: name,
type_: type_,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn type_(&self) -> &Type {
&self.type_
}
}
/// A trait implemented by types that can index into columns of a row.
pub trait RowIndex {
/// Returns the index of the appropriate column, or `None` if no such
/// column exists.
fn idx(&self, stmt: &[Column]) -> Option<usize>;
}
impl RowIndex for usize {
#[inline]
fn idx(&self, stmt: &[Column]) -> Option<usize> {
if *self >= stmt.len() {
None
} else {
Some(*self)
}
}
}
impl<'a> RowIndex for str {
#[inline]
fn idx(&self, stmt: &[Column]) -> Option<usize> {
if let Some(idx) = stmt.iter().position(|d| d.name() == self) {
return Some(idx);
};
// FIXME ASCII-only case insensitivity isn't really the right thing to
// do. Postgres itself uses a dubious wrapper around tolower and JDBC
// uses the US locale.
stmt.iter().position(|d| d.name().eq_ignore_ascii_case(self))
}
}
impl<'a, T> RowIndex for &'a T
where T: RowIndex
{
#[inline]
fn idx(&self, columns: &[Column]) -> Option<usize> {
T::idx(*self, columns)
}
}