Skip to main content

sqlite_functions/
options.rs

1use rusqlite::functions::FunctionFlags;
2
3/// The number of SQL arguments accepted by a function.
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5pub enum Arity {
6    /// Accept exactly this many arguments.
7    Exact(u16),
8    /// Accept any number of arguments allowed by SQLite.
9    Variadic,
10}
11
12impl Arity {
13    pub(crate) const fn as_sqlite(self) -> i32 {
14        match self {
15            Self::Exact(value) => value as i32,
16            Self::Variadic => -1,
17        }
18    }
19}
20
21/// Name, arity, and SQLite properties for a function registration.
22///
23/// Options default to UTF-8 and do not claim that a callback is deterministic,
24/// innocuous, or direct-only. These properties must reflect the callback's
25/// actual behavior, so authors opt into them explicitly.
26#[derive(Clone, Debug)]
27pub struct FunctionOptions {
28    name: String,
29    arity: Arity,
30    flags: FunctionFlags,
31}
32
33impl FunctionOptions {
34    /// Create schema-accessible UTF-8 function options.
35    #[must_use]
36    pub fn new(name: impl Into<String>, arity: Arity) -> Self {
37        Self {
38            name: name.into(),
39            arity,
40            flags: FunctionFlags::SQLITE_UTF8,
41        }
42    }
43
44    /// Declare that equal inputs always produce equal outputs.
45    #[must_use]
46    pub fn deterministic(mut self) -> Self {
47        self.flags |= FunctionFlags::SQLITE_DETERMINISTIC;
48        self
49    }
50
51    /// Declare that the function has no harmful side effects or data leaks.
52    #[must_use]
53    pub fn innocuous(mut self) -> Self {
54        self.flags |= FunctionFlags::SQLITE_INNOCUOUS;
55        self
56    }
57
58    /// Restrict the function to top-level SQL.
59    #[must_use]
60    pub fn direct_only(mut self) -> Self {
61        self.flags |= FunctionFlags::SQLITE_DIRECTONLY;
62        self
63    }
64
65    /// Add advanced `rusqlite` function flags.
66    #[must_use]
67    pub fn with_flags(mut self, flags: FunctionFlags) -> Self {
68        self.flags |= flags;
69        self
70    }
71
72    /// SQL function name.
73    #[must_use]
74    pub fn name(&self) -> &str {
75        &self.name
76    }
77
78    /// Declared SQL arity.
79    #[must_use]
80    pub const fn arity(&self) -> Arity {
81        self.arity
82    }
83
84    /// Effective SQLite function flags.
85    #[must_use]
86    pub const fn flags(&self) -> FunctionFlags {
87        self.flags
88    }
89
90    pub(crate) fn into_parts(self) -> (String, i32, FunctionFlags) {
91        (self.name, self.arity.as_sqlite(), self.flags)
92    }
93}