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