reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Hybrid Property Integration with DML Operations
//!
//! This module provides integration between reinhardt-hybrid properties
//! and DML (Data Manipulation Language) operations like INSERT and UPDATE.
//!
//! Based on SQLAlchemy's hybrid property DML support.

use crate::backends::backend::DatabaseBackend;
use crate::hybrid::HybridProperty;
use std::collections::HashMap;
use std::sync::Arc;

/// Internal marker key for expanded hybrid property values.
///
/// When a hybrid property expands to multiple columns (e.g., Point(x, y) -> x, y),
/// we store them under this special key to distinguish from regular columns.
///
/// Uses a single underscore prefix following Rust conventions for internal identifiers.
const EXPANDED_MARKER: &str = "_expanded";

/// A value that can be inserted/updated, either direct or from a hybrid property
#[derive(Debug, Clone)]
pub enum DmlValue {
	/// Direct value
	Direct(String),
	/// Value from hybrid property expression
	HybridExpression(String),
	/// Multiple columns from hybrid property (e.g., Point(x, y) -> x, y)
	Expanded(Vec<(String, String)>),
}

/// Builder for INSERT statements with hybrid property support
pub struct InsertBuilder {
	table_name: String,
	values: HashMap<String, DmlValue>,
	backend: Option<Arc<dyn DatabaseBackend>>,
}

impl InsertBuilder {
	/// Create a new INSERT builder with hybrid property support
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::InsertBuilder;
	///
	/// let builder = InsertBuilder::new("users");
	/// // Can chain: .value().hybrid_value().build()
	/// ```
	pub fn new(table_name: &str) -> Self {
		Self {
			table_name: table_name.to_string(),
			values: HashMap::new(),
			backend: None,
		}
	}

	/// Set the database backend for placeholder generation
	pub fn with_backend(mut self, backend: Arc<dyn DatabaseBackend>) -> Self {
		self.backend = Some(backend);
		self
	}
	/// Add a direct column value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::InsertBuilder;
	///
	/// let builder = InsertBuilder::new("users")
	///     .value("name", "Alice")
	///     .value("email", "alice@example.com");
	///
	/// let (sql, params) = builder.build();
	/// // SQL output order may vary, verify components separately
	/// assert!(sql.starts_with("INSERT INTO users ("));
	/// assert!(sql.contains("name"));
	/// assert!(sql.contains("email"));
	/// assert!(sql.contains(") VALUES (?, ?)"));
	/// assert_eq!(params.len(), 2);
	/// // HashMap doesn't guarantee order, so check both values are present
	/// assert!(params.contains(&"Alice".to_string()));
	/// assert!(params.contains(&"alice@example.com".to_string()));
	/// ```
	pub fn value(mut self, column: &str, value: &str) -> Self {
		self.values
			.insert(column.to_string(), DmlValue::Direct(value.to_string()));
		self
	}
	/// Add a hybrid property value
	///
	/// This method integrates hybrid properties with DML operations.
	/// If the hybrid property has an SQL expression, it will be used;
	/// otherwise, the value is treated as a direct parameter.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::InsertBuilder;
	/// use reinhardt_db::hybrid::HybridProperty;
	///
	/// struct User { email: String }
	///
	/// let lower_email = HybridProperty::new(|user: &User| user.email.to_lowercase())
	///     .with_expression(|| "LOWER(email)".to_string());
	///
	/// let builder = InsertBuilder::new("users")
	///     .hybrid_value("email", &lower_email, "TEST@EXAMPLE.COM");
	///
	/// let (sql, _) = builder.build();
	/// assert_eq!(
	///     sql,
	///     "INSERT INTO users (email) VALUES (LOWER('TEST@EXAMPLE.COM'))",
	///     "Expected INSERT with LOWER expression, got: {}",
	///     sql
	/// );
	/// ```
	pub fn hybrid_value<T, R>(
		mut self,
		column: &str,
		property: &HybridProperty<T, R>,
		value: &str,
	) -> Self {
		// If the property has an expression, use it; otherwise treat as direct value
		if let Some(expr) = property.expression() {
			// Replace the column reference in the expression with the actual value
			// For example: "LOWER(email)" -> "LOWER('value')"
			let value_expr = format!("'{}'", value.replace('\'', "''"));
			let expanded_expr =
				expr.replace(&format!("({})", column), &format!("({})", value_expr));
			self.values.insert(
				column.to_string(),
				DmlValue::HybridExpression(expanded_expr),
			);
		} else {
			// No expression, use direct value
			self.values
				.insert(column.to_string(), DmlValue::Direct(value.to_string()));
		}
		self
	}
	/// Add an expanded hybrid property (e.g., Point -> x, y)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::InsertBuilder;
	///
	/// let builder = InsertBuilder::new("points")
	///     .expanded_hybrid(vec![("x", "10"), ("y", "20")]);
	///
	/// let (sql, params) = builder.build();
	/// assert_eq!(
	///     sql,
	///     "INSERT INTO points (x, y) VALUES (?, ?)",
	///     "Expected INSERT with expanded columns x and y, got: {}",
	///     sql
	/// );
	/// assert_eq!(params.len(), 2);
	/// assert_eq!(params[0], "10");
	/// assert_eq!(params[1], "20");
	/// ```
	pub fn expanded_hybrid(mut self, columns: Vec<(&str, &str)>) -> Self {
		let expanded = columns
			.into_iter()
			.map(|(col, val)| (col.to_string(), val.to_string()))
			.collect();

		// Add a special marker for expanded values
		self.values
			.insert(EXPANDED_MARKER.to_string(), DmlValue::Expanded(expanded));
		self
	}
	/// Build the SQL INSERT statement
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::InsertBuilder;
	///
	/// let builder = InsertBuilder::new("users")
	///     .value("name", "Bob")
	///     .value("age", "25");
	///
	/// let (sql, params) = builder.build();
	/// // SQL output order may vary, verify components separately
	/// assert!(sql.starts_with("INSERT INTO users ("));
	/// assert!(sql.contains("name"));
	/// assert!(sql.contains("age"));
	/// assert!(sql.contains(") VALUES (?, ?)"));
	/// assert_eq!(params.len(), 2);
	/// assert!(params.contains(&"Bob".to_string()));
	/// assert!(params.contains(&"25".to_string()));
	/// ```
	pub fn build(&self) -> (String, Vec<String>) {
		let mut columns = Vec::new();
		let mut placeholders = Vec::new();
		let mut params = Vec::new();
		let mut param_index = 1;

		// Get placeholder function
		let get_placeholder = |index: usize| -> String {
			if let Some(ref backend) = self.backend {
				backend.placeholder(index)
			} else {
				// Fallback to ? for backward compatibility
				"?".to_string()
			}
		};

		// Handle expanded values first
		if let Some(DmlValue::Expanded(expanded)) = self.values.get(EXPANDED_MARKER) {
			for (col, val) in expanded {
				columns.push(col.clone());
				placeholders.push(get_placeholder(param_index));
				param_index += 1;
				params.push(val.clone());
			}
		}

		// Handle regular values
		for (col, val) in &self.values {
			if col == EXPANDED_MARKER {
				continue;
			}
			match val {
				DmlValue::Direct(v) => {
					columns.push(col.clone());
					placeholders.push(get_placeholder(param_index));
					param_index += 1;
					params.push(v.clone());
				}
				DmlValue::HybridExpression(expr) => {
					columns.push(col.clone());
					placeholders.push(expr.clone());
				}
				DmlValue::Expanded(_) => {
					// Already handled above
				}
			}
		}

		let sql = format!(
			"INSERT INTO {} ({}) VALUES ({})",
			self.table_name,
			columns.join(", "),
			placeholders.join(", ")
		);

		(sql, params)
	}
}

/// Builder for UPDATE statements with hybrid property support
pub struct UpdateBuilder {
	table_name: String,
	values: HashMap<String, DmlValue>,
	where_clause: Option<(String, String)>,
	backend: Option<Arc<dyn DatabaseBackend>>,
}

impl UpdateBuilder {
	/// Create a new UPDATE builder with hybrid property support
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	///
	/// let builder = UpdateBuilder::new("users");
	/// // Can chain: .set().where_clause().build()
	/// ```
	pub fn new(table_name: &str) -> Self {
		Self {
			table_name: table_name.to_string(),
			values: HashMap::new(),
			where_clause: None,
			backend: None,
		}
	}

	/// Set the database backend for placeholder generation
	pub fn with_backend(mut self, backend: Arc<dyn DatabaseBackend>) -> Self {
		self.backend = Some(backend);
		self
	}
	/// Add a direct column value
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	///
	/// let builder = UpdateBuilder::new("users")
	///     .set("name", "Charlie")
	///     .set("age", "30")
	///     .where_clause("id", "1");
	///
	/// let (sql, params) = builder.build();
	/// // SQL output order may vary, verify components separately
	/// assert!(sql.starts_with("UPDATE users SET "));
	/// assert!(sql.contains("name=?"));
	/// assert!(sql.contains("age=?"));
	/// assert!(sql.contains(" WHERE \"id\"=?"));
	/// assert_eq!(params.len(), 3);
	/// assert!(params.contains(&"Charlie".to_string()));
	/// assert!(params.contains(&"30".to_string()));
	/// assert!(params.contains(&"1".to_string()));
	/// ```
	pub fn set(mut self, column: &str, value: &str) -> Self {
		self.values
			.insert(column.to_string(), DmlValue::Direct(value.to_string()));
		self
	}
	/// Add a hybrid property value
	///
	/// This method integrates hybrid properties with UPDATE operations.
	/// If the hybrid property has an SQL expression, it will be used;
	/// otherwise, the value is treated as a direct parameter.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	/// use reinhardt_db::hybrid::HybridProperty;
	///
	/// struct User { email: String }
	///
	/// let lower_email = HybridProperty::new(|user: &User| user.email.to_lowercase())
	///     .with_expression(|| "LOWER(email)".to_string());
	///
	/// let builder = UpdateBuilder::new("users")
	///     .set_hybrid("email", &lower_email, "UPDATED@EXAMPLE.COM")
	///     .where_clause("id", "1");
	///
	/// let (sql, params) = builder.build();
	/// assert!(sql.contains("email=LOWER('UPDATED@EXAMPLE.COM')"));
	/// assert!(sql.contains("WHERE \"id\"=?"));
	/// assert_eq!(params, vec!["1"]);
	/// ```
	pub fn set_hybrid<T, R>(
		mut self,
		column: &str,
		property: &HybridProperty<T, R>,
		value: &str,
	) -> Self {
		// If the property has an expression, use it; otherwise treat as direct value
		if let Some(expr) = property.expression() {
			// Replace the column reference in the expression with the actual value
			let value_expr = format!("'{}'", value.replace('\'', "''"));
			let expanded_expr =
				expr.replace(&format!("({})", column), &format!("({})", value_expr));
			self.values.insert(
				column.to_string(),
				DmlValue::HybridExpression(expanded_expr),
			);
		} else {
			// No expression, use direct value
			self.values
				.insert(column.to_string(), DmlValue::Direct(value.to_string()));
		}
		self
	}
	/// Add an expanded hybrid property (e.g., Point -> x, y)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	///
	/// let builder = UpdateBuilder::new("points")
	///     .set_expanded(vec![("x", "100"), ("y", "200")])
	///     .where_clause("id", "5");
	///
	/// let (sql, params) = builder.build();
	/// assert!(sql.contains("UPDATE points SET x=?, y=?"));
	/// assert!(sql.contains("WHERE \"id\"=?"));
	/// assert_eq!(params.len(), 3);
	/// assert_eq!(params[0], "100");
	/// assert_eq!(params[1], "200");
	/// assert_eq!(params[2], "5");
	/// ```
	pub fn set_expanded(mut self, columns: Vec<(&str, &str)>) -> Self {
		let expanded = columns
			.into_iter()
			.map(|(col, val)| (col.to_string(), val.to_string()))
			.collect();

		self.values
			.insert(EXPANDED_MARKER.to_string(), DmlValue::Expanded(expanded));
		self
	}
	/// Add a parameterized WHERE clause using column equality.
	///
	/// Uses `"column" = ?` with a bind parameter to prevent SQL injection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	///
	/// let builder = UpdateBuilder::new("users")
	///     .set("status", "active")
	///     .where_clause("id", "42");
	///
	/// let (sql, params) = builder.build();
	/// assert!(sql.contains("UPDATE users SET status=?"));
	/// assert!(sql.contains("WHERE \"id\"=?"));
	/// assert_eq!(params.len(), 2);
	/// assert_eq!(params[0], "active");
	/// assert_eq!(params[1], "42");
	/// ```
	pub fn where_clause(mut self, column: &str, value: &str) -> Self {
		self.where_clause = Some((column.to_string(), value.to_string()));
		self
	}
	/// Build the SQL UPDATE statement
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::orm::hybrid_dml::UpdateBuilder;
	///
	/// let builder = UpdateBuilder::new("users")
	///     .set("name", "David")
	///     .where_clause("id", "10");
	///
	/// let (sql, params) = builder.build();
	/// assert!(sql.contains("UPDATE users SET name=?"));
	/// assert!(sql.contains("WHERE \"id\"=?"));
	/// assert_eq!(params.len(), 2);
	/// assert_eq!(params[0], "David");
	/// assert_eq!(params[1], "10");
	/// ```
	pub fn build(&self) -> (String, Vec<String>) {
		let mut set_clauses = Vec::new();
		let mut params = Vec::new();
		let mut param_index = 1;

		// Get placeholder function
		let get_placeholder = |index: usize| -> String {
			if let Some(ref backend) = self.backend {
				backend.placeholder(index)
			} else {
				// Fallback to ? for backward compatibility
				"?".to_string()
			}
		};

		// Handle expanded values first
		if let Some(DmlValue::Expanded(expanded)) = self.values.get(EXPANDED_MARKER) {
			for (col, val) in expanded {
				set_clauses.push(format!("{}={}", col, get_placeholder(param_index)));
				param_index += 1;
				params.push(val.clone());
			}
		}

		// Handle regular values
		for (col, val) in &self.values {
			if col == EXPANDED_MARKER {
				continue;
			}
			match val {
				DmlValue::Direct(v) => {
					set_clauses.push(format!("{}={}", col, get_placeholder(param_index)));
					param_index += 1;
					params.push(v.clone());
				}
				DmlValue::HybridExpression(expr) => {
					set_clauses.push(format!("{}={}", col, expr));
				}
				DmlValue::Expanded(_) => {
					// Already handled above
				}
			}
		}

		let mut sql = format!("UPDATE {} SET {}", self.table_name, set_clauses.join(", "));

		if let Some((column, value)) = &self.where_clause {
			sql.push_str(&format!(" WHERE \"{}\"=?", column));
			params.push(value.clone());
		}

		(sql, params)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_insert_builder_simple() {
		let builder = InsertBuilder::new("person")
			.value("first_name", "John")
			.value("last_name", "Doe");

		let (sql, params) = builder.build();
		// SQL output order may vary, verify components separately
		assert!(
			sql.starts_with("INSERT INTO person ("),
			"Expected INSERT INTO person, got: {}",
			sql
		);
		assert!(
			sql.contains("first_name"),
			"Expected first_name in SQL: {}",
			sql
		);
		assert!(
			sql.contains("last_name"),
			"Expected last_name in SQL: {}",
			sql
		);
		assert!(
			sql.contains(") VALUES (?, ?)"),
			"Expected VALUES (?, ?), got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			2,
			"Expected 2 parameters, got: {}",
			params.len()
		);
		assert!(
			params.contains(&"John".to_string()),
			"Expected 'John' in params: {:?}",
			params
		);
		assert!(
			params.contains(&"Doe".to_string()),
			"Expected 'Doe' in params: {:?}",
			params
		);
	}

	#[test]
	fn test_update_builder_simple() {
		let builder = UpdateBuilder::new("person")
			.set("first_name", "Jane")
			.where_clause("id", "1");

		let (sql, params) = builder.build();
		assert!(
			sql.contains("UPDATE person SET first_name=?"),
			"Expected UPDATE person SET, got: {}",
			sql
		);
		assert!(
			sql.contains("WHERE \"id\"=?"),
			"Expected parameterized WHERE, got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			2,
			"Expected 2 parameters, got: {}",
			params.len()
		);
		assert_eq!(params[0], "Jane", "Expected 'Jane', got: {}", params[0]);
		assert_eq!(params[1], "1", "Expected '1', got: {}", params[1]);
	}

	#[test]
	fn test_insert_builder_expanded() {
		let builder = InsertBuilder::new("points").expanded_hybrid(vec![("x", "10"), ("y", "20")]);

		let (sql, params) = builder.build();
		assert_eq!(
			sql, "INSERT INTO points (x, y) VALUES (?, ?)",
			"Expected INSERT with expanded columns, got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			2,
			"Expected 2 parameters, got: {}",
			params.len()
		);
		assert_eq!(
			params[0], "10",
			"Expected '10' as first param, got: {}",
			params[0]
		);
		assert_eq!(
			params[1], "20",
			"Expected '20' as second param, got: {}",
			params[1]
		);
	}

	#[test]
	fn test_update_builder_expanded() {
		let builder = UpdateBuilder::new("points")
			.set_expanded(vec![("x", "30"), ("y", "40")])
			.where_clause("id", "1");

		let (sql, params) = builder.build();
		assert!(
			sql.contains("UPDATE points SET x=?, y=?"),
			"Expected UPDATE with expanded columns, got: {}",
			sql
		);
		assert!(
			sql.contains("WHERE \"id\"=?"),
			"Expected parameterized WHERE, got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			3,
			"Expected 3 parameters, got: {}",
			params.len()
		);
		assert_eq!(params[0], "30");
		assert_eq!(params[1], "40");
		assert_eq!(params[2], "1");
	}

	#[test]
	fn test_insert_builder_with_hybrid_expression() {
		struct User {
			email: String,
		}

		let lower_email = HybridProperty::new(|user: &User| user.email.to_lowercase())
			.with_expression(|| "LOWER(email)".to_string());

		let builder = InsertBuilder::new("users")
			.value("name", "John")
			.hybrid_value("email", &lower_email, "TEST@EXAMPLE.COM");

		let (sql, params) = builder.build();
		// SQL output order may vary, verify components separately
		assert!(
			sql.starts_with("INSERT INTO users ("),
			"Expected INSERT INTO users, got: {}",
			sql
		);
		assert!(
			sql.contains("name"),
			"Expected 'name' column in SQL: {}",
			sql
		);
		assert!(
			sql.contains("email"),
			"Expected 'email' column in SQL: {}",
			sql
		);
		assert!(
			sql.contains("LOWER('TEST@EXAMPLE.COM')"),
			"Expected LOWER expression in SQL: {}",
			sql
		);
		assert_eq!(
			params.len(),
			1,
			"Expected 1 parameter for name, got: {}",
			params.len()
		);
		assert_eq!(
			params[0], "John",
			"Expected 'John' as parameter, got: {}",
			params[0]
		);
	}

	#[test]
	fn test_insert_builder_with_hybrid_no_expression() {
		struct User {
			email: String,
		}

		let simple_prop = HybridProperty::new(|user: &User| user.email.clone());

		let builder = InsertBuilder::new("users")
			.value("name", "John")
			.hybrid_value("email", &simple_prop, "test@example.com");

		let (sql, params) = builder.build();
		// SQL output order may vary, verify components separately
		assert!(
			sql.starts_with("INSERT INTO users ("),
			"Expected INSERT INTO users, got: {}",
			sql
		);
		assert!(
			sql.contains("name"),
			"Expected 'name' column in SQL: {}",
			sql
		);
		assert!(
			sql.contains("email"),
			"Expected 'email' column in SQL: {}",
			sql
		);
		assert!(
			sql.contains(") VALUES (?, ?)"),
			"Expected VALUES (?, ?), got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			2,
			"Expected 2 parameters, got: {}",
			params.len()
		);
		assert!(
			params.contains(&"John".to_string()),
			"Expected 'John' in params: {:?}",
			params
		);
		assert!(
			params.contains(&"test@example.com".to_string()),
			"Expected 'test@example.com' in params: {:?}",
			params
		);
	}

	#[test]
	fn test_update_builder_with_hybrid_expression() {
		struct User {
			email: String,
		}

		let lower_email = HybridProperty::new(|user: &User| user.email.to_lowercase())
			.with_expression(|| "LOWER(email)".to_string());

		let builder = UpdateBuilder::new("users")
			.set_hybrid("email", &lower_email, "UPDATED@EXAMPLE.COM")
			.where_clause("id", "1");

		let (sql, params) = builder.build();
		assert!(
			sql.contains("email=LOWER('UPDATED@EXAMPLE.COM')"),
			"Expected LOWER expression, got: {}",
			sql
		);
		assert!(
			sql.contains("WHERE \"id\"=?"),
			"Expected parameterized WHERE, got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			1,
			"Expected 1 parameter (WHERE value), got: {}",
			params.len()
		);
		assert_eq!(params[0], "1");
	}

	#[test]
	fn test_update_builder_with_hybrid_no_expression() {
		struct User {
			email: String,
		}

		let simple_prop = HybridProperty::new(|user: &User| user.email.clone());

		let builder = UpdateBuilder::new("users")
			.set_hybrid("email", &simple_prop, "updated@example.com")
			.where_clause("id", "1");

		let (sql, params) = builder.build();
		assert!(
			sql.contains("UPDATE users SET email=?"),
			"Expected UPDATE with direct value, got: {}",
			sql
		);
		assert!(
			sql.contains("WHERE \"id\"=?"),
			"Expected parameterized WHERE, got: {}",
			sql
		);
		assert_eq!(
			params.len(),
			2,
			"Expected 2 parameters, got: {}",
			params.len()
		);
		assert_eq!(params[0], "updated@example.com");
		assert_eq!(params[1], "1");
	}

	#[test]
	fn test_insert_builder_hybrid_value_escapes_single_quotes() {
		// Arrange
		use crate::hybrid::property::HybridProperty;
		let prop: HybridProperty<String, String> = HybridProperty::new(|s: &String| s.clone())
			.with_expression(|| "LOWER(email)".to_string());

		// Act
		let builder = InsertBuilder::new("users").hybrid_value("email", &prop, "test@o'brien.com");
		let (sql, _params) = builder.build();

		// Assert
		assert!(
			sql.contains("LOWER('test@o''brien.com')"),
			"Single quotes in values must be escaped with double single quotes, got: {}",
			sql
		);
		assert!(
			!sql.contains("o'brien.com')"),
			"Unescaped single quote detected (SQL injection vulnerability), got: {}",
			sql
		);
	}

	#[test]
	fn test_update_builder_set_hybrid_escapes_single_quotes() {
		// Arrange
		use crate::hybrid::property::HybridProperty;
		let prop: HybridProperty<String, String> = HybridProperty::new(|s: &String| s.clone())
			.with_expression(|| "LOWER(email)".to_string());

		// Act
		let builder = UpdateBuilder::new("users")
			.set_hybrid("email", &prop, "'; DROP TABLE users;--")
			.where_clause("id", "1");
		let (sql, _params) = builder.build();

		// Assert: the single quote in value is escaped to ''
		// Input: '; DROP TABLE users;-- -> escaped: ''; DROP TABLE users;--
		// Wrapped: ''''; DROP TABLE users;--' (open-quote, escaped-quote-pair, rest, close-quote)
		// Wait: format!("'{}'", "''; DROP TABLE users;--") = "'''; DROP TABLE users;--'"
		// 3 quotes = open + escaped pair, then rest + close
		assert!(
			sql.contains("'''; DROP TABLE users;--'"),
			"SQL injection attempt must have single quotes escaped, got: {}",
			sql
		);
	}
}