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