From c82b23795dc135955f99f4fb475d635ccb136eba Mon Sep 17 00:00:00 2001 From: Chris Tsang Date: Fri, 16 Jul 2021 21:41:12 +0800 Subject: [PATCH] #48: Select model from raw sql --- src/executor/select.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/src/executor/select.rs b/src/executor/select.rs index d2d21593..15b23b65 100644 --- a/src/executor/select.rs +++ b/src/executor/select.rs @@ -1,7 +1,7 @@ use crate::{ error::*, query::combine, DatabaseConnection, EntityTrait, FromQueryResult, Iterable, JsonValue, ModelTrait, Paginator, PrimaryKeyToColumn, QueryResult, Select, SelectTwo, - SelectTwoMany, + SelectTwoMany, Statement, }; use sea_query::SelectStatement; use std::marker::PhantomData; @@ -15,6 +15,15 @@ where selector: S, } +#[derive(Clone, Debug)] +pub struct SelectorRaw +where + S: SelectorTrait, +{ + stmt: Statement, + selector: S, +} + pub trait SelectorTrait { type Item: Sized; @@ -67,6 +76,13 @@ impl Select where E: EntityTrait, { + pub fn from_raw_sql(stmt: Statement) -> SelectorRaw> { + SelectorRaw { + stmt, + selector: SelectModel { model: PhantomData }, + } + } + pub fn into_model(self) -> Selector> where M: FromQueryResult, @@ -216,6 +232,28 @@ where } } +impl SelectorRaw +where + S: SelectorTrait, +{ + pub async fn one(self, db: &DatabaseConnection) -> Result, DbErr> { + let row = db.query_one(self.stmt).await?; + match row { + Some(row) => Ok(Some(S::from_raw_query_result(row)?)), + None => Ok(None), + } + } + + pub async fn all(self, db: &DatabaseConnection) -> Result, DbErr> { + let rows = db.query_all(self.stmt).await?; + let mut models = Vec::new(); + for row in rows.into_iter() { + models.push(S::from_raw_query_result(row)?); + } + Ok(models) + } +} + fn consolidate_query_result( rows: Vec<(L::Model, Option)>, ) -> Vec<(L::Model, Vec)>