mirror of
https://github.com/actix/examples
synced 2025-04-21 16:16:51 +02:00
diesel
Basic integration of Diesel-async using PostgreSQL for Actix Web.
Usage
Install PostgreSQL
# on any OS
docker run -d --restart unless-stopped --name postgresql -e POSTGRES_USER=test-user -e POSTGRES_PASSWORD=password -p 5432:5432 -v postgres_data:/var/lib/postgresql/data postgres:alpine
make sure it has successfully started up and is running
# on any OS
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"
Initialize PostgreSQL Database
cd databases/diesel-async
cargo install diesel_cli --no-default-features --features postgres
echo DATABASE_URL=postgres://test-user:password@localhost:5432/test_db > .env
diesel setup
diesel migration run
The database will now be created in your PostgreSQL instance.
docker exec -i postgresql psql -U test-user -c "\l"
Running Server
cd databases/diesel-async
cargo run
# Started http server: 127.0.0.1:8080
Available Routes
POST /items
Inserts a new item into the PostgreSQL DB.
Provide a JSON payload with a name. Eg:
{ "name": "thingamajig" }
On success, a response like the following is returned:
{
"id": "01948982-67d0-7a55-b4b1-8b8b962d8c6b",
"name": "thingamajig"
}
Client Examples
Using HTTPie:
http POST localhost:8080/items name=thingamajig
Using cURL:
curl -S -X POST --header "Content-Type: application/json" --data '{"name":"thingamajig"}' http://localhost:8080/items
GET /items/{item_uid}
Gets an item from the DB using its UID (returned from the insert request or taken from the DB directly). Returns a 404 when no item exists with that UID.
Client Examples
Using HTTPie:
http localhost:8080/items/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
Using cURL:
curl -S http://localhost:8080/items/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
Explore The PostgreSQL DB
docker exec -i postgresql psql -U test-user -d test_db -c "select * from public.items"
Using Other Databases
You can find a complete example of Diesel + PostgreSQL at: https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix