mirror of
https://github.com/actix/examples
synced 2025-06-28 18:00:37 +02:00
Restructure folders (#411)
This commit is contained in:
committed by
GitHub
parent
9db98162b2
commit
c3407627d0
1
database_interactions/diesel/.env
Normal file
1
database_interactions/diesel/.env
Normal file
@ -0,0 +1 @@
|
||||
DATABASE_URL=test.db
|
1
database_interactions/diesel/.gitignore
vendored
Normal file
1
database_interactions/diesel/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
test.db
|
20
database_interactions/diesel/Cargo.toml
Normal file
20
database_interactions/diesel/Cargo.toml
Normal file
@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "diesel-example"
|
||||
version = "1.0.0"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
diesel = { version = "^1.1.0", features = ["sqlite", "r2d2"] }
|
||||
dotenv = "0.15"
|
||||
env_logger = "0.8"
|
||||
failure = "0.1.8"
|
||||
futures = "0.3.1"
|
||||
r2d2 = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
uuid = { version = "0.8", features = ["serde", "v4"] }
|
109
database_interactions/diesel/README.md
Normal file
109
database_interactions/diesel/README.md
Normal file
@ -0,0 +1,109 @@
|
||||
# diesel
|
||||
|
||||
Basic integration of [Diesel](https://diesel.rs/) using SQLite for Actix web.
|
||||
|
||||
## Usage
|
||||
|
||||
### Install SQLite
|
||||
|
||||
```sh
|
||||
# on OpenSUSE
|
||||
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
|
||||
cargo install diesel_cli --no-default-features --features sqlite
|
||||
|
||||
echo "DATABASE_URL=test.db" > .env
|
||||
diesel migration run
|
||||
```
|
||||
|
||||
There will now be a database file at `./test.db`.
|
||||
|
||||
### Running Server
|
||||
|
||||
```sh
|
||||
cd examples/diesel
|
||||
cargo run (or ``cargo watch -x run``)
|
||||
|
||||
# Started http server: 127.0.0.1:8080
|
||||
```
|
||||
|
||||
### Available Routes
|
||||
|
||||
#### `POST /user`
|
||||
|
||||
Inserts a new user into the SQLite DB.
|
||||
|
||||
Provide a JSON payload with a name. Eg:
|
||||
```json
|
||||
{ "name": "bill" }
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
```
|
||||
sqlite> .tables
|
||||
sqlite> SELECT * FROM users;
|
||||
```
|
||||
|
||||
|
||||
## Using Other Databases
|
||||
|
||||
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)
|
@ -0,0 +1 @@
|
||||
DROP TABLE users
|
@ -0,0 +1,4 @@
|
||||
CREATE TABLE users (
|
||||
id VARCHAR NOT NULL PRIMARY KEY,
|
||||
name VARCHAR NOT NULL
|
||||
)
|
40
database_interactions/diesel/src/actions.rs
Normal file
40
database_interactions/diesel/src/actions.rs
Normal file
@ -0,0 +1,40 @@
|
||||
use diesel::prelude::*;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models;
|
||||
|
||||
/// Run query using Diesel to find user by uid and return it.
|
||||
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)
|
||||
}
|
94
database_interactions/diesel/src/main.rs
Normal file
94
database_interactions/diesel/src/main.rs
Normal file
@ -0,0 +1,94 @@
|
||||
//! Actix web Diesel integration example
|
||||
//!
|
||||
//! Diesel does not support tokio, so we have to run it in separate threads using the web::block
|
||||
//! function which offloads blocking code (like Diesel's) in order to not block the server's thread.
|
||||
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
|
||||
use actix_web::{get, middleware, post, web, App, Error, HttpResponse, HttpServer};
|
||||
use diesel::prelude::*;
|
||||
use diesel::r2d2::{self, ConnectionManager};
|
||||
use uuid::Uuid;
|
||||
|
||||
mod actions;
|
||||
mod models;
|
||||
mod schema;
|
||||
|
||||
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
|
||||
|
||||
/// Finds user by UID.
|
||||
#[get("/user/{user_id}")]
|
||||
async fn get_user(
|
||||
pool: web::Data<DbPool>,
|
||||
user_uid: web::Path<Uuid>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let user_uid = user_uid.into_inner();
|
||||
let conn = pool.get().expect("couldn't get db connection from pool");
|
||||
|
||||
// use web::block to offload blocking Diesel code without blocking server thread
|
||||
let user = web::block(move || actions::find_user_by_uid(user_uid, &conn))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("{}", e);
|
||||
HttpResponse::InternalServerError().finish()
|
||||
})?;
|
||||
|
||||
if let Some(user) = user {
|
||||
Ok(HttpResponse::Ok().json(user))
|
||||
} else {
|
||||
let res = HttpResponse::NotFound()
|
||||
.body(format!("No user found with uid: {}", user_uid));
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts new user with name defined in form.
|
||||
#[post("/user")]
|
||||
async fn add_user(
|
||||
pool: web::Data<DbPool>,
|
||||
form: web::Json<models::NewUser>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
let conn = pool.get().expect("couldn't get db connection from 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
|
||||
.map_err(|e| {
|
||||
eprintln!("{}", e);
|
||||
HttpResponse::InternalServerError().finish()
|
||||
})?;
|
||||
|
||||
Ok(HttpResponse::Ok().json(user))
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
std::env::set_var("RUST_LOG", "actix_web=info");
|
||||
env_logger::init();
|
||||
dotenv::dotenv().ok();
|
||||
|
||||
// set up database connection pool
|
||||
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
|
||||
let manager = ConnectionManager::<SqliteConnection>::new(connspec);
|
||||
let pool = r2d2::Pool::builder()
|
||||
.build(manager)
|
||||
.expect("Failed to create pool.");
|
||||
|
||||
let bind = "127.0.0.1:8080";
|
||||
|
||||
println!("Starting server at: {}", &bind);
|
||||
|
||||
// Start HTTP server
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
// set up DB pool to be used with web::Data<Pool> extractor
|
||||
.data(pool.clone())
|
||||
.wrap(middleware::Logger::default())
|
||||
.service(get_user)
|
||||
.service(add_user)
|
||||
})
|
||||
.bind(&bind)?
|
||||
.run()
|
||||
.await
|
||||
}
|
14
database_interactions/diesel/src/models.rs
Normal file
14
database_interactions/diesel/src/models.rs
Normal file
@ -0,0 +1,14 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::schema::users;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Queryable, Insertable)]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NewUser {
|
||||
pub name: String,
|
||||
}
|
6
database_interactions/diesel/src/schema.rs
Normal file
6
database_interactions/diesel/src/schema.rs
Normal file
@ -0,0 +1,6 @@
|
||||
table! {
|
||||
users (id) {
|
||||
id -> Text,
|
||||
name -> Text,
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user