use std::{fmt, str::FromStr};
#[cfg(feature = "rusqlite")]
use rusqlite::{
ToSql,
types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef}
};
use crate::{StrVal, err::Error};
#[derive(Debug, Clone)]
pub struct Select<E> {
sval: String,
val: E
}
impl<E> Default for Select<E>
where
E: Default + std::fmt::Display
{
fn default() -> Self {
let val = E::default();
let sval = val.to_string();
Self { sval, val }
}
}
impl<E> StrVal for Select<E>
where
E: Copy + Clone + FromStr
{
type Type = E;
fn set(&mut self, sval: &str) -> Result<Self::Type, Error> {
let dv = sval.parse::<Self>()?;
self.sval = sval.to_string();
self.val = dv.val;
Ok(dv.val)
}
fn get(&self) -> Self::Type {
self.val
}
fn val_str(&self) -> Option<String> {
None
}
fn get_str_vals(&self) -> (String, Option<String>) {
(self.sval.clone(), None)
}
}
impl<E> AsRef<str> for Select<E> {
fn as_ref(&self) -> &str {
&self.sval
}
}
impl<E> fmt::Display for Select<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.sval)
}
}
impl<E> FromStr for Select<E>
where
E: FromStr
{
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let v = s
.parse::<E>()
.map_err(|_| Error::Invalid("Unknown variant".into()))?;
Ok(Self {
sval: s.to_string(),
val: v
})
}
}
#[cfg(feature = "rusqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusqlite")))]
impl<E> ToSql for Select<E> {
fn to_sql(&self) -> Result<ToSqlOutput<'_>, rusqlite::Error> {
self.sval.to_sql()
}
}
#[cfg(feature = "rusqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusqlite")))]
impl<E> FromSql for Select<E>
where
E: FromStr
{
#[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let s = String::column_result(value)?;
s.parse::<Self>()
.map_err(|e| FromSqlError::Other(Box::new(e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use strum::{Display, EnumString};
#[cfg(feature = "rusqlite")]
use rusqlite::{Connection, params};
#[derive(Copy, Clone, Debug, Default, PartialEq, Display, EnumString)]
enum MyEnum {
#[default]
#[strum(serialize = "variant1")]
Variant1,
#[strum(serialize = "variant2")]
Variant2
}
#[test]
fn default() {
let eval = Select::<MyEnum>::default();
assert_eq!(eval.as_ref(), "variant1");
assert_eq!(eval.get(), MyEnum::Variant1);
}
#[test]
fn fromstr() {
let eval = "variant2".parse::<Select<MyEnum>>().unwrap();
assert_eq!(eval.as_ref(), "variant2");
assert_eq!(eval.get(), MyEnum::Variant2);
}
#[test]
#[should_panic(expected = "Invalid(\"Unknown variant\")")]
fn bad_variant() {
let _eval = "nonexistent".parse::<Select<MyEnum>>().unwrap();
}
#[cfg(feature = "rusqlite")]
fn memdb() -> Result<Connection, rusqlite::Error> {
let conn = Connection::open_in_memory()?;
conn.execute_batch(
"CREATE TABLE tbl (id INTEGER PRIMARY KEY, txtval TEXT)"
)?;
Ok(conn)
}
#[cfg(feature = "rusqlite")]
#[test]
#[should_panic(expected = "FromSqlConversionFailure(0, Text, \
Invalid(\"Unknown variant\"))")]
fn bad_query() {
let conn = memdb().unwrap();
conn
.execute(
"INSERT INTO tbl (id, txtval) VALUES (?, ?);",
params![1, "invalidselection"]
)
.unwrap();
let mut stmt = conn.prepare("SELECT txtval FROM tbl WHERE id=?;").unwrap();
let _v: Select<MyEnum> = stmt.query_one([1], |row| row.get(0)).unwrap();
}
}