1
0
mirror of https://github.com/actix/examples synced 2025-06-29 02:10:36 +02:00

Update db/basic, db/sqlx_todo and db/r2d2 to v4 (#506)

This commit is contained in:
Luca Palmieri
2022-01-29 16:25:46 +00:00
committed by GitHub
parent 6e3ae0fd19
commit 8b5de155bd
11 changed files with 225 additions and 165 deletions

View File

@ -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

View File

@ -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)