feat(core): add ColumnIndex

This commit is contained in:
Ryan Leckey 2021-02-22 21:22:04 -08:00
parent 6099468c7d
commit 3470195839
No known key found for this signature in database
GPG Key ID: F8AA68C235AB08C9
2 changed files with 38 additions and 7 deletions

View File

@ -70,7 +70,7 @@ pub use isolation_level::IsolationLevel;
pub use options::ConnectOptions;
pub use query_result::QueryResult;
pub use r#type::{Type, TypeDecode, TypeEncode};
pub use row::Row;
pub use row::{ColumnIndex, Row};
#[cfg(feature = "actix")]
pub use runtime::Actix;
#[cfg(feature = "async")]

View File

@ -1,6 +1,7 @@
use crate::database::HasRawValue;
use crate::{Database, Decode};
/// A single row from a result set generated from the database.
pub trait Row: 'static + Send + Sync {
type Database: Database;
@ -31,18 +32,48 @@ pub trait Row: 'static + Send + Sync {
fn try_ordinal_of(&self, name: &str) -> crate::Result<usize>;
/// Returns the decoded value at the index.
fn try_get<'r, T>(&'r self, index: usize) -> crate::Result<T>
fn try_get<'r, T, I>(&'r self, index: I) -> crate::Result<T>
where
I: ColumnIndex<Self>,
T: Decode<'r, Self::Database>;
/// Returns the raw representation of the value at the index.
#[allow(clippy::needless_lifetimes)]
fn try_get_raw<'r>(
fn try_get_raw<'r, I: ColumnIndex<Self>>(
&'r self,
index: usize,
index: I,
) -> crate::Result<<Self::Database as HasRawValue<'r>>::RawValue>;
}
// TODO: fn type_info_of(index)
// TODO: fn try_type_info_of(index)
// TODO: trait ColumnIndex
/// A helper trait used for indexing into a [`Row`].
pub trait ColumnIndex<R: Row + ?Sized> {
/// Returns the ordinal of the column at this index, if present.
#[allow(clippy::needless_lifetimes)]
fn get<'r>(&self, row: &'r R) -> crate::Result<usize>;
}
// access an ordinal by index
impl<R: Row> ColumnIndex<R> for usize {
#[allow(clippy::needless_lifetimes)]
fn get<'r>(&self, _row: &'r R) -> crate::Result<usize> {
// note: the "index out of bounds" error will be surfaced
// by [try_get]
Ok(*self)
}
}
// access an ordinal by name
impl<R: Row> ColumnIndex<R> for &'_ str {
#[allow(clippy::needless_lifetimes)]
fn get<'r>(&self, row: &'r R) -> crate::Result<usize> {
row.try_ordinal_of(self)
}
}
// access by reference
impl<R: Row, I: ColumnIndex<R>> ColumnIndex<R> for &'_ I {
#[allow(clippy::needless_lifetimes)]
fn get<'r>(&self, row: &'r R) -> crate::Result<usize> {
(*self).get(row)
}
}