Skip to content

Commit 6080b20

Browse files
authored
Update to anansi 0.14.2 (#8051)
* Update to anansi 0.14.2 * fixed update test for anansi * fixed other update test for anansi --------- Co-authored-by: sarutora <example.com>
1 parent a802bc0 commit 6080b20

File tree

9 files changed

+117
-62
lines changed

9 files changed

+117
-62
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 = "87830d6", features = ["postgres", "minimal", "redis"] }
15+
anansi = { git = "https://github.com/saru-tora/anansi", rev = "b59c7d0", features = ["postgres", "minimal", "redis"] }
1616
async-trait = "0.1.57"
1717
rand = "0.8.4"
1818
serde = "1"

frameworks/Rust/anansi/benchmark_config.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"webserver": "hyper",
2323
"os": "Linux",
2424
"database_os": "Linux",
25-
"display_name": "Anansi",
25+
"display_name": "Anansi [minimal]",
2626
"notes": "",
2727
"versus": "None"
2828
},
@@ -44,7 +44,7 @@
4444
"webserver": "hyper",
4545
"os": "Linux",
4646
"database_os": "Linux",
47-
"display_name": "Anansi [raw]",
47+
"display_name": "Anansi [minimal, raw]",
4848
"notes": "",
4949
"versus": "None"
5050
}
Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
use std::fmt;
1+
use std::fmt::{self, Write};
22
use std::sync::Arc;
3-
use anansi::db::postgres::{PgDbRow, PgDbRowVec, PgStatement};
3+
use anansi::db::postgres::{PgDbPool, PgDbRow, PgDbRowVec, PgStatement};
44

55
#[macro_export]
66
macro_rules! impl_pg {
@@ -9,16 +9,45 @@ macro_rules! impl_pg {
99
impl crate::hello::middleware::Pg for HttpRequest {
1010
async fn get_world(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRow> {
1111
use anansi::web::BaseRequest;
12-
self.mid.stmt.0.world.fetch_one(&[&Self::random_num()], self.raw().pool()).await
12+
self.raw().app_state().stmt.0.world.fetch_one(&[&Self::random_num()], self.raw().pool()).await
13+
}
14+
async fn update_worlds(&self, n: usize, params: &[&(dyn tokio_postgres::types::ToSql + Sync)]) -> anansi::web::Result<()> {
15+
use anansi::web::BaseRequest;
16+
self.raw().app_state().stmt.0.updates[n].execute(params, self.raw().pool()).await
1317
}
1418
async fn get_fortunes(&self) -> anansi::web::Result<anansi::db::postgres::PgDbRowVec> {
1519
use anansi::web::BaseRequest;
16-
self.mid.stmt.0.fortune.fetch_all(&[], self.raw().pool()).await
20+
self.raw().app_state().stmt.0.fortune.fetch_all(&[], self.raw().pool()).await
21+
}
22+
}
23+
impl crate::hello::middleware::AsStmt for AppData {
24+
fn as_stmt(&self) -> &crate::hello::middleware::Stmt {
25+
&self.stmt
1726
}
1827
}
1928
}
2029
}
2130

31+
fn update_statement(num: u16) -> String {
32+
let mut pl = 1;
33+
let mut q = "UPDATE world SET randomnumber = CASE id ".to_string();
34+
for _ in 1..=num {
35+
let _ = write!(q, "WHEN ${} THEN ${} ", pl, pl + 1);
36+
pl += 2;
37+
}
38+
39+
q.push_str("ELSE randomnumber END WHERE id IN (");
40+
41+
for _ in 1..=num {
42+
let _ = write!(q, "${},", pl);
43+
pl += 1;
44+
}
45+
46+
q.pop();
47+
q.push(')');
48+
q
49+
}
50+
2251
#[derive(Clone)]
2352
pub struct Stmt(pub Arc<State>);
2453

@@ -30,25 +59,36 @@ impl fmt::Debug for Stmt {
3059
}
3160

3261
impl Stmt {
33-
pub async fn new(raw: &mut anansi::web::RawRequest<anansi::db::postgres::PgDbPool>) -> anansi::web::Result<Self> {
62+
pub async fn new(pool: &PgDbPool) -> anansi::web::Result<Self> {
63+
let mut updates = vec![];
64+
for n in 1..=500 {
65+
updates.push(PgStatement::new(&update_statement(n), pool).await?);
66+
}
3467
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?,
68+
world: PgStatement::new("SELECT * FROM world WHERE id = $1", pool).await?,
69+
updates,
70+
fortune: PgStatement::new("SELECT * FROM fortune", pool).await?,
3771
})))
3872
}
3973
}
4074

4175
pub struct State {
4276
pub world: PgStatement,
77+
pub updates: Vec<PgStatement>,
4378
pub fortune: PgStatement,
4479
}
4580

81+
pub trait AsStmt {
82+
fn as_stmt(&self) -> &Stmt;
83+
}
84+
4685
#[async_trait::async_trait]
4786
pub trait Pg {
4887
fn random_num() -> i32 {
4988
use rand::Rng;
5089
rand::thread_rng().gen_range(1..=10_000)
5190
}
5291
async fn get_world(&self) -> anansi::web::Result<PgDbRow>;
92+
async fn update_worlds(&self, n: usize, params: &[&(dyn tokio_postgres::types::ToSql + Sync)]) -> anansi::web::Result<()>;
5393
async fn get_fortunes(&self) -> anansi::web::Result<PgDbRowVec>;
5494
}

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

Lines changed: 19 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,11 @@
11
use crate::prelude::*;
2+
use crate::hello::middleware::Pg;
23
use serde::Serialize;
3-
use anansi::{check, prep};
4+
use anansi::check;
45
use super::util::get_query;
5-
use std::borrow::Cow;
6-
use anansi::db::DbRow;
76
use rand::Rng;
8-
use std::fmt::Write;
97
use tokio_postgres::types::ToSql;
108

11-
fn update_statement(num: u16) -> String {
12-
let mut pl = 1;
13-
let mut q = "UPDATE world SET randomnumber = CASE id ".to_string();
14-
for _ in 1..=num {
15-
let _ = write!(q, "WHEN ${} THEN ${} ", pl, pl + 1);
16-
pl += 2;
17-
}
18-
19-
q.push_str("ELSE randomnumber END WHERE id IN (");
20-
21-
for _ in 1..=num {
22-
let _ = write!(q, "${},", pl);
23-
pl += 1;
24-
}
25-
26-
q.pop();
27-
q.push(')');
28-
q
29-
}
30-
319
fn random_num() -> i32 {
3210
rand::thread_rng().gen_range(1..=10_000)
3311
}
@@ -39,36 +17,36 @@ pub struct World {
3917
}
4018

4119
#[derive(Serialize, Debug)]
42-
pub struct Fortune {
20+
pub struct Fortune<'a> {
4321
id: i32,
44-
message: Cow<'static, str>,
22+
message: &'a str,
4523
}
4624

4725
#[base_view]
4826
fn base<R: Request>(_req: &mut R) -> Result<Response> {}
4927

5028
#[viewer]
51-
impl<R: Request> WorldView<R> {
29+
impl<R: Request + Pg> WorldView<R> {
30+
async fn one_world(req: &R) -> Result<World> {
31+
let row = req.get_world().await?;
32+
let world = World {
33+
id: row.get_i32(0),
34+
randomnumber: row.get_i32(1),
35+
};
36+
Ok(world)
37+
}
5238
async fn get_worlds(req: &R) -> Result<Vec<World>> {
5339
let q = get_query(req.params());
5440
let mut worlds = Vec::with_capacity(q as usize);
5541
for _ in 0..q {
56-
let row = req.get_world().await?;
57-
let world = World {
58-
id: row.try_i32("id")?,
59-
randomnumber: row.try_i32("randomnumber")?,
60-
};
42+
let world = Self::one_world(req).await?;
6143
worlds.push(world);
6244
}
6345
Ok(worlds)
6446
}
6547
#[check(Site::is_visitor)]
6648
pub async fn db(req: &mut R) -> Result<Response> {
67-
let row = req.get_world().await?;
68-
let world = World {
69-
id: row.get_i32(0),
70-
randomnumber: row.get_i32(1),
71-
};
49+
let world = Self::one_world(req).await?;
7250
Response::json(&world)
7351
}
7452
#[check(Site::is_visitor)]
@@ -83,11 +61,11 @@ impl<R: Request> WorldView<R> {
8361
let mut fortunes = Vec::with_capacity(rows.len() + 1);
8462
fortunes.push(Fortune {
8563
id: 0,
86-
message: Cow::Borrowed("Additional fortune added at request time.")
64+
message: "Additional fortune added at request time.",
8765
});
8866
fortunes.extend(rows.iter().map(|row| Fortune {
8967
id: row.get(0),
90-
message: Cow::Owned(row.get(1)),
68+
message: row.get(1),
9169
}));
9270
fortunes.sort_by(|it, next| it.message.cmp(&next.message));
9371
}
@@ -99,7 +77,7 @@ impl<R: Request> WorldView<R> {
9977
for _ in 0..q {
10078
let row = req.get_world().await?;
10179
let world = World {
102-
id: row.try_i32("id")?,
80+
id: row.get_i32(0),
10381
randomnumber: random_num(),
10482
};
10583
worlds.push(world);
@@ -111,7 +89,7 @@ impl<R: Request> WorldView<R> {
11189
for world in &worlds {
11290
params.push(&world.id);
11391
}
114-
prep!(req, format!("update{}", q), update_statement(q as u16), params.as_slice(), execute)?;
92+
req.update_worlds(q - 1, params.as_slice()).await?;
11593
Response::json(&worlds)
11694
}
11795
#[check(Site::is_visitor)]
Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
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}
1+
{_args._content = {let mut _c = String::new();_c.push_str("<table><tr><th>id</th><th>message</th></tr>");
2+
for fortune in fortunes {_c.push_str("<tr><td>");_c.push_str(&anansi::web::html_escape(&format!("{}", fortune.id)));_c.push_str("</td><td>");
3+
_c.push_str(&anansi::web::html_escape(&format!("{}", fortune.message)));_c.push_str("</td></tr>");}_c.push_str("</table>"); _c};
4+
_args._title = {let mut _c = String::new();_c.push_str(&anansi::web::html_escape(&format!("{}", title))); _c};_args}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl<R: Request> WorldView<R> {
6565
for world in &mut worlds {
6666
world.randomNumber = random_int();
6767
}
68-
transact!(req, raw_bulk_update!(req, World, &worlds, randomNumber).await)?;
68+
raw_bulk_update!(req, World, &worlds, randomNumber).await?;
6969
Response::json(&worlds)
7070
}
7171
#[check(Site::is_visitor)]

frameworks/Rust/anansi/src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ min_main!(server, {
1515
use anansi::cache::prelude::*;
1616
use hello::records::World;
1717
use anansi::records::Record;
18-
let worlds = World::get_all().raw_query(&server.pool).await.expect("problem fetching worlds");
18+
use anansi::db::AsDb;
19+
let worlds = World::get_all().raw_query(server.app_data.as_db()).await.expect("problem fetching worlds");
1920
let mut items = vec![];
2021
for world in worlds {
2122
let id = world.pk().to_string();

frameworks/Rust/anansi/src/project.rs

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use anansi::project::prelude::*;
2+
use crate::app_migrations;
23

34
#[cfg(feature = "raw")]
4-
use super::hello::middleware::{Pg, Stmt};
5+
use super::hello::middleware::Stmt;
56

67
#[cfg(feature = "raw")]
78
use crate::impl_pg;
@@ -18,10 +19,44 @@ database!(postgres);
1819
raw_middleware!();
1920

2021
#[cfg(feature = "raw")]
21-
anansi::setup!(stmt, Stmt, Pg);
22+
anansi::setup!();
2223

2324
#[cfg(feature = "raw")]
2425
impl_pg!();
2526

2627
#[cfg(not(feature = "raw"))]
2728
middleware!();
29+
30+
#[derive(Clone, Debug)]
31+
pub struct AppData {
32+
pub pool: Pool,
33+
#[cfg(feature = "raw")]
34+
pub stmt: Stmt,
35+
}
36+
37+
#[cfg(feature = "raw")]
38+
impl AppData {
39+
pub async fn new() -> Self {
40+
let pool = anansi::server::get_db::<AppData>(app_migrations).await;
41+
let stmt = Stmt::new(&pool).await.unwrap();
42+
Self {pool, stmt}
43+
}
44+
}
45+
46+
#[cfg(not(feature = "raw"))]
47+
impl AppData {
48+
pub async fn new() -> Self {
49+
let pool = anansi::server::get_db::<AppData>(app_migrations).await;
50+
Self {pool}
51+
}
52+
}
53+
54+
impl anansi::db::AsDb for AppData {
55+
type SqlDb = Pool;
56+
fn as_db(&self) -> &Pool {
57+
&self.pool
58+
}
59+
fn as_db_mut(&mut self) -> &mut Pool {
60+
&mut self.pool
61+
}
62+
}

frameworks/Rust/anansi/src/urls.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,10 @@ pub fn routes<R: Request>() -> Router<R> {
1919
use crate::hello::world::raw::WorldView;
2020

2121
#[cfg(feature = "raw")]
22-
pub fn routes<R: Request>() -> Router<R> {
22+
use crate::hello::middleware::Pg;
23+
24+
#[cfg(feature = "raw")]
25+
pub fn routes<R: Request + Pg>() -> Router<R> {
2326
Router::new()
2427
.route("/db", WorldView::db)
2528
.route("/queries", WorldView::queries)

0 commit comments

Comments
 (0)