Skip to main content

grow_core/
lib.rs

1use std::fmt::Display;
2
3/// Represents a SQL value that can be used across different database drivers
4#[derive(Debug, Clone, PartialEq)]
5pub enum SqlValue {
6    Integer(i64),
7    Float(f64),
8    Text(String),
9    Boolean(bool),
10    Null,
11}
12
13impl SqlValue {
14    /// Creates a new Text variant from a string
15    pub fn text<T: Into<String>>(value: T) -> Self {
16        SqlValue::Text(value.into())
17    }
18
19    /// Creates a new Integer variant
20    pub fn integer(value: i64) -> Self {
21        SqlValue::Integer(value)
22    }
23
24    /// Creates a new Float variant
25    pub fn float(value: f64) -> Self {
26        SqlValue::Float(value)
27    }
28
29    /// Creates a new Boolean variant
30    pub fn boolean(value: bool) -> Self {
31        SqlValue::Boolean(value)
32    }
33
34    /// Creates a Null variant
35    pub fn null() -> Self {
36        SqlValue::Null
37    }
38
39    /// Returns true if the value is NULL
40    pub fn is_null(&self) -> bool {
41        matches!(self, SqlValue::Null)
42    }
43
44    /// Returns the type name as a string
45    pub fn type_name(&self) -> &'static str {
46        match self {
47            SqlValue::Integer(_) => "INTEGER",
48            SqlValue::Float(_) => "REAL",
49            SqlValue::Text(_) => "TEXT",
50            SqlValue::Boolean(_) => "BOOLEAN",
51            SqlValue::Null => "NULL",
52        }
53    }
54}
55
56impl Display for SqlValue {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            SqlValue::Integer(i) => write!(f, "{}", i),
60            SqlValue::Float(fl) => write!(f, "{}", fl),
61            SqlValue::Text(s) => write!(f, "{}", s),
62            SqlValue::Boolean(b) => write!(f, "{}", b),
63            SqlValue::Null => write!(f, "NULL"),
64        }
65    }
66}
67
68impl From<i64> for SqlValue {
69    fn from(value: i64) -> Self {
70        SqlValue::Integer(value)
71    }
72}
73
74impl From<f64> for SqlValue {
75    fn from(value: f64) -> Self {
76        SqlValue::Float(value)
77    }
78}
79
80impl From<String> for SqlValue {
81    fn from(value: String) -> Self {
82        SqlValue::Text(value)
83    }
84}
85
86impl From<&str> for SqlValue {
87    fn from(value: &str) -> Self {
88        SqlValue::Text(value.to_string())
89    }
90}
91
92impl From<bool> for SqlValue {
93    fn from(value: bool) -> Self {
94        SqlValue::Boolean(value)
95    }
96}
97
98impl<T> From<Option<T>> for SqlValue
99where
100    T: Into<SqlValue>,
101{
102    fn from(value: Option<T>) -> Self {
103        match value {
104            Some(v) => v.into(),
105            None => SqlValue::Null,
106        }
107    }
108}