Skip to content

Commit e1fb6ea

Browse files
saru-torafranz1981
authored andcommitted
Update to anansi 0.14.1 (TechEmpower#8028)
* Update to anansi 0.14.1 * Fixed anansi raw test * Fixed rust version for anansi --------- Co-authored-by: sarutora <example.com>
1 parent 5532582 commit e1fb6ea

File tree

9 files changed

+110
-46
lines changed

9 files changed

+110
-46
lines changed

frameworks/Rust/anansi/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ edition = "2021"
1212
raw = []
1313

1414
[dependencies]
15-
anansi = { git = "https://github.com/saru-tora/anansi", rev = "bcbd687", features = ["postgres", "minimal", "redis"] }
15+
anansi = { git = "https://github.com/saru-tora/anansi", rev = "87830d6", features = ["postgres", "minimal", "redis"] }
1616
async-trait = "0.1.57"
1717
rand = "0.8.4"
1818
serde = "1"
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
use std::fmt;
2+
use std::sync::Arc;
3+
use anansi::db::postgres::{PgDbRow, PgDbRowVec, PgStatement};
4+
5+
#[macro_export]
6+
macro_rules! impl_pg {
7+
() => {
8+
#[async_trait::async_trait]
9+
impl crate::hello::middleware::Pg for HttpRequest {
10+
async fn get_world(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRow> {
11+
use anansi::web::BaseRequest;
12+
self.mid.stmt.0.world.fetch_one(&[&Self::random_num()], self.raw().pool()).await
13+
}
14+
async fn get_fortunes(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRowVec> {
15+
use anansi::web::BaseRequest;
16+
self.mid.stmt.0.fortune.fetch_all(&[], self.raw().pool()).await
17+
}
18+
}
19+
}
20+
}
21+
22+
#[derive(Clone)]
23+
pub struct Stmt(pub Arc<State>);
24+
25+
impl fmt::Debug for Stmt {
26+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27+
f.debug_struct("Stmt")
28+
.finish()
29+
}
30+
}
31+
32+
impl Stmt {
33+
pub async fn new(raw: &mut anansi::web::RawRequest<anansi::db::postgres::PgDbPool>) -> anansi::web::Result<Self> {
34+
Ok(Self(Arc::new(State {
35+
world: PgStatement::new("SELECT * FROM world WHERE id = $1", raw.pool()).await?,
36+
fortune: PgStatement::new("SELECT * FROM fortune", raw.pool()).await?,
37+
})))
38+
}
39+
}
40+
41+
pub struct State {
42+
pub world: PgStatement,
43+
pub fortune: PgStatement,
44+
}
45+
46+
#[async_trait::async_trait]
47+
pub trait Pg {
48+
fn random_num() -> i32 {
49+
use rand::Rng;
50+
rand::thread_rng().gen_range(1..=10_000)
51+
}
52+
async fn get_world(&self) -> anansi::web::Result<PgDbRow>;
53+
async fn get_fortunes(&self) -> anansi::web::Result<PgDbRowVec>;
54+
}
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
pub mod urls;
21
pub mod records;
32
pub mod migrations;
43

54
pub const APP_NAME: &'static str = "hello";
65
pub mod world;
6+
7+
#[cfg(feature = "raw")]
8+
pub mod middleware;

frameworks/Rust/anansi/src/hello/urls.rs

Lines changed: 0 additions & 3 deletions
This file was deleted.

frameworks/Rust/anansi/src/hello/world/raw.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use crate::prelude::*;
22
use serde::Serialize;
33
use anansi::{check, prep};
4-
use anansi::db::postgres::PgDbRow;
54
use super::util::get_query;
65
use std::borrow::Cow;
76
use anansi::db::DbRow;
@@ -50,14 +49,11 @@ fn base<R: Request>(_req: &mut R) -> Result<Response> {}
5049

5150
#[viewer]
5251
impl<R: Request> WorldView<R> {
53-
async fn get_world(req: &R) -> Result<PgDbRow> {
54-
anansi::db::postgres::PgStatement::raw_one(0, &[&random_num()], req.raw().pool()).await
55-
}
5652
async fn get_worlds(req: &R) -> Result<Vec<World>> {
5753
let q = get_query(req.params());
5854
let mut worlds = Vec::with_capacity(q as usize);
5955
for _ in 0..q {
60-
let row = Self::get_world(req).await?;
56+
let row = req.get_world().await?;
6157
let world = World {
6258
id: row.try_i32("id")?,
6359
randomnumber: row.try_i32("randomnumber")?,
@@ -68,10 +64,10 @@ impl<R: Request> WorldView<R> {
6864
}
6965
#[check(Site::is_visitor)]
7066
pub async fn db(req: &mut R) -> Result<Response> {
71-
let row = Self::get_world(req).await?;
67+
let row = req.get_world().await?;
7268
let world = World {
73-
id: row.try_i32("id")?,
74-
randomnumber: row.try_i32("randomnumber")?,
69+
id: row.get_i32(0),
70+
randomnumber: row.get_i32(1),
7571
};
7672
Response::json(&world)
7773
}
@@ -83,17 +79,16 @@ impl<R: Request> WorldView<R> {
8379
#[view(Site::is_visitor)]
8480
pub async fn raw_fortunes(req: &mut R) -> Result<Response> {
8581
let title = "Fortunes";
86-
let rows = anansi::db::postgres::PgStatement::raw_all(1, &[], req.raw().pool()).await?;
87-
let mut fortunes = vec![Fortune {
82+
let rows = req.get_fortunes().await?;
83+
let mut fortunes = Vec::with_capacity(rows.len() + 1);
84+
fortunes.push(Fortune {
8885
id: 0,
8986
message: Cow::Borrowed("Additional fortune added at request time.")
90-
}];
91-
for row in rows {
92-
fortunes.push(Fortune {
93-
id: row.try_i32("id")?,
94-
message: Cow::Owned(row.try_string("message")?),
95-
})
96-
}
87+
});
88+
fortunes.extend(rows.iter().map(|row| Fortune {
89+
id: row.get(0),
90+
message: Cow::Owned(row.get(1)),
91+
}));
9792
fortunes.sort_by(|it, next| it.message.cmp(&next.message));
9893
}
9994
#[check(Site::is_visitor)]
@@ -102,7 +97,7 @@ impl<R: Request> WorldView<R> {
10297
let mut worlds = Vec::with_capacity(q);
10398
let mut params: Vec<&(dyn ToSql + Sync)> = Vec::with_capacity(q * 3);
10499
for _ in 0..q {
105-
let row = Self::get_world(req).await?;
100+
let row = req.get_world().await?;
106101
let world = World {
107102
id: row.try_i32("id")?,
108103
randomnumber: random_num(),
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
{_args._title = {let mut _c = String::new();_c.push_str(&anansi::web::html_escape(&format!("{}", title))); _c};
2-
_args._content = {let mut _c = String::new();_c.push_str("<table><tr><th>id</th><th>message</th></tr>");
3-
for fortune in fortunes {_c.push_str("<tr><td>"); _c.push_str(&anansi::web::html_escape(&format!("{}", fortune.id)));
4-
_c.push_str("</td><td>"); _c.push_str(&anansi::web::html_escape(&format!("{}", fortune.message))); _c.push_str("</td></tr>");
5-
} _c.push_str("</table>"); _c};_args}
1+
{_args._content = {let mut _c = String::new();_c.push_str(" <table>
2+
<tr><th>id</th><th>message</th></tr>
3+
");for fortune in fortunes {_c.push_str("
4+
<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>
5+
");}_c.push_str("
6+
</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}

frameworks/Rust/anansi/src/main.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ min_main!(server, {
1515
use anansi::cache::prelude::*;
1616
use hello::records::World;
1717
use anansi::records::Record;
18-
if cfg!(feature = "raw") {
19-
server.pool.2.write().unwrap().push(Arc::new(anansi::db::postgres::PgStatement::new("SELECT * FROM world WHERE id = $1", &server.pool).await.unwrap()));
20-
server.pool.2.write().unwrap().push(Arc::new(anansi::db::postgres::PgStatement::new("SELECT * FROM fortune", &server.pool).await.unwrap()));
21-
}
2218
let worlds = World::get_all().raw_query(&server.pool).await.expect("problem fetching worlds");
2319
let mut items = vec![];
2420
for world in worlds {

frameworks/Rust/anansi/src/project.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
use anansi::project::prelude::*;
22

3+
#[cfg(feature = "raw")]
4+
use super::hello::middleware::{Pg, Stmt};
5+
6+
#[cfg(feature = "raw")]
7+
use crate::impl_pg;
8+
39
#[cfg(feature = "raw")]
410
app_cache!(local);
511

@@ -8,4 +14,14 @@ app_cache!(redis);
814

915
database!(postgres);
1016

17+
#[cfg(feature = "raw")]
18+
raw_middleware!();
19+
20+
#[cfg(feature = "raw")]
21+
anansi::setup!(stmt, Stmt, Pg);
22+
23+
#[cfg(feature = "raw")]
24+
impl_pg!();
25+
26+
#[cfg(not(feature = "raw"))]
1127
middleware!();

frameworks/Rust/anansi/src/urls.rs

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,29 @@
11
use anansi::web::prelude::*;
2+
use crate::prelude::Request;
23
#[cfg(not(feature = "raw"))]
34
use crate::hello::world::views::WorldView;
45

56
#[cfg(not(feature = "raw"))]
6-
routes! {
7-
path!("/json", WorldView::json),
8-
path!("/db", WorldView::db),
9-
path!("/queries", WorldView::queries),
10-
path!("/fortunes", WorldView::fortunes),
11-
path!("/updates", WorldView::updates),
12-
path!("/plaintext", WorldView::plaintext),
13-
path!("/cached-queries", WorldView::cached_queries),
7+
pub fn routes<R: Request>() -> Router<R> {
8+
Router::new()
9+
.route("/json", WorldView::json)
10+
.route("/db", WorldView::db)
11+
.route("/queries", WorldView::queries)
12+
.route("/fortunes", WorldView::fortunes)
13+
.route("/updates", WorldView::updates)
14+
.route("/plaintext", WorldView::plaintext)
15+
.route("/cached-queries", WorldView::cached_queries)
1416
}
1517

1618
#[cfg(feature = "raw")]
1719
use crate::hello::world::raw::WorldView;
1820

1921
#[cfg(feature = "raw")]
20-
routes! {
21-
path!("/db", WorldView::db),
22-
path!("/queries", WorldView::queries),
23-
path!("/fortunes", WorldView::raw_fortunes),
24-
path!("/updates", WorldView::updates),
25-
path!("/cached-queries", WorldView::cached_queries),
22+
pub fn routes<R: Request>() -> Router<R> {
23+
Router::new()
24+
.route("/db", WorldView::db)
25+
.route("/queries", WorldView::queries)
26+
.route("/fortunes", WorldView::raw_fortunes)
27+
.route("/updates", WorldView::updates)
28+
.route("/cached-queries", WorldView::cached_queries)
2629
}

0 commit comments

Comments
 (0)