Skip to main content

diesel/query_builder/
query_id.rs

1use super::QueryFragment;
2use alloc::boxed::Box;
3use core::any::{Any, TypeId};
4
5/// Uniquely identifies queries by their type for the purpose of prepared
6/// statement caching.
7///
8/// All types which implement `QueryFragment` should also implement this trait
9/// (It is not an actual supertrait of `QueryFragment` for boxing purposes).
10///
11/// See the documentation of [the `QueryId` type] and [`HAS_STATIC_QUERY_ID`]
12/// for more details.
13///
14/// [the `QueryId` type]: QueryId::QueryId
15/// [`HAS_STATIC_QUERY_ID`]: QueryId::HAS_STATIC_QUERY_ID
16///
17/// ### Deriving
18///
19/// This trait can [be automatically derived](derive@QueryId)
20/// by Diesel.
21/// For example, given this struct:
22///
23/// If the SQL generated by a struct is not uniquely identifiable by its type,
24/// meaning that `HAS_STATIC_QUERY_ID` should always be false,
25/// you should not derive this trait.
26/// In that case you should manually implement it instead.
27pub trait QueryId {
28    /// A type which uniquely represents `Self` in a SQL query.
29    ///
30    /// Typically this will be a re-construction of `Self` using the `QueryId`
31    /// type of each of your type parameters. For example, the type `And<Left,
32    /// Right>` would have `type QueryId = And<Left::QueryId, Right::QueryId>`.
33    ///
34    /// The exception to this is when one of your type parameters does not
35    /// affect whether the same prepared statement can be used or not. For
36    /// example, a bind parameter is represented as `Bound<SqlType, RustType>`.
37    /// The actual Rust type we are serializing does not matter for the purposes
38    /// of prepared statement reuse, but a query which has identical SQL but
39    /// different types for its bind parameters requires a new prepared
40    /// statement. For this reason, `Bound` would have `type QueryId =
41    /// Bound<SqlType::QueryId, ()>`.
42    ///
43    /// If `HAS_STATIC_QUERY_ID` is `false`, you can put any type here
44    /// (typically `()`).
45    type QueryId: Any;
46
47    /// Can the SQL generated by `Self` be uniquely identified by its type?
48    ///
49    /// Typically this question can be answered by looking at whether
50    /// `unsafe_to_cache_prepared` is called in your implementation of
51    /// `QueryFragment::walk_ast`. In Diesel itself, the only type which has
52    /// `false` here, but is potentially safe to store in the prepared statement
53    /// cache is a boxed query.
54    const HAS_STATIC_QUERY_ID: bool = true;
55
56    #[doc(hidden)]
57    const IS_WINDOW_FUNCTION: bool = false;
58
59    /// Returns the type id of `Self::QueryId` if `Self::HAS_STATIC_QUERY_ID`.
60    /// Returns `None` otherwise.
61    ///
62    /// You should never need to override this method.
63    fn query_id() -> Option<TypeId> {
64        if Self::HAS_STATIC_QUERY_ID {
65            Some(TypeId::of::<Self::QueryId>())
66        } else {
67            None
68        }
69    }
70}
71
72#[doc(inline)]
73pub use diesel_derives::QueryId;
74
75impl QueryId for () {
76    type QueryId = ();
77
78    const HAS_STATIC_QUERY_ID: bool = true;
79}
80
81impl<T: QueryId + ?Sized> QueryId for Box<T> {
82    type QueryId = T::QueryId;
83
84    const HAS_STATIC_QUERY_ID: bool = T::HAS_STATIC_QUERY_ID;
85
86    const IS_WINDOW_FUNCTION: bool = T::IS_WINDOW_FUNCTION;
87}
88
89impl<T: QueryId + ?Sized> QueryId for &T {
90    type QueryId = T::QueryId;
91
92    const HAS_STATIC_QUERY_ID: bool = T::HAS_STATIC_QUERY_ID;
93    const IS_WINDOW_FUNCTION: bool = T::IS_WINDOW_FUNCTION;
94}
95
96impl<DB> QueryId for dyn QueryFragment<DB> {
97    type QueryId = ();
98
99    const HAS_STATIC_QUERY_ID: bool = false;
100    // todo: we need to deal with IS_WINDOW_FUNCTION here
101}
102
103#[cfg(test)]
104#[allow(unused_parens)] // FIXME: Remove this attribute once false positive is resolved.
105mod tests {
106    use std::any::TypeId;
107
108    use super::QueryId;
109    use crate::prelude::*;
110
111    table! {
112        users {
113            id -> Integer,
114            name -> VarChar,
115        }
116    }
117
118    fn query_id<T: QueryId>(_: T) -> Option<TypeId> {
119        T::query_id()
120    }
121
122    #[diesel_test_helper::test]
123    fn queries_with_no_dynamic_elements_have_a_static_id() {
124        use self::users::dsl::*;
125        assert!(query_id(users).is_some());
126        assert!(query_id(users.select(name)).is_some());
127        assert!(query_id(users.filter(name.eq("Sean"))).is_some());
128    }
129
130    #[diesel_test_helper::test]
131    fn queries_with_different_types_have_different_ids() {
132        let id1 = query_id(users::table.select(users::name));
133        let id2 = query_id(users::table.select(users::id));
134        assert_ne!(id1, id2);
135    }
136
137    #[diesel_test_helper::test]
138    fn bind_params_use_only_sql_type_for_query_id() {
139        use self::users::dsl::*;
140        let id1 = query_id(users.filter(name.eq("Sean")));
141        let id2 = query_id(users.filter(name.eq("Tess".to_string())));
142
143        assert_eq!(id1, id2);
144    }
145
146    #[diesel_test_helper::test]
147    #[cfg(feature = "postgres")]
148    fn boxed_queries_do_not_have_static_query_id() {
149        use crate::pg::Pg;
150        assert!(query_id(users::table.into_boxed::<Pg>()).is_none());
151    }
152}