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