Skip to main content

no_mistakes_postgres_engine/embedded/helpers/
summary.rs

1//! Summaries of exported SQL helpers and the call sites that need them.
2
3use super::split::{with_origin_entry, Marker};
4use super::template::{Spliced, TemplateHelper};
5use crate::embedded::walk::resolve::functions::provenance::RecoveredSql;
6use crate::embedded::EmbeddedSqlCall;
7use std::path::Path;
8
9/// A string literal passed to a helper, plus where it was written.
10///
11/// `line == 0` means the location was not recorded (a value rebuilt inside a
12/// helper, or a synthetic site). The splice then keeps the `${param}` line.
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub struct LiteralArg {
15    pub text: String,
16    pub line: u32,
17    pub origin: u32,
18}
19
20impl LiteralArg {
21    pub fn bare(text: impl Into<String>) -> Self {
22        Self {
23            text: text.into(),
24            line: 0,
25            origin: 0,
26        }
27    }
28
29    fn splice<'a>(&'a self, caller: &Path) -> Spliced<'a> {
30        Spliced {
31            text: std::borrow::Cow::Borrowed(&self.text),
32            at: (self.line > 0).then(|| Marker {
33                line: self.line,
34                path: Some(caller.to_path_buf()),
35                origin: self.origin,
36            }),
37        }
38    }
39}
40
41impl From<&str> for LiteralArg {
42    fn from(text: &str) -> Self {
43        Self::bare(text)
44    }
45}
46
47impl From<String> for LiteralArg {
48    fn from(text: String) -> Self {
49        Self::bare(text)
50    }
51}
52
53/// One argument of an imported-helper call, as far as the walk can tell.
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub enum SiteArg {
56    Literal(LiteralArg),
57    Bool(bool),
58    Null,
59    Undefined,
60    /// An object literal whose properties are all values the walk can classify.
61    Object(Vec<(String, SiteArg)>),
62    /// An array literal whose elements are all classifiable values.
63    Array(Vec<SiteArg>),
64    /// An identifier or number. It never contributes SQL text.
65    Scalar,
66    /// A SQL builder whose text precedes the call's hole.
67    Builder,
68}
69
70/// An imported helper called from this file.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum SiteKind {
73    Sql,
74    PlainClause,
75    ParameterizedMember,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct ImportedSite {
80    /// The callee's local name; the projection looks up its import binding.
81    pub local: String,
82    /// Static export selected from a runtime namespace import, for constants only.
83    pub member: Option<String>,
84    /// Plain text is legal only inside an ordinary template's complete SQL.
85    pub kind: SiteKind,
86    pub args: Vec<SiteArg>,
87    /// The call's result feeds an expression (not just a statement), so a
88    /// builder helper must hand back the builder it was given.
89    pub value_used: bool,
90    /// Line of the call in the caller's file.
91    pub line: u32,
92    /// `Some(allow_fragment)` reads an exported constant instead of calling a helper.
93    /// The flag is true only for `.append`, which may take a tagged fragment.
94    pub constant: Option<bool>,
95}
96
97/// Executor SQL that is complete once the holes of `sites` are filled.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct PendingImportedSql {
100    /// The executor call's source span, as recorded in `call_spans`.
101    pub span: (u32, u32),
102    /// The call with hole markers still in `sql_text`.
103    pub template: EmbeddedSqlCall,
104    pub sites: Vec<(usize, ImportedSite)>,
105    /// Hole indexes that must take the same alternative, keyed by site index.
106    pub correlation: crate::fx::FxHashMap<usize, u32>,
107}
108
109/// A helper function that is summarized once, where it is declared.
110#[derive(Clone, PartialEq, Eq)]
111pub enum HelperSummary {
112    /// Fixed text; arguments never reach the SQL.
113    Static(RecoveredSql),
114    /// Untagged template over its own parameters.
115    Template(TemplateHelper),
116    /// Appends fixed fragments to one `SQLStatement` parameter and returns it.
117    Builder(BuilderHelper),
118}
119
120#[derive(Clone, PartialEq, Eq)]
121pub struct BuilderHelper {
122    pub parameter_index: usize,
123    pub parameter_count: usize,
124    /// Everything the helper appends, in order.
125    pub suffix: RecoveredSql,
126}
127
128impl HelperSummary {
129    /// The text that fills a call's hole.
130    ///
131    /// Helper text is attributed to `helper`. A string literal spliced into a
132    /// template is attributed to `caller` instead, at the literal's own line.
133    pub fn fill(&self, site: &ImportedSite, helper: &Path, caller: &Path) -> Option<RecoveredSql> {
134        let builders = site
135            .args
136            .iter()
137            .filter(|arg| **arg == SiteArg::Builder)
138            .count();
139        let recovered = match self {
140            Self::Static(sql) if builders == 0 => sql.clone(),
141            Self::Template(template) if builders == 0 => {
142                let literals = site
143                    .args
144                    .iter()
145                    .map(|arg| match arg {
146                        SiteArg::Literal(literal) => Some(literal.splice(caller)),
147                        _ => None,
148                    })
149                    .collect::<Option<Vec<_>>>()?;
150                template.apply(&literals)?
151            }
152            Self::Builder(builder)
153                if builders == 1
154                    && site.args.len() == builder.parameter_count
155                    && site.args.get(builder.parameter_index) == Some(&SiteArg::Builder) =>
156            {
157                builder.suffix.clone()
158            }
159            _ => return None,
160        };
161        Some(with_origin_entry(recovered).with_source_file(helper))
162    }
163}