reinhardt-db 0.1.1

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
//! Django-style accessor for ForeignKey reverse relationships.
//!
//! This module provides the ReverseAccessor type, which implements
//! Django-style API for accessing reverse ForeignKey relationships:
//! - `all()` - Get all related records
//! - `count()` - Count related records
//! - `limit()` / `offset()` / `paginate()` - Query modifiers
//!
//! ## Usage
//!
//! The recommended way to access reverse relationships is through the
//! `ForeignKeyAccessor` returned by `{field_name}_accessor()` methods
//! generated by the `#[model(...)]` macro:
//!
//! ```rust,ignore
//! // Tweet has: #[rel(foreign_key)] user: ForeignKeyField<User>
//! let user = User::objects().filter(...).first_with_db(&db).await?;
//!
//! // Get reverse accessor through ForeignKeyAccessor
//! let tweets_accessor = Tweet::user_accessor().reverse(&user, db.clone());
//! let tweets = tweets_accessor.all().await?;
//! let tweet_count = tweets_accessor.count().await?;
//!
//! // Paginate results
//! let page1 = tweets_accessor.paginate(1, 10).all().await?;
//! ```
//!
//! For advanced use cases, you can also create a ReverseAccessor manually:
//!
//! ```rust,ignore
//! let user = User::objects().filter(...).first_with_db(&db).await?;
//! let accessor = ReverseAccessor::<User, Tweet>::new(&user, "user_id", db.clone());
//! let tweets = accessor.all().await?;
//! ```
//!
//! ## Type Safety
//!
//! The `ForeignKeyAccessor` approach provides full type safety and IDE
//! auto-completion support, as all relationship information is determined
//! at compile time. No string literals are required.

use super::connection::{DatabaseBackend, DatabaseConnection};
use crate::orm::Model;
use reinhardt_query::prelude::{
	Alias, BinOper, ColumnRef, Expr, Func, MySqlQueryBuilder, PostgresQueryBuilder, Query,
	QueryBuilder, SelectStatement, SqliteQueryBuilder,
};
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, reinhardt_query::prelude::Values) {
	match backend {
		DatabaseBackend::Postgres => PostgresQueryBuilder.build_select(stmt),
		DatabaseBackend::MySql => MySqlQueryBuilder.build_select(stmt),
		DatabaseBackend::Sqlite => SqliteQueryBuilder.build_select(stmt),
	}
}

/// Django-style accessor for ForeignKey reverse relationships.
///
/// This type provides methods to access related records via the reverse
/// side of a ForeignKey relationship (e.g., user.tweets()).
///
/// # Type Parameters
///
/// - `S`: Source model type (the model being referenced, e.g., User)
/// - `T`: Target model type (the model with the FK field, e.g., Tweet)
///
/// # Recommended Usage
///
/// Use `ForeignKeyAccessor::reverse()` to create a `ReverseAccessor`:
///
/// ```rust,ignore
/// // Tweet has: #[rel(foreign_key)] user: ForeignKeyField<User>
/// let tweets_accessor = Tweet::user_accessor().reverse(&user, db.clone());
/// let tweets = tweets_accessor.all().await?;
/// ```
///
/// # Manual Creation
///
/// For advanced use cases, you can create a ReverseAccessor directly:
///
/// ```rust,ignore
/// # #[tokio::main]
/// # async fn main() {
/// use reinhardt_db::orm::{Model, ReverseAccessor};
///
/// let user = User::objects().filter(...).first_with_db(&db).await?;
/// let accessor = ReverseAccessor::<User, Tweet>::new(&user, "user_id", db.clone());
///
/// // Get all related records
/// let tweets = accessor.all().await?;
///
/// // Count related records
/// let count = accessor.count().await?;
///
/// // Paginate results
/// let page1 = accessor.paginate(1, 10).all().await?;
///
/// # }
/// ```
pub struct ReverseAccessor<S, T>
where
	S: Model,
	T: Model + Serialize + DeserializeOwned,
{
	source_id: S::PrimaryKey,
	foreign_key_field: String,
	db: DatabaseConnection,
	limit: Option<usize>,
	offset: Option<usize>,
	_phantom_source: PhantomData<S>,
	_phantom_target: PhantomData<T>,
}

impl<S, T> ReverseAccessor<S, T>
where
	S: Model,
	T: Model + Serialize + DeserializeOwned,
{
	/// Create a new ReverseAccessor.
	///
	/// # Parameters
	///
	/// - `source`: The source model instance (e.g., User)
	/// - `foreign_key_field`: The name of the ForeignKey field in the target model (e.g., "user_id")
	/// - `db`: Database connection
	///
	/// # Panics
	///
	/// Panics if the source model has no primary key.
	pub fn new(source: &S, foreign_key_field: &str, db: DatabaseConnection) -> Self {
		let source_id = source
			.primary_key()
			.expect("Source model must have primary key")
			.clone();

		Self {
			source_id,
			foreign_key_field: foreign_key_field.to_string(),
			db,
			limit: None,
			offset: None,
			_phantom_source: PhantomData,
			_phantom_target: PhantomData,
		}
	}

	/// Get all related target models.
	///
	/// Queries the target table to fetch all records where the foreign key
	/// matches the source instance's primary key.
	///
	/// # Errors
	///
	/// Returns an error if the database operation fails.
	///
	/// # Examples
	///
	/// ```ignore
	/// let tweets = accessor.all().await?;
	/// ```
	pub async fn all(&self) -> Result<Vec<T>, String> {
		let mut query = Query::select();
		query
			.from(Alias::new(T::table_name()))
			.column(ColumnRef::table_asterisk(Alias::new(T::table_name())))
			.and_where(
				Expr::col(Alias::new(&self.foreign_key_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()
	}

	/// 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_tweets = accessor.count().await?;
	/// ```
	pub async fn count(&self) -> Result<usize, String> {
		let query = Query::select()
			.from(Alias::new(T::table_name()))
			.expr(Func::count(Expr::asterisk().into_simple_expr()))
			.and_where(
				Expr::col(Alias::new(&self.foreign_key_field))
					.binary(BinOper::Equal, Expr::val(self.source_id.to_string())),
			)
			.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)
	}

	/// Set LIMIT clause
	///
	/// Limits the number of records returned by the query.
	///
	/// # Examples
	///
	/// ```ignore
	/// let tweets = 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 tweets = 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 tweets = 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)
	}
}

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

	#[test]
	fn test_sql_generation_all() {
		// Test that SELECT SQL is generated correctly
		let query = Query::select()
			.from(Alias::new("tweets"))
			.column(ColumnRef::table_asterisk(Alias::new("tweets")))
			.and_where(
				Expr::col(Alias::new("user_id")).binary(BinOper::Equal, Expr::val("user-123")),
			)
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("SELECT"));
		assert!(sql.contains("tweets"));
		assert!(sql.contains("user_id"));
	}

	#[test]
	fn test_sql_generation_count() {
		// Test that COUNT SQL is generated correctly
		let query = Query::select()
			.from(Alias::new("tweets"))
			.expr(Func::count(Expr::asterisk().into_simple_expr()))
			.and_where(
				Expr::col(Alias::new("user_id")).binary(BinOper::Equal, Expr::val("user-123")),
			)
			.to_owned();

		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("SELECT"));
		assert!(sql.contains("COUNT"));
		assert!(sql.contains("tweets"));
		assert!(sql.contains("user_id"));
	}

	#[test]
	fn test_sql_generation_with_limit_offset() {
		// Test that LIMIT and OFFSET clauses are generated correctly
		let mut query = Query::select();
		query
			.from(Alias::new("tweets"))
			.column(ColumnRef::table_asterisk(Alias::new("tweets")))
			.and_where(
				Expr::col(Alias::new("user_id")).binary(BinOper::Equal, Expr::val("user-123")),
			)
			.limit(10)
			.offset(20);

		let query = query.to_owned();
		let (sql, _) = query.build(PostgresQueryBuilder);
		assert!(sql.contains("LIMIT"));
		assert!(sql.contains("OFFSET"));
	}

	// Allow dead_code: test model struct not instantiated; only its trait implementations are tested
	#[allow(dead_code)]
	#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
	struct TestUser {
		id: String,
		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 = String;
		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.clone())
		}

		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
		}
	}

	// Allow dead_code: test model struct for reverse accessor verification
	#[allow(dead_code)]
	#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
	struct TestTweet {
		id: String,
		user_id: String,
		content: String,
	}

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

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

	impl Model for TestTweet {
		type PrimaryKey = String;
		type Fields = TestTweetFields;

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

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

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

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

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

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