mirror of
https://github.com/actix/examples
synced 2025-02-20 08:20:32 +01:00
improve diesel example (#241)
* improve diesel example * Update diesel/README.md Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
This commit is contained in:
parent
16a3c47a2c
commit
e50aecc953
1
diesel/.gitignore
vendored
Normal file
1
diesel/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
test.db
|
@ -1,7 +1,10 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "diesel-example"
|
name = "diesel-example"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = [
|
||||||
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
|
]
|
||||||
workspace = ".."
|
workspace = ".."
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
@ -9,13 +12,12 @@ edition = "2018"
|
|||||||
actix-rt = "1.0.0"
|
actix-rt = "1.0.0"
|
||||||
actix-web = "2.0.0"
|
actix-web = "2.0.0"
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.5"
|
||||||
env_logger = "0.6"
|
diesel = { version = "^1.1.0", features = ["sqlite", "r2d2"] }
|
||||||
|
dotenv = "0.15"
|
||||||
|
env_logger = "0.7"
|
||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
uuid = { version = "0.5", features = ["serde", "v4"] }
|
r2d2 = "0.8"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
uuid = { version = "0.8", features = ["serde", "v4"] }
|
||||||
diesel = { version = "^1.1.0", features = ["sqlite", "r2d2"] }
|
|
||||||
r2d2 = "0.8"
|
|
||||||
dotenv = "0.10"
|
|
||||||
|
103
diesel/README.md
103
diesel/README.md
@ -1,46 +1,109 @@
|
|||||||
# diesel
|
# diesel
|
||||||
|
|
||||||
Diesel's `Getting Started` guide using SQLite for Actix web
|
Basic integration of [Diesel](https://diesel.rs/) using SQLite for Actix web.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### init database sqlite
|
### Install SQLite
|
||||||
|
|
||||||
```bash
|
```sh
|
||||||
# if opensuse: sudo zypper install sqlite3-devel
|
# on OpenSUSE
|
||||||
cargo install diesel_cli --no-default-features --features sqlite
|
sudo zypper install sqlite3-devel libsqlite3-0 sqlite3
|
||||||
|
|
||||||
|
# on Ubuntu
|
||||||
|
sudo apt-get install libsqlite3-dev sqlite3
|
||||||
|
|
||||||
|
# on Fedora
|
||||||
|
sudo dnf install libsqlite3x-devel sqlite3x
|
||||||
|
|
||||||
|
# on macOS (using homebrew)
|
||||||
|
brew install sqlite3
|
||||||
|
```
|
||||||
|
|
||||||
|
### Initialize SQLite Database
|
||||||
|
|
||||||
|
```sh
|
||||||
cd examples/diesel
|
cd examples/diesel
|
||||||
|
cargo install diesel_cli --no-default-features --features sqlite
|
||||||
|
|
||||||
echo "DATABASE_URL=test.db" > .env
|
echo "DATABASE_URL=test.db" > .env
|
||||||
diesel migration run
|
diesel migration run
|
||||||
```
|
```
|
||||||
|
|
||||||
### server
|
There will now be a database file at `./test.db`.
|
||||||
|
|
||||||
```bash
|
### Running Server
|
||||||
# if ubuntu : sudo apt-get install libsqlite3-dev
|
|
||||||
# if fedora : sudo dnf install libsqlite3x-devel
|
```sh
|
||||||
# if opensuse: sudo zypper install libsqlite3-0
|
|
||||||
cd examples/diesel
|
cd examples/diesel
|
||||||
cargo run (or ``cargo watch -x run``)
|
cargo run (or ``cargo watch -x run``)
|
||||||
|
|
||||||
# Started http server: 127.0.0.1:8080
|
# Started http server: 127.0.0.1:8080
|
||||||
```
|
```
|
||||||
|
|
||||||
### web client
|
### Available Routes
|
||||||
|
|
||||||
[http://127.0.0.1:8080/NAME](http://127.0.0.1:8080/NAME)
|
#### `POST /user`
|
||||||
|
|
||||||
### sqlite client
|
Inserts a new user into the SQLite DB.
|
||||||
|
|
||||||
```bash
|
Provide a JSON payload with a name. Eg:
|
||||||
# if ubuntu : sudo apt-get install sqlite3
|
```json
|
||||||
# if fedora : sudo dnf install sqlite3x
|
{ "name": "bill" }
|
||||||
# if opensuse: sudo zypper install sqlite3
|
```
|
||||||
|
|
||||||
|
On success, a response like the following is returned:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "9e46baba-a001-4bb3-b4cf-4b3e5bab5e97",
|
||||||
|
"name": "bill"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Client Examples</summary>
|
||||||
|
|
||||||
|
Using [HTTPie](https://httpie.org/):
|
||||||
|
```sh
|
||||||
|
http POST localhost:8080/user name=bill
|
||||||
|
```
|
||||||
|
|
||||||
|
Using cURL:
|
||||||
|
```sh
|
||||||
|
curl -S -X POST --header "Content-Type: application/json" --data '{"name":"bill"}' http://localhost:8080/user
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
#### `GET /user/{user_uid}`
|
||||||
|
|
||||||
|
Gets a user from the DB using its UID (returned from the insert request or taken from the DB directly). Returns a 404 when no user exists with that UID.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Client Examples</summary>
|
||||||
|
|
||||||
|
Using [HTTPie](https://httpie.org/):
|
||||||
|
```sh
|
||||||
|
http localhost:8080/user/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
|
||||||
|
```
|
||||||
|
|
||||||
|
Using cURL:
|
||||||
|
```sh
|
||||||
|
curl -S http://localhost:8080/user/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
|
### Explore The SQLite DB
|
||||||
|
|
||||||
|
```sh
|
||||||
sqlite3 test.db
|
sqlite3 test.db
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
sqlite> .tables
|
sqlite> .tables
|
||||||
sqlite> select * from users;
|
sqlite> SELECT * FROM users;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Postgresql
|
## Using Other Databases
|
||||||
|
|
||||||
You will also find another complete example of diesel+postgresql on [https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)
|
You can find a complete example of Diesel + PostgreSQL at: [https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)
|
||||||
|
40
diesel/src/actions.rs
Normal file
40
diesel/src/actions.rs
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
use diesel::prelude::*;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::models;
|
||||||
|
|
||||||
|
/// Run query using Diesel to insert a new database row and return the result.
|
||||||
|
pub fn find_user_by_uid(
|
||||||
|
uid: Uuid,
|
||||||
|
conn: &SqliteConnection,
|
||||||
|
) -> Result<Option<models::User>, diesel::result::Error> {
|
||||||
|
use crate::schema::users::dsl::*;
|
||||||
|
|
||||||
|
let user = users
|
||||||
|
.filter(id.eq(uid.to_string()))
|
||||||
|
.first::<models::User>(conn)
|
||||||
|
.optional()?;
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run query using Diesel to insert a new database row and return the result.
|
||||||
|
pub fn insert_new_user(
|
||||||
|
// prevent collision with `name` column imported inside the function
|
||||||
|
nm: &str,
|
||||||
|
conn: &SqliteConnection,
|
||||||
|
) -> Result<models::User, diesel::result::Error> {
|
||||||
|
// It is common when using Diesel with Actix web to import schema-related
|
||||||
|
// modules inside a function's scope (rather than the normal module's scope)
|
||||||
|
// to prevent import collisions and namespace pollution.
|
||||||
|
use crate::schema::users::dsl::*;
|
||||||
|
|
||||||
|
let new_user = models::User {
|
||||||
|
id: Uuid::new_v4().to_string(),
|
||||||
|
name: nm.to_owned(),
|
||||||
|
};
|
||||||
|
|
||||||
|
diesel::insert_into(users).values(&new_user).execute(conn)?;
|
||||||
|
|
||||||
|
Ok(new_user)
|
||||||
|
}
|
@ -1,140 +1,94 @@
|
|||||||
//! Actix web diesel example
|
//! Actix web Diesel integration example
|
||||||
//!
|
//!
|
||||||
//! Diesel does not support tokio, so we have to run it in separate threads.
|
//! Diesel does not support tokio, so we have to run it in separate threads using the web::block
|
||||||
//! Actix supports sync actors by default, so we going to create sync actor
|
//! function which offloads blocking code (like Diesel's) in order to not block the server's thread.
|
||||||
//! that use diesel. Technically sync actors are worker style actors, multiple
|
|
||||||
//! of them can run in parallel and process messages from same queue.
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate diesel;
|
extern crate diesel;
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
|
use actix_web::{get, middleware, post, web, App, Error, HttpResponse, HttpServer};
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use diesel::r2d2::{self, ConnectionManager};
|
use diesel::r2d2::{self, ConnectionManager};
|
||||||
use dotenv;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
mod actions;
|
||||||
mod models;
|
mod models;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
|
||||||
type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
|
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
/// Finds user by UID.
|
||||||
struct MyUser {
|
#[get("/user/{user_id}")]
|
||||||
name: String,
|
async fn get_user(
|
||||||
}
|
pool: web::Data<DbPool>,
|
||||||
|
user_uid: web::Path<Uuid>,
|
||||||
/// Diesel query
|
|
||||||
fn query(
|
|
||||||
nm: String,
|
|
||||||
pool: web::Data<Pool>,
|
|
||||||
) -> Result<models::User, diesel::result::Error> {
|
|
||||||
use self::schema::users::dsl::*;
|
|
||||||
|
|
||||||
let uuid = format!("{}", uuid::Uuid::new_v4());
|
|
||||||
let new_user = models::NewUser {
|
|
||||||
id: &uuid,
|
|
||||||
name: nm.as_str(),
|
|
||||||
};
|
|
||||||
let conn: &SqliteConnection = &pool.get().unwrap();
|
|
||||||
|
|
||||||
diesel::insert_into(users).values(&new_user).execute(conn)?;
|
|
||||||
|
|
||||||
let mut items = users.filter(id.eq(&uuid)).load::<models::User>(conn)?;
|
|
||||||
Ok(items.pop().unwrap())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Async request handler
|
|
||||||
async fn add(
|
|
||||||
name: web::Path<String>,
|
|
||||||
pool: web::Data<Pool>,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
// run diesel blocking code
|
let user_uid = user_uid.into_inner();
|
||||||
Ok(web::block(move || query(name.into_inner(), pool))
|
let conn = pool.get().expect("couldn't get db connection from pool");
|
||||||
.await
|
|
||||||
.map(|user| HttpResponse::Ok().json(user))
|
|
||||||
.map_err(|_| HttpResponse::InternalServerError())?)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This handler manually parse json object. Bytes object supports FromRequest trait (extractor)
|
// use web::block to offload blocking Diesel code without blocking server thread
|
||||||
/// and could be loaded from request payload automatically
|
let user = web::block(move || actions::find_user_by_uid(user_uid, &conn))
|
||||||
async fn index_add(
|
|
||||||
body: web::Bytes,
|
|
||||||
pool: web::Data<Pool>,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
// body is loaded, now we can deserialize id with serde-json
|
|
||||||
let r_obj = serde_json::from_slice::<MyUser>(&body);
|
|
||||||
|
|
||||||
// Send to the db for create return response to peer
|
|
||||||
match r_obj {
|
|
||||||
Ok(obj) => {
|
|
||||||
let user = web::block(move || query(obj.name, pool))
|
|
||||||
.await
|
.await
|
||||||
.map_err(|_| Error::from(HttpResponse::InternalServerError()))?;
|
.map_err(|e| {
|
||||||
|
eprintln!("{}", e);
|
||||||
|
HttpResponse::InternalServerError().finish()
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if let Some(user) = user {
|
||||||
Ok(HttpResponse::Ok().json(user))
|
Ok(HttpResponse::Ok().json(user))
|
||||||
}
|
} else {
|
||||||
Err(_) => Err(error::ErrorBadRequest("Json Decode Failed")),
|
let res = HttpResponse::NotFound()
|
||||||
|
.body(format!("No user found with uid: {}", user_uid));
|
||||||
|
Ok(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This handler offloads json deserialization to actix-web's Json extrator
|
/// Inserts new user with name defined in form.
|
||||||
async fn add2(
|
#[post("/user")]
|
||||||
item: web::Json<MyUser>,
|
async fn add_user(
|
||||||
pool: web::Data<Pool>,
|
pool: web::Data<DbPool>,
|
||||||
|
form: web::Json<models::NewUser>,
|
||||||
) -> Result<HttpResponse, Error> {
|
) -> Result<HttpResponse, Error> {
|
||||||
// run diesel blocking code
|
let conn = pool.get().expect("couldn't get db connection from pool");
|
||||||
let user = web::block(move || query(item.into_inner().name, pool))
|
|
||||||
|
// use web::block to offload blocking Diesel code without blocking server thread
|
||||||
|
let user = web::block(move || actions::insert_new_user(&form.name, &conn))
|
||||||
.await
|
.await
|
||||||
.map_err(|_| HttpResponse::InternalServerError())?; // convert diesel error to http response
|
.map_err(|e| {
|
||||||
|
eprintln!("{}", e);
|
||||||
|
HttpResponse::InternalServerError().finish()
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(user))
|
Ok(HttpResponse::Ok().json(user))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_rt::main]
|
#[actix_rt::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
std::env::set_var("RUST_LOG", "actix_web=info,diesel=debug");
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
|
||||||
dotenv::dotenv().ok();
|
dotenv::dotenv().ok();
|
||||||
|
|
||||||
|
// set up database connection pool
|
||||||
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
||||||
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
|
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
|
||||||
let pool = r2d2::Pool::builder()
|
let pool = r2d2::Pool::builder()
|
||||||
.build(manager)
|
.build(manager)
|
||||||
.expect("Failed to create pool.");
|
.expect("Failed to create pool.");
|
||||||
|
|
||||||
// Start http server
|
let bind = "127.0.0.1:8080";
|
||||||
|
|
||||||
|
println!("Starting server at: {}", &bind);
|
||||||
|
|
||||||
|
// Start HTTP server
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
|
// set up DB pool to be used with web::Data<Pool> extractor
|
||||||
.data(pool.clone())
|
.data(pool.clone())
|
||||||
// enable logger
|
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
// This can be called with:
|
.service(get_user)
|
||||||
// curl -S --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1:8080/add
|
.service(add_user)
|
||||||
// Use of the extractors makes some post conditions simpler such
|
|
||||||
// as size limit protections and built in json validation.
|
|
||||||
.service(
|
|
||||||
web::resource("/add2")
|
|
||||||
.data(
|
|
||||||
web::JsonConfig::default()
|
|
||||||
.limit(4096) // <- limit size of the payload
|
|
||||||
.error_handler(|err, _| {
|
|
||||||
// <- create custom error response
|
|
||||||
error::InternalError::from_response(
|
|
||||||
err,
|
|
||||||
HttpResponse::Conflict().finish(),
|
|
||||||
)
|
|
||||||
.into()
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.route(web::post().to(add2)),
|
|
||||||
)
|
|
||||||
// Manual parsing would allow custom error construction, use of
|
|
||||||
// other parsers *beside* json (for example CBOR, protobuf, xml), and allows
|
|
||||||
// an application to standardise on a single parser implementation.
|
|
||||||
.service(web::resource("/add").route(web::post().to(index_add)))
|
|
||||||
.service(web::resource("/add/{name}").route(web::get().to(add)))
|
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind(&bind)?
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
@ -1,15 +1,14 @@
|
|||||||
use super::schema::users;
|
use serde::{Deserialize, Serialize};
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Serialize, Queryable)]
|
use crate::schema::users;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Queryable, Insertable)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Insertable)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[table_name = "users"]
|
pub struct NewUser {
|
||||||
pub struct NewUser<'a> {
|
pub name: String,
|
||||||
pub id: &'a str,
|
|
||||||
pub name: &'a str,
|
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user