Skip to main content

sea_orm_relations_kit/
key.rs

1//! Keys: the value that links a row to its owner, in a form that can be hashed and
2//! compared whatever integer width or string type each table uses for it.
3
4use sea_orm::{
5    sea_query::ColumnType, ColumnTrait, DbErr, EntityName, EntityTrait, Iterable, ModelTrait,
6    PrimaryKeyToColumn, QueryResult, Value,
7};
8
9/// A primary key value, normalized.
10///
11/// `posts.id` may be `INTEGER` while `comments.commentable_id` is `BIGINT` or even
12/// `VARCHAR`; all three hold the same key. `Key` lets the crate match them up and
13/// write a key into any of those columns.
14#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
15pub enum Key {
16    /// Any integer key.
17    Int(i64),
18    /// A string key, such as a UUID or a slug.
19    Text(String),
20}
21
22impl Key {
23    /// The primary key of `model`.
24    ///
25    /// # Panics
26    ///
27    /// If the entity has a composite primary key; relations here link single keys.
28    #[must_use]
29    pub fn of<M: ModelTrait>(model: &M) -> Option<Self> {
30        Self::from_value(&model.get(primary_column::<M::Entity>()))
31    }
32
33    /// The key a column value holds, or `None` for `NULL` and types that are not keys.
34    ///
35    /// A string holding a canonical integer (`"15"`, not `"015"`) becomes
36    /// [`Key::Int`], so a `VARCHAR` morph column matches an integer primary key.
37    #[must_use]
38    pub fn from_value(value: &Value) -> Option<Self> {
39        match value {
40            Value::TinyInt(Some(v)) => Some(Self::Int(i64::from(*v))),
41            Value::SmallInt(Some(v)) => Some(Self::Int(i64::from(*v))),
42            Value::Int(Some(v)) => Some(Self::Int(i64::from(*v))),
43            Value::BigInt(Some(v)) => Some(Self::Int(*v)),
44            Value::TinyUnsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
45            Value::SmallUnsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
46            Value::Unsigned(Some(v)) => Some(Self::Int(i64::from(*v))),
47            Value::BigUnsigned(Some(v)) => i64::try_from(*v).ok().map(Self::Int),
48            Value::String(Some(v)) => Some(Self::from_text(v.clone())),
49            Value::Char(Some(v)) => Some(Self::from_text(v.to_string())),
50            #[cfg(feature = "with-uuid")]
51            Value::Uuid(Some(v)) => Some(Self::Text(v.to_string())),
52            _ => None,
53        }
54    }
55
56    fn from_text(text: String) -> Self {
57        match text.parse::<i64>() {
58            Ok(number) if number.to_string() == text => Self::Int(number),
59            _ => Self::Text(text),
60        }
61    }
62
63    /// This key as a value of the type `column` stores, ready to be written to it
64    /// or compared with it.
65    ///
66    /// # Errors
67    ///
68    /// When the key does not fit: a negative key in an unsigned column, a word in an
69    /// integer column, a non-UUID in a UUID column.
70    pub fn to_value_for<C: ColumnTrait>(&self, column: C) -> Result<Value, DbErr> {
71        let column_type = column.def().get_column_type().clone();
72        let mismatch = || {
73            DbErr::Type(format!(
74                "the key {self} does not fit the {column_type:?} column {}",
75                column.as_str()
76            ))
77        };
78        let value = match (self, &column_type) {
79            (Self::Int(v), ColumnType::TinyInteger) => {
80                Value::TinyInt(Some(i8::try_from(*v).map_err(|_| mismatch())?))
81            }
82            (Self::Int(v), ColumnType::SmallInteger) => {
83                Value::SmallInt(Some(i16::try_from(*v).map_err(|_| mismatch())?))
84            }
85            (Self::Int(v), ColumnType::Integer) => {
86                Value::Int(Some(i32::try_from(*v).map_err(|_| mismatch())?))
87            }
88            (Self::Int(v), ColumnType::BigInteger) => Value::BigInt(Some(*v)),
89            (Self::Int(v), ColumnType::TinyUnsigned) => {
90                Value::TinyUnsigned(Some(u8::try_from(*v).map_err(|_| mismatch())?))
91            }
92            (Self::Int(v), ColumnType::SmallUnsigned) => {
93                Value::SmallUnsigned(Some(u16::try_from(*v).map_err(|_| mismatch())?))
94            }
95            (Self::Int(v), ColumnType::Unsigned) => {
96                Value::Unsigned(Some(u32::try_from(*v).map_err(|_| mismatch())?))
97            }
98            (Self::Int(v), ColumnType::BigUnsigned) => {
99                Value::BigUnsigned(Some(u64::try_from(*v).map_err(|_| mismatch())?))
100            }
101            (_, ColumnType::String(_) | ColumnType::Text | ColumnType::Char(_)) => {
102                Value::String(Some(self.to_string()))
103            }
104            #[cfg(feature = "with-uuid")]
105            (Self::Text(v), ColumnType::Uuid) => Value::Uuid(Some(
106                sea_orm::prelude::Uuid::parse_str(v).map_err(|_| mismatch())?,
107            )),
108            _ => return Err(mismatch()),
109        };
110        Ok(value)
111    }
112
113    /// Reads a key from a raw query result, whatever type the column has.
114    pub(crate) fn read(row: &QueryResult, column: &str) -> Result<Self, DbErr> {
115        let found = row
116            .try_get::<Option<i64>>("", column)
117            .map(|v| v.map(Self::Int))
118            .or_else(|_| {
119                row.try_get::<Option<i32>>("", column)
120                    .map(|v| v.map(|v| Self::Int(v.into())))
121            })
122            .or_else(|_| {
123                row.try_get::<Option<i16>>("", column)
124                    .map(|v| v.map(|v| Self::Int(v.into())))
125            })
126            .or_else(|_| {
127                row.try_get::<Option<u32>>("", column)
128                    .map(|v| v.map(|v| Self::Int(v.into())))
129            })
130            .or_else(|_| {
131                row.try_get::<Option<u64>>("", column)
132                    .map(|v| v.and_then(|v| i64::try_from(v).ok()).map(Self::Int))
133            })
134            .or_else(|_| {
135                row.try_get::<Option<String>>("", column)
136                    .map(|v| v.map(Self::from_text))
137            });
138        #[cfg(feature = "with-uuid")]
139        let found = found.or_else(|_| {
140            row.try_get::<Option<sea_orm::prelude::Uuid>>("", column)
141                .map(|v| v.map(|v| Self::Text(v.to_string())))
142        });
143        found?.ok_or_else(|| DbErr::Type(format!("the key column {column} is NULL")))
144    }
145}
146
147impl std::fmt::Display for Key {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        match self {
150            Self::Int(v) => write!(f, "{v}"),
151            Self::Text(v) => f.write_str(v),
152        }
153    }
154}
155
156macro_rules! key_from_int {
157    ($($t:ty),+) => {$(
158        impl From<$t> for Key {
159            fn from(value: $t) -> Self {
160                Self::Int(i64::from(value))
161            }
162        }
163    )+};
164}
165
166key_from_int!(i8, i16, i32, i64, u8, u16, u32);
167
168impl From<&str> for Key {
169    fn from(value: &str) -> Self {
170        Self::from_text(value.to_string())
171    }
172}
173
174impl From<String> for Key {
175    fn from(value: String) -> Self {
176        Self::from_text(value)
177    }
178}
179
180impl From<&Self> for Key {
181    fn from(value: &Self) -> Self {
182        value.clone()
183    }
184}
185
186#[cfg(feature = "with-uuid")]
187impl From<sea_orm::prelude::Uuid> for Key {
188    fn from(value: sea_orm::prelude::Uuid) -> Self {
189        Self::Text(value.to_string())
190    }
191}
192
193/// The single primary key column of `E`.
194///
195/// # Panics
196///
197/// If the entity has a composite primary key.
198pub fn primary_column<E: EntityTrait>() -> E::Column {
199    let mut keys = E::PrimaryKey::iter();
200    let first = keys.next().expect("every SeaORM entity has a primary key");
201    assert!(
202        keys.next().is_none(),
203        "sea-orm-relations-kit links single-column primary keys only, and `{}` has a composite one",
204        E::default().table_name()
205    );
206    first.into_column()
207}
208
209/// The primary key of `model`, which must not be `NULL`.
210pub fn require_key<M: ModelTrait>(model: &M) -> Result<Key, DbErr> {
211    let value = model.get(primary_column::<M::Entity>());
212    key_or_error(&value, M::Entity::default().table_name())
213}
214
215/// The key `value` holds, or an error saying why there is none.
216pub fn key_or_error(value: &Value, table: &str) -> Result<Key, DbErr> {
217    Key::from_value(value).ok_or_else(|| {
218        if value.is_some() {
219            DbErr::Type(format!(
220                "a `{table}` key of type {value:?} is not supported; UUID keys need the `with-uuid` feature of sea-orm-relations-kit"
221            ))
222        } else {
223            DbErr::Type(format!("a `{table}` row has a NULL key"))
224        }
225    })
226}
227
228/// `keys` converted for `column`, with duplicates dropped and the order kept.
229pub fn values_for<C: ColumnTrait>(keys: &[Key], column: C) -> Result<Vec<Value>, DbErr> {
230    let mut seen = std::collections::HashSet::new();
231    keys.iter()
232        .filter(|key| seen.insert(*key))
233        .map(|key| key.to_value_for(column))
234        .collect()
235}
236
237#[cfg(test)]
238mod tests {
239    use super::Key;
240    use sea_orm::Value;
241
242    #[test]
243    fn integers_of_every_width_are_one_key() {
244        assert_eq!(Key::from_value(&Value::Int(Some(15))), Some(Key::Int(15)));
245        assert_eq!(
246            Key::from_value(&Value::BigInt(Some(15))),
247            Some(Key::Int(15))
248        );
249        assert_eq!(
250            Key::from_value(&Value::SmallUnsigned(Some(15))),
251            Some(Key::Int(15))
252        );
253    }
254
255    #[test]
256    fn a_numeric_string_matches_an_integer_key() {
257        assert_eq!(
258            Key::from_value(&Value::String(Some("15".into()))),
259            Some(Key::Int(15))
260        );
261        assert_eq!(
262            Key::from_value(&Value::String(Some("015".into()))),
263            Some(Key::Text("015".into()))
264        );
265        assert_eq!(Key::from("abc"), Key::Text("abc".into()));
266    }
267
268    #[test]
269    fn null_and_non_key_values_are_no_key() {
270        assert_eq!(Key::from_value(&Value::Int(None)), None);
271        assert_eq!(Key::from_value(&Value::Bool(Some(true))), None);
272        assert_eq!(Key::from_value(&Value::BigUnsigned(Some(u64::MAX))), None);
273    }
274}