ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! Parameter Binding Safety and CRUD Operations
//!
//! This module provides safe parameter binding, type validation, and CRUD operations
//! that integrate with our SQL safety system to prevent injection attacks.

use crate::common::validate_identifier;
use crate::macros::sql_safety::{SafeSqlBuilder, SqlSafetyContext};
use anyhow::{Context, Result};
use sqlx::{Executor, Postgres};
use std::collections::HashMap;

/// Safe parameter binding context for tracking bound values
#[derive(Debug, Clone)]
pub struct ParameterBindingContext {
    /// Track bound parameters with their types and values
    pub bound_parameters: HashMap<String, BoundParameter>,
    /// SQL safety context for the current operation
    pub safety_context: SqlSafetyContext,
    /// Current operation type
    pub operation: OperationType,
}

#[derive(Debug, Clone, Copy)]
pub enum OperationType {
    Insert,
    Update,
    Delete,
    Select,
}

#[derive(Debug, Clone)]
pub struct BoundParameter {
    /// The parameter name/placeholder
    pub name: String,
    /// The actual value
    pub value: BindValue,
    /// The expected SQL type
    pub sql_type: String,
    /// Whether the parameter has been validated
    pub validated: bool,
}

/// Safe value binding for database operations
#[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), // Store composite types as JSON for now
    Array(Vec<serde_json::Value>), // Store arrays of composite types as JSON array
    Null,
}

impl BindValue {
    /// Get the SQL type string for this value
    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", // Generic composite type
            BindValue::Array(_) => "COMPOSITE[]",   // Array of composite types
            BindValue::Null => "NULL",
        }
    }

    /// Validate that this value is safe for database binding
    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(()),
        }
    }

    /// Convert to the parameter binding format (for compatibility with derive macros)
    pub fn to_parameter_binding(self) -> BindValue {
        self // We're already the parameter binding format!
    }

    /// Get the value for sqlx binding
    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,
        }
    }
}

// From implementations for common types
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,
        }
    }
}

/// Reference to BindValue for sqlx binding
#[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), // Store composite types as JSON reference
    Array(&'a Vec<serde_json::Value>), // Store arrays as JSON array reference
    Null,
}

/// Safe CRUD operations builder
pub struct SafeCrudBuilder {
    table_name: String,
    binding_context: ParameterBindingContext,
    sql_builder: SafeSqlBuilder,
}

impl SafeCrudBuilder {
    /// Create a new safe CRUD builder
    pub fn new(operation: OperationType, table_name: &str) -> Result<Self> {
        // Validate table name and store the validated version
        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,
        })
    }

    /// Add a parameter binding
    pub fn bind(mut self, name: &str, value: BindValue) -> Result<Self> {
        // Validate the value
        value
            .validate()
            .with_context(|| format!("Validating parameter '{}'", name))?;

        // Create parameter placeholder
        let placeholder = format!("${}", self.binding_context.bound_parameters.len() + 1);

        // Store the binding
        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,
            },
        );

        // Add to SQL builder
        self.sql_builder = self.sql_builder.raw(&placeholder);

        Ok(self)
    }

    /// Get the validated table name
    pub fn table_name(&self) -> &str {
        &self.table_name
    }

    /// Build the final SQL with parameter placeholders
    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))
    }

    /// Execute the operation
    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()))?;

        // Execute the query (parameters will be bound by the caller)
        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())
    }
}

/// Safe INSERT operation builder
pub struct SafeInsertBuilder {
    table_name: String,
    columns: Vec<String>,
    values: Vec<BindValue>,
}

impl SafeInsertBuilder {
    /// Create a new safe INSERT builder
    pub fn new(table_name: &str) -> Result<Self> {
        // Handle schema-qualified table names properly
        let validated_table = if table_name.contains('.') {
            // Split schema and table name
            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(),
        })
    }

    /// Add a column-value pair
    pub fn value(mut self, column: &str, value: BindValue) -> Result<Self> {
        let validated_column = validate_identifier(column)
            .with_context(|| format!("Invalid column name: '{}'", column))?;

        // Validate the value
        value
            .validate()
            .with_context(|| format!("Validating value for column '{}'", column))?;

        self.columns.push(validated_column);
        self.values.push(value);

        Ok(self)
    }

    /// Build the INSERT SQL
    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()))
    }

    /// Execute the INSERT
    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()))?;

        // Build the query and bind all parameters
        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), // Bind as JSONB for now
                BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), // Bind as JSON array
                BindValue::Null => query.bind(Option::<String>::None),
            };
        }

        let result = query.execute(executor).await?;
        Ok(result.rows_affected())
    }
}

/// Safe UPDATE operation builder
pub struct SafeUpdateBuilder {
    table_name: String,
    set_clauses: Vec<(String, BindValue)>,
    where_clauses: Vec<(String, BindValue)>,
}

impl SafeUpdateBuilder {
    /// Create a new safe UPDATE builder
    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(),
        })
    }

    /// Add a SET clause
    pub fn set(mut self, column: &str, value: BindValue) -> Result<Self> {
        let validated_column = validate_identifier(column)
            .with_context(|| format!("Invalid column name: '{}'", column))?;

        // Validate the value
        value
            .validate()
            .with_context(|| format!("Validating value for SET column '{}'", column))?;

        self.set_clauses.push((validated_column, value));
        Ok(self)
    }

    /// Add a WHERE clause
    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))?;

        // Validate the value
        value
            .validate()
            .with_context(|| format!("Validating value for WHERE column '{}'", column))?;

        self.where_clauses.push((validated_column, value));
        Ok(self)
    }

    /// Build the UPDATE SQL
    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);

        // Build SET clause
        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(", ")));

        // Build WHERE clause
        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 ")));
        }

        // Collect all parameters
        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))
    }

    /// Execute the UPDATE
    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()))?;

        // Build the query and bind all parameters
        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), // Bind as JSONB for now
                BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), // Bind as JSON array
                BindValue::Null => query.bind(Option::<String>::None),
            };
        }

        let result = query.execute(executor).await?;
        Ok(result.rows_affected())
    }
}

/// Safe DELETE operation builder
pub struct SafeDeleteBuilder {
    table_name: String,
    where_clauses: Vec<(String, BindValue)>,
}

impl SafeDeleteBuilder {
    /// Create a new safe DELETE builder
    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(),
        })
    }

    /// Add a WHERE clause
    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))?;

        // Validate the value
        value
            .validate()
            .with_context(|| format!("Validating value for WHERE column '{}'", column))?;

        self.where_clauses.push((validated_column, value));
        Ok(self)
    }

    /// Build the DELETE SQL
    pub fn build_sql(&self) -> Result<(String, Vec<BindValue>)> {
        let mut sql = format!("DELETE FROM {}", self.table_name);

        // Build WHERE clause
        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 ")));
        }

        // Collect all parameters
        let parameters: Vec<BindValue> =
            self.where_clauses.iter().map(|(_, v)| v.clone()).collect();

        Ok((sql, parameters))
    }

    /// Execute the DELETE
    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()))?;

        // Build the query and bind all parameters
        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), // Bind as JSONB for now
                BindValue::Array(v) => query.bind(serde_json::Value::Array(v.clone())), // Bind as JSON array
                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);
    }
}