Skip to main content

sqlx_askama_template/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use sqlx_core::{Error, database::Database};
4
5pub use askama;
6pub use sqlx_askama_template_macro::*;
7mod db_adapter;
8mod sql_template_execute;
9mod template_adapter;
10mod template_arg;
11
12pub use db_adapter::*;
13pub use sql_template_execute::*;
14pub use template_adapter::*;
15pub use template_arg::*;
16
17/// SQL template trait
18///
19/// Defines basic operations for rendering SQL from templates
20pub trait SqlTemplate<'q, DB>: Sized + Clone
21where
22    DB: Database,
23{
24    /// Renders the SQL template using a custom placeholder encoding function
25    ///
26    /// Writes the rendered SQL to the provided buffer and handles parameter encoding.
27    /// The placeholder function (if provided) formats parameter placeholders (e.g., $1, ?)
28    /// based on their index.
29    ///
30    /// # Parameters
31    /// - `f`: Optional function to format parameter placeholders (receives index and buffer)
32    /// - `sql_buffer`: Mutable string buffer to store the rendered SQL
33    ///
34    /// # Returns
35    /// Encoded database arguments (None if no parameters) or an error if rendering fails
36    fn render_sql_with_encode_placeholder_fn(
37        self,
38        f: Option<fn(usize, &mut String)>,
39        sql_buffer: &mut String,
40    ) -> Result<Option<DB::Arguments>, Error>;
41    /// Renders SQL template and returns query string with parameters
42    fn render_sql(self) -> Result<(String, Option<DB::Arguments>), Error> {
43        let mut sql_buff = String::new();
44        let arg = self.render_sql_with_encode_placeholder_fn(None, &mut sql_buff)?;
45        Ok((sql_buff, arg))
46    }
47
48    /// Renders SQL template and returns executable query result
49    fn render_executable(self) -> Result<SqlTemplateExecute<DB>, Error> {
50        let (sql, arguments) = self.render_sql()?;
51
52        Ok(SqlTemplateExecute {
53            sql,
54            arguments,
55            persistent: true,
56        })
57    }
58
59    /// Creates a database adapter manager for the template
60    ///
61    /// Provides an adapter pattern interface for managing template rendering
62    /// in database-specific scenarios.
63    ///
64    /// # Returns
65    /// A new `DBAdapterManager` instance wrapping the template
66    fn adapter_render(self) -> DBAdapterManager<'q, DB, Self> {
67        DBAdapterManager::new(self)
68    }
69}