ignis_db/macros/
sql_safety.rs1use crate::common::{validate_identifier, validate_string_literal};
7use anyhow::{Context, Result};
8
9#[derive(Debug, Clone)]
11pub struct SqlSafetyContext {
12 pub in_dynamic_context: bool,
14 pub current_statement: Option<String>,
16 pub validated_identifiers: Vec<String>,
18 pub escaped_literals: Vec<String>,
20}
21
22impl Default for SqlSafetyContext {
23 fn default() -> Self {
24 Self {
25 in_dynamic_context: false,
26 current_statement: None,
27 validated_identifiers: Vec::new(),
28 escaped_literals: Vec::new(),
29 }
30 }
31}
32
33impl SqlSafetyContext {
34 pub fn new(statement_type: &str) -> Self {
36 Self {
37 current_statement: Some(statement_type.to_string()),
38 ..Default::default()
39 }
40 }
41
42 pub fn validate_identifier(&mut self, identifier: &str) -> Result<String> {
44 let validated = validate_identifier(identifier).with_context(|| {
45 format!(
46 "Invalid identifier '{}' in statement {:?}",
47 identifier, self.current_statement
48 )
49 })?;
50
51 self.validated_identifiers.push(validated.clone());
52 Ok(validated)
53 }
54
55 pub fn escape_literal(&mut self, literal: &str) -> Result<String> {
57 let escaped = validate_string_literal(literal).with_context(|| {
58 format!(
59 "Invalid string literal in statement {:?}",
60 self.current_statement
61 )
62 })?;
63
64 self.escaped_literals.push(escaped.clone());
65 Ok(escaped)
66 }
67
68 pub fn safety_summary(&self) -> String {
70 let validated_list = if self.validated_identifiers.is_empty() {
71 "none".to_string()
72 } else {
73 self.validated_identifiers.join(", ")
74 };
75
76 let escaped_list = if self.escaped_literals.is_empty() {
77 "none".to_string()
78 } else {
79 self.escaped_literals.join(", ")
80 };
81
82 format!(
83 "SQL Safety Context: Statement={:?}, Validated=[{}], Escaped=[{}], Dynamic={}",
84 self.current_statement, validated_list, escaped_list, self.in_dynamic_context
85 )
86 }
87}
88
89#[derive(Clone)]
91pub struct SafeSqlBuilder {
92 context: SqlSafetyContext,
93 sql_parts: Vec<String>,
94}
95
96impl SafeSqlBuilder {
97 pub fn new(statement_type: &str) -> Self {
99 Self {
100 context: SqlSafetyContext::new(statement_type),
101 sql_parts: Vec::new(),
102 }
103 }
104
105 pub fn identifier(mut self, identifier: &str) -> Result<Self> {
107 let validated = self.context.validate_identifier(identifier)?;
108 self.sql_parts.push(validated);
110 Ok(self)
111 }
112
113 pub fn identifiers(mut self, identifiers: &[&str]) -> Result<Self> {
115 for (i, &id) in identifiers.iter().enumerate() {
116 if i > 0 {
117 self.sql_parts.push(",".to_string());
118 }
119 let escaped = self.context.validate_identifier(id)?;
120 self.sql_parts.push(escaped);
121 }
122 Ok(self)
123 }
124
125 pub fn literal(mut self, literal: &str) -> Result<Self> {
127 let escaped = self.context.escape_literal(literal)?;
128 self.sql_parts.push(escaped);
129 Ok(self)
130 }
131
132 pub fn raw(mut self, text: &str) -> Self {
134 self.context.in_dynamic_context = true;
135 self.sql_parts.push(text.to_string());
136 self
137 }
138
139 pub fn placeholder(mut self) -> Self {
141 self.sql_parts.push("?".to_string());
142 self
143 }
144
145 pub fn placeholders(mut self, count: usize) -> Self {
147 for _ in 0..count {
148 self.sql_parts.push("?".to_string());
149 }
150 self
151 }
152
153 pub fn join_with(mut self, separator: &str) -> Self {
155 let joined = self.sql_parts.join(separator);
156 self.sql_parts = vec![joined];
157 self
158 }
159
160 pub fn build(self) -> Result<String> {
162 if self.context.in_dynamic_context {
163 eprintln!(
165 "⚠️ Warning: SQL built with dynamic content: {}",
166 self.context.safety_summary()
167 );
168 }
169
170 let mut result = String::new();
172 for (i, part) in self.sql_parts.iter().enumerate() {
173 if i > 0 {
174 if !part.starts_with(',') && !part.starts_with('(') && !part.starts_with(')') {
176 result.push(' ');
177 }
178 }
179 result.push_str(part);
180 }
181
182 Ok(result)
183 }
184
185 pub fn context(&self) -> &SqlSafetyContext {
187 &self.context
188 }
189}
190
191pub mod safe_sql {
193 use super::*;
194
195 pub fn select(table: &str, columns: &[&str]) -> Result<String> {
197 let mut builder = SafeSqlBuilder::new("SELECT");
198
199 builder = builder.raw("SELECT");
201
202 for (i, &col) in columns.iter().enumerate() {
204 if i > 0 {
205 builder = builder.raw(",");
207 }
208 builder = builder.identifier(col)?;
209 }
210
211 builder = builder.raw("FROM").identifier(table)?;
213
214 builder.build()
215 }
216
217 pub fn insert(table: &str, columns: &[&str]) -> Result<String> {
219 let mut builder = SafeSqlBuilder::new("INSERT");
220
221 builder = builder.raw("INSERT INTO").identifier(table)?;
223
224 builder = builder.raw("(");
226 for (i, &col) in columns.iter().enumerate() {
227 if i > 0 {
228 builder = builder.raw(",");
229 }
230 builder = builder.identifier(col)?;
231 }
232 builder = builder.raw(")");
233
234 builder = builder.raw("VALUES").raw("(");
236 for (i, _) in columns.iter().enumerate() {
237 if i > 0 {
238 builder = builder.raw(",");
239 }
240 builder = builder.placeholder();
241 }
242 builder = builder.raw(")");
243
244 builder.build()
245 }
246
247 pub fn update(table: &str, columns: &[&str]) -> Result<String> {
249 let mut builder = SafeSqlBuilder::new("UPDATE");
250
251 builder = builder.raw("UPDATE").identifier(table)?;
253
254 builder = builder.raw("SET");
256 for (i, &col) in columns.iter().enumerate() {
257 if i > 0 {
258 builder = builder.raw(",");
259 }
260 builder = builder.identifier(col)?.raw("=").placeholder();
261 }
262
263 builder.build()
264 }
265
266 pub fn delete(table: &str) -> Result<String> {
268 let mut builder = SafeSqlBuilder::new("DELETE");
269
270 builder = builder.raw("DELETE FROM").identifier(table)?;
271
272 builder.build()
273 }
274
275 pub fn where_clause(conditions: &[(&str, &str)]) -> Result<String> {
277 if conditions.is_empty() {
278 return Ok(String::new());
279 }
280
281 let mut builder = SafeSqlBuilder::new("WHERE");
282 builder = builder.raw("WHERE");
283
284 for (i, (column, _)) in conditions.iter().enumerate() {
285 if i > 0 {
286 builder = builder.raw("AND");
287 }
288 builder = builder.identifier(column)?.raw("=").placeholder();
289 }
290
291 builder.build()
292 }
293}
294
295#[macro_export]
297macro_rules! safe_sql {
298 (SELECT $($col:ident),* FROM $table:ident) => {{
299 let columns = vec![$(stringify!($col)),*];
300 let table_name = stringify!($table);
301 $crate::macros::sql_safety::safe_sql::select(table_name, &columns)
302 }};
303
304 (INSERT INTO $table:ident ($($col:ident),*) VALUES) => {{
305 let columns = vec![$(stringify!($col)),*];
306 let table_name = stringify!($table);
307 $crate::macros::sql_safety::safe_sql::insert(table_name, &columns)
308 }};
309
310 (UPDATE $table:ident SET $($col:ident),*) => {{
311 let columns = vec![$(stringify!($col)),*];
312 let table_name = stringify!($table);
313 $crate::macros::sql_safety::safe_sql::update(table_name, &columns)
314 }};
315
316 (DELETE FROM $table:ident) => {{
317 let table_name = stringify!($table);
318 $crate::macros::sql_safety::safe_sql::delete(table_name)
319 }};
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
327 fn test_safe_sql_builder() {
328 let builder = SafeSqlBuilder::new("SELECT")
329 .identifier("users")
330 .unwrap()
331 .raw("FROM")
332 .identifier("users")
333 .unwrap();
334
335 let sql = builder.build().unwrap();
336 assert_eq!(sql, "\"users\" FROM \"users\"");
337 }
338
339 #[test]
340 fn test_safe_sql_macros() {
341 let select_sql = safe_sql!(SELECT id, name FROM users).unwrap();
342 assert_eq!(select_sql, "SELECT \"id\", \"name\" FROM \"users\"");
343
344 let insert_sql = safe_sql!(INSERT INTO users (id, name) VALUES).unwrap();
345 assert!(insert_sql.contains("INSERT INTO \"users\""));
346 assert!(insert_sql.contains("VALUES"));
347 }
348
349 #[test]
350 fn test_sql_safety_context() {
351 let mut context = SqlSafetyContext::new("SELECT");
352 context.validate_identifier("users").unwrap();
353 context.escape_literal("test").unwrap();
354
355 let summary = context.safety_summary();
356 assert!(summary.contains("users"));
357 assert!(summary.contains("test"));
358 }
359}