1use crate::{
2 BelongsTo, CompiledQuery, CurrentDialect, DatabaseValue, Expr, HasMany, MigrationGraph, Model,
3 ModelField, QueryAst, QueryBuildError, QueryValue, Row, SelectQuery, SqlCompiler,
4 ValidatedWrite, backend,
5};
6use std::{
7 collections::{HashMap, HashSet},
8 future::Future,
9 marker::PhantomData,
10 pin::Pin,
11};
12
13#[derive(Debug, thiserror::Error)]
14pub enum OrmError {
15 #[error("database configuration error: {0}")]
16 Configuration(String),
17 #[error("database pool error: {0}")]
18 Pool(String),
19 #[error("database interaction error: {0}")]
20 Interaction(String),
21 #[cfg(feature = "sqlite")]
22 #[error("sqlite error: {0}")]
23 Sqlite(#[from] rusqlite::Error),
24 #[cfg(feature = "postgres")]
25 #[error("postgres error: {0}")]
26 Postgres(#[from] tokio_postgres::Error),
27 #[error("row decoding error: {0}")]
28 Decode(#[from] crate::DecodeError),
29 #[error("query build error: {0:?}")]
30 QueryBuild(QueryBuildError),
31 #[error("migration error: {0}")]
32 Migration(String),
33}
34
35impl From<QueryBuildError> for OrmError {
36 fn from(value: QueryBuildError) -> Self {
37 Self::QueryBuild(value)
38 }
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum ConstraintKind {
43 Unique,
44 ForeignKey,
45 NotNull,
46 Check,
47}
48
49impl OrmError {
50 pub fn constraint_kind(&self) -> Option<ConstraintKind> {
51 #[cfg(feature = "postgres")]
52 if let Some(code) = self.sql_state() {
53 return match code {
54 "23505" => Some(ConstraintKind::Unique),
55 "23503" => Some(ConstraintKind::ForeignKey),
56 "23502" => Some(ConstraintKind::NotNull),
57 "23514" => Some(ConstraintKind::Check),
58 _ => None,
59 };
60 }
61 #[cfg(feature = "sqlite")]
62 if let Self::Sqlite(rusqlite::Error::SqliteFailure(error, _)) = self {
63 return match error.extended_code {
64 rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
65 | rusqlite::ffi::SQLITE_CONSTRAINT_PRIMARYKEY => Some(ConstraintKind::Unique),
66 rusqlite::ffi::SQLITE_CONSTRAINT_FOREIGNKEY => Some(ConstraintKind::ForeignKey),
67 rusqlite::ffi::SQLITE_CONSTRAINT_NOTNULL => Some(ConstraintKind::NotNull),
68 rusqlite::ffi::SQLITE_CONSTRAINT_CHECK => Some(ConstraintKind::Check),
69 _ => None,
70 };
71 }
72 None
73 }
74 pub fn sql_state(&self) -> Option<&str> {
76 #[cfg(feature = "postgres")]
77 if let Self::Postgres(error) = self {
78 return error.code().map(|code| code.code());
79 }
80 None
81 }
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub struct ExecuteResult {
86 pub rows_affected: usize,
87 pub last_insert_rowid: Option<i64>,
89}
90
91#[derive(Clone)]
93pub struct Database {
94 pool: backend::Pool,
95 runtime: Option<std::sync::Arc<dyn ModelRuntime>>,
96}
97
98pub type TransactionFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, OrmError>> + Send + 'a>>;
99
100pub trait ModelRuntime: Send + Sync {
103 fn role(&self, table: &str) -> Option<crate::ModelRole>;
104 fn captures_table(&self, table: &str) -> bool {
106 self.role(table).is_some()
107 }
108 fn transaction_lock(&self) -> Option<std::sync::Arc<tokio::sync::Mutex<()>>> {
109 None
110 }
111 fn prepare_read(&self, ast: QueryAst) -> QueryAst {
112 ast
113 }
114 fn authorize_read(&self, _ast: &QueryAst) -> Result<(), OrmError> {
117 Ok(())
118 }
119 fn write<'a>(
120 &'a self,
121 tx: &'a Transaction,
122 ast: QueryAst,
123 ) -> TransactionFuture<'a, ModelWriteResult>;
124}
125
126pub struct ModelWriteResult {
127 pub result: ExecuteResult,
128 pub rows: Vec<Row>,
129}
130
131fn write_table(ast: &QueryAst) -> Option<&str> {
132 match ast {
133 QueryAst::Insert(ast) => Some(ast.table.name),
134 QueryAst::Update(ast) => Some(ast.table.name),
135 QueryAst::Delete(ast) => Some(ast.table.name),
136 _ => None,
137 }
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum IsolationLevel {
142 ReadCommitted,
143 RepeatableRead,
144 Serializable,
145}
146
147impl Database {
148 pub async fn connect(url: impl Into<String>) -> Result<Self, OrmError> {
149 let url = url.into();
150 let size = if url == ":memory:" || url == "sqlite://:memory:" {
151 1
152 } else {
153 4
154 };
155 Self::connect_with_pool_size(url, size).await
156 }
157 pub async fn connect_with_pool_size(
158 url: impl Into<String>,
159 size: usize,
160 ) -> Result<Self, OrmError> {
161 Ok(Self {
162 pool: backend::connect(url.into(), size).await?,
163 runtime: None,
164 })
165 }
166 #[cfg(feature = "sqlite")]
167 pub async fn connect_in_memory() -> Result<Self, OrmError> {
168 Self::connect(":memory:").await
169 }
170
171 pub async fn execute(&self, ast: QueryAst) -> Result<ExecuteResult, OrmError> {
172 ast.validate()?;
173 if self.captures(&ast) {
174 return self
175 .transaction(move |tx| Box::pin(async move { tx.execute(ast).await }))
176 .await;
177 }
178 let ast = match &self.runtime {
179 Some(runtime) => prepare_runtime_ast(runtime.as_ref(), ast)?,
180 None => ast,
181 };
182 backend::Session::acquire(&self.pool)
183 .await?
184 .execute(SqlCompiler::<CurrentDialect>::compile(&ast))
185 .await
186 }
187
188 pub fn with_model_runtime(mut self, runtime: std::sync::Arc<dyn ModelRuntime>) -> Self {
190 self.runtime = Some(runtime);
191 self
192 }
193
194 pub fn model_role<M: Model>(&self) -> Option<crate::ModelRole> {
195 self.runtime
196 .as_ref()
197 .and_then(|runtime| runtime.role(M::table_name()))
198 }
199
200 fn captures(&self, ast: &QueryAst) -> bool {
201 write_table(ast).is_some_and(|table| {
202 self.runtime
203 .as_ref()
204 .is_some_and(|runtime| runtime.captures_table(table))
205 })
206 }
207 pub async fn execute_sql(
209 &self,
210 sql: impl Into<String>,
211 params: Vec<DatabaseValue>,
212 ) -> Result<ExecuteResult, OrmError> {
213 backend::Session::acquire(&self.pool)
214 .await?
215 .execute(CompiledQuery {
216 sql: sql.into(),
217 params,
218 })
219 .await
220 }
221 pub async fn query_sql(
222 &self,
223 sql: impl Into<String>,
224 params: Vec<DatabaseValue>,
225 ) -> Result<Vec<Row>, OrmError> {
226 backend::Session::acquire(&self.pool)
227 .await?
228 .query(CompiledQuery {
229 sql: sql.into(),
230 params,
231 })
232 .await
233 }
234 pub async fn create_table<M: Model>(&self) -> Result<ExecuteResult, OrmError> {
235 M::schema().validate().map_err(|error| {
236 OrmError::QueryBuild(QueryBuildError::InvalidSchema(format!("{error:?}")))
237 })?;
238 let schema = SqlCompiler::<CurrentDialect>::compile_schema(&M::schema());
239 self.transaction(move |tx| {
240 Box::pin(async move {
241 tx.session.batch(&schema.table).await?;
242 for sql in schema.indexes {
243 tx.session.batch(&sql).await?;
244 }
245 Ok(ExecuteResult {
246 rows_affected: 0,
247 last_insert_rowid: None,
248 })
249 })
250 })
251 .await
252 }
253 pub async fn insert<M: Model>(&self, model: &M) -> Result<ExecuteResult, OrmError> {
255 self.execute(insert_ast(model)).await
256 }
257 pub async fn save<M: Model + Send + 'static>(&self, model: &M) -> Result<Option<M>, OrmError> {
267 self.execute_returning(
268 crate::UpdateQuery::from_model(model)
269 .returning_all()
270 .into_ast()?,
271 )
272 .await
273 }
274 pub async fn fetch_all<M: Model + Send + 'static>(
275 &self,
276 query: SelectQuery<M>,
277 ) -> Result<Vec<M>, OrmError> {
278 decode_models(self.rows(query.into_ast()?).await?)
279 }
280 pub async fn fetch_one<M: Model + Send + 'static>(
281 &self,
282 query: SelectQuery<M>,
283 ) -> Result<Option<M>, OrmError> {
284 Ok(self.fetch_all(query.limit(1)).await?.pop())
285 }
286 pub async fn get<M: Model + Send + 'static>(
287 &self,
288 id: M::PrimaryKey,
289 ) -> Result<Option<M>, OrmError> {
290 self.fetch_one(M::query().filter(M::primary_key().eq(id)))
291 .await
292 }
293 pub async fn all<M: Model + Send + 'static>(&self) -> Result<Vec<M>, OrmError> {
294 self.fetch_all(M::query()).await
295 }
296 pub async fn count<M: Model + Send + 'static>(&self) -> Result<usize, OrmError> {
297 self.count_query(M::query()).await
298 }
299 pub async fn count_query<M: Model + Send + 'static>(
300 &self,
301 query: SelectQuery<M>,
302 ) -> Result<usize, OrmError> {
303 let query = count_query(query, self.runtime.as_deref())?;
304 count_rows(
305 backend::Session::acquire(&self.pool)
306 .await?
307 .query(query)
308 .await?,
309 )
310 }
311 pub fn create<M: Model>(&self) -> CreateBuilder<'_, M> {
312 CreateBuilder {
313 database: self,
314 query: M::insert(),
315 }
316 }
317 pub fn update<M: Model>(&self, id: M::PrimaryKey) -> UpdateBuilder<'_, M> {
318 UpdateBuilder {
319 database: self,
320 query: M::update().filter(M::primary_key().eq(id)),
321 }
322 }
323 pub async fn delete<M: Model + Send + 'static>(
324 &self,
325 id: M::PrimaryKey,
326 ) -> Result<bool, OrmError> {
327 Ok(self
328 .execute(M::delete().filter(M::primary_key().eq(id)).into_ast()?)
329 .await?
330 .rows_affected
331 == 1)
332 }
333 pub fn query<M: Model>(&self) -> DatabaseQuery<M> {
334 DatabaseQuery::new(M::query())
335 }
336 pub async fn fetch_by<M, T, V>(
337 &self,
338 field: ModelField<M, T>,
339 value: V,
340 ) -> Result<Vec<M>, OrmError>
341 where
342 M: Model + Send + 'static,
343 V: QueryValue<T>,
344 {
345 self.fetch_all(M::query().filter(field.eq(value))).await
346 }
347 pub async fn fetch_by_many<M, T, I, V>(
348 &self,
349 field: ModelField<M, T>,
350 values: I,
351 ) -> Result<Vec<M>, OrmError>
352 where
353 M: Model + Send + 'static,
354 I: IntoIterator<Item = V>,
355 V: QueryValue<T>,
356 {
357 let values = values
358 .into_iter()
359 .map(QueryValue::<T>::into_query_value)
360 .collect::<Vec<_>>();
361 let mut result = Vec::new();
362 for chunk in values.chunks(backend::MAX_PARAMETERS) {
363 result.extend(
364 self.fetch_all(M::query().filter(Expr::In {
365 left: Box::new(Expr::Column(field.column())),
366 values: chunk.to_vec(),
367 }))
368 .await?,
369 );
370 }
371 let mut seen = HashSet::new();
372 result.retain(|model| seen.insert(model.primary_key_value()));
373 Ok(result)
374 }
375
376 pub async fn transaction<T, F>(&self, action: F) -> Result<T, OrmError>
380 where
381 T: Send + 'static,
382 F: for<'a> FnOnce(&'a Transaction) -> TransactionFuture<'a, T> + Send,
383 {
384 self.transaction_with_isolation(IsolationLevel::Serializable, action)
385 .await
386 }
387
388 pub async fn transaction_with_isolation<T, F>(
390 &self,
391 isolation: IsolationLevel,
392 action: F,
393 ) -> Result<T, OrmError>
394 where
395 T: Send + 'static,
396 F: for<'a> FnOnce(&'a Transaction) -> TransactionFuture<'a, T> + Send,
397 {
398 self.transaction_result_with_isolation(isolation, action)
399 .await
400 }
401
402 pub async fn transaction_result<T, E, F>(&self, action: F) -> Result<T, E>
404 where
405 T: Send + 'static,
406 E: From<OrmError>,
407 F: for<'a> FnOnce(
408 &'a Transaction,
409 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>
410 + Send,
411 {
412 self.transaction_result_with_isolation(IsolationLevel::Serializable, action)
413 .await
414 }
415
416 async fn transaction_result_with_isolation<T, E, F>(
417 &self,
418 isolation: IsolationLevel,
419 action: F,
420 ) -> Result<T, E>
421 where
422 T: Send + 'static,
423 E: From<OrmError>,
424 F: for<'a> FnOnce(
425 &'a Transaction,
426 ) -> Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>
427 + Send,
428 {
429 let _runtime_guard = match self
430 .runtime
431 .as_ref()
432 .and_then(|runtime| runtime.transaction_lock())
433 {
434 Some(lock) => Some(lock.lock_owned().await),
435 None => None,
436 };
437 let session = backend::Session::acquire(&self.pool).await?;
438 let mut guard = TransactionGuard {
439 session: session.clone(),
440 active: true,
441 };
442 #[cfg(feature = "sqlite")]
443 let begin = {
444 let _ = isolation;
445 "BEGIN"
446 };
447 #[cfg(all(feature = "postgres", not(feature = "sqlite")))]
448 let begin = match isolation {
449 IsolationLevel::ReadCommitted => "BEGIN ISOLATION LEVEL READ COMMITTED",
450 IsolationLevel::RepeatableRead => "BEGIN ISOLATION LEVEL REPEATABLE READ",
451 IsolationLevel::Serializable => "BEGIN ISOLATION LEVEL SERIALIZABLE",
452 };
453 session.batch(begin).await?;
454 let transaction = Transaction {
455 session,
456 runtime: self.runtime.clone(),
457 };
458 match action(&transaction).await {
459 Ok(value) => {
460 transaction.session.commit().await?;
461 guard.active = false;
462 Ok(value)
463 }
464 Err(error) => {
465 transaction.session.batch("ROLLBACK").await?;
466 guard.active = false;
467 Err(error)
468 }
469 }
470 }
471 #[deprecated(since = "0.3.0", note = "use Database::transaction instead")]
473 pub async fn typed_transaction<T, F>(&self, action: F) -> Result<T, OrmError>
474 where
475 T: Send + 'static,
476 F: for<'a> FnOnce(&'a Transaction) -> TransactionFuture<'a, T> + Send,
477 {
478 self.transaction(action).await
479 }
480
481 #[cfg(feature = "sqlite")]
483 pub async fn raw_transaction<T, F>(&self, action: F) -> Result<T, OrmError>
484 where
485 T: Send + 'static,
486 F: FnOnce(&rusqlite::Connection) -> rusqlite::Result<T> + Send + 'static,
487 {
488 self.transaction(move |tx| {
489 Box::pin(async move {
490 tx.session
491 .interact(move |connection| action(connection).map_err(Into::into))
492 .await
493 })
494 })
495 .await
496 }
497 pub async fn migrate(&self, graph: MigrationGraph) -> Result<usize, OrmError> {
498 self.migrate_to(graph, None).await
499 }
500 pub async fn migrate_to(
501 &self,
502 graph: MigrationGraph,
503 target: Option<crate::MigrationId>,
504 ) -> Result<usize, OrmError> {
505 backend::Session::acquire(&self.pool)
506 .await?
507 .migrate(graph, target)
508 .await
509 }
510 pub async fn migration_history(&self) -> Result<HashMap<(String, String), String>, OrmError> {
511 backend::Session::acquire(&self.pool).await?.history().await
512 }
513 async fn rows(&self, ast: QueryAst) -> Result<Vec<Row>, OrmError> {
514 ast.validate()?;
515 if self.captures(&ast) {
516 return self
517 .transaction(move |tx| Box::pin(async move { tx.rows(ast).await }))
518 .await;
519 }
520 let ast = match &self.runtime {
521 Some(runtime) => prepare_runtime_ast(runtime.as_ref(), ast)?,
522 None => ast,
523 };
524 backend::Session::acquire(&self.pool)
525 .await?
526 .query(SqlCompiler::<CurrentDialect>::compile(&ast))
527 .await
528 }
529 async fn execute_returning<M: Model + Send + 'static>(
530 &self,
531 ast: QueryAst,
532 ) -> Result<Option<M>, OrmError> {
533 Ok(decode_models(self.rows(ast).await?)?.pop())
534 }
535}
536
537pub(crate) struct TransactionGuard {
538 pub(crate) session: backend::Session,
539 pub(crate) active: bool,
540}
541impl Drop for TransactionGuard {
542 fn drop(&mut self) {
543 if self.active {
544 let session = self.session.clone();
545 tokio::spawn(async move {
546 let _ = session.batch("ROLLBACK").await;
547 });
548 }
549 }
550}
551
552pub struct Transaction {
554 session: backend::Session,
555 runtime: Option<std::sync::Arc<dyn ModelRuntime>>,
556}
557impl Transaction {
558 pub async fn execute_sql(
560 &self,
561 sql: impl Into<String>,
562 params: Vec<DatabaseValue>,
563 ) -> Result<ExecuteResult, OrmError> {
564 self.session
565 .execute(CompiledQuery {
566 sql: sql.into(),
567 params,
568 })
569 .await
570 }
571
572 pub async fn query_sql(
574 &self,
575 sql: impl Into<String>,
576 params: Vec<DatabaseValue>,
577 ) -> Result<Vec<Row>, OrmError> {
578 self.session
579 .query(CompiledQuery {
580 sql: sql.into(),
581 params,
582 })
583 .await
584 }
585
586 pub async fn execute(&self, ast: QueryAst) -> Result<ExecuteResult, OrmError> {
587 ast.validate()?;
588 let ast = match &self.runtime {
589 Some(runtime) => prepare_runtime_ast(runtime.as_ref(), ast)?,
590 None => ast,
591 };
592 if let Some(runtime) = &self.runtime
593 && write_table(&ast).is_some_and(|table| runtime.captures_table(table))
594 {
595 return Ok(runtime.write(self, ast).await?.result);
596 }
597 self.session
598 .execute(SqlCompiler::<CurrentDialect>::compile(&ast))
599 .await
600 }
601 pub async fn insert<M: Model>(&self, model: &M) -> Result<ExecuteResult, OrmError> {
602 self.execute(insert_ast(model)).await
603 }
604 pub async fn save<M: Model + Send + 'static>(&self, model: &M) -> Result<Option<M>, OrmError> {
607 self.execute_returning(
608 crate::UpdateQuery::from_model(model)
609 .returning_all()
610 .into_ast()?,
611 )
612 .await
613 }
614 pub async fn fetch_all<M: Model + Send + 'static>(
615 &self,
616 query: SelectQuery<M>,
617 ) -> Result<Vec<M>, OrmError> {
618 decode_models(self.rows(query.into_ast()?).await?)
619 }
620 pub async fn fetch_one<M: Model + Send + 'static>(
621 &self,
622 query: SelectQuery<M>,
623 ) -> Result<Option<M>, OrmError> {
624 Ok(self.fetch_all(query.limit(1)).await?.pop())
625 }
626 pub async fn get<M: Model + Send + 'static>(
627 &self,
628 id: M::PrimaryKey,
629 ) -> Result<Option<M>, OrmError> {
630 self.fetch_one(M::query().filter(M::primary_key().eq(id)))
631 .await
632 }
633 pub async fn all<M: Model + Send + 'static>(&self) -> Result<Vec<M>, OrmError> {
634 self.fetch_all(M::query()).await
635 }
636 pub async fn count<M: Model + Send + 'static>(&self) -> Result<usize, OrmError> {
637 count_rows(
638 self.session
639 .query(count_query(M::query(), self.runtime.as_deref())?)
640 .await?,
641 )
642 }
643 pub async fn delete<M: Model + Send + 'static>(
644 &self,
645 id: M::PrimaryKey,
646 ) -> Result<bool, OrmError> {
647 Ok(self
648 .execute(M::delete().filter(M::primary_key().eq(id)).into_ast()?)
649 .await?
650 .rows_affected
651 == 1)
652 }
653 pub fn create<M: Model>(&self) -> TransactionCreateBuilder<'_, M> {
654 TransactionCreateBuilder {
655 transaction: self,
656 query: M::insert(),
657 }
658 }
659 pub fn update<M: Model>(&self, id: M::PrimaryKey) -> TransactionUpdateBuilder<'_, M> {
660 TransactionUpdateBuilder {
661 transaction: self,
662 query: M::update().filter(M::primary_key().eq(id)),
663 }
664 }
665 pub fn query<M: Model>(&self) -> TransactionQuery<'_, M> {
666 TransactionQuery {
667 transaction: self,
668 query: M::query(),
669 }
670 }
671 pub async fn fetch_by_many<M, T, I, V>(
672 &self,
673 field: ModelField<M, T>,
674 values: I,
675 ) -> Result<Vec<M>, OrmError>
676 where
677 M: Model + Send + 'static,
678 I: IntoIterator<Item = V>,
679 V: QueryValue<T>,
680 {
681 let values = values
682 .into_iter()
683 .map(QueryValue::<T>::into_query_value)
684 .collect::<Vec<_>>();
685 let mut result = Vec::new();
686 for chunk in values.chunks(backend::MAX_PARAMETERS) {
687 result.extend(
688 self.fetch_all(M::query().filter(Expr::In {
689 left: Box::new(Expr::Column(field.column())),
690 values: chunk.to_vec(),
691 }))
692 .await?,
693 );
694 }
695 let mut seen = HashSet::new();
696 result.retain(|model| seen.insert(model.primary_key_value()));
697 Ok(result)
698 }
699 async fn rows(&self, ast: QueryAst) -> Result<Vec<Row>, OrmError> {
700 ast.validate()?;
701 let ast = match &self.runtime {
702 Some(runtime) => prepare_runtime_ast(runtime.as_ref(), ast)?,
703 None => ast,
704 };
705 if let Some(runtime) = &self.runtime
706 && write_table(&ast).is_some_and(|table| runtime.captures_table(table))
707 {
708 return Ok(runtime.write(self, ast).await?.rows);
709 }
710 self.session
711 .query(SqlCompiler::<CurrentDialect>::compile(&ast))
712 .await
713 }
714 async fn execute_returning<M: Model + Send + 'static>(
715 &self,
716 ast: QueryAst,
717 ) -> Result<Option<M>, OrmError> {
718 Ok(decode_models(self.rows(ast).await?)?.pop())
719 }
720}
721
722fn insert_ast<M: Model>(model: &M) -> QueryAst {
723 QueryAst::Insert(crate::InsertAst {
724 table: crate::TableRef::new(M::table_name()),
725 values: model.insert_values(),
726 returning: Vec::new(),
727 })
728}
729fn prepare_runtime_ast(
733 runtime: &dyn ModelRuntime,
734 mut ast: QueryAst,
735) -> Result<QueryAst, OrmError> {
736 match &mut ast {
737 QueryAst::Select(select) => {
738 if let Some(filter) = &mut select.filter {
739 prepare_runtime_expr(runtime, filter)?;
740 }
741 for join in &mut select.joins {
742 prepare_runtime_expr(runtime, &mut join.on)?;
743 }
744 }
745 QueryAst::Update(update) => {
746 if let Some(filter) = &mut update.filter {
747 prepare_runtime_expr(runtime, filter)?;
748 }
749 }
750 QueryAst::Delete(delete) => {
751 if let Some(filter) = &mut delete.filter {
752 prepare_runtime_expr(runtime, filter)?;
753 }
754 }
755 QueryAst::Insert(_) | QueryAst::CreateTable(_) => {}
756 }
757 if matches!(ast, QueryAst::Select(_)) {
758 runtime.authorize_read(&ast)?;
759 ast = runtime.prepare_read(ast);
760 if !matches!(ast, QueryAst::Select(_)) {
761 return Err(OrmError::Configuration(
762 "read runtime must preserve SELECT queries".into(),
763 ));
764 }
765 }
766 ast.validate()?;
767 Ok(ast)
768}
769fn prepare_runtime_expr(runtime: &dyn ModelRuntime, expr: &mut Expr) -> Result<(), OrmError> {
770 match expr {
771 Expr::InQuery { left, query } => {
772 prepare_runtime_expr(runtime, left)?;
773 let QueryAst::Select(prepared) =
774 prepare_runtime_ast(runtime, QueryAst::Select((**query).clone()))?
775 else {
776 unreachable!()
777 };
778 **query = prepared;
779 }
780 Expr::Compare { left, right, .. }
781 | Expr::And { left, right }
782 | Expr::Or { left, right } => {
783 prepare_runtime_expr(runtime, left)?;
784 prepare_runtime_expr(runtime, right)?;
785 }
786 Expr::Like { left, pattern } => {
787 prepare_runtime_expr(runtime, left)?;
788 prepare_runtime_expr(runtime, pattern)?;
789 }
790 Expr::In { left, .. } => prepare_runtime_expr(runtime, left)?,
791 Expr::Not(expr) | Expr::IsNull(expr) | Expr::IsNotNull(expr) => {
792 prepare_runtime_expr(runtime, expr)?
793 }
794 Expr::Column(_) | Expr::Value(_) => {}
795 }
796 Ok(())
797}
798
799fn count_query<M: Model>(
800 query: SelectQuery<M>,
801 runtime: Option<&dyn ModelRuntime>,
802) -> Result<CompiledQuery, OrmError> {
803 let ast = QueryAst::Select(query.into_select_ast()?);
804 let ast = match runtime {
805 Some(runtime) => prepare_runtime_ast(runtime, ast)?,
806 None => ast,
807 };
808 let compiled = SqlCompiler::<CurrentDialect>::compile(&ast);
809 Ok(CompiledQuery {
810 sql: format!("SELECT COUNT(*) FROM ({}) AS che_count", compiled.sql),
811 params: compiled.params,
812 })
813}
814fn count_rows(rows: Vec<Row>) -> Result<usize, OrmError> {
815 let count: i64 = rows
816 .first()
817 .ok_or_else(|| OrmError::Interaction("count returned no row".into()))?
818 .get(0)?;
819 usize::try_from(count).map_err(|error| OrmError::Interaction(error.to_string()))
820}
821fn decode_models<M: Model>(rows: Vec<Row>) -> Result<Vec<M>, OrmError> {
822 rows.iter()
823 .map(|row| M::from_row(row).map_err(Into::into))
824 .collect()
825}
826
827pub struct TransactionCreateBuilder<'tx, M> {
828 transaction: &'tx Transaction,
829 query: crate::InsertQuery<M>,
830}
831impl<M: Model> TransactionCreateBuilder<'_, M> {
832 pub fn set<T, V: QueryValue<T>>(self, field: ModelField<M, T>, value: V) -> Self {
833 Self {
834 query: self.query.set(field, value),
835 ..self
836 }
837 }
838 pub async fn execute(self) -> Result<M, OrmError>
839 where
840 M: Send + 'static,
841 {
842 self.transaction
843 .execute_returning(self.query.returning_all().into_ast()?)
844 .await?
845 .ok_or_else(|| OrmError::Interaction("insert did not return a row".into()))
846 }
847}
848pub struct TransactionUpdateBuilder<'tx, M> {
849 transaction: &'tx Transaction,
850 query: crate::UpdateQuery<M>,
851}
852impl<M: Model> TransactionUpdateBuilder<'_, M> {
853 pub fn set<T, V: QueryValue<T>>(self, field: ModelField<M, T>, value: V) -> Self {
854 Self {
855 query: self.query.set(field, value),
856 ..self
857 }
858 }
859 pub async fn execute(self) -> Result<Option<M>, OrmError>
860 where
861 M: Send + 'static,
862 {
863 self.transaction
864 .execute_returning(self.query.returning_all().into_ast()?)
865 .await
866 }
867}
868pub struct TransactionQuery<'tx, M> {
869 transaction: &'tx Transaction,
870 query: SelectQuery<M>,
871}
872impl<M: Model> TransactionQuery<'_, M> {
873 pub fn filter(self, expr: Expr) -> Self {
874 Self {
875 query: self.query.filter(expr),
876 ..self
877 }
878 }
879 pub fn order_by(self, order: crate::OrderBy) -> Self {
880 Self {
881 query: self.query.order_by(order),
882 ..self
883 }
884 }
885 pub fn limit(self, limit: u64) -> Self {
886 Self {
887 query: self.query.limit(limit),
888 ..self
889 }
890 }
891 pub fn offset(self, offset: u64) -> Self {
892 Self {
893 query: self.query.offset(offset),
894 ..self
895 }
896 }
897 pub async fn all(self) -> Result<Vec<M>, OrmError>
898 where
899 M: Send + 'static,
900 {
901 self.transaction.fetch_all(self.query).await
902 }
903 pub async fn first(self) -> Result<Option<M>, OrmError>
904 where
905 M: Send + 'static,
906 {
907 self.transaction.fetch_one(self.query).await
908 }
909}
910impl<M: Model + Send + 'static> ValidatedWrite<M> {
911 pub async fn save_in(self, transaction: &Transaction) -> Result<Option<M>, OrmError> {
913 let ast = match self {
914 Self::Create(query) => query.returning_all().into_ast()?,
915 Self::Update(query) => query.returning_all().into_ast()?,
916 };
917 transaction.execute_returning(ast).await
918 }
919
920 pub async fn save(self, database: &Database) -> Result<Option<M>, OrmError> {
921 let ast = match self {
922 Self::Create(query) => query.returning_all().into_ast()?,
923 Self::Update(query) => query.returning_all().into_ast()?,
924 };
925 database.execute_returning(ast).await
926 }
927}
928pub struct CreateBuilder<'db, M> {
929 database: &'db Database,
930 query: crate::InsertQuery<M>,
931}
932impl<M: Model> CreateBuilder<'_, M> {
933 pub fn set<T, V: QueryValue<T>>(self, field: ModelField<M, T>, value: V) -> Self {
934 Self {
935 query: self.query.set(field, value),
936 ..self
937 }
938 }
939 pub async fn execute(self) -> Result<M, OrmError>
940 where
941 M: Send + 'static,
942 {
943 self.database
944 .execute_returning(self.query.returning_all().into_ast()?)
945 .await?
946 .ok_or_else(|| OrmError::Interaction("insert did not return a row".into()))
947 }
948}
949pub struct UpdateBuilder<'db, M> {
950 database: &'db Database,
951 query: crate::UpdateQuery<M>,
952}
953impl<M: Model> UpdateBuilder<'_, M> {
954 pub fn set<T, V: QueryValue<T>>(self, field: ModelField<M, T>, value: V) -> Self {
955 Self {
956 query: self.query.set(field, value),
957 ..self
958 }
959 }
960 pub async fn execute(self) -> Result<Option<M>, OrmError>
961 where
962 M: Send + 'static,
963 {
964 self.database
965 .execute_returning(self.query.returning_all().into_ast()?)
966 .await
967 }
968}
969pub struct DatabaseQuery<M> {
970 query: SelectQuery<M>,
971}
972impl<M: Model> DatabaseQuery<M> {
973 pub fn new(query: SelectQuery<M>) -> Self {
974 Self { query }
975 }
976 pub fn filter(self, expr: Expr) -> Self {
977 Self {
978 query: self.query.filter(expr),
979 }
980 }
981 pub fn order_by(self, order: crate::OrderBy) -> Self {
982 Self {
983 query: self.query.order_by(order),
984 }
985 }
986 pub fn limit(self, limit: u64) -> Self {
987 Self {
988 query: self.query.limit(limit),
989 }
990 }
991 pub fn offset(self, offset: u64) -> Self {
992 Self {
993 query: self.query.offset(offset),
994 }
995 }
996 pub fn select_related<R, Relation, Key>(
997 self,
998 relation: BelongsTo<M, R, Relation, Key>,
999 ) -> SelectRelatedQuery<M, R, Relation, Key> {
1000 SelectRelatedQuery {
1001 query: self.query,
1002 relation,
1003 }
1004 }
1005 pub fn prefetch_related<P: PrefetchRelation<M>>(self, plan: P) -> P::Query {
1006 plan.into_query(self.query)
1007 }
1008 pub async fn all(self, db: &Database) -> Result<Vec<M>, OrmError>
1009 where
1010 M: Send + 'static,
1011 {
1012 db.fetch_all(self.query).await
1013 }
1014 pub async fn first(self, db: &Database) -> Result<Option<M>, OrmError>
1015 where
1016 M: Send + 'static,
1017 {
1018 db.fetch_one(self.query).await
1019 }
1020 pub async fn count(self, db: &Database) -> Result<usize, OrmError>
1021 where
1022 M: Send + 'static,
1023 {
1024 db.count_query(self.query).await
1025 }
1026 pub fn into_select_query(self) -> SelectQuery<M> {
1027 self.query
1028 }
1029}
1030pub trait PrefetchRelation<Owner: Model> {
1031 type Query;
1032 fn into_query(self, query: SelectQuery<Owner>) -> Self::Query;
1033}
1034
1035#[derive(Debug)]
1036pub struct WithOne<M, R, Relation = (), Key = i64> {
1037 pub model: M,
1038 pub related: R,
1039 pub(crate) _relation: PhantomData<Relation>,
1040 pub(crate) _key: PhantomData<Key>,
1041}
1042#[derive(Debug)]
1043pub struct WithOptionalOne<M, R, Relation = ()> {
1044 pub model: M,
1045 pub related: Option<R>,
1046 pub(crate) _relation: PhantomData<Relation>,
1047}
1048#[derive(Debug)]
1049pub struct WithMany<M, R, Relation = (), Key = i64> {
1050 pub model: M,
1051 pub related: Vec<R>,
1052 pub(crate) _relation: PhantomData<Relation>,
1053 pub(crate) _key: PhantomData<Key>,
1054}
1055#[derive(Debug)]
1056pub struct Loaded<M, Relations> {
1057 pub model: M,
1058 pub relations: Relations,
1059}
1060#[derive(Debug)]
1061pub struct LoadedMany<R, Relation = ()> {
1062 pub related: Vec<R>,
1063 pub(crate) _relation: PhantomData<Relation>,
1064}
1065#[derive(Debug)]
1066pub struct LoadedOne<R, Relation = ()> {
1067 pub related: R,
1068 pub(crate) _relation: PhantomData<Relation>,
1069}
1070
1071pub struct SelectRelatedQuery<M, R, Relation = (), Key = i64> {
1072 query: SelectQuery<M>,
1073 relation: BelongsTo<M, R, Relation, Key>,
1074}
1075impl<M: Model, R, Relation, Key> SelectRelatedQuery<M, R, Relation, Key> {
1076 pub fn filter(self, expr: Expr) -> Self {
1077 Self {
1078 query: self.query.filter(expr),
1079 ..self
1080 }
1081 }
1082 pub fn order_by(self, order: crate::OrderBy) -> Self {
1083 Self {
1084 query: self.query.order_by(order),
1085 ..self
1086 }
1087 }
1088 pub fn limit(self, limit: u64) -> Self {
1089 Self {
1090 query: self.query.limit(limit),
1091 ..self
1092 }
1093 }
1094 pub fn offset(self, offset: u64) -> Self {
1095 Self {
1096 query: self.query.offset(offset),
1097 ..self
1098 }
1099 }
1100 pub async fn count(self, db: &Database) -> Result<usize, OrmError>
1101 where
1102 M: Send + 'static,
1103 R: Model,
1104 Key: crate::ForeignKeyValue<R::PrimaryKey>,
1105 {
1106 let kind = if Key::OPTIONAL {
1107 crate::JoinType::Left
1108 } else {
1109 crate::JoinType::Inner
1110 };
1111 let ast = self.query.into_joined_ast_with_kind(self.relation, kind)?;
1112 let compiled = SqlCompiler::<CurrentDialect>::compile(&ast);
1113 count_rows(
1114 db.query_sql(
1115 format!("SELECT COUNT(*) FROM ({}) AS che_count", compiled.sql),
1116 compiled.params,
1117 )
1118 .await?,
1119 )
1120 }
1121}
1122impl<M, R, Relation, Key: crate::PrimaryKey> SelectRelatedQuery<M, R, Relation, Key>
1123where
1124 M: Model + Send + 'static,
1125 R: Model + Send + 'static,
1126{
1127 pub fn select_related<R2: Model, Relation2>(
1128 self,
1129 relation: BelongsTo<M, R2, Relation2, R2::PrimaryKey>,
1130 ) -> MultiSelectRelatedQuery<M, R, Relation, R2, Relation2, Key> {
1131 MultiSelectRelatedQuery {
1132 query: self.query,
1133 first: self.relation,
1134 second: relation,
1135 }
1136 }
1137 pub async fn all(self, db: &Database) -> Result<Vec<WithOne<M, R, Relation, Key>>, OrmError> {
1138 let offset = M::columns().len();
1139 db.rows(self.query.into_joined_ast(self.relation)?)
1140 .await?
1141 .iter()
1142 .map(|row| {
1143 Ok(WithOne {
1144 model: M::from_row_at(row, 0)?,
1145 related: R::from_row_at(row, offset)?,
1146 _relation: PhantomData,
1147 _key: PhantomData,
1148 })
1149 })
1150 .collect()
1151 }
1152}
1153impl<M, R, Relation, Key: crate::PrimaryKey> SelectRelatedQuery<M, R, Relation, Option<Key>>
1154where
1155 M: Model + Send + 'static,
1156 R: Model + Send + 'static,
1157{
1158 pub async fn all(
1159 self,
1160 db: &Database,
1161 ) -> Result<Vec<WithOptionalOne<M, R, Relation>>, OrmError> {
1162 let offset = M::columns().len();
1163 let pk_offset = R::columns()
1164 .iter()
1165 .position(|column| *column == R::primary_key().column().name)
1166 .ok_or_else(|| {
1167 OrmError::Interaction("primary key missing from model columns".into())
1168 })?;
1169 db.rows(self.query.into_optional_joined_ast(self.relation)?)
1170 .await?
1171 .iter()
1172 .map(|row| {
1173 let id: Option<R::PrimaryKey> = row.get(offset + pk_offset)?;
1174 Ok(WithOptionalOne {
1175 model: M::from_row_at(row, 0)?,
1176 related: id.map(|_| R::from_row_at(row, offset)).transpose()?,
1177 _relation: PhantomData,
1178 })
1179 })
1180 .collect()
1181 }
1182}
1183pub struct MultiSelectRelatedQuery<M, R1, Relation1, R2: Model, Relation2, Key1 = i64> {
1184 query: SelectQuery<M>,
1185 first: BelongsTo<M, R1, Relation1, Key1>,
1186 second: BelongsTo<M, R2, Relation2, R2::PrimaryKey>,
1187}
1188impl<M, R1, Relation1, R2, Relation2, Key1>
1189 MultiSelectRelatedQuery<M, R1, Relation1, R2, Relation2, Key1>
1190where
1191 M: Model + Send + 'static,
1192 R1: Model + Send + 'static,
1193 R2: Model + Send + 'static,
1194{
1195 pub fn filter(self, expr: Expr) -> Self {
1196 Self {
1197 query: self.query.filter(expr),
1198 ..self
1199 }
1200 }
1201 pub fn order_by(self, order: crate::OrderBy) -> Self {
1202 Self {
1203 query: self.query.order_by(order),
1204 ..self
1205 }
1206 }
1207 pub async fn all(
1208 self,
1209 db: &Database,
1210 ) -> Result<Vec<Loaded<M, (LoadedOne<R1, Relation1>, LoadedOne<R2, Relation2>)>>, OrmError>
1211 {
1212 let second = self.second;
1213 let mut ast = self.query.into_joined_ast(self.first)?;
1214 if let QueryAst::Select(select) = &mut ast {
1215 select.columns.extend(
1216 R2::columns()
1217 .iter()
1218 .map(|column| crate::ColumnRef::new(second.alias(), column)),
1219 );
1220 select.joins.push(crate::JoinAst {
1221 table: crate::TableRef::new(R2::table_name()),
1222 alias: second.alias(),
1223 kind: crate::JoinType::Inner,
1224 on: crate::Expr::Compare {
1225 left: Box::new(Expr::Column(second.field())),
1226 op: crate::CompareOp::Eq,
1227 right: Box::new(Expr::Column(crate::ColumnRef::new(
1228 second.alias(),
1229 R2::primary_key().column().name,
1230 ))),
1231 },
1232 });
1233 }
1234 let offset = M::columns().len();
1235 db.rows(ast)
1236 .await?
1237 .iter()
1238 .map(|row| {
1239 Ok(Loaded {
1240 model: M::from_row_at(row, 0)?,
1241 relations: (
1242 LoadedOne {
1243 related: R1::from_row_at(row, offset)?,
1244 _relation: PhantomData,
1245 },
1246 LoadedOne {
1247 related: R2::from_row_at(row, offset + R1::columns().len())?,
1248 _relation: PhantomData,
1249 },
1250 ),
1251 })
1252 })
1253 .collect()
1254 }
1255}
1256
1257pub struct PrefetchRelatedQuery<M, R, Relation = (), Key = i64> {
1258 query: SelectQuery<M>,
1259 relation: HasMany<M, R, Relation, Key>,
1260}
1261impl<M: Model, R, Relation, Key: crate::ForeignKeyValue<M::PrimaryKey>> PrefetchRelation<M>
1262 for HasMany<M, R, Relation, Key>
1263{
1264 type Query = PrefetchRelatedQuery<M, R, Relation, Key>;
1265 fn into_query(self, query: SelectQuery<M>) -> Self::Query {
1266 PrefetchRelatedQuery {
1267 query,
1268 relation: self,
1269 }
1270 }
1271}
1272fn ids<M: Model>(models: &[M]) -> Vec<M::PrimaryKey> {
1273 models
1274 .iter()
1275 .map(Model::primary_key_value)
1276 .collect::<HashSet<_>>()
1277 .into_iter()
1278 .collect()
1279}
1280fn group<M: Model, R, Relation, Key: crate::ForeignKeyValue<M::PrimaryKey>>(
1281 relation: &HasMany<M, R, Relation, Key>,
1282 models: Vec<R>,
1283) -> HashMap<M::PrimaryKey, Vec<R>> {
1284 let mut grouped = HashMap::<M::PrimaryKey, Vec<R>>::new();
1285 for model in models {
1286 if let Some(key) = crate::ForeignKeyValue::owner_key(relation.foreign_key(&model)) {
1287 grouped.entry(key).or_default().push(model);
1288 }
1289 }
1290 grouped
1291}
1292impl<M, R, Relation, Key> PrefetchRelatedQuery<M, R, Relation, Key>
1293where
1294 M: Model + Send + 'static,
1295 R: Model + Send + 'static,
1296 Key: crate::ForeignKeyValue<M::PrimaryKey>,
1297{
1298 pub fn filter(self, expr: Expr) -> Self {
1299 Self {
1300 query: self.query.filter(expr),
1301 ..self
1302 }
1303 }
1304 pub fn order_by(self, order: crate::OrderBy) -> Self {
1305 Self {
1306 query: self.query.order_by(order),
1307 ..self
1308 }
1309 }
1310 pub fn limit(self, limit: u64) -> Self {
1311 Self {
1312 query: self.query.limit(limit),
1313 ..self
1314 }
1315 }
1316 pub fn offset(self, offset: u64) -> Self {
1317 Self {
1318 query: self.query.offset(offset),
1319 ..self
1320 }
1321 }
1322 pub fn prefetch_related<R2, Relation2, Key2: crate::ForeignKeyValue<M::PrimaryKey>>(
1323 self,
1324 relation: HasMany<M, R2, Relation2, Key2>,
1325 ) -> MultiPrefetchRelatedQuery<M, R, Relation, R2, Relation2, Key, Key2> {
1326 MultiPrefetchRelatedQuery {
1327 query: self.query,
1328 first: self.relation,
1329 second: relation,
1330 }
1331 }
1332 pub async fn count(self, db: &Database) -> Result<usize, OrmError> {
1333 db.count_query(self.query).await
1334 }
1335 pub async fn all(
1336 self,
1337 db: &Database,
1338 ) -> Result<Vec<Loaded<M, (LoadedMany<R, Relation>,)>>, OrmError>
1339 where
1340 Relation: Send + 'static,
1341 {
1342 db.transaction(move |tx| {
1343 Box::pin(async move {
1344 let parents = tx.fetch_all(self.query).await?;
1345 let field = self.relation.field();
1346 let related = tx
1347 .fetch_by_many(
1348 ModelField::<R, M::PrimaryKey>::new(field.table, field.name),
1349 ids(&parents),
1350 )
1351 .await?;
1352 let mut related = group(&self.relation, related);
1353 Ok(parents
1354 .into_iter()
1355 .map(|model| {
1356 let key = model.primary_key_value();
1357 Loaded {
1358 model,
1359 relations: (LoadedMany {
1360 related: related.remove(&key).unwrap_or_default(),
1361 _relation: PhantomData,
1362 },),
1363 }
1364 })
1365 .collect())
1366 })
1367 })
1368 .await
1369 }
1370}
1371pub struct MultiPrefetchRelatedQuery<
1372 M: Model,
1373 R1,
1374 Relation1,
1375 R2,
1376 Relation2,
1377 Key1 = <M as Model>::PrimaryKey,
1378 Key2 = <M as Model>::PrimaryKey,
1379> {
1380 query: SelectQuery<M>,
1381 first: HasMany<M, R1, Relation1, Key1>,
1382 second: HasMany<M, R2, Relation2, Key2>,
1383}
1384impl<M, R1, Relation1, R2, Relation2, Key1, Key2>
1385 MultiPrefetchRelatedQuery<M, R1, Relation1, R2, Relation2, Key1, Key2>
1386where
1387 M: Model + Send + 'static,
1388 R1: Model + Send + 'static,
1389 R2: Model + Send + 'static,
1390 Relation1: Send + 'static,
1391 Relation2: Send + 'static,
1392 Key1: crate::ForeignKeyValue<M::PrimaryKey>,
1393 Key2: crate::ForeignKeyValue<M::PrimaryKey>,
1394{
1395 pub async fn all(
1396 self,
1397 db: &Database,
1398 ) -> Result<Vec<Loaded<M, (LoadedMany<R1, Relation1>, LoadedMany<R2, Relation2>)>>, OrmError>
1399 {
1400 db.transaction(move |tx| {
1401 Box::pin(async move {
1402 let parents = tx.fetch_all(self.query).await?;
1403 let keys = ids(&parents);
1404 let field = self.first.field();
1405 let first = tx
1406 .fetch_by_many(
1407 ModelField::<R1, M::PrimaryKey>::new(field.table, field.name),
1408 keys.clone(),
1409 )
1410 .await?;
1411 let field = self.second.field();
1412 let second = tx
1413 .fetch_by_many(
1414 ModelField::<R2, M::PrimaryKey>::new(field.table, field.name),
1415 keys,
1416 )
1417 .await?;
1418 let mut first = group(&self.first, first);
1419 let mut second = group(&self.second, second);
1420 Ok(parents
1421 .into_iter()
1422 .map(|model| {
1423 let key = model.primary_key_value();
1424 Loaded {
1425 model,
1426 relations: (
1427 LoadedMany {
1428 related: first.remove(&key).unwrap_or_default(),
1429 _relation: PhantomData,
1430 },
1431 LoadedMany {
1432 related: second.remove(&key).unwrap_or_default(),
1433 _relation: PhantomData,
1434 },
1435 ),
1436 }
1437 })
1438 .collect())
1439 })
1440 })
1441 .await
1442 }
1443}
1444pub struct NestedPrefetchPlan<
1445 M: Model,
1446 R: Model,
1447 Relation,
1448 C,
1449 ChildRelation,
1450 OuterKey = <M as Model>::PrimaryKey,
1451 InnerKey = <R as Model>::PrimaryKey,
1452> {
1453 outer: HasMany<M, R, Relation, OuterKey>,
1454 inner: HasMany<R, C, ChildRelation, InnerKey>,
1455}
1456impl<M: Model, R: Model, Relation, Key: crate::ForeignKeyValue<M::PrimaryKey>>
1457 HasMany<M, R, Relation, Key>
1458{
1459 pub fn prefetch<C, ChildRelation, InnerKey: crate::ForeignKeyValue<R::PrimaryKey>>(
1460 self,
1461 inner: HasMany<R, C, ChildRelation, InnerKey>,
1462 ) -> NestedPrefetchPlan<M, R, Relation, C, ChildRelation, Key, InnerKey> {
1463 NestedPrefetchPlan { outer: self, inner }
1464 }
1465}
1466impl<
1467 M: Model,
1468 R: Model,
1469 Relation,
1470 C,
1471 ChildRelation,
1472 OuterKey: crate::ForeignKeyValue<M::PrimaryKey>,
1473 InnerKey: crate::ForeignKeyValue<R::PrimaryKey>,
1474> PrefetchRelation<M> for NestedPrefetchPlan<M, R, Relation, C, ChildRelation, OuterKey, InnerKey>
1475{
1476 type Query = NestedPrefetchQuery<M, R, Relation, C, ChildRelation, OuterKey, InnerKey>;
1477 fn into_query(self, query: SelectQuery<M>) -> Self::Query {
1478 NestedPrefetchQuery {
1479 query,
1480 outer: self.outer,
1481 inner: self.inner,
1482 }
1483 }
1484}
1485pub struct NestedPrefetchQuery<
1486 M: Model,
1487 R: Model,
1488 Relation,
1489 C,
1490 ChildRelation,
1491 OuterKey = <M as Model>::PrimaryKey,
1492 InnerKey = <R as Model>::PrimaryKey,
1493> {
1494 query: SelectQuery<M>,
1495 outer: HasMany<M, R, Relation, OuterKey>,
1496 inner: HasMany<R, C, ChildRelation, InnerKey>,
1497}
1498impl<M, R, Relation, C, ChildRelation, OuterKey, InnerKey>
1499 NestedPrefetchQuery<M, R, Relation, C, ChildRelation, OuterKey, InnerKey>
1500where
1501 M: Model + Send + 'static,
1502 R: Model + Send + 'static,
1503 C: Model + Send + 'static,
1504 Relation: Send + 'static,
1505 ChildRelation: Send + 'static,
1506 OuterKey: crate::ForeignKeyValue<M::PrimaryKey>,
1507 InnerKey: crate::ForeignKeyValue<R::PrimaryKey>,
1508{
1509 pub async fn all(
1510 self,
1511 db: &Database,
1512 ) -> Result<
1513 Vec<Loaded<M, (LoadedMany<Loaded<R, (LoadedMany<C, ChildRelation>,)>, Relation>,)>>,
1514 OrmError,
1515 > {
1516 db.transaction(move |tx| {
1517 Box::pin(async move {
1518 let parents = tx.fetch_all(self.query).await?;
1519 let field = self.outer.field();
1520 let children = tx
1521 .fetch_by_many(
1522 ModelField::<R, M::PrimaryKey>::new(field.table, field.name),
1523 ids(&parents),
1524 )
1525 .await?;
1526 let field = self.inner.field();
1527 let grandchildren = tx
1528 .fetch_by_many(
1529 ModelField::<C, R::PrimaryKey>::new(field.table, field.name),
1530 ids(&children),
1531 )
1532 .await?;
1533 let mut grandchildren = group(&self.inner, grandchildren);
1534 let mut grouped = HashMap::<M::PrimaryKey, Vec<_>>::new();
1535 for model in children {
1536 if let Some(owner) =
1537 crate::ForeignKeyValue::owner_key(self.outer.foreign_key(&model))
1538 {
1539 let related = grandchildren
1540 .remove(&model.primary_key_value())
1541 .unwrap_or_default();
1542 grouped.entry(owner).or_default().push(Loaded {
1543 model,
1544 relations: (LoadedMany {
1545 related,
1546 _relation: PhantomData,
1547 },),
1548 });
1549 }
1550 }
1551 Ok(parents
1552 .into_iter()
1553 .map(|model| {
1554 let key = model.primary_key_value();
1555 Loaded {
1556 model,
1557 relations: (LoadedMany {
1558 related: grouped.remove(&key).unwrap_or_default(),
1559 _relation: PhantomData,
1560 },),
1561 }
1562 })
1563 .collect())
1564 })
1565 })
1566 .await
1567 }
1568}