mirror of
https://github.com/actix/examples
synced 2025-06-28 09:50:36 +02:00
Update db/basic, db/sqlx_todo and db/r2d2 to v4 (#506)
This commit is contained in:
@ -2,16 +2,16 @@
|
||||
name = "async_db"
|
||||
version = "2.0.0"
|
||||
authors = ["Darin Gordon <dkcdkg@gmail.com>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
env_logger = "0.8"
|
||||
actix-web = "4.0.0-beta.21"
|
||||
env_logger = "0.9.0"
|
||||
failure = "0.1.7"
|
||||
futures = "0.3.1"
|
||||
num_cpus = "1.13"
|
||||
r2d2 = "0.8.2"
|
||||
r2d2_sqlite = "0.14"
|
||||
rusqlite = "0.21"
|
||||
r2d2_sqlite = "0.18.0"
|
||||
rusqlite = "0.25.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
@ -1,7 +1,6 @@
|
||||
use actix_web::{web, Error as AWError};
|
||||
use actix_web::{error::InternalError, http::StatusCode, web};
|
||||
use failure::Error;
|
||||
use futures::{Future, TryFutureExt};
|
||||
use rusqlite::{Statement, NO_PARAMS};
|
||||
use rusqlite::Statement;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{thread::sleep, time::Duration};
|
||||
|
||||
@ -23,10 +22,10 @@ pub enum Queries {
|
||||
GetTopTenColdestMonths,
|
||||
}
|
||||
|
||||
pub fn execute(
|
||||
pub async fn execute(
|
||||
pool: &Pool,
|
||||
query: Queries,
|
||||
) -> impl Future<Output = Result<Vec<WeatherAgg>, AWError>> {
|
||||
) -> Result<Vec<WeatherAgg>, InternalError<Error>> {
|
||||
let pool = pool.clone();
|
||||
web::block(move || {
|
||||
// simulate an expensive query, see comments at top of main.rs
|
||||
@ -40,7 +39,9 @@ pub fn execute(
|
||||
};
|
||||
result.map_err(Error::from)
|
||||
})
|
||||
.map_err(AWError::from)
|
||||
.await
|
||||
.unwrap()
|
||||
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))
|
||||
}
|
||||
|
||||
fn get_hottest_years(conn: Connection) -> WeatherAggResult {
|
||||
@ -73,7 +74,7 @@ fn get_coldest_years(conn: Connection) -> WeatherAggResult {
|
||||
|
||||
fn get_rows_as_annual_agg(mut statement: Statement) -> WeatherAggResult {
|
||||
statement
|
||||
.query_map(NO_PARAMS, |row| {
|
||||
.query_map([], |row| {
|
||||
Ok(WeatherAgg::AnnualAgg {
|
||||
year: row.get(0)?,
|
||||
total: row.get(1)?,
|
||||
@ -112,7 +113,7 @@ fn get_coldest_months(conn: Connection) -> WeatherAggResult {
|
||||
|
||||
fn get_rows_as_month_agg(mut statement: Statement) -> WeatherAggResult {
|
||||
statement
|
||||
.query_map(NO_PARAMS, |row| {
|
||||
.query_map([], |row| {
|
||||
Ok(WeatherAgg::MonthAgg {
|
||||
year: row.get(0)?,
|
||||
month: row.get(1)?,
|
||||
|
@ -61,7 +61,7 @@ async fn main() -> io::Result<()> {
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
// store db pool as Data object
|
||||
.data(pool.clone())
|
||||
.app_data(web::Data::new(pool.clone()))
|
||||
.wrap(middleware::Logger::default())
|
||||
.service(
|
||||
web::resource("/asyncio_weather").route(web::get().to(asyncio_weather)),
|
||||
|
@ -2,14 +2,14 @@
|
||||
name = "r2d2-example"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
actix-web = "4.0.0-beta.21"
|
||||
|
||||
env_logger = "0.8"
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
env_logger = "0.9.0"
|
||||
uuid = { version = "1.0.0-alpha.1", features = ["v4"] }
|
||||
|
||||
r2d2 = "0.8"
|
||||
r2d2_sqlite = "0.14"
|
||||
rusqlite = "0.21"
|
||||
r2d2_sqlite = "0.18.0"
|
||||
rusqlite = "0.25.4"
|
||||
|
@ -1,7 +1,10 @@
|
||||
//! Actix web r2d2 example
|
||||
use std::io;
|
||||
|
||||
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
|
||||
use actix_web::{
|
||||
error::InternalError, http::StatusCode, middleware, web, App, Error, HttpResponse,
|
||||
HttpServer,
|
||||
};
|
||||
use r2d2::Pool;
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
|
||||
@ -26,8 +29,9 @@ async fn index(
|
||||
})
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.map(|user| HttpResponse::Ok().json(user))
|
||||
.map_err(|_| HttpResponse::InternalServerError())?;
|
||||
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
@ -43,7 +47,7 @@ async fn main() -> io::Result<()> {
|
||||
// start http server
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.data(pool.clone()) // <- store db pool in app state
|
||||
.app_data(web::Data::new(pool.clone())) // <- store db pool in app state
|
||||
.wrap(middleware::Logger::default())
|
||||
.route("/{name}", web::get().to(index))
|
||||
})
|
||||
|
@ -2,17 +2,17 @@
|
||||
name = "sqlx_todo"
|
||||
version = "0.1.0"
|
||||
authors = ["Milan Zivkovic <zivkovic.milan@gmail.com>"]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
actix-web = "4.0.0-beta.21"
|
||||
serde = "1.0.106"
|
||||
serde_json = "1.0.51"
|
||||
sqlx = { version = "0.3", features = ["sqlite"] }
|
||||
sqlx = { version = "0.5.9", features = ["sqlite", "runtime-actix-rustls"] }
|
||||
dotenv = "0.15.0"
|
||||
env_logger = "0.7.1"
|
||||
env_logger = "0.9.0"
|
||||
log = "0.4.8"
|
||||
anyhow = "1.0.28"
|
||||
futures = "0.3.13"
|
||||
|
@ -19,7 +19,12 @@ $ cd database_interactions/sqlx_todo
|
||||
|
||||
## Set up the database
|
||||
|
||||
* Create new database using `schema.sql`
|
||||
* Create new database:
|
||||
|
||||
```bash
|
||||
./setup_db.sh
|
||||
```
|
||||
|
||||
* Copy `.env.example` into `.env` and adjust `DATABASE_URL` to match your SQLite address, if needed
|
||||
|
||||
```sh
|
||||
@ -35,4 +40,4 @@ To run the application execute:
|
||||
cargo run
|
||||
```
|
||||
|
||||
By default application will be available on `http://localhost:8080`. If you wish to change address or port you can do it inside the `.env` file
|
||||
By default the application will be available on `http://localhost:8080`. If you wish to change address or port you can do it inside the `.env` file
|
||||
|
2
database_interactions/sqlx_todo/setup_db.sh
Executable file
2
database_interactions/sqlx_todo/setup_db.sh
Executable file
@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env bash
|
||||
sqlite3 test.db < schema.sql
|
@ -40,7 +40,7 @@ async fn main() -> Result<()> {
|
||||
.expect("PORT should be a u16");
|
||||
|
||||
info!("using sqlite database at: {}", &database_url);
|
||||
let db_pool = SqlitePool::new(&database_url).await?;
|
||||
let db_pool = SqlitePool::connect(&database_url).await?;
|
||||
|
||||
// startup connection+schema check
|
||||
sqlx::query!("SELECT * FROM todos")
|
||||
@ -51,7 +51,7 @@ async fn main() -> Result<()> {
|
||||
let server = HttpServer::new(move || {
|
||||
App::new()
|
||||
// pass database pool to application so we can access it inside handlers
|
||||
.data(db_pool.clone())
|
||||
.app_data(web::Data::new(db_pool.clone()))
|
||||
.wrap(middleware::Logger::default())
|
||||
.route("/", web::get().to(index))
|
||||
.configure(todo::init) // init todo routes
|
||||
|
@ -1,4 +1,4 @@
|
||||
use actix_web::{Error, HttpRequest, HttpResponse, Responder};
|
||||
use actix_web::{body::BoxBody, HttpRequest, HttpResponse, Responder};
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
@ -14,17 +14,16 @@ pub struct TodoRequest {
|
||||
// this struct will be used to represent database record
|
||||
#[derive(Serialize, FromRow)]
|
||||
pub struct Todo {
|
||||
pub id: i32,
|
||||
pub id: i64,
|
||||
pub description: String,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
// implementation of Actix Responder for Todo struct so we can return Todo from action handler
|
||||
impl Responder for Todo {
|
||||
type Error = Error;
|
||||
type Future = HttpResponse;
|
||||
type Body = BoxBody;
|
||||
|
||||
fn respond_to(self, _req: &HttpRequest) -> Self::Future {
|
||||
fn respond_to(self, _req: &HttpRequest) -> HttpResponse {
|
||||
// create response and set content type
|
||||
HttpResponse::Ok().json(&self)
|
||||
}
|
||||
@ -130,7 +129,8 @@ impl Todo {
|
||||
id,
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
if n == 0 {
|
||||
return Ok(None);
|
||||
@ -168,7 +168,8 @@ impl Todo {
|
||||
id,
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(n_deleted)
|
||||
|
Reference in New Issue
Block a user