Forráskód Böngészése

Update to anansi 0.14.1 (#8028)

* Update to anansi 0.14.1

* Fixed anansi raw test

* Fixed rust version for anansi

---------

Co-authored-by: sarutora <example.com>
saru-tora 2 éve
szülő
commit
38281f23b4

+ 1 - 1
frameworks/Rust/anansi/Cargo.toml

@@ -12,7 +12,7 @@ edition = "2021"
 raw = []
 
 [dependencies]
-anansi = { git = "https://github.com/saru-tora/anansi", rev = "bcbd687", features = ["postgres", "minimal", "redis"] }
+anansi = { git = "https://github.com/saru-tora/anansi", rev = "87830d6", features = ["postgres", "minimal", "redis"] }
 async-trait = "0.1.57"
 rand = "0.8.4"
 serde = "1"

+ 54 - 0
frameworks/Rust/anansi/src/hello/middleware.rs

@@ -0,0 +1,54 @@
+use std::fmt;
+use std::sync::Arc;
+use anansi::db::postgres::{PgDbRow, PgDbRowVec, PgStatement};
+
+#[macro_export]
+macro_rules! impl_pg {
+    () => {
+        #[async_trait::async_trait]
+        impl crate::hello::middleware::Pg for HttpRequest {
+            async fn get_world(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRow> {
+                use anansi::web::BaseRequest;
+                self.mid.stmt.0.world.fetch_one(&[&Self::random_num()], self.raw().pool()).await
+            }
+            async fn get_fortunes(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRowVec> {
+                use anansi::web::BaseRequest;
+                self.mid.stmt.0.fortune.fetch_all(&[], self.raw().pool()).await
+            }
+        }
+    }
+}
+
+#[derive(Clone)]
+pub struct Stmt(pub Arc<State>);
+
+impl fmt::Debug for Stmt {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("Stmt")
+         .finish()
+    }
+}
+
+impl Stmt {
+    pub async fn new(raw: &mut anansi::web::RawRequest<anansi::db::postgres::PgDbPool>) -> anansi::web::Result<Self> {
+        Ok(Self(Arc::new(State {
+            world: PgStatement::new("SELECT * FROM world WHERE id = $1", raw.pool()).await?,
+            fortune: PgStatement::new("SELECT * FROM fortune", raw.pool()).await?,
+        })))
+    }
+}
+
+pub struct State {
+    pub world: PgStatement,
+    pub fortune: PgStatement,
+}
+
+#[async_trait::async_trait]
+pub trait Pg {
+    fn random_num() -> i32 {
+        use rand::Rng;
+        rand::thread_rng().gen_range(1..=10_000)
+    }
+    async fn get_world(&self) -> anansi::web::Result<PgDbRow>;
+    async fn get_fortunes(&self) -> anansi::web::Result<PgDbRowVec>;
+}

+ 3 - 1
frameworks/Rust/anansi/src/hello/mod.rs

@@ -1,6 +1,8 @@
-pub mod urls;
 pub mod records;
 pub mod migrations;
 
 pub const APP_NAME: &'static str = "hello";
 pub mod world;
+
+#[cfg(feature = "raw")]
+pub mod middleware;

+ 0 - 3
frameworks/Rust/anansi/src/hello/urls.rs

@@ -1,3 +0,0 @@
-use anansi::web::prelude::*;
-
-routes! {}

+ 13 - 18
frameworks/Rust/anansi/src/hello/world/raw.rs

@@ -1,7 +1,6 @@
 use crate::prelude::*;
 use serde::Serialize;
 use anansi::{check, prep};
-use anansi::db::postgres::PgDbRow;
 use super::util::get_query;
 use std::borrow::Cow;
 use anansi::db::DbRow;
@@ -50,14 +49,11 @@ fn base<R: Request>(_req: &mut R) -> Result<Response> {}
 
 #[viewer]
 impl<R: Request> WorldView<R> {
-    async fn get_world(req: &R) -> Result<PgDbRow> {
-        anansi::db::postgres::PgStatement::raw_one(0, &[&random_num()], req.raw().pool()).await
-    }
     async fn get_worlds(req: &R) -> Result<Vec<World>> {
         let q = get_query(req.params());
         let mut worlds = Vec::with_capacity(q as usize);
         for _ in 0..q {
-            let row = Self::get_world(req).await?;
+            let row = req.get_world().await?;
             let world = World {
                 id: row.try_i32("id")?,
                 randomnumber: row.try_i32("randomnumber")?,
@@ -68,10 +64,10 @@ impl<R: Request> WorldView<R> {
     }
     #[check(Site::is_visitor)]
     pub async fn db(req: &mut R) -> Result<Response> {
-        let row = Self::get_world(req).await?;
+        let row = req.get_world().await?;
         let world = World {
-            id: row.try_i32("id")?,
-            randomnumber: row.try_i32("randomnumber")?,
+            id: row.get_i32(0),
+            randomnumber: row.get_i32(1),
         };
         Response::json(&world)
     }
@@ -83,17 +79,16 @@ impl<R: Request> WorldView<R> {
     #[view(Site::is_visitor)]
     pub async fn raw_fortunes(req: &mut R) -> Result<Response> {
         let title = "Fortunes";
-        let rows = anansi::db::postgres::PgStatement::raw_all(1, &[], req.raw().pool()).await?;
-        let mut fortunes = vec![Fortune {
+        let rows = req.get_fortunes().await?;
+        let mut fortunes = Vec::with_capacity(rows.len() + 1);
+        fortunes.push(Fortune {
             id: 0,
             message: Cow::Borrowed("Additional fortune added at request time.")
-        }];
-        for row in rows {
-            fortunes.push(Fortune {
-                id: row.try_i32("id")?,
-                message: Cow::Owned(row.try_string("message")?),
-            })
-        }
+        });
+        fortunes.extend(rows.iter().map(|row| Fortune {
+            id: row.get(0),
+            message: Cow::Owned(row.get(1)),
+        }));
         fortunes.sort_by(|it, next| it.message.cmp(&next.message));
     }
     #[check(Site::is_visitor)]
@@ -102,7 +97,7 @@ impl<R: Request> WorldView<R> {
         let mut worlds = Vec::with_capacity(q);
         let mut params: Vec<&(dyn ToSql + Sync)> = Vec::with_capacity(q * 3);
         for _ in 0..q {
-            let row = Self::get_world(req).await?;
+            let row = req.get_world().await?;
             let world = World {
                 id: row.try_i32("id")?,
                 randomnumber: random_num(),

+ 6 - 5
frameworks/Rust/anansi/src/hello/world/templates/.parsed/raw_fortunes.in

@@ -1,5 +1,6 @@
-{_args._title = {let mut _c = String::new();_c.push_str(&anansi::web::html_escape(&format!("{}", title))); _c};
-_args._content = {let mut _c = String::new();_c.push_str("<table><tr><th>id</th><th>message</th></tr>");
-for fortune in fortunes {_c.push_str("<tr><td>"); _c.push_str(&anansi::web::html_escape(&format!("{}", fortune.id)));
-_c.push_str("</td><td>"); _c.push_str(&anansi::web::html_escape(&format!("{}", fortune.message))); _c.push_str("</td></tr>");
-} _c.push_str("</table>"); _c};_args}
+{_args._content = {let mut _c = String::new();_c.push_str("    <table>
+    <tr><th>id</th><th>message</th></tr>
+    ");for fortune in fortunes {_c.push_str("
+        <tr><td>");_c.push_str(&anansi::web::html_escape(&format!("{}", fortune.id)));_c.push_str("</td><td>");_c.push_str(&anansi::web::html_escape(&format!("{}", fortune.message)));_c.push_str("</td></tr>
+    ");}_c.push_str("
+    </table>"); _c};_args._title = {let mut _c = String::new();_c.push_str("");_c.push_str(&anansi::web::html_escape(&format!("{}", title)));_c.push_str(""); _c};_args}

+ 0 - 4
frameworks/Rust/anansi/src/main.rs

@@ -15,10 +15,6 @@ min_main!(server, {
     use anansi::cache::prelude::*;
     use hello::records::World;
     use anansi::records::Record;
-    if cfg!(feature = "raw") {
-        server.pool.2.write().unwrap().push(Arc::new(anansi::db::postgres::PgStatement::new("SELECT * FROM world WHERE id = $1", &server.pool).await.unwrap()));
-        server.pool.2.write().unwrap().push(Arc::new(anansi::db::postgres::PgStatement::new("SELECT * FROM fortune", &server.pool).await.unwrap()));
-    }
     let worlds = World::get_all().raw_query(&server.pool).await.expect("problem fetching worlds");
     let mut items = vec![];
     for world in worlds {

+ 16 - 0
frameworks/Rust/anansi/src/project.rs

@@ -1,5 +1,11 @@
 use anansi::project::prelude::*;
 
+#[cfg(feature = "raw")]
+use super::hello::middleware::{Pg, Stmt};
+
+#[cfg(feature = "raw")]
+use crate::impl_pg;
+
 #[cfg(feature = "raw")]
 app_cache!(local);
 
@@ -8,4 +14,14 @@ app_cache!(redis);
 
 database!(postgres);
 
+#[cfg(feature = "raw")]
+raw_middleware!();
+
+#[cfg(feature = "raw")]
+anansi::setup!(stmt, Stmt, Pg);
+
+#[cfg(feature = "raw")]
+impl_pg!();
+
+#[cfg(not(feature = "raw"))]
 middleware!();

+ 17 - 14
frameworks/Rust/anansi/src/urls.rs

@@ -1,26 +1,29 @@
 use anansi::web::prelude::*;
+use crate::prelude::Request;
 #[cfg(not(feature = "raw"))]
 use crate::hello::world::views::WorldView;
 
 #[cfg(not(feature = "raw"))]
-routes! {
-    path!("/json", WorldView::json),
-    path!("/db", WorldView::db),
-    path!("/queries", WorldView::queries),
-    path!("/fortunes", WorldView::fortunes),
-    path!("/updates", WorldView::updates),
-    path!("/plaintext", WorldView::plaintext),
-    path!("/cached-queries", WorldView::cached_queries),
+pub fn routes<R: Request>() -> Router<R> {
+    Router::new()
+        .route("/json", WorldView::json)
+        .route("/db", WorldView::db)
+        .route("/queries", WorldView::queries)
+        .route("/fortunes", WorldView::fortunes)
+        .route("/updates", WorldView::updates)
+        .route("/plaintext", WorldView::plaintext)
+        .route("/cached-queries", WorldView::cached_queries)
 }
 
 #[cfg(feature = "raw")]
 use crate::hello::world::raw::WorldView;
 
 #[cfg(feature = "raw")]
-routes! {
-    path!("/db", WorldView::db),
-    path!("/queries", WorldView::queries),
-    path!("/fortunes", WorldView::raw_fortunes),
-    path!("/updates", WorldView::updates),
-    path!("/cached-queries", WorldView::cached_queries),
+pub fn routes<R: Request>() -> Router<R> {
+    Router::new()
+        .route("/db", WorldView::db)
+        .route("/queries", WorldView::queries)
+        .route("/fortunes", WorldView::raw_fortunes)
+        .route("/updates", WorldView::updates)
+        .route("/cached-queries", WorldView::cached_queries)
 }