reinhardt-db 0.1.2

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
838
839
840
841
842
843
844
845
//! Django-style accessor for ManyToMany relationships.
//!
//! This module provides the ManyToManyAccessor type, which implements
//! Django-style API for managing many-to-many relationships:
//! - `add()` - Add a relationship
//! - `remove()` - Remove a relationship
//! - `all()` - Get all related records
//! - `clear()` - Remove all relationships
//! - `set()` - Replace all relationships

use super::Manager;
use super::connection::{DatabaseBackend, DatabaseConnection};
use super::relationship::RelationshipType;
use crate::m2m_naming::{default_m2m_columns, default_through_table};
use crate::orm::Model;
use reinhardt_query::prelude::{
	Alias, BinOper, ColumnRef, DeleteStatement, Expr, Func, InsertStatement, MySqlQueryBuilder,
	PostgresQueryBuilder, Query, QueryBuilder, SelectStatement, SqliteQueryBuilder, Values,
};
use serde::{Serialize, de::DeserializeOwned};
use std::marker::PhantomData;

/// Build SELECT SQL using the appropriate QueryBuilder for the given backend.
fn build_select_sql(stmt: &SelectStatement, backend: DatabaseBackend) -> (String, Values) {
	match backend {
		DatabaseBackend::Postgres => PostgresQueryBuilder.build_select(stmt),
		DatabaseBackend::MySql => MySqlQueryBuilder.build_select(stmt),
		DatabaseBackend::Sqlite => SqliteQueryBuilder.build_select(stmt),
	}
}

/// Build INSERT SQL using the appropriate QueryBuilder for the given backend.
fn build_insert_sql(stmt: &InsertStatement, backend: DatabaseBackend) -> (String, Values) {
	match backend {
		DatabaseBackend::Postgres => PostgresQueryBuilder.build_insert(stmt),
		DatabaseBackend::MySql => MySqlQueryBuilder.build_insert(stmt),
		DatabaseBackend::Sqlite => SqliteQueryBuilder.build_insert(stmt),
	}
}

/// Build DELETE SQL using the appropriate QueryBuilder for the given backend.
fn build_delete_sql(stmt: &DeleteStatement, backend: DatabaseBackend) -> (String, Values) {
	match backend {
		DatabaseBackend::Postgres => PostgresQueryBuilder.build_delete(stmt),
		DatabaseBackend::MySql => MySqlQueryBuilder.build_delete(stmt),
		DatabaseBackend::Sqlite => SqliteQueryBuilder.build_delete(stmt),
	}
}

/// Django-style accessor for ManyToMany relationships.
///
/// This type provides methods to manage many-to-many relationships
/// using an intermediate/through table.
///
/// # Type Parameters
///
/// - `S`: Source model type (the model that owns the ManyToMany field)
/// - `T`: Target model type (the related model)
///
/// # Examples
///
/// ```rust,ignore
/// # #[tokio::main]
/// # async fn main() {
/// use reinhardt_db::orm::{Model, ManyToManyAccessor};
///
/// let user = User::find_by_id(&db, user_id).await?;
/// let accessor = ManyToManyAccessor::new(&user, "groups", db.clone());
///
/// // Add a relationship
/// accessor.add(&group).await?;
///
/// // Get all related records
/// let groups = accessor.all().await?;
///
/// // Remove a relationship
/// accessor.remove(&group).await?;
///
/// // Clear all relationships
/// accessor.clear().await?;
///
/// # }
/// ```
pub struct ManyToManyAccessor<S, T>
where
	S: Model,
	T: Model + Serialize + DeserializeOwned,
{
	source_id: S::PrimaryKey,
	through_table: String,
	source_field: String,
	target_field: String,
	db: DatabaseConnection,
	limit: Option<usize>,
	offset: Option<usize>,
	_phantom_source: PhantomData<S>,
	_phantom_target: PhantomData<T>,
}

impl<S, T> ManyToManyAccessor<S, T>
where
	S: Model,
	T: Model + Serialize + DeserializeOwned,
{
	/// Create a new ManyToManyAccessor.
	///
	/// # Parameters
	///
	/// - `source`: The source model instance
	/// - `field_name`: The name of the ManyToMany field
	/// - `db`: Database connection
	///
	/// # Panics
	///
	/// Panics if:
	/// - The field_name does not correspond to a ManyToMany field
	/// - The source model has no primary key
	pub fn new(source: &S, field_name: &str, db: DatabaseConnection) -> Self {
		// Try to get through table info from model metadata
		let rel_info = S::relationship_metadata()
			.into_iter()
			.find(|r| r.name == field_name && r.relationship_type == RelationshipType::ManyToMany);

		// Get through table name and FK column names from metadata, falling
		// back to the canonical convention defined in `crate::m2m_naming`
		// (single source of truth shared with the migration autodetector;
		// see issues #4659 and #4665). `default_m2m_columns` applies the
		// `from_/to_` prefix only for self-referential M2M, matching what
		// `MigrationAutodetector::create_intermediate_table_for_m2m` emits.
		let through_table = rel_info
			.as_ref()
			.and_then(|r| r.through_table.clone())
			.unwrap_or_else(|| default_through_table(S::table_name(), field_name));

		let source_id = source
			.primary_key()
			.expect("Source model must have primary key")
			.clone();

		let (default_source_field, default_target_field) =
			default_m2m_columns(S::table_name(), T::table_name());
		let source_field = rel_info
			.as_ref()
			.and_then(|r| r.source_field.clone())
			.unwrap_or(default_source_field);

		let target_field = rel_info
			.as_ref()
			.and_then(|r| r.target_field.clone())
			.unwrap_or(default_target_field);

		Self {
			source_id,
			through_table,
			source_field,
			target_field,
			db,
			limit: None,
			offset: None,
			_phantom_source: PhantomData,
			_phantom_target: PhantomData,
		}
	}

	/// Add a relationship to the target model.
	///
	/// Creates a record in the intermediate table linking the source and target.
	///
	/// # Parameters
	///
	/// - `target`: The target model to add
	///
	/// # Errors
	///
	/// Returns an error if:
	/// - The target model has no primary key
	/// - The database operation fails
	///
	/// # Examples
	///
	/// ```ignore
	/// accessor.add(&group).await?;
	/// ```
	pub async fn add(&self, target: &T) -> Result<(), String> {
		let target_id = target
			.primary_key()
			.ok_or_else(|| "Target model has no primary key".to_string())?;

		let query = Query::insert()
			.into_table(Alias::new(&self.through_table))
			.columns([
				Alias::new(&self.source_field),
				Alias::new(&self.target_field),
			])
			.values_panic([
				Expr::val(self.source_id.to_string()),
				Expr::val(target_id.to_string()),
			])
			.to_owned();

		let (sql, _values) = build_insert_sql(&query, self.db.backend());

		self.db
			.execute(&sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		Ok(())
	}

	/// Remove a relationship to the target model.
	///
	/// Deletes the record in the intermediate table linking the source and target.
	///
	/// # Parameters
	///
	/// - `target`: The target model to remove
	///
	/// # Errors
	///
	/// Returns an error if:
	/// - The target model has no primary key
	/// - The database operation fails
	///
	/// # Examples
	///
	/// ```ignore
	/// accessor.remove(&group).await?;
	/// ```
	pub async fn remove(&self, target: &T) -> Result<(), String> {
		let target_id = target
			.primary_key()
			.ok_or_else(|| "Target model has no primary key".to_string())?;

		let query = Query::delete()
			.from_table(Alias::new(&self.through_table))
			.and_where(
				Expr::col(Alias::new(&self.source_field))
					.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			)
			.and_where(
				Expr::col(Alias::new(&self.target_field))
					.binary(BinOper::Equal, Expr::val(target_id.to_string())),
			)
			.to_owned();

		let (sql, _values) = build_delete_sql(&query, self.db.backend());

		self.db
			.execute(&sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		Ok(())
	}

	/// Set LIMIT clause
	///
	/// Limits the number of records returned by the query.
	///
	/// # Examples
	///
	/// ```ignore
	/// let followers = accessor.limit(10).all().await?;
	/// ```
	pub fn limit(mut self, limit: usize) -> Self {
		self.limit = Some(limit);
		self
	}

	/// Set OFFSET clause
	///
	/// Skips the specified number of records before returning results.
	///
	/// # Examples
	///
	/// ```ignore
	/// let followers = accessor.offset(20).limit(10).all().await?;
	/// ```
	pub fn offset(mut self, offset: usize) -> Self {
		self.offset = Some(offset);
		self
	}

	/// Paginate results using page number and page size
	///
	/// Convenience method that calculates offset automatically.
	///
	/// # Examples
	///
	/// ```ignore
	/// // Page 3, 10 items per page (offset=20, limit=10)
	/// let followers = accessor.paginate(3, 10).all().await?;
	/// ```
	pub fn paginate(self, page: usize, page_size: usize) -> Self {
		let offset = page.saturating_sub(1) * page_size;
		self.offset(offset).limit(page_size)
	}

	/// Count total number of related items
	///
	/// Executes a COUNT(*) query to get the total number of related records
	/// without fetching them.
	///
	/// # Errors
	///
	/// Returns an error if the database operation fails.
	///
	/// # Examples
	///
	/// ```ignore
	/// let total_followers = accessor.count().await?;
	/// ```
	pub async fn count(&self) -> Result<usize, String> {
		let mut query = Query::select();
		query
			.from(Alias::new(&self.through_table))
			.expr(Func::count(Expr::asterisk().into_simple_expr()))
			.and_where(
				Expr::col(Alias::new(&self.source_field))
					.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			);

		let query = query.to_owned();
		let (sql, _) = build_select_sql(&query, self.db.backend());
		let rows = self
			.db
			.query(&sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		if let Some(row) = rows.first()
			&& let Some(count_value) = row.data.get("count")
			&& let Some(count) = count_value.as_i64()
		{
			return Ok(count as usize);
		}

		Ok(0)
	}

	/// Get all related target models.
	///
	/// Queries the target table joined with the intermediate table to fetch all
	/// related records.
	///
	/// # Errors
	///
	/// Returns an error if the database operation fails.
	///
	/// # Examples
	///
	/// ```ignore
	/// let groups = accessor.all().await?;
	/// ```
	pub async fn all(&self) -> Result<Vec<T>, String> {
		let mut query = Query::select();
		query.from(Alias::new(T::table_name()));

		// Use explicit column selection instead of SELECT * to avoid conflicts
		// with intermediate table columns in JOIN queries.
		// When JOIN is used with SELECT *, all columns from both tables are returned,
		// which can cause type conflicts (e.g., intermediate table's INTEGER id vs
		// target table's UUID id).
		let field_metadata = T::field_metadata();
		if field_metadata.is_empty() {
			// Fallback: if no field metadata is available, select all from target table only
			query.column(ColumnRef::table_asterisk(Alias::new(T::table_name())));
		} else {
			// Explicitly select only target table columns
			for field in field_metadata {
				query.column((Alias::new(T::table_name()), Alias::new(&field.name)));
			}
		}

		query
			.inner_join(
				Alias::new(&self.through_table),
				Expr::col((Alias::new(T::table_name()), Alias::new("id"))).equals((
					Alias::new(&self.through_table),
					Alias::new(&self.target_field),
				)),
			)
			.and_where(
				Expr::col((
					Alias::new(&self.through_table),
					Alias::new(&self.source_field),
				))
				.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			);

		// Apply LIMIT/OFFSET
		if let Some(limit) = self.limit {
			query.limit(limit as u64);
		}
		if let Some(offset) = self.offset {
			query.offset(offset as u64);
		}

		let query = query.to_owned();
		let (sql, _values) = build_select_sql(&query, self.db.backend());

		let rows = self
			.db
			.query(&sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		rows.into_iter()
			.map(|row| serde_json::from_value(row.data).map_err(|e| e.to_string()))
			.collect()
	}

	/// Remove all relationships.
	///
	/// Deletes all records in the intermediate table for this source instance.
	///
	/// # Errors
	///
	/// Returns an error if the database operation fails.
	///
	/// # Examples
	///
	/// ```ignore
	/// accessor.clear().await?;
	/// ```
	pub async fn clear(&self) -> Result<(), String> {
		let query = Query::delete()
			.from_table(Alias::new(&self.through_table))
			.and_where(
				Expr::col(Alias::new(&self.source_field))
					.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			)
			.to_owned();

		let (sql, _values) = build_delete_sql(&query, self.db.backend());

		self.db
			.execute(&sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		Ok(())
	}

	/// Replace all relationships with a new set.
	///
	/// This is a transactional operation that:
	/// 1. Removes all existing relationships
	/// 2. Adds new relationships
	///
	/// # Parameters
	///
	/// - `targets`: The new set of target models
	///
	/// # Errors
	///
	/// Returns an error if the database operation fails.
	///
	/// # Examples
	///
	/// ```ignore
	/// accessor.set(&[group1, group2, group3]).await?;
	/// ```
	pub async fn set(&self, targets: &[T]) -> Result<(), String> {
		// Use transaction for atomicity
		let mut tx = self.db.begin().await.map_err(|e| e.to_string())?;
		let backend = self.db.backend();

		// Build and execute clear query within transaction
		let clear_query = Query::delete()
			.from_table(Alias::new(&self.through_table))
			.and_where(
				Expr::col(Alias::new(&self.source_field))
					.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			)
			.to_owned();
		let (clear_sql, _) = build_delete_sql(&clear_query, backend);
		tx.execute(&clear_sql, vec![])
			.await
			.map_err(|e| e.to_string())?;

		// Add new relationships within transaction
		for target in targets {
			let target_id = target
				.primary_key()
				.ok_or_else(|| "Target model has no primary key".to_string())?;

			let insert_query = Query::insert()
				.into_table(Alias::new(&self.through_table))
				.columns([
					Alias::new(&self.source_field),
					Alias::new(&self.target_field),
				])
				.values_panic([
					Expr::val(self.source_id.to_string()),
					Expr::val(target_id.to_string()),
				])
				.to_owned();

			let (insert_sql, _) = build_insert_sql(&insert_query, backend);
			tx.execute(&insert_sql, vec![])
				.await
				.map_err(|e| e.to_string())?;
		}

		// Commit transaction
		tx.commit().await.map_err(|e| e.to_string())?;

		Ok(())
	}

	/// Filter source models by target model via many-to-many relationship
	///
	/// Returns all source model instances that have a relationship with the given target.
	/// This is more efficient than loading all source instances and checking relationships
	/// individually, as it uses a single JOIN query.
	///
	/// # Type Parameters
	///
	/// - `S`: Source model type (the model that owns the ManyToMany field)
	/// - `T`: Target model type (the related model)
	///
	/// # Arguments
	///
	/// - `source_manager`: Manager for the source model
	/// - `field_name`: Name of the ManyToMany field on the source model
	/// - `target`: The target model instance to filter by
	/// - `db`: Database connection
	///
	/// # Returns
	///
	/// All source model instances related to the target
	///
	/// # Errors
	///
	/// Returns an error if:
	/// - The target model has no primary key
	/// - The database operation fails
	/// - The query results cannot be deserialized
	///
	/// # Examples
	///
	/// ```ignore
	/// // Find all rooms where a specific user is a member
	/// let user = User::find_by_id(&db, user_id).await?;
	/// let rooms = ManyToManyAccessor::<DMRoom, User>::filter_by_target(
	///     &DMRoom::objects(),
	///     "members",
	///     &user,
	///     db.clone()
	/// ).await?;
	/// ```
	///
	/// SQL equivalent:
	/// ```sql
	/// SELECT source_table.*
	/// FROM source_table
	/// INNER JOIN through_table ON source_table.id = through_table.source_id
	/// WHERE through_table.target_id = $1
	/// ```
	pub async fn filter_by_target(
		_source_manager: &Manager<S>,
		field_name: &str,
		target: &T,
		db: DatabaseConnection,
	) -> Result<Vec<S>, String> {
		let target_id = target
			.primary_key()
			.ok_or_else(|| "Target model has no primary key".to_string())?;

		// Resolve through-table and FK column names through the same
		// metadata-aware path as `new()`, routing the fallbacks through
		// `crate::m2m_naming` (single source of truth shared with the
		// migration autodetector; see issues #4659, #4665). The helpers
		// apply `from_/to_` prefixes for self-referential M2M, matching
		// `MigrationAutodetector::create_intermediate_table_for_m2m`.
		let rel_info = S::relationship_metadata()
			.into_iter()
			.find(|r| r.name == field_name && r.relationship_type == RelationshipType::ManyToMany);

		let through_table = rel_info
			.as_ref()
			.and_then(|r| r.through_table.clone())
			.unwrap_or_else(|| default_through_table(S::table_name(), field_name));

		let (default_source_field, default_target_field) =
			default_m2m_columns(S::table_name(), T::table_name());
		let source_field = rel_info
			.as_ref()
			.and_then(|r| r.source_field.clone())
			.unwrap_or(default_source_field);
		let target_field = rel_info
			.as_ref()
			.and_then(|r| r.target_field.clone())
			.unwrap_or(default_target_field);

		// Build JOIN query using reinhardt-query
		let mut query = Query::select();
		query.from(Alias::new(S::table_name()));

		// Use explicit column selection instead of SELECT * to avoid conflicts
		// with intermediate table columns in JOIN queries.
		let field_metadata = S::field_metadata();
		if field_metadata.is_empty() {
			query.column(ColumnRef::table_asterisk(Alias::new(S::table_name())));
		} else {
			for field in field_metadata {
				query.column((Alias::new(S::table_name()), Alias::new(&field.name)));
			}
		}

		let query = query
			.inner_join(
				Alias::new(&through_table),
				Expr::col((Alias::new(S::table_name()), Alias::new("id")))
					.equals((Alias::new(&through_table), Alias::new(&source_field))),
			)
			.and_where(
				Expr::col((Alias::new(&through_table), Alias::new(&target_field)))
					.binary(BinOper::Equal, Expr::val(target_id.to_string())),
			)
			.to_owned();

		let (sql, _values) = build_select_sql(&query, db.backend());

		let rows = db.query(&sql, vec![]).await.map_err(|e| e.to_string())?;

		rows.into_iter()
			.map(|row| serde_json::from_value(row.data).map_err(|e| e.to_string()))
			.collect()
	}
}

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

	/// Regression test for #4659: the runtime accessor's default
	/// through-table name MUST agree with the name `makemigrations`
	/// synthesizes. The autodetector uses
	/// `format!("{}_{}", source_model.table_name, field_name)`; the
	/// accessor must do the same. Previously it prepended `S::app_label()`
	/// as a separate segment, producing names like `auth_users_groups`
	/// instead of `users_groups` (or `dm_dm_room_members` instead of
	/// `dm_room_members`), so runtime M2M queries targeted a table that
	/// `makemigrations` never created.
	#[test]
	fn default_through_table_matches_autodetector_convention() {
		// Arrange / Act: TestUser has table_name = "users". The accessor now
		// routes through `crate::m2m_naming::default_through_table`, so this
		// regression test exercises the same helper the autodetector uses.
		let through = default_through_table(TestUser::table_name(), "members");

		// Assert
		assert_eq!(through, "users_members");
		assert!(
			!through.starts_with("auth_"),
			"app_label must NOT be prepended; that would double-count it \
			 when table_name already carries the prefix (e.g. \"dm_room\"). \
			 See #4659 for the breakage this causes."
		);
	}

	#[test]
	fn test_sql_generation_add() {
		// Test that INSERT SQL is generated correctly
		let query = Query::insert()
			.into_table(Alias::new("auth_users_groups"))
			.columns([Alias::new("users_id"), Alias::new("groups_id")])
			.values_panic([Expr::val("1"), Expr::val("10")])
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("INSERT INTO"));
		assert!(sql.contains("auth_users_groups"));
		assert!(sql.contains("users_id"));
		assert!(sql.contains("groups_id"));
	}

	#[test]
	fn test_sql_generation_remove() {
		// Test that DELETE SQL is generated correctly
		let query = Query::delete()
			.from_table(Alias::new("auth_users_groups"))
			.and_where(Expr::col(Alias::new("users_id")).binary(BinOper::Equal, Expr::val("1")))
			.and_where(Expr::col(Alias::new("groups_id")).binary(BinOper::Equal, Expr::val("10")))
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("DELETE FROM"));
		assert!(sql.contains("auth_users_groups"));
		assert!(sql.contains("users_id"));
		assert!(sql.contains("groups_id"));
	}

	#[test]
	fn test_sql_generation_clear() {
		// Test that DELETE SQL for clear is generated correctly
		let query = Query::delete()
			.from_table(Alias::new("auth_users_groups"))
			.and_where(Expr::col(Alias::new("users_id")).binary(BinOper::Equal, Expr::val("1")))
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("DELETE FROM"));
		assert!(sql.contains("auth_users_groups"));
		assert!(sql.contains("users_id"));
	}

	#[test]
	fn test_sql_generation_all() {
		// Test that SELECT SQL with JOIN is generated correctly
		let query = Query::select()
			.from(Alias::new("groups"))
			.column((Alias::new("groups"), Alias::new("*")))
			.inner_join(
				Alias::new("auth_users_groups"),
				Expr::col((Alias::new("groups"), Alias::new("id")))
					.equals((Alias::new("auth_users_groups"), Alias::new("groups_id"))),
			)
			.and_where(
				Expr::col((Alias::new("auth_users_groups"), Alias::new("users_id")))
					.binary(BinOper::Equal, Expr::val("1")),
			)
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("SELECT"));
		assert!(sql.contains("INNER JOIN"));
		assert!(sql.contains("auth_users_groups"));
	}

	#[test]
	fn test_sql_generation_filter_by_target() {
		// Test that SELECT SQL with JOIN for filter_by_target is generated correctly
		let query = Query::select()
			.from(Alias::new("dm_room"))
			.column((Alias::new("dm_room"), Alias::new("*")))
			.inner_join(
				Alias::new("dm_room_members"),
				Expr::col((Alias::new("dm_room"), Alias::new("id")))
					.equals((Alias::new("dm_room_members"), Alias::new("dmroom_id"))),
			)
			.and_where(
				Expr::col((Alias::new("dm_room_members"), Alias::new("user_id")))
					.binary(BinOper::Equal, Expr::val("test-user-id")),
			)
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("SELECT"));
		assert!(sql.contains("dm_room"));
		assert!(sql.contains("INNER JOIN"));
		assert!(sql.contains("dm_room_members"));
		assert!(sql.contains("user_id"));
		// Note: reinhardt-query uses parameterized queries, so the value may be in a parameter
		// instead of inline in the SQL string
	}

	// Test models for SQL generation tests
	#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
	struct TestUser {
		id: i64,
		username: String,
	}

	#[derive(Debug, Clone)]
	struct TestUserFields;

	impl crate::orm::model::FieldSelector for TestUserFields {
		fn with_alias(self, _alias: &str) -> Self {
			self
		}
	}

	impl Model for TestUser {
		type PrimaryKey = i64;
		type Fields = TestUserFields;

		fn table_name() -> &'static str {
			"users"
		}

		fn app_label() -> &'static str {
			"auth"
		}

		fn primary_key(&self) -> Option<Self::PrimaryKey> {
			Some(self.id)
		}

		fn set_primary_key(&mut self, value: Self::PrimaryKey) {
			self.id = value;
		}

		fn primary_key_field() -> &'static str {
			"id"
		}

		fn new_fields() -> Self::Fields {
			TestUserFields
		}
	}

	#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
	struct TestGroup {
		id: i64,
		name: String,
	}

	#[derive(Clone)]
	struct TestGroupFields;
	impl crate::orm::model::FieldSelector for TestGroupFields {
		fn with_alias(self, _alias: &str) -> Self {
			self
		}
	}

	impl Model for TestGroup {
		type PrimaryKey = i64;
		type Fields = TestGroupFields;

		fn table_name() -> &'static str {
			"groups"
		}

		fn app_label() -> &'static str {
			"auth"
		}

		fn new_fields() -> Self::Fields {
			TestGroupFields
		}

		fn primary_key(&self) -> Option<Self::PrimaryKey> {
			Some(self.id)
		}

		fn set_primary_key(&mut self, value: Self::PrimaryKey) {
			self.id = value;
		}
	}
}