coven_foundation/column_names.rs
1//! Coven stores some values in its tables and views as names, such as a
2//! member's role in `coven_members.role`. Each value has one name. Coven
3//! writes and reads that name, and the app reads it from the column or
4//! parses it from a JSON array of the column's values (api.md E4).
5
6/// The SQL value conversions [`column_names!`](crate::column_names!)
7/// implements. The macro names them through this crate, so a crate that
8/// calls it needs no rusqlite dependency of its own.
9#[doc(hidden)]
10pub mod sql {
11 pub use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
12 pub use rusqlite::{Result, ToSql};
13}
14
15/// Text that names none of a type's values.
16#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
17#[error("`{text}` names no {kind}")]
18pub struct UnknownName {
19 /// The kind of value coven tried to parse the text as, such as
20 /// "member role".
21 pub kind: &'static str,
22 /// The text.
23 pub text: String,
24}
25
26/// Give the enum `$type`, whose values are `Copy`, the name each value has
27/// in coven's columns: `name()` gives it, `FromStr` reads it, and `ToSql`
28/// and `FromSql` bind and read it as SQL text. `$kind` names the kind of
29/// value, such as "member role", that `UnknownName` reports when `FromStr`
30/// finds no value with the text's name.
31#[macro_export]
32macro_rules! column_names {
33 ($type:ty, $kind:literal, { $($value:ident => $name:literal),+ $(,)? }) => {
34 impl $type {
35 /// The name coven's columns hold for this value.
36 pub fn name(self) -> &'static str {
37 match self {
38 $(Self::$value => $name,)+
39 }
40 }
41 }
42
43 impl ::std::str::FromStr for $type {
44 type Err = $crate::column_names::UnknownName;
45 fn from_str(text: &str) -> Result<Self, Self::Err> {
46 match text {
47 $($name => Ok(Self::$value),)+
48 _ => Err($crate::column_names::UnknownName {
49 kind: $kind,
50 text: text.to_owned(),
51 }),
52 }
53 }
54 }
55
56 const _: () = {
57 use $crate::column_names::sql::{
58 FromSql, FromSqlError, FromSqlResult, Result, ToSql, ToSqlOutput, ValueRef,
59 };
60
61 impl ToSql for $type {
62 fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
63 Ok(ToSqlOutput::Borrowed(ValueRef::Text(self.name().as_bytes())))
64 }
65 }
66
67 impl FromSql for $type {
68 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
69 value.as_str()?.parse().map_err(|error| FromSqlError::Other(Box::new(error)))
70 }
71 }
72 };
73 };
74}
75
76#[cfg(test)]
77#[path = "column_names_tests.rs"]
78mod tests;