use crate::common::validate_identifier;
use crate::macros::sql_safety::{SafeSqlBuilder, SqlSafetyContext};
use anyhow::{Context, Result};
use sqlx::{Executor, Postgres};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub struct ParameterBindingContext {
pub bound_parameters: HashMap<String, BoundParameter>,
pub safety_context: SqlSafetyContext,
pub operation: OperationType,
}
#[derive(Debug, Clone, Copy)]
pub enum OperationType {
Insert,
Update,
Delete,
Select,
}
#[derive(Debug, Clone)]
pub struct BoundParameter {
pub name: String,
pub value: BindValue,
pub sql_type: String,
pub validated: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum BindValue {
Int4(i32),
Int8(i64),
Text(String),
Bool(bool),
Uuid(uuid::Uuid),
Timestamptz(chrono::DateTime<chrono::Utc>),
Numeric(rust_decimal::Decimal),
Jsonb(serde_json::Value),
Composite(serde_json::Value), Array(Vec<serde_json::Value>), Null,
}
impl BindValue {
pub fn sql_type(&self) -> &'static str {
match self {
BindValue::Int4(_) => "INTEGER",
BindValue::Int8(_) => "BIGINT",
BindValue::Text(_) => "TEXT",
BindValue::Bool(_) => "BOOLEAN",
BindValue::Uuid(_) => "UUID",
BindValue::Timestamptz(_) => "TIMESTAMPTZ",
BindValue::Numeric(_) => "NUMERIC",
BindValue::Jsonb(_) => "JSONB",
BindValue::Composite(_) => "COMPOSITE", BindValue::Array(_) => "COMPOSITE[]", BindValue::Null => "NULL",
}
}
pub fn validate(&self) -> Result<()> {
match self {
BindValue::Text(s) => {
if s.contains('\0') {
return Err(anyhow::anyhow!("String contains null bytes"));
}
if s.len() > 1000000 {
return Err(anyhow::anyhow!("String too long ({}), max 1MB", s.len()));
}
Ok(())
}
BindValue::Jsonb(v) => {
if v.to_string().len() > 1000000 {
return Err(anyhow::anyhow!(
"JSON too large ({}), max 1MB",
v.to_string().len()
));
}
Ok(())
}
_ => Ok(()),
}
}
pub fn to_parameter_binding(self) -> BindValue {
self }
pub fn as_ref(&self) -> BindValueRef<'_> {
match self {
BindValue::Int4(v) => BindValueRef::Int4(*v),
BindValue::Int8(v) => BindValueRef::Int8(*v),
BindValue::Text(v) => BindValueRef::Text(v.as_str()),
BindValue::Bool(v) => BindValueRef::Bool(*v),
BindValue::Uuid(v) => BindValueRef::Uuid(*v),
BindValue::Timestamptz(v) => BindValueRef::Timestamptz(*v),
BindValue::Numeric(v) => BindValueRef::Numeric(*v),
BindValue::Jsonb(v) => BindValueRef::Jsonb(v),
BindValue::Composite(v) => BindValueRef::Composite(v),
BindValue::Array(v) => BindValueRef::Array(v),
BindValue::Null => BindValueRef::Null,
}
}
}
impl From<i32> for BindValue {
fn from(value: i32) -> Self {
BindValue::Int4(value)
}
}
impl From<i64> for BindValue {
fn from(value: i64) -> Self {
BindValue::Int8(value)
}
}
impl From<String> for BindValue {
fn from(value: String) -> Self {
BindValue::Text(value)
}
}
impl From<&str> for BindValue {
fn from(value: &str) -> Self {
BindValue::Text(value.to_string())
}
}
impl From<bool> for BindValue {
fn from(value: bool) -> Self {
BindValue::Bool(value)
}
}
impl From<uuid::Uuid> for BindValue {
fn from(value: uuid::Uuid) -> Self {
BindValue::Uuid(value)
}
}
impl From<chrono::DateTime<chrono::Utc>> for BindValue {
fn from(value: chrono::DateTime<chrono::Utc>) -> Self {
BindValue::Timestamptz(value)
}
}
impl From<rust_decimal::Decimal> for BindValue {
fn from(value: rust_decimal::Decimal) -> Self {
BindValue::Numeric(value)
}
}
impl From<serde_json::Value> for BindValue {
fn from(value: serde_json::Value) -> Self {
BindValue::Jsonb(value)
}
}
impl From<Option<String>> for BindValue {
fn from(value: Option<String>) -> Self {
match value {
Some(v) => BindValue::Text(v),
None => BindValue::Null,
}
}
}
impl From<Option<i32>> for BindValue {
fn from(value: Option<i32>) -> Self {
match value {
Some(v) => BindValue::Int4(v),
None => BindValue::Null,
}
}
}
impl From<Option<i64>> for BindValue {
fn from(value: Option<i64>) -> Self {
match value {
Some(v) => BindValue::Int8(v),
None => BindValue::Null,
}
}
}
impl From<Option<bool>> for BindValue {
fn from(value: Option<bool>) -> Self {
match value {
Some(v) => BindValue::Bool(v),
None => BindValue::Null,
}
}
}
impl From<Option<chrono::DateTime<chrono::Utc>>> for BindValue {
fn from(value: Option<chrono::DateTime<chrono::Utc>>) -> Self {
match value {
Some(v) => BindValue::Timestamptz(v),
None => BindValue::Null,
}
}
}
impl From<Option<chrono::NaiveDate>> for BindValue {
fn from(value: Option<chrono::NaiveDate>) -> Self {
match value {
Some(v) => BindValue::Text(v.format("%Y-%m-%d").to_string()),
None => BindValue::Null,
}
}
}
impl From<Option<rust_decimal::Decimal>> for BindValue {
fn from(value: Option<rust_decimal::Decimal>) -> Self {
match value {
Some(v) => BindValue::Numeric(v),
None => BindValue::Null,
}
}
}
impl From<Option<uuid::Uuid>> for BindValue {
fn from(value: Option<uuid::Uuid>) -> Self {
match value {
Some(v) => BindValue::Uuid(v),
None => BindValue::Null,
}
}
}
impl From<Option<serde_json::Value>> for BindValue {
fn from(value: Option<serde_json::Value>) -> Self {
match value {
Some(v) => BindValue::Jsonb(v),
None => BindValue::Null,
}
}
}
#[derive(Debug)]
pub enum BindValueRef<'a> {
Int4(i32),
Int8(i64),
Text(&'a str),
Bool(bool),
Uuid(uuid::Uuid),
Timestamptz(chrono::DateTime<chrono::Utc>),
Numeric(rust_decimal::Decimal),
Jsonb(&'a serde_json::Value),
Composite(&'a serde_json::Value), Array(&'a Vec<serde_json::Value>), Null,
}
pub struct SafeCrudBuilder {
table_name: String,
binding_context: ParameterBindingContext,
sql_builder: SafeSqlBuilder,
}
impl SafeCrudBuilder {
pub fn new(operation: OperationType, table_name: &str) -> Result<Self> {
let validated_table = validate_identifier(table_name)
.with_context(|| format!("Invalid table name: '{}'", table_name))?;
let safety_context = SqlSafetyContext::new(match operation {
OperationType::Insert => "INSERT",
OperationType::Update => "UPDATE",
OperationType::Delete => "DELETE",
OperationType::Select => "SELECT",
});
let binding_context = ParameterBindingContext {
bound_parameters: HashMap::new(),
safety_context,
operation,
};
let sql_builder = SafeSqlBuilder::new(match operation {
OperationType::Insert => "INSERT",
OperationType::Update => "UPDATE",
OperationType::Delete => "DELETE",
OperationType::Select => "SELECT",
});
Ok(Self {
table_name: validated_table,
binding_context,
sql_builder,
})
}
pub fn bind(mut self, name: &str, value: BindValue) -> Result<Self> {
value
.validate()
.with_context(|| format!("Validating parameter '{}'", name))?;
let placeholder = format!("${}", self.binding_context.bound_parameters.len() + 1);
self.binding_context.bound_parameters.insert(
name.to_string(),
BoundParameter {
name: placeholder.clone(),
value: value.clone(),
sql_type: value.sql_type().to_string(),
validated: true,
},
);
self.sql_builder = self.sql_builder.raw(&placeholder);
Ok(self)
}
pub fn table_name(&self) -> &str {
&self.table_name
}
pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
let sql = self
.sql_builder
.clone()
.build()
.context("Building SQL from SafeSqlBuilder")?;
let parameters: Vec<BindValue> = self
.binding_context
.bound_parameters
.values()
.map(|p| p.value.clone())
.collect();
Ok((sql, parameters))
}
pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
where
E: Executor<'e, Database = Postgres>,
{
let (sql, _parameters) = self
.build_sql()
.map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
let result = match self.binding_context.operation {
OperationType::Insert | OperationType::Update | OperationType::Delete => {
sqlx::query(&sql).execute(executor).await?
}
OperationType::Select => {
return Err(sqlx::Error::Protocol(
"SELECT operations should use query!".into(),
));
}
};
Ok(result.rows_affected())
}
}
pub struct SafeInsertBuilder {
table_name: String,
columns: Vec<String>,
values: Vec<BindValue>,
}
impl SafeInsertBuilder {
pub fn new(table_name: &str) -> Result<Self> {
let validated_table = if table_name.contains('.') {
let parts: Vec<&str> = table_name.split('.').collect();
if parts.len() != 2 {
return Err(anyhow::anyhow!(
"Invalid schema-qualified table name: '{}'",
table_name
));
}
let schema = validate_identifier(parts[0])
.with_context(|| format!("Invalid schema name: '{}'", parts[0]))?;
let table = validate_identifier(parts[1])
.with_context(|| format!("Invalid table name: '{}'", parts[1]))?;
format!("{}.{}", schema, table)
} else {
validate_identifier(table_name)
.with_context(|| format!("Invalid table name: '{}'", table_name))?
};
Ok(Self {
table_name: validated_table,
columns: Vec::new(),
values: Vec::new(),
})
}
pub fn value(mut self, column: &str, value: BindValue) -> Result<Self> {
let validated_column = validate_identifier(column)
.with_context(|| format!("Invalid column name: '{}'", column))?;
value
.validate()
.with_context(|| format!("Validating value for column '{}'", column))?;
self.columns.push(validated_column);
self.values.push(value);
Ok(self)
}
pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
if self.columns.is_empty() {
return Err(anyhow::anyhow!("No columns specified for INSERT"));
}
let columns_str = self.columns.join(", ");
let placeholders: Vec<String> =
(1..=self.values.len()).map(|i| format!("${}", i)).collect();
let placeholders_str = placeholders.join(", ");
let sql = format!(
"INSERT INTO {} ({}) VALUES ({})",
self.table_name, columns_str, placeholders_str
);
Ok((sql, self.values.clone()))
}
pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
where
E: Executor<'e, Database = Postgres>,
{
let (sql, parameters) = self
.build_sql()
.map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
let mut query = sqlx::query(&sql);
for value in parameters {
query = match value {
BindValue::Int4(v) => query.bind(v),
BindValue::Int8(v) => query.bind(v),
BindValue::Text(v) => query.bind(v),
BindValue::Bool(v) => query.bind(v),
BindValue::Uuid(v) => query.bind(v),
BindValue::Timestamptz(v) => query.bind(v),
BindValue::Numeric(v) => query.bind(v),
BindValue::Jsonb(v) => query.bind(v),
BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
};
}
let result = query.execute(executor).await?;
Ok(result.rows_affected())
}
}
pub struct SafeUpdateBuilder {
table_name: String,
set_clauses: Vec<(String, BindValue)>,
where_clauses: Vec<(String, BindValue)>,
}
impl SafeUpdateBuilder {
pub fn new(table_name: &str) -> Result<Self> {
let validated_table = validate_identifier(table_name)
.with_context(|| format!("Invalid table name: '{}'", table_name))?;
Ok(Self {
table_name: validated_table,
set_clauses: Vec::new(),
where_clauses: Vec::new(),
})
}
pub fn set(mut self, column: &str, value: BindValue) -> Result<Self> {
let validated_column = validate_identifier(column)
.with_context(|| format!("Invalid column name: '{}'", column))?;
value
.validate()
.with_context(|| format!("Validating value for SET column '{}'", column))?;
self.set_clauses.push((validated_column, value));
Ok(self)
}
pub fn r#where(mut self, column: &str, value: BindValue) -> Result<Self> {
let validated_column = validate_identifier(column)
.with_context(|| format!("Invalid column name: '{}'", column))?;
value
.validate()
.with_context(|| format!("Validating value for WHERE column '{}'", column))?;
self.where_clauses.push((validated_column, value));
Ok(self)
}
pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
if self.set_clauses.is_empty() {
return Err(anyhow::anyhow!("No SET clauses specified for UPDATE"));
}
let mut sql = format!("UPDATE {}", self.table_name);
let set_parts: Vec<String> = self
.set_clauses
.iter()
.enumerate()
.map(|(i, (col, _))| format!("{} = ${}", col, i + 1))
.collect();
sql.push_str(&format!(" SET {}", set_parts.join(", ")));
if !self.where_clauses.is_empty() {
let where_parts: Vec<String> = self
.where_clauses
.iter()
.enumerate()
.map(|(i, (col, _))| format!("{} = ${}", col, i + 1 + self.set_clauses.len()))
.collect();
sql.push_str(&format!(" WHERE {}", where_parts.join(" AND ")));
}
let mut parameters = Vec::new();
parameters.extend(self.set_clauses.iter().map(|(_, v)| v.clone()));
parameters.extend(self.where_clauses.iter().map(|(_, v)| v.clone()));
Ok((sql, parameters))
}
pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
where
E: Executor<'e, Database = Postgres>,
{
let (sql, parameters) = self
.build_sql()
.map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
let mut query = sqlx::query(&sql);
for value in parameters {
query = match value {
BindValue::Int4(v) => query.bind(v),
BindValue::Int8(v) => query.bind(v),
BindValue::Text(v) => query.bind(v),
BindValue::Bool(v) => query.bind(v),
BindValue::Uuid(v) => query.bind(v),
BindValue::Timestamptz(v) => query.bind(v),
BindValue::Numeric(v) => query.bind(v),
BindValue::Jsonb(v) => query.bind(v),
BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
};
}
let result = query.execute(executor).await?;
Ok(result.rows_affected())
}
}
pub struct SafeDeleteBuilder {
table_name: String,
where_clauses: Vec<(String, BindValue)>,
}
impl SafeDeleteBuilder {
pub fn new(table_name: &str) -> Result<Self> {
let validated_table = validate_identifier(table_name)
.with_context(|| format!("Invalid table name: '{}'", table_name))?;
Ok(Self {
table_name: validated_table,
where_clauses: Vec::new(),
})
}
pub fn r#where(mut self, column: &str, value: BindValue) -> Result<Self> {
let validated_column = validate_identifier(column)
.with_context(|| format!("Invalid column name: '{}'", column))?;
value
.validate()
.with_context(|| format!("Validating value for WHERE column '{}'", column))?;
self.where_clauses.push((validated_column, value));
Ok(self)
}
pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
let mut sql = format!("DELETE FROM {}", self.table_name);
if !self.where_clauses.is_empty() {
let where_parts: Vec<String> = self
.where_clauses
.iter()
.enumerate()
.map(|(i, (col, _))| format!("{} = ${}", col, i + 1))
.collect();
sql.push_str(&format!(" WHERE {}", where_parts.join(" AND ")));
}
let parameters: Vec<BindValue> =
self.where_clauses.iter().map(|(_, v)| v.clone()).collect();
Ok((sql, parameters))
}
pub async fn execute<'e, E>(self, executor: E) -> Result<u64, sqlx::Error>
where
E: Executor<'e, Database = Postgres>,
{
let (sql, parameters) = self
.build_sql()
.map_err(|e| sqlx::Error::Protocol(format!("{:?}", e).into()))?;
let mut query = sqlx::query(&sql);
for value in parameters {
query = match value {
BindValue::Int4(v) => query.bind(v),
BindValue::Int8(v) => query.bind(v),
BindValue::Text(v) => query.bind(v),
BindValue::Bool(v) => query.bind(v),
BindValue::Uuid(v) => query.bind(v),
BindValue::Timestamptz(v) => query.bind(v),
BindValue::Numeric(v) => query.bind(v),
BindValue::Jsonb(v) => query.bind(v),
BindValue::Composite(v) => query.bind(v), BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), BindValue::Null => query.bind(Option::<String>::None),
};
}
let result = query.execute(executor).await?;
Ok(result.rows_affected())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bind_value_validation() {
let valid_text = BindValue::Text("safe text".to_string());
assert!(valid_text.validate().is_ok());
let null_text = BindValue::Text("text\0with\0nulls".to_string());
assert!(null_text.validate().is_err());
let valid_int = BindValue::Int4(42);
assert!(valid_int.validate().is_ok());
}
#[test]
fn test_safe_insert_builder() {
let builder = SafeInsertBuilder::new("users")
.unwrap()
.value("id", BindValue::Int4(1))
.unwrap()
.value("name", BindValue::Text("John".to_string()))
.unwrap();
let (sql, params) = builder.build_sql().unwrap();
assert!(sql.contains("INSERT INTO"));
assert!(sql.contains("id"));
assert!(sql.contains("name"));
assert_eq!(params.len(), 2);
}
#[test]
fn test_safe_update_builder() {
let builder = SafeUpdateBuilder::new("users")
.unwrap()
.set("name", BindValue::Text("Jane".to_string()))
.unwrap()
.r#where("id", BindValue::Int4(1))
.unwrap();
let (sql, params) = builder.build_sql().unwrap();
assert!(sql.contains("UPDATE"));
assert!(sql.contains("SET"));
assert!(sql.contains("WHERE"));
assert_eq!(params.len(), 2);
}
#[test]
fn test_safe_delete_builder() {
let builder = SafeDeleteBuilder::new("users")
.unwrap()
.r#where("id", BindValue::Int4(1))
.unwrap();
let (sql, params) = builder.build_sql().unwrap();
assert!(sql.contains("DELETE FROM"));
assert!(sql.contains("WHERE"));
assert_eq!(params.len(), 1);
}
}