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
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"
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]]
name = "local-channel"
version = "0.1.2"
@ -5780,7 +5769,6 @@ dependencies = [
"dotenv",
"env_logger 0.7.1",
"futures",
"listenfd",
"log",
"serde 1.0.130",
"serde_json",

View File

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

View File

@ -8,7 +8,6 @@ edition = "2018"
[dependencies]
actix-web = "3"
listenfd = "0.3.3"
serde = "1.0.106"
serde_json = "1.0.51"
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
All instructions assume you have changed into this folder:
All instructions assume you have changed into this directory:
```bash
cd examples/sqlx_todo
$ cd database_interactions/sqlx_todo
```
## Set up the database
* 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
@ -30,4 +35,4 @@ To run the application execute:
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]
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 dotenv::dotenv;
use listenfd::ListenFd;
use sqlx::SqlitePool;
use std::env;
// import todo module (routes and model)
mod todo;
// default / handler
// root (/) handler
async fn index() -> impl Responder {
HttpResponse::Ok().body(r#"
HttpResponse::Ok().body(
r#"
Welcome to Actix-web with SQLx Todos example.
Available routes:
GET /todos -> list of all todos
@ -30,28 +31,32 @@ async fn main() -> Result<()> {
dotenv().ok();
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 =
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 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()
.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))
.configure(todo::init) // init todo routes
});
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))?
}
};
})
.bind((host, port))?;
info!("Starting server");
server.run().await?;

View File

@ -1,6 +1,5 @@
use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use anyhow::Result;
use futures::future::{ready, Ready};
use serde::{Deserialize, Serialize};
use sqlx::sqlite::SqliteRow;
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
impl Responder for Todo {
type Error = Error;
type Future = Ready<Result<HttpResponse, Error>>;
type Future = HttpResponse;
fn respond_to(self, _req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self).unwrap();
// create response and set content type
ready(Ok(HttpResponse::Ok()
.content_type("application/json")
.body(body)))
HttpResponse::Ok().json(&self)
}
}
// Implementation for Todo struct, functions for read/write/update and delete todo from database
impl Todo {
pub async fn find_all(pool: &SqlitePool) -> Result<Vec<Todo>> {
let mut todos = vec![];
let recs = sqlx::query!(
let todos = sqlx::query!(
r#"
SELECT id, description, done
FROM todos
@ -46,29 +41,70 @@ impl Todo {
"#
)
.fetch_all(pool)
.await?;
for rec in recs {
todos.push(Todo {
.await?
.into_iter()
.map(|rec| Todo {
id: rec.id,
description: rec.description,
done: rec.done,
});
}
})
.collect();
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!(
r#"
SELECT * FROM todos WHERE id = $1
SELECT id, description, done
FROM todos
WHERE id = $1
"#,
id
)
.fetch_one(&*pool)
.fetch_optional(&*pool)
.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 {
id: rec.id,
description: rec.description,
@ -76,53 +112,65 @@ impl Todo {
})
}
pub async fn create(todo: TodoRequest, pool: &SqlitePool) -> Result<Todo> {
let mut tx = pool.begin().await?;
let todo = sqlx::query("INSERT INTO todos (description, done) VALUES ($1, $2) RETURNING id, description, done")
.bind(&todo.description)
.bind(todo.done)
.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> {
pub async fn update(
id: i32,
todo: TodoRequest,
pool: &SqlitePool,
) -> Result<Option<Todo>> {
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)
.bind(todo.done)
.bind(id)
.map(|row: SqliteRow| {
Todo {
id: row.get(0),
description: row.get(1),
done: row.get(2)
}
})
.fetch_one(&mut tx)
let n = sqlx::query!(
r#"
UPDATE todos
SET description = $1, done = $2
WHERE id = $3
"#,
todo.description,
todo.done,
id,
)
.execute(&mut tx)
.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();
Ok(todo)
Ok(Some(todo))
}
pub async fn delete(id: i32, pool: &SqlitePool) -> Result<u64> {
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)
.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 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")]
async fn find_all(db_pool: web::Data<SqlitePool>) -> impl Responder {
let result = Todo::find_all(db_pool.get_ref()).await;
match result {
Ok(todos) => HttpResponse::Ok().json(todos),
_ => HttpResponse::BadRequest()
.body("Error trying to read all todos from database"),
Err(err) => {
error!("error fetching todos: {}", err);
HttpResponse::InternalServerError()
.body("Error trying to read all todos from database")
}
}
}
#[get("/todo/{id}")]
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;
match result {
Ok(todo) => HttpResponse::Ok().json(todo),
_ => HttpResponse::BadRequest().body("Todo not found"),
Ok(Some(todo)) => HttpResponse::Ok().json(todo),
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;
match result {
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>,
db_pool: web::Data<SqlitePool>,
) -> impl Responder {
let result =
Todo::update(id.into_inner(), todo.into_inner(), db_pool.get_ref()).await;
let result = Todo::update(*id, todo.into_inner(), &db_pool).await;
match result {
Ok(todo) => HttpResponse::Ok().json(todo),
_ => HttpResponse::BadRequest().body("Todo not found"),
Ok(Some(todo)) => HttpResponse::Ok().json(todo),
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}")]
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;
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"),
}
}
let result = Todo::delete(*id, db_pool.get_ref()).await;
// 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);
cfg.service(find);
cfg.service(create);
cfg.service(update);
cfg.service(delete);
match result {
Ok(rows_deleted) => {
if rows_deleted > 0 {
let msg = format!("Successfully deleted {} record(s)", rows_deleted);
HttpResponse::Ok().body(msg)
} else {
HttpResponse::NotFound().body("Todo not found")
}
}
Err(err) => {
error!("error deleting todo: {}", err);
HttpResponse::InternalServerError().body("Todo not found")
}
}
}