Skip to main content

turso_orm/entity/
primary_key.rs

1//! The primary key of an entity, modeled by [`PrimaryKeyTrait`].
2//!
3//! The derive macro generates a `PrimaryKey` enum with one variant per key
4//! column and implements both traits here on it. Splitting the key out of
5//! the `Column` enum lets the query builders iterate exactly the key columns
6//! when rendering `WHERE pk = ?` conditions, and lets
7//! [`PrimaryKeyTrait::ValueType`] be the field type for a single column or a
8//! tuple for a composite key, so `find_by_id(1)` and
9//! `find_by_id((1, "a".to_owned()))` both type-check.
10
11use crate::types::{IntoValueTuple, TryFromU64};
12
13use super::iden::{IdenStatic, Iterable};
14
15/// The primary key of an entity, derived on the `PrimaryKey` enum.
16pub trait PrimaryKeyTrait: IdenStatic + Iterable {
17    /// The Rust type of the key: the field type for a single column, a tuple
18    /// of field types for a composite key.
19    type ValueType: IntoValueTuple + TryFromU64 + Clone + std::fmt::Debug + Send + Sync;
20
21    /// Whether the database generates the key, as with `INTEGER PRIMARY KEY`.
22    fn auto_increment() -> bool;
23}
24
25/// The mapping between primary-key variants and column variants.
26pub trait PrimaryKeyToColumn {
27    /// The entity's column enum.
28    type Column;
29
30    /// The column this key variant corresponds to.
31    fn into_column(self) -> Self::Column;
32
33    /// The key variant for `column`, or `None` when the column is not part of the key.
34    fn from_column(column: Self::Column) -> Option<Self>
35    where
36        Self: Sized;
37}