1use crate::common::validate_identifier;
7use crate::macros::sql_safety::{SafeSqlBuilder, SqlSafetyContext};
8use anyhow::{Context, Result};
9use sqlx::{Executor, Postgres};
10use std::collections::HashMap;
11
12#[derive(Debug, Clone)]
14pub struct ParameterBindingContext {
15 pub bound_parameters: HashMap<String, BoundParameter>,
17 pub safety_context: SqlSafetyContext,
19 pub operation: OperationType,
21}
22
23#[derive(Debug, Clone, Copy)]
24pub enum OperationType {
25 Insert,
26 Update,
27 Delete,
28 Select,
29}
30
31#[derive(Debug, Clone)]
32pub struct BoundParameter {
33 pub name: String,
35 pub value: BindValue,
37 pub sql_type: String,
39 pub validated: bool,
41}
42
43#[derive(Debug, Clone, PartialEq)]
45pub enum BindValue {
46 Int4(i32),
47 Int8(i64),
48 Text(String),
49 Bool(bool),
50 Uuid(uuid::Uuid),
51 Timestamptz(chrono::DateTime<chrono::Utc>),
52 Numeric(rust_decimal::Decimal),
53 Jsonb(serde_json::Value),
54 Composite(serde_json::Value), Array(Vec<serde_json::Value>), Null,
57}
58
59impl BindValue {
60 pub fn sql_type(&self) -> &'static str {
62 match self {
63 BindValue::Int4(_) => "INTEGER",
64 BindValue::Int8(_) => "BIGINT",
65 BindValue::Text(_) => "TEXT",
66 BindValue::Bool(_) => "BOOLEAN",
67 BindValue::Uuid(_) => "UUID",
68 BindValue::Timestamptz(_) => "TIMESTAMPTZ",
69 BindValue::Numeric(_) => "NUMERIC",
70 BindValue::Jsonb(_) => "JSONB",
71 BindValue::Composite(_) => "COMPOSITE", BindValue::Array(_) => "COMPOSITE[]", BindValue::Null => "NULL",
74 }
75 }
76
77 pub fn validate(&self) -> Result<()> {
79 match self {
80 BindValue::Text(s) => {
81 if s.contains('\0') {
82 return Err(anyhow::anyhow!("String contains null bytes"));
83 }
84 if s.len() > 1000000 {
85 return Err(anyhow::anyhow!("String too long ({}), max 1MB", s.len()));
86 }
87 Ok(())
88 }
89 BindValue::Jsonb(v) => {
90 if v.to_string().len() > 1000000 {
91 return Err(anyhow::anyhow!(
92 "JSON too large ({}), max 1MB",
93 v.to_string().len()
94 ));
95 }
96 Ok(())
97 }
98 _ => Ok(()),
99 }
100 }
101
102 pub fn to_parameter_binding(self) -> BindValue {
104 self }
106
107 pub fn as_ref(&self) -> BindValueRef<'_> {
109 match self {
110 BindValue::Int4(v) => BindValueRef::Int4(*v),
111 BindValue::Int8(v) => BindValueRef::Int8(*v),
112 BindValue::Text(v) => BindValueRef::Text(v.as_str()),
113 BindValue::Bool(v) => BindValueRef::Bool(*v),
114 BindValue::Uuid(v) => BindValueRef::Uuid(*v),
115 BindValue::Timestamptz(v) => BindValueRef::Timestamptz(*v),
116 BindValue::Numeric(v) => BindValueRef::Numeric(*v),
117 BindValue::Jsonb(v) => BindValueRef::Jsonb(v),
118 BindValue::Composite(v) => BindValueRef::Composite(v),
119 BindValue::Array(v) => BindValueRef::Array(v),
120 BindValue::Null => BindValueRef::Null,
121 }
122 }
123}
124
125impl From<i32> for BindValue {
127 fn from(value: i32) -> Self {
128 BindValue::Int4(value)
129 }
130}
131
132impl From<i64> for BindValue {
133 fn from(value: i64) -> Self {
134 BindValue::Int8(value)
135 }
136}
137
138impl From<String> for BindValue {
139 fn from(value: String) -> Self {
140 BindValue::Text(value)
141 }
142}
143
144impl From<&str> for BindValue {
145 fn from(value: &str) -> Self {
146 BindValue::Text(value.to_string())
147 }
148}
149
150impl From<bool> for BindValue {
151 fn from(value: bool) -> Self {
152 BindValue::Bool(value)
153 }
154}
155
156impl From<uuid::Uuid> for BindValue {
157 fn from(value: uuid::Uuid) -> Self {
158 BindValue::Uuid(value)
159 }
160}
161
162impl From<chrono::DateTime<chrono::Utc>> for BindValue {
163 fn from(value: chrono::DateTime<chrono::Utc>) -> Self {
164 BindValue::Timestamptz(value)
165 }
166}
167
168impl From<rust_decimal::Decimal> for BindValue {
169 fn from(value: rust_decimal::Decimal) -> Self {
170 BindValue::Numeric(value)
171 }
172}
173
174impl From<serde_json::Value> for BindValue {
175 fn from(value: serde_json::Value) -> Self {
176 BindValue::Jsonb(value)
177 }
178}
179
180impl From<Option<String>> for BindValue {
181 fn from(value: Option<String>) -> Self {
182 match value {
183 Some(v) => BindValue::Text(v),
184 None => BindValue::Null,
185 }
186 }
187}
188
189impl From<Option<i32>> for BindValue {
190 fn from(value: Option<i32>) -> Self {
191 match value {
192 Some(v) => BindValue::Int4(v),
193 None => BindValue::Null,
194 }
195 }
196}
197
198impl From<Option<i64>> for BindValue {
199 fn from(value: Option<i64>) -> Self {
200 match value {
201 Some(v) => BindValue::Int8(v),
202 None => BindValue::Null,
203 }
204 }
205}
206
207impl From<Option<bool>> for BindValue {
208 fn from(value: Option<bool>) -> Self {
209 match value {
210 Some(v) => BindValue::Bool(v),
211 None => BindValue::Null,
212 }
213 }
214}
215
216impl From<Option<chrono::DateTime<chrono::Utc>>> for BindValue {
217 fn from(value: Option<chrono::DateTime<chrono::Utc>>) -> Self {
218 match value {
219 Some(v) => BindValue::Timestamptz(v),
220 None => BindValue::Null,
221 }
222 }
223}
224
225impl From<Option<chrono::NaiveDate>> for BindValue {
226 fn from(value: Option<chrono::NaiveDate>) -> Self {
227 match value {
228 Some(v) => BindValue::Text(v.format("%Y-%m-%d").to_string()),
229 None => BindValue::Null,
230 }
231 }
232}
233
234impl From<Option<rust_decimal::Decimal>> for BindValue {
235 fn from(value: Option<rust_decimal::Decimal>) -> Self {
236 match value {
237 Some(v) => BindValue::Numeric(v),
238 None => BindValue::Null,
239 }
240 }
241}
242
243impl From<Option<uuid::Uuid>> for BindValue {
244 fn from(value: Option<uuid::Uuid>) -> Self {
245 match value {
246 Some(v) => BindValue::Uuid(v),
247 None => BindValue::Null,
248 }
249 }
250}
251
252impl From<Option<serde_json::Value>> for BindValue {
253 fn from(value: Option<serde_json::Value>) -> Self {
254 match value {
255 Some(v) => BindValue::Jsonb(v),
256 None => BindValue::Null,
257 }
258 }
259}
260
261#[derive(Debug)]
263pub enum BindValueRef<'a> {
264 Int4(i32),
265 Int8(i64),
266 Text(&'a str),
267 Bool(bool),
268 Uuid(uuid::Uuid),
269 Timestamptz(chrono::DateTime<chrono::Utc>),
270 Numeric(rust_decimal::Decimal),
271 Jsonb(&'a serde_json::Value),
272 Composite(&'a serde_json::Value), Array(&'a Vec<serde_json::Value>), Null,
275}
276
277pub struct SafeCrudBuilder {
279 table_name: String,
280 binding_context: ParameterBindingContext,
281 sql_builder: SafeSqlBuilder,
282}
283
284impl SafeCrudBuilder {
285 pub fn new(operation: OperationType, table_name: &str) -> Result<Self> {
287 let validated_table = validate_identifier(table_name)
289 .with_context(|| format!("Invalid table name: '{}'", table_name))?;
290
291 let safety_context = SqlSafetyContext::new(match operation {
292 OperationType::Insert => "INSERT",
293 OperationType::Update => "UPDATE",
294 OperationType::Delete => "DELETE",
295 OperationType::Select => "SELECT",
296 });
297
298 let binding_context = ParameterBindingContext {
299 bound_parameters: HashMap::new(),
300 safety_context,
301 operation,
302 };
303
304 let sql_builder = SafeSqlBuilder::new(match operation {
305 OperationType::Insert => "INSERT",
306 OperationType::Update => "UPDATE",
307 OperationType::Delete => "DELETE",
308 OperationType::Select => "SELECT",
309 });
310
311 Ok(Self {
312 table_name: validated_table,
313 binding_context,
314 sql_builder,
315 })
316 }
317
318 pub fn bind(mut self, name: &str, value: BindValue) -> Result<Self> {
320 value
322 .validate()
323 .with_context(|| format!("Validating parameter '{}'", name))?;
324
325 let placeholder = format!("${}", self.binding_context.bound_parameters.len() + 1);
327
328 self.binding_context.bound_parameters.insert(
330 name.to_string(),
331 BoundParameter {
332 name: placeholder.clone(),
333 value: value.clone(),
334 sql_type: value.sql_type().to_string(),
335 validated: true,
336 },
337 );
338
339 self.sql_builder = self.sql_builder.raw(&placeholder);
341
342 Ok(self)
343 }
344
345 pub fn table_name(&self) -> &str {
347 &self.table_name
348 }
349
350 pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
352 let sql = self
353 .sql_builder
354 .clone()
355 .build()
356 .context("Building SQL from SafeSqlBuilder")?;
357 let parameters: Vec<BindValue> = self
358 .binding_context
359 .bound_parameters
360 .values()
361 .map(|p| p.value.clone())
362 .collect();
363
364 Ok((sql, parameters))
365 }
366
367 pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
369 where
370 E: Executor<'e, Database = Postgres>,
371 {
372 let (sql, _parameters) = self
373 .build_sql()
374 .map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
375
376 let result = match self.binding_context.operation {
378 OperationType::Insert | OperationType::Update | OperationType::Delete => {
379 sqlx::query(&sql).execute(executor).await?
380 }
381 OperationType::Select => {
382 return Err(sqlx::Error::Protocol(
383 "SELECT operations should use query!".into(),
384 ));
385 }
386 };
387
388 Ok(result.rows_affected())
389 }
390}
391
392pub struct SafeInsertBuilder {
394 table_name: String,
395 columns: Vec<String>,
396 values: Vec<BindValue>,
397}
398
399impl SafeInsertBuilder {
400 pub fn new(table_name: &str) -> Result<Self> {
402 let validated_table = if table_name.contains('.') {
404 let parts: Vec<&str> = table_name.split('.').collect();
406 if parts.len() != 2 {
407 return Err(anyhow::anyhow!(
408 "Invalid schema-qualified table name: '{}'",
409 table_name
410 ));
411 }
412 let schema = validate_identifier(parts[0])
413 .with_context(|| format!("Invalid schema name: '{}'", parts[0]))?;
414 let table = validate_identifier(parts[1])
415 .with_context(|| format!("Invalid table name: '{}'", parts[1]))?;
416 format!("{}.{}", schema, table)
417 } else {
418 validate_identifier(table_name)
419 .with_context(|| format!("Invalid table name: '{}'", table_name))?
420 };
421
422 Ok(Self {
423 table_name: validated_table,
424 columns: Vec::new(),
425 values: Vec::new(),
426 })
427 }
428
429 pub fn value(mut self, column: &str, value: BindValue) -> Result<Self> {
431 let validated_column = validate_identifier(column)
432 .with_context(|| format!("Invalid column name: '{}'", column))?;
433
434 value
436 .validate()
437 .with_context(|| format!("Validating value for column '{}'", column))?;
438
439 self.columns.push(validated_column);
440 self.values.push(value);
441
442 Ok(self)
443 }
444
445 pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
447 if self.columns.is_empty() {
448 return Err(anyhow::anyhow!("No columns specified for INSERT"));
449 }
450
451 let columns_str = self.columns.join(", ");
452 let placeholders: Vec<String> =
453 (1..=self.values.len()).map(|i| format!("${}", i)).collect();
454 let placeholders_str = placeholders.join(", ");
455
456 let sql = format!(
457 "INSERT INTO {} ({}) VALUES ({})",
458 self.table_name, columns_str, placeholders_str
459 );
460
461 Ok((sql, self.values.clone()))
462 }
463
464 pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
466 where
467 E: Executor<'e, Database = Postgres>,
468 {
469 let (sql, parameters) = self
470 .build_sql()
471 .map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
472
473 let mut query = sqlx::query(&sql);
475 for value in parameters {
476 query = match value {
477 BindValue::Int4(v) => query.bind(v),
478 BindValue::Int8(v) => query.bind(v),
479 BindValue::Text(v) => query.bind(v),
480 BindValue::Bool(v) => query.bind(v),
481 BindValue::Uuid(v) => query.bind(v),
482 BindValue::Timestamptz(v) => query.bind(v),
483 BindValue::Numeric(v) => query.bind(v),
484 BindValue::Jsonb(v) => query.bind(v),
485 BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
488 };
489 }
490
491 let result = query.execute(executor).await?;
492 Ok(result.rows_affected())
493 }
494}
495
496pub struct SafeUpdateBuilder {
498 table_name: String,
499 set_clauses: Vec<(String, BindValue)>,
500 where_clauses: Vec<(String, BindValue)>,
501}
502
503impl SafeUpdateBuilder {
504 pub fn new(table_name: &str) -> Result<Self> {
506 let validated_table = validate_identifier(table_name)
507 .with_context(|| format!("Invalid table name: '{}'", table_name))?;
508
509 Ok(Self {
510 table_name: validated_table,
511 set_clauses: Vec::new(),
512 where_clauses: Vec::new(),
513 })
514 }
515
516 pub fn set(mut self, column: &str, value: BindValue) -> Result<Self> {
518 let validated_column = validate_identifier(column)
519 .with_context(|| format!("Invalid column name: '{}'", column))?;
520
521 value
523 .validate()
524 .with_context(|| format!("Validating value for SET column '{}'", column))?;
525
526 self.set_clauses.push((validated_column, value));
527 Ok(self)
528 }
529
530 pub fn r#where(mut self, column: &str, value: BindValue) -> Result<Self> {
532 let validated_column = validate_identifier(column)
533 .with_context(|| format!("Invalid column name: '{}'", column))?;
534
535 value
537 .validate()
538 .with_context(|| format!("Validating value for WHERE column '{}'", column))?;
539
540 self.where_clauses.push((validated_column, value));
541 Ok(self)
542 }
543
544 pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
546 if self.set_clauses.is_empty() {
547 return Err(anyhow::anyhow!("No SET clauses specified for UPDATE"));
548 }
549
550 let mut sql = format!("UPDATE {}", self.table_name);
551
552 let set_parts: Vec<String> = self
554 .set_clauses
555 .iter()
556 .enumerate()
557 .map(|(i, (col, _))| format!("{} = ${}", col, i + 1))
558 .collect();
559 sql.push_str(&format!(" SET {}", set_parts.join(", ")));
560
561 if !self.where_clauses.is_empty() {
563 let where_parts: Vec<String> = self
564 .where_clauses
565 .iter()
566 .enumerate()
567 .map(|(i, (col, _))| format!("{} = ${}", col, i + 1 + self.set_clauses.len()))
568 .collect();
569 sql.push_str(&format!(" WHERE {}", where_parts.join(" AND ")));
570 }
571
572 let mut parameters = Vec::new();
574 parameters.extend(self.set_clauses.iter().map(|(_, v)| v.clone()));
575 parameters.extend(self.where_clauses.iter().map(|(_, v)| v.clone()));
576
577 Ok((sql, parameters))
578 }
579
580 pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
582 where
583 E: Executor<'e, Database = Postgres>,
584 {
585 let (sql, parameters) = self
586 .build_sql()
587 .map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
588
589 let mut query = sqlx::query(&sql);
591 for value in parameters {
592 query = match value {
593 BindValue::Int4(v) => query.bind(v),
594 BindValue::Int8(v) => query.bind(v),
595 BindValue::Text(v) => query.bind(v),
596 BindValue::Bool(v) => query.bind(v),
597 BindValue::Uuid(v) => query.bind(v),
598 BindValue::Timestamptz(v) => query.bind(v),
599 BindValue::Numeric(v) => query.bind(v),
600 BindValue::Jsonb(v) => query.bind(v),
601 BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
604 };
605 }
606
607 let result = query.execute(executor).await?;
608 Ok(result.rows_affected())
609 }
610}
611
612pub struct SafeDeleteBuilder {
614 table_name: String,
615 where_clauses: Vec<(String, BindValue)>,
616}
617
618impl SafeDeleteBuilder {
619 pub fn new(table_name: &str) -> Result<Self> {
621 let validated_table = validate_identifier(table_name)
622 .with_context(|| format!("Invalid table name: '{}'", table_name))?;
623
624 Ok(Self {
625 table_name: validated_table,
626 where_clauses: Vec::new(),
627 })
628 }
629
630 pub fn r#where(mut self, column: &str, value: BindValue) -> Result<Self> {
632 let validated_column = validate_identifier(column)
633 .with_context(|| format!("Invalid column name: '{}'", column))?;
634
635 value
637 .validate()
638 .with_context(|| format!("Validating value for WHERE column '{}'", column))?;
639
640 self.where_clauses.push((validated_column, value));
641 Ok(self)
642 }
643
644 pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
646 let mut sql = format!("DELETE FROM {}", self.table_name);
647
648 if !self.where_clauses.is_empty() {
650 let where_parts: Vec<String> = self
651 .where_clauses
652 .iter()
653 .enumerate()
654 .map(|(i, (col, _))| format!("{} = ${}", col, i + 1))
655 .collect();
656 sql.push_str(&format!(" WHERE {}", where_parts.join(" AND ")));
657 }
658
659 let parameters: Vec<BindValue> =
661 self.where_clauses.iter().map(|(_, v)| v.clone()).collect();
662
663 Ok((sql, parameters))
664 }
665
666 pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
668 where
669 E: Executor<'e, Database = Postgres>,
670 {
671 let (sql, parameters) = self
672 .build_sql()
673 .map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
674
675 let mut query = sqlx::query(&sql);
677 for value in parameters {
678 query = match value {
679 BindValue::Int4(v) => query.bind(v),
680 BindValue::Int8(v) => query.bind(v),
681 BindValue::Text(v) => query.bind(v),
682 BindValue::Bool(v) => query.bind(v),
683 BindValue::Uuid(v) => query.bind(v),
684 BindValue::Timestamptz(v) => query.bind(v),
685 BindValue::Numeric(v) => query.bind(v),
686 BindValue::Jsonb(v) => query.bind(v),
687 BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
690 };
691 }
692
693 let result = query.execute(executor).await?;
694 Ok(result.rows_affected())
695 }
696}
697
698#[cfg(test)]
699mod tests {
700 use super::*;
701
702 #[test]
703 fn test_bind_value_validation() {
704 let valid_text = BindValue::Text("safe text".to_string());
705 assert!(valid_text.validate().is_ok());
706
707 let null_text = BindValue::Text("text\0with\0nulls".to_string());
708 assert!(null_text.validate().is_err());
709
710 let valid_int = BindValue::Int4(42);
711 assert!(valid_int.validate().is_ok());
712 }
713
714 #[test]
715 fn test_safe_insert_builder() {
716 let builder = SafeInsertBuilder::new("users")
717 .unwrap()
718 .value("id", BindValue::Int4(1))
719 .unwrap()
720 .value("name", BindValue::Text("John".to_string()))
721 .unwrap();
722
723 let (sql, params) = builder.build_sql().unwrap();
724 assert!(sql.contains("INSERT INTO"));
725 assert!(sql.contains("id"));
726 assert!(sql.contains("name"));
727 assert_eq!(params.len(), 2);
728 }
729
730 #[test]
731 fn test_safe_update_builder() {
732 let builder = SafeUpdateBuilder::new("users")
733 .unwrap()
734 .set("name", BindValue::Text("Jane".to_string()))
735 .unwrap()
736 .r#where("id", BindValue::Int4(1))
737 .unwrap();
738
739 let (sql, params) = builder.build_sql().unwrap();
740 assert!(sql.contains("UPDATE"));
741 assert!(sql.contains("SET"));
742 assert!(sql.contains("WHERE"));
743 assert_eq!(params.len(), 2);
744 }
745
746 #[test]
747 fn test_safe_delete_builder() {
748 let builder = SafeDeleteBuilder::new("users")
749 .unwrap()
750 .r#where("id", BindValue::Int4(1))
751 .unwrap();
752
753 let (sql, params) = builder.build_sql().unwrap();
754 assert!(sql.contains("DELETE FROM"));
755 assert!(sql.contains("WHERE"));
756 assert_eq!(params.len(), 1);
757 }
758}