Skip to main content

rok_db_core/
key.rs

1use crate::{Column, Error, Expr, Model, Result, Value};
2
3/// A primary key value: a single value, or a tuple for models with a
4/// composite primary key (`#[rok(primary_key)]` on several fields).
5///
6/// ```ignore
7/// User::find(&db, 42).await?;                       // single key
8/// Membership::find(&db, (org_id, user_id)).await?;  // composite key, in field order
9/// ```
10pub trait IntoKey {
11    /// The key's values, in primary-key column order.
12    fn into_key(self) -> Vec<Value>;
13}
14
15impl<T: Into<Value>> IntoKey for T {
16    fn into_key(self) -> Vec<Value> {
17        vec![self.into()]
18    }
19}
20
21macro_rules! tuple_keys {
22    ($(($($t:ident),+)),+) => {$(
23        #[allow(non_snake_case)]
24        impl<$($t: Into<Value>),+> IntoKey for ($($t,)+) {
25            fn into_key(self) -> Vec<Value> {
26                let ($($t,)+) = self;
27                vec![$($t.into()),+]
28            }
29        }
30    )+};
31}
32
33tuple_keys!((A, B), (A, B, C), (A, B, C, D));
34
35/// `pk1 = v1 AND pk2 = v2 …` for model `M`.
36pub(crate) fn key_expr<M: Model>(values: Vec<Value>) -> Result<Expr<M>> {
37    if values.len() != M::PRIMARY_KEYS.len() {
38        return Err(Error::InvalidQuery(format!(
39            "`{}` has a {}-column primary key, got {} value(s)",
40            M::TABLE,
41            M::PRIMARY_KEYS.len(),
42            values.len()
43        )));
44    }
45    Ok(Expr::all_of(
46        M::PRIMARY_KEYS
47            .iter()
48            .zip(values)
49            .map(|(c, v)| Column::<M>::new(c).eq(v)),
50    ))
51}
52
53/// Human-readable key for error messages: `42` or `(1, 2)`.
54pub(crate) fn key_string(values: &[Value]) -> String {
55    match values {
56        [single] => single.to_string(),
57        many => format!(
58            "({})",
59            many.iter()
60                .map(ToString::to_string)
61                .collect::<Vec<_>>()
62                .join(", ")
63        ),
64    }
65}
66
67/// SQL rendering the key of the current row of `M` exactly as the change
68/// and audit triggers store it: `to_jsonb(row) ->> 'pk'` for a single key,
69/// a JSON array of those texts for composite keys.
70pub(crate) fn key_text_sql<M: Model>() -> String {
71    let table = M::TABLE.rsplit('.').next().unwrap_or(M::TABLE);
72    let mut row = String::new();
73    crate::sql::push_ident(&mut row, table);
74    let field = |c: &str| format!("(to_jsonb({row}) ->> '{}')", c.replace('\'', "''"));
75    match M::PRIMARY_KEYS {
76        [single] => field(single),
77        many => format!(
78            "to_jsonb(ARRAY[{}])::text",
79            many.iter().map(|c| field(c)).collect::<Vec<_>>().join(", ")
80        ),
81    }
82}
83
84/// SQL comparing a stored key text against bound key values: `?::text` or
85/// `to_jsonb(ARRAY[?::text, …])::text`.
86#[cfg_attr(not(feature = "json"), allow(dead_code))]
87pub(crate) fn key_param_sql(len: usize) -> String {
88    match len {
89        1 => "?::text".to_owned(),
90        n => format!("to_jsonb(ARRAY[{}])::text", vec!["?::text"; n].join(", ")),
91    }
92}
93
94/// The key column list passed to triggers.
95pub(crate) fn key_columns_arg<M: Model>() -> String {
96    M::PRIMARY_KEYS.join(",")
97}
98
99/// Trigger-side counterpart of [`key_text_sql`]: `keys` is the
100/// comma-separated key column list passed as a trigger argument and `j` the
101/// row as JSONB.
102pub(crate) const TRIGGER_KEY_SQL: &str = "CASE WHEN cardinality(keys) = 1 THEN j ->> keys[1] \
103     ELSE (SELECT to_jsonb(array_agg(j ->> c ORDER BY o))::text FROM unnest(keys) WITH ORDINALITY AS t(c, o)) END";