diesel/sqlite/function_behavior.rs
1//! SQLite function behavior flags for custom SQL functions.
2
3#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
4extern crate libsqlite3_sys as ffi;
5
6#[cfg(all(target_family = "wasm", target_os = "unknown"))]
7use sqlite_wasm_rs as ffi;
8
9bitflags::bitflags! {
10 /// Flags controlling SQLite custom function behavior.
11 ///
12 /// These flags are passed to `sqlite3_create_function_v2()` and control
13 /// how SQLite treats the function in various contexts.
14 ///
15 /// # Availability
16 ///
17 /// - [`DETERMINISTIC`][Self::DETERMINISTIC]: SQLite 3.8.3 (2014-02)
18 /// - [`DIRECTONLY`][Self::DIRECTONLY], [`INNOCUOUS`][Self::INNOCUOUS]: SQLite 3.31.0 (2020-01)
19 /// - [`SUBTYPE`][Self::SUBTYPE]: SQLite 3.30.0 (2019-10)
20 ///
21 /// # Security Considerations
22 ///
23 /// When using [`SqliteConnection::set_trusted_schema(false)`][crate::sqlite::SqliteConnection::set_trusted_schema]
24 /// for security hardening, custom functions must be marked with [`INNOCUOUS`][Self::INNOCUOUS]
25 /// to be callable from views, triggers, CHECK constraints, DEFAULT expressions,
26 /// generated columns, and expression indexes.
27 ///
28 /// Conversely, functions with side effects or that expose sensitive state
29 /// should be marked with [`DIRECTONLY`][Self::DIRECTONLY] to prevent them from being called
30 /// via malicious schema objects in untrusted database files.
31 ///
32 /// # Example
33 ///
34 /// ```rust
35 /// use diesel::sqlite::SqliteFunctionBehavior;
36 ///
37 /// // Deterministic function (most common case)
38 /// let flags = SqliteFunctionBehavior::DETERMINISTIC;
39 /// assert!(flags.contains(SqliteFunctionBehavior::DETERMINISTIC));
40 ///
41 /// // Non-deterministic function (e.g., random())
42 /// let flags = SqliteFunctionBehavior::empty();
43 /// assert!(flags.is_empty());
44 ///
45 /// // Safe for use in untrusted schemas (views, triggers, etc.)
46 /// let flags = SqliteFunctionBehavior::DETERMINISTIC | SqliteFunctionBehavior::INNOCUOUS;
47 /// assert!(flags.contains(SqliteFunctionBehavior::DETERMINISTIC));
48 /// assert!(flags.contains(SqliteFunctionBehavior::INNOCUOUS));
49 ///
50 /// // Has side effects, block from schema objects
51 /// let flags = SqliteFunctionBehavior::DIRECTONLY;
52 /// assert!(flags.contains(SqliteFunctionBehavior::DIRECTONLY));
53 /// ```
54 ///
55 /// When registering a custom SQL function:
56 ///
57 /// ```rust
58 /// # include!("../doctest_setup.rs");
59 /// use diesel::sqlite::SqliteFunctionBehavior;
60 /// use diesel::prelude::*;
61 ///
62 /// # // This test registers a Rust callback that sqlite invokes through the
63 /// # // FFI boundary, which is not supported by miri `-Zmiri-native-lib`.
64 /// # #[cfg(miri)]
65 /// # fn main() {}
66 /// # #[cfg(not(miri))]
67 /// # fn main() {
68 /// # run_test().unwrap();
69 /// # }
70 /// #
71 /// # fn run_test() -> diesel::result::QueryResult<()> {
72 /// # let mut conn = establish_connection();
73 /// // Use SqliteFunctionBehavior when registering SQL functions
74 /// conn.register_sql_function::<diesel::sql_types::Text, diesel::sql_types::Text, _, _, _>(
75 /// "my_upper",
76 /// SqliteFunctionBehavior::DETERMINISTIC | SqliteFunctionBehavior::INNOCUOUS,
77 /// |x: String| x.to_uppercase(),
78 /// )?;
79 /// # Ok(())
80 /// # }
81 /// ```
82 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83 pub struct SqliteFunctionBehavior: i32 {
84 /// The function always returns the same result given the same inputs
85 /// within a single SQL statement.
86 ///
87 /// This allows SQLite to optimize by caching results and factoring
88 /// the function out of inner loops. Most pure functions should use this flag.
89 ///
90 /// # Availability
91 ///
92 /// Requires SQLite 3.8.3 (2014-02) or later.
93 ///
94 /// # Example
95 ///
96 /// `abs(x)` is deterministic. `random()` is not.
97 const DETERMINISTIC = ffi::SQLITE_DETERMINISTIC;
98
99 /// The function cannot be called from schema objects (views, triggers,
100 /// CHECK constraints, DEFAULT expressions, generated columns, or
101 /// expression indexes).
102 ///
103 /// Use this for functions that:
104 /// - Have side effects (network, file I/O, logging, etc.)
105 /// - Return sensitive application state
106 /// - Should not be triggered by opening an untrusted database
107 ///
108 /// # Availability
109 ///
110 /// Requires SQLite 3.31.0 (2020-01) or later.
111 ///
112 /// # Security Recommendation
113 ///
114 /// Mark all functions with side effects or that expose internal state
115 /// with `DIRECTONLY` to prevent schema injection attacks.
116 const DIRECTONLY = ffi::SQLITE_DIRECTONLY;
117
118 /// The function is safe to call from untrusted schema contexts.
119 ///
120 /// When [`SqliteConnection::set_trusted_schema(false)`][crate::sqlite::SqliteConnection::set_trusted_schema]
121 /// is set, only functions marked `INNOCUOUS` can be called from schema
122 /// objects (views, triggers, CHECK constraints, DEFAULT expressions,
123 /// generated columns, expression indexes).
124 ///
125 /// # Availability
126 ///
127 /// Requires SQLite 3.31.0 (2020-01) or later.
128 ///
129 /// # Safety Requirements
130 ///
131 /// **Only mark a function as INNOCUOUS if it:**
132 /// - Has no side effects
133 /// - Does not reveal internal application state
134 /// - Output depends solely on its input parameters
135 ///
136 /// # Security Warning
137 ///
138 /// Incorrectly marking a function as `INNOCUOUS` can create security
139 /// vulnerabilities when processing untrusted database files. An attacker
140 /// could craft a database with malicious views or triggers that invoke
141 /// your function in unexpected ways.
142 const INNOCUOUS = ffi::SQLITE_INNOCUOUS;
143
144 /// The function may call `sqlite3_value_subtype()` to inspect the
145 /// subtype of its arguments.
146 ///
147 /// # Availability
148 ///
149 /// Requires SQLite 3.30.0 (2019-10) or later.
150 const SUBTYPE = ffi::SQLITE_SUBTYPE;
151 }
152}
153
154impl Default for SqliteFunctionBehavior {
155 /// Returns `Self::empty()`
156 fn default() -> Self {
157 Self::empty()
158 }
159}
160
161impl SqliteFunctionBehavior {
162 /// Returns the raw flags value including UTF8 encoding flag.
163 ///
164 /// This is used internally when calling `sqlite3_create_function_v2`.
165 pub(crate) fn to_flags(self) -> i32 {
166 ffi::SQLITE_UTF8 | self.bits()
167 }
168}