Skip to main content

sqlive/
connection_setup.rs

1//! What the host registers on a connection as it opens, before any statement
2//! runs: SQL functions and collations.
3
4use std::cell::RefCell;
5use std::cmp::Ordering;
6use std::collections::BTreeSet;
7
8use rusqlite::functions::{Context, FunctionFlags};
9use rusqlite::types::ToSql;
10
11use crate::authorization::{FunctionCall, HostFunctions, Policy, SqlAuthorization};
12use crate::snapshot_values::{SnapshotValue, SnapshotValues};
13
14/// What a connection's setup may register.
15pub struct Setup<'a, P: Policy> {
16    connection: &'a rusqlite::Connection,
17    functions: HostFunctions<P>,
18    /// The values the host's functions read as each transaction's snapshot
19    /// saw them.
20    values: RefCell<SnapshotValues>,
21}
22
23impl<'a, P: Policy> Setup<'a, P> {
24    pub(crate) fn new(
25        connection: &'a rusqlite::Connection,
26        authorization: &SqlAuthorization<P>,
27    ) -> Self {
28        Self {
29            connection,
30            functions: authorization.functions(),
31            values: RefCell::new(SnapshotValues::new()),
32        }
33    }
34
35    /// The values registered, which the connection's transactions take.
36    pub(crate) fn into_snapshot_values(self) -> SnapshotValues {
37        self.values.into_inner()
38    }
39
40    /// Run `register` on `connection`, a connection a test opened itself,
41    /// as the setup of a connection judged by `policy` would run it.
42    #[cfg(any(test, feature = "test-utils"))]
43    pub fn on_test_connection(
44        connection: &rusqlite::Connection,
45        policy: P,
46        register: impl FnOnce(&Setup<'_, P>) -> rusqlite::Result<()>,
47    ) -> rusqlite::Result<()> {
48        let authorization = SqlAuthorization::new(
49            std::sync::Arc::new(crate::WholeViews::new([])),
50            std::sync::Arc::new(policy),
51        );
52        register(&Setup::new(connection, &authorization))
53    }
54
55    /// Register `function` as `name`. rusqlite turns a function's panic into
56    /// an error that names no bug, so the authorizer catches the panic and
57    /// records it as a bug: the statement fails with the bug's text, and the
58    /// app's call fails with `Error::Bug` (E15).
59    pub fn scalar_function<T: ToSql>(
60        &self,
61        name: &'static str,
62        arguments: i32,
63        flags: FunctionFlags,
64        function: impl Fn(&FunctionCall<'_, P>) -> rusqlite::Result<T> + Send + 'static,
65    ) -> rusqlite::Result<()> {
66        self.connection.create_scalar_function(
67            name,
68            arguments,
69            flags,
70            self.functions.function(name, function),
71        )
72    }
73
74    /// Register `function` as `name`, a name only known as the connection
75    /// opens. Nothing catches a panic in it: the function ends the process
76    /// itself, or doesn't panic.
77    pub fn named_function<T: ToSql>(
78        &self,
79        name: &str,
80        arguments: i32,
81        flags: FunctionFlags,
82        function: impl Fn(&Context<'_>) -> rusqlite::Result<T> + Send + 'static,
83    ) -> rusqlite::Result<()> {
84        self.connection
85            .create_scalar_function(name, arguments, flags, move |context| function(context))
86    }
87
88    /// A value the host keeps in memory, which `now` reads, for this
89    /// connection's functions to read as each transaction's snapshot saw it
90    /// (`snapshot_values.rs`).
91    pub fn snapshot_value<T: Clone + Send + 'static>(
92        &self,
93        now: impl Fn() -> T + Send + Sync + 'static,
94    ) -> SnapshotValue<T> {
95        self.values.borrow_mut().value(now)
96    }
97
98    /// Register `compare` as the order the collation `name` gives text.
99    pub fn collation(
100        &self,
101        name: &str,
102        compare: impl Fn(&str, &str) -> Ordering + Send + 'static,
103    ) -> rusqlite::Result<()> {
104        self.connection.create_collation(name, compare)
105    }
106
107    /// The names of the functions registered so far, SQLite's own included,
108    /// in lowercase.
109    pub fn function_names(&self) -> rusqlite::Result<BTreeSet<String>> {
110        self.connection
111            .prepare("SELECT DISTINCT lower(name) FROM pragma_function_list")?
112            .query_map([], |row| row.get::<_, String>(0))?
113            .collect()
114    }
115}