1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

improve sqlx example

inspired by #455
This commit is contained in:
Rob Ede 2021-10-07 03:00:13 +01:00
parent c69b7598fb
commit bfede4c1bb
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
8 changed files with 198 additions and 129 deletions

3
.gitignore vendored
View File

@ -20,3 +20,6 @@
# For multipart example # For multipart example
upload.png upload.png
# any dotenv files
.env

12
Cargo.lock generated
View File

@ -3623,17 +3623,6 @@ version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]]
name = "listenfd"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e514e2cb8a9624701346ea3e694c1766d76778e343e537d873c1c366e79a7"
dependencies = [
"libc",
"uuid",
"winapi 0.3.9",
]
[[package]] [[package]]
name = "local-channel" name = "local-channel"
version = "0.1.2" version = "0.1.2"
@ -5780,7 +5769,6 @@ dependencies = [
"dotenv", "dotenv",
"env_logger 0.7.1", "env_logger 0.7.1",
"futures", "futures",
"listenfd",
"log", "log",
"serde 1.0.130", "serde 1.0.130",
"serde_json", "serde_json",

View File

@ -1,4 +1,4 @@
HOST=127.0.0.1 HOST=127.0.0.1
PORT=5000 PORT=8080
DATABASE_URL=sqlite://database_interactions/sqlx_todo/test.db DATABASE_URL=sqlite://${CARGO_MANIFEST_DIR}/test.db
RUST_LOG=sqlx_todo=info,actix=info RUST_LOG=sqlx_todo=info,actix=info

View File

@ -8,7 +8,6 @@ edition = "2018"
[dependencies] [dependencies]
actix-web = "3" actix-web = "3"
listenfd = "0.3.3"
serde = "1.0.106" serde = "1.0.106"
serde_json = "1.0.51" serde_json = "1.0.51"
sqlx = { version = "0.3", features = ["sqlite"] } sqlx = { version = "0.3", features = ["sqlite"] }

View File

@ -11,16 +11,21 @@ Example Todo application using Actix-web and [SQLx](https://github.com/launchbad
## Change into the project sub-directory ## Change into the project sub-directory
All instructions assume you have changed into this folder: All instructions assume you have changed into this directory:
```bash ```bash
cd examples/sqlx_todo $ cd database_interactions/sqlx_todo
``` ```
## Set up the database ## Set up the database
* Create new database using `schema.sql` * Create new database using `schema.sql`
* Copy `.env-example` into `.env` and adjust DATABASE_URL to match your SQLite address, username and password * Copy `.env.example` into `.env` and adjust `DATABASE_URL` to match your SQLite address, if needed
```sh
cat schema.sql | sqlite3 test.db
cp .env.example .env
```
## Run the application ## Run the application
@ -30,4 +35,4 @@ To run the application execute:
cargo run cargo run
``` ```
By default application will be available on `http://localhost:5000`. If you wish to change address or port you can do it inside `.env` file 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

View File

@ -1,19 +1,20 @@
#[macro_use] #[macro_use]
extern crate log; extern crate log;
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use std::env;
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Responder};
use anyhow::Result; use anyhow::Result;
use dotenv::dotenv; use dotenv::dotenv;
use listenfd::ListenFd;
use sqlx::SqlitePool; use sqlx::SqlitePool;
use std::env;
// import todo module (routes and model) // import todo module (routes and model)
mod todo; mod todo;
// default / handler // root (/) handler
async fn index() -> impl Responder { async fn index() -> impl Responder {
HttpResponse::Ok().body(r#" HttpResponse::Ok().body(
r#"
Welcome to Actix-web with SQLx Todos example. Welcome to Actix-web with SQLx Todos example.
Available routes: Available routes:
GET /todos -> list of all todos GET /todos -> list of all todos
@ -30,28 +31,32 @@ async fn main() -> Result<()> {
dotenv().ok(); dotenv().ok();
env_logger::init(); env_logger::init();
// this will enable us to keep application running during recompile: systemfd --no-pid -s http::5000 -- cargo watch -x run
let mut listenfd = ListenFd::from_env();
let database_url = let database_url =
env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file"); env::var("DATABASE_URL").expect("DATABASE_URL is not set in .env file");
let host = env::var("HOST").expect("HOST is not set in .env file");
let port = env::var("PORT")
.expect("PORT is not set in .env file")
.parse::<u16>()
.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::new(&database_url).await?;
let mut server = HttpServer::new(move || { // startup connection+schema check
sqlx::query!("SELECT * FROM todos")
.fetch_one(&db_pool)
.await
.expect("no connection to database");
let server = HttpServer::new(move || {
App::new() App::new()
.data(db_pool.clone()) // pass database pool to application so we can access it inside handlers // pass database pool to application so we can access it inside handlers
.data(db_pool.clone())
.wrap(middleware::Logger::default())
.route("/", web::get().to(index)) .route("/", web::get().to(index))
.configure(todo::init) // init todo routes .configure(todo::init) // init todo routes
}); })
.bind((host, port))?;
server = match listenfd.take_tcp_listener(0)? {
Some(listener) => server.listen(listener)?,
None => {
let host = env::var("HOST").expect("HOST is not set in .env file");
let port = env::var("PORT").expect("PORT is not set in .env file");
server.bind(format!("{}:{}", host, port))?
}
};
info!("Starting server"); info!("Starting server");
server.run().await?; server.run().await?;

View File

@ -1,6 +1,5 @@
use actix_web::{Error, HttpRequest, HttpResponse, Responder}; use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use anyhow::Result; use anyhow::Result;
use futures::future::{ready, Ready};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::sqlite::SqliteRow; use sqlx::sqlite::SqliteRow;
use sqlx::{FromRow, Row, SqlitePool}; use sqlx::{FromRow, Row, SqlitePool};
@ -23,22 +22,18 @@ pub struct Todo {
// implementation of Actix Responder for Todo struct so we can return Todo from action handler // implementation of Actix Responder for Todo struct so we can return Todo from action handler
impl Responder for Todo { impl Responder for Todo {
type Error = Error; type Error = Error;
type Future = Ready<Result<HttpResponse, Error>>; type Future = HttpResponse;
fn respond_to(self, _req: &HttpRequest) -> Self::Future { fn respond_to(self, _req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self).unwrap();
// create response and set content type // create response and set content type
ready(Ok(HttpResponse::Ok() HttpResponse::Ok().json(&self)
.content_type("application/json")
.body(body)))
} }
} }
// Implementation for Todo struct, functions for read/write/update and delete todo from database // Implementation for Todo struct, functions for read/write/update and delete todo from database
impl Todo { impl Todo {
pub async fn find_all(pool: &SqlitePool) -> Result<Vec<Todo>> { pub async fn find_all(pool: &SqlitePool) -> Result<Vec<Todo>> {
let mut todos = vec![]; let todos = sqlx::query!(
let recs = sqlx::query!(
r#" r#"
SELECT id, description, done SELECT id, description, done
FROM todos FROM todos
@ -46,29 +41,70 @@ impl Todo {
"# "#
) )
.fetch_all(pool) .fetch_all(pool)
.await?; .await?
.into_iter()
for rec in recs { .map(|rec| Todo {
todos.push(Todo {
id: rec.id, id: rec.id,
description: rec.description, description: rec.description,
done: rec.done, done: rec.done,
}); })
} .collect();
Ok(todos) Ok(todos)
} }
pub async fn find_by_id(id: i32, pool: &SqlitePool) -> Result<Todo> { pub async fn find_by_id(id: i32, pool: &SqlitePool) -> Result<Option<Todo>> {
let rec = sqlx::query!( let rec = sqlx::query!(
r#" r#"
SELECT * FROM todos WHERE id = $1 SELECT id, description, done
FROM todos
WHERE id = $1
"#, "#,
id id
) )
.fetch_one(&*pool) .fetch_optional(&*pool)
.await?; .await?;
Ok(rec.map(|rec| Todo {
id: rec.id,
description: rec.description,
done: rec.done,
}))
}
pub async fn create(todo: TodoRequest, pool: &SqlitePool) -> Result<Todo> {
let mut tx = pool.begin().await?;
sqlx::query!(
r#"
INSERT INTO todos (description, done)
VALUES ($1, $2)
"#,
todo.description,
todo.done,
)
.execute(&mut tx)
.await?;
// TODO: this can be replaced with RETURNING with sqlite v3.35+ and/or sqlx v0.5+
let row_id: i32 = sqlx::query("SELECT last_insert_rowid()")
.map(|row: SqliteRow| row.get(0))
.fetch_one(&mut tx)
.await?;
let rec = sqlx::query!(
r#"
SELECT id, description, done
FROM todos
WHERE id = $1
"#,
row_id,
)
.fetch_one(&mut tx)
.await?;
tx.commit().await?;
Ok(Todo { Ok(Todo {
id: rec.id, id: rec.id,
description: rec.description, description: rec.description,
@ -76,53 +112,65 @@ impl Todo {
}) })
} }
pub async fn create(todo: TodoRequest, pool: &SqlitePool) -> Result<Todo> { pub async fn update(
let mut tx = pool.begin().await?; id: i32,
let todo = sqlx::query("INSERT INTO todos (description, done) VALUES ($1, $2) RETURNING id, description, done") todo: TodoRequest,
.bind(&todo.description) pool: &SqlitePool,
.bind(todo.done) ) -> Result<Option<Todo>> {
.map(|row: SqliteRow| {
Todo {
id: row.get(0),
description: row.get(1),
done: row.get(2)
}
})
.fetch_one(&mut tx)
.await?;
tx.commit().await?;
Ok(todo)
}
pub async fn update(id: i32, todo: TodoRequest, pool: &SqlitePool) -> Result<Todo> {
let mut tx = pool.begin().await.unwrap(); let mut tx = pool.begin().await.unwrap();
let todo = sqlx::query("UPDATE todos SET description = $1, done = $2 WHERE id = $3 RETURNING id, description, done")
.bind(&todo.description) let n = sqlx::query!(
.bind(todo.done) r#"
.bind(id) UPDATE todos
.map(|row: SqliteRow| { SET description = $1, done = $2
Todo { WHERE id = $3
id: row.get(0), "#,
description: row.get(1), todo.description,
done: row.get(2) todo.done,
} id,
}) )
.fetch_one(&mut tx) .execute(&mut tx)
.await?; .await?;
if n == 0 {
return Ok(None);
}
// TODO: this can be replaced with RETURNING with sqlite v3.35+ and/or sqlx v0.5+
let todo = sqlx::query!(
r#"
SELECT id, description, done
FROM todos
WHERE id = $1
"#,
id,
)
.fetch_one(&mut tx)
.await
.map(|rec| Todo {
id: rec.id,
description: rec.description,
done: rec.done,
})?;
tx.commit().await.unwrap(); tx.commit().await.unwrap();
Ok(todo) Ok(Some(todo))
} }
pub async fn delete(id: i32, pool: &SqlitePool) -> Result<u64> { pub async fn delete(id: i32, pool: &SqlitePool) -> Result<u64> {
let mut tx = pool.begin().await?; let mut tx = pool.begin().await?;
let deleted = sqlx::query("DELETE FROM todos WHERE id = $1")
.bind(id) let n_deleted = sqlx::query!(
r#"
DELETE FROM todos
WHERE id = $1
"#,
id,
)
.execute(&mut tx) .execute(&mut tx)
.await?; .await?;
tx.commit().await?; tx.commit().await?;
Ok(deleted) Ok(n_deleted)
} }
} }

View File

@ -1,23 +1,42 @@
use crate::todo::{Todo, TodoRequest};
use actix_web::{delete, get, post, put, web, HttpResponse, Responder}; use actix_web::{delete, get, post, put, web, HttpResponse, Responder};
use sqlx::SqlitePool; use sqlx::SqlitePool;
use crate::todo::{Todo, TodoRequest};
// function that will be called on new Application to configure routes for this module
pub fn init(cfg: &mut web::ServiceConfig) {
cfg.service(find_all)
.service(find)
.service(create)
.service(update)
.service(delete);
}
#[get("/todos")] #[get("/todos")]
async fn find_all(db_pool: web::Data<SqlitePool>) -> impl Responder { async fn find_all(db_pool: web::Data<SqlitePool>) -> impl Responder {
let result = Todo::find_all(db_pool.get_ref()).await; let result = Todo::find_all(db_pool.get_ref()).await;
match result { match result {
Ok(todos) => HttpResponse::Ok().json(todos), Ok(todos) => HttpResponse::Ok().json(todos),
_ => HttpResponse::BadRequest() Err(err) => {
.body("Error trying to read all todos from database"), error!("error fetching todos: {}", err);
HttpResponse::InternalServerError()
.body("Error trying to read all todos from database")
}
} }
} }
#[get("/todo/{id}")] #[get("/todo/{id}")]
async fn find(id: web::Path<i32>, db_pool: web::Data<SqlitePool>) -> impl Responder { async fn find(id: web::Path<i32>, db_pool: web::Data<SqlitePool>) -> impl Responder {
let result = Todo::find_by_id(id.into_inner(), db_pool.get_ref()).await; let result = Todo::find_by_id(id.into_inner(), db_pool.get_ref()).await;
match result { match result {
Ok(todo) => HttpResponse::Ok().json(todo), Ok(Some(todo)) => HttpResponse::Ok().json(todo),
_ => HttpResponse::BadRequest().body("Todo not found"), Ok(None) => HttpResponse::NotFound().body("Todo not found"),
Err(err) => {
error!("error fetching todo: {}", err);
HttpResponse::InternalServerError()
.body("Error trying to read todo from database")
}
} }
} }
@ -29,7 +48,10 @@ async fn create(
let result = Todo::create(todo.into_inner(), db_pool.get_ref()).await; let result = Todo::create(todo.into_inner(), db_pool.get_ref()).await;
match result { match result {
Ok(todo) => HttpResponse::Ok().json(todo), Ok(todo) => HttpResponse::Ok().json(todo),
_ => HttpResponse::BadRequest().body("Error trying to create new todo"), Err(err) => {
error!("error creating todo: {}", err);
HttpResponse::InternalServerError().body("Error trying to create new todo")
}
} }
} }
@ -39,35 +61,34 @@ async fn update(
todo: web::Json<TodoRequest>, todo: web::Json<TodoRequest>,
db_pool: web::Data<SqlitePool>, db_pool: web::Data<SqlitePool>,
) -> impl Responder { ) -> impl Responder {
let result = let result = Todo::update(*id, todo.into_inner(), &db_pool).await;
Todo::update(id.into_inner(), todo.into_inner(), db_pool.get_ref()).await;
match result { match result {
Ok(todo) => HttpResponse::Ok().json(todo), Ok(Some(todo)) => HttpResponse::Ok().json(todo),
_ => HttpResponse::BadRequest().body("Todo not found"), Ok(None) => HttpResponse::NotFound().body("Todo not found"),
Err(err) => {
error!("error updating todo: {}", err);
HttpResponse::InternalServerError().body("Error trying to update todo")
}
} }
} }
#[delete("/todo/{id}")] #[delete("/todo/{id}")]
async fn delete(id: web::Path<i32>, db_pool: web::Data<SqlitePool>) -> impl Responder { async fn delete(id: web::Path<i32>, db_pool: web::Data<SqlitePool>) -> impl Responder {
let result = Todo::delete(id.into_inner(), db_pool.get_ref()).await; let result = Todo::delete(*id, db_pool.get_ref()).await;
match result {
Ok(rows) => {
if rows > 0 {
HttpResponse::Ok()
.body(format!("Successfully deleted {} record(s)", rows))
} else {
HttpResponse::BadRequest().body("Todo not found")
}
}
_ => HttpResponse::BadRequest().body("Todo not found"),
}
}
// function that will be called on new Application to configure routes for this module match result {
pub fn init(cfg: &mut web::ServiceConfig) { Ok(rows_deleted) => {
cfg.service(find_all); if rows_deleted > 0 {
cfg.service(find); let msg = format!("Successfully deleted {} record(s)", rows_deleted);
cfg.service(create); HttpResponse::Ok().body(msg)
cfg.service(update); } else {
cfg.service(delete); HttpResponse::NotFound().body("Todo not found")
}
}
Err(err) => {
error!("error deleting todo: {}", err);
HttpResponse::InternalServerError().body("Todo not found")
}
}
} }