Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Diesel-async usage example #992

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/ci-nightly.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,21 @@ jobs:
with:
toolchain: ${{ matrix.version }}

- name: Install system packages
run: |
sudo apt-get update
sudo apt-get -y install sqlite3
sudo apt-get -y install libpq-dev

- name: Install DB CLI tools
run: |
cargo install --force sqlx-cli --no-default-features --features=sqlite,rustls
cargo install --force diesel_cli --no-default-features --features sqlite
cargo install --force diesel_cli --no-default-features --features=sqlite,postgres

- name: Create Test DBs
env:
DATABASE_URL: sqlite://./todo.db
run: |
sudo apt-get update && sudo apt-get install sqlite3
sqlx database create
chmod a+rwx ./todo.db
sqlx migrate run --source=./basics/todo/migrations
Expand Down
9 changes: 7 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,21 @@ jobs:
with:
toolchain: ${{ matrix.version }}

- name: Install system packages
run: |
sudo apt-get update
sudo apt-get -y install sqlite3
sudo apt-get -y install libpq-dev

- name: Install DB CLI tools
run: |
cargo install --force sqlx-cli --no-default-features --features=sqlite,rustls
cargo install --force diesel_cli --no-default-features --features sqlite
cargo install --force diesel_cli --no-default-features --features=sqlite,postgres

- name: Create Test DBs
env:
DATABASE_URL: sqlite://./todo.db
run: |
sudo apt-get update && sudo apt-get install sqlite3
sqlx database create
chmod a+rwx ./todo.db
sqlx migrate run --source=./basics/todo/migrations
Expand Down
75 changes: 74 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ members = [
"cors/backend",
"data-factory",
"databases/diesel",
"databases/diesel-async",
"databases/mongodb",
"databases/mysql",
"databases/postgres",
Expand Down Expand Up @@ -109,7 +110,7 @@ openssl = { version = "0.10.60", features = ["v110"] }
parking_lot = "0.12"
pin-project-lite = "0.2"
rand = "0.9"
redis = { version = "0.27" }
redis = { version = "0.28" }
reqwest = { version = "0.12", features = ["json", "stream"] }
rustls = "0.23"
rustls-pemfile = "2"
Expand Down
14 changes: 14 additions & 0 deletions databases/diesel-async/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "db-diesel-async"
version = "1.0.0"
edition = "2021"

[dependencies]
actix-web.workspace = true
diesel = { version = "2", default-features = false, features = ["uuid"] }
diesel-async = { version = "0.5", features = ["postgres", "bb8", "async-connection-wrapper"] }
serde.workspace = true
uuid.workspace = true
dotenvy.workspace = true
env_logger.workspace = true
log.workspace = true
113 changes: 113 additions & 0 deletions databases/diesel-async/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# diesel

Basic integration of [Diesel-async](https://github.com/weiznich/diesel_async) using PostgreSQL for Actix Web.

## Usage

### Install PostgreSQL

```sh
# 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
```sh
# on any OS
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"
```

### Initialize PostgreSQL Database

```sh
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.
```sh
docker exec -i postgresql psql -U test-user -c "\l"
```

### Running Server

```sh
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:

```json
{ "name": "thingamajig" }
```

On success, a response like the following is returned:

```json
{
"id": "01948982-67d0-7a55-b4b1-8b8b962d8c6b",
"name": "thingamajig"
}
```

<details>
<summary>Client Examples</summary>

Using [HTTPie]:

```sh
http POST localhost:8080/items name=thingamajig
```

Using cURL:

```sh
curl -S -X POST --header "Content-Type: application/json" --data '{"name":"thingamajig"}' http://localhost:8080/items
```

</details>

#### `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.

<details>
<summary>Client Examples</summary>

Using [HTTPie]:

```sh
http localhost:8080/items/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
```

Using cURL:

```sh
curl -S http://localhost:8080/items/9e46baba-a001-4bb3-b4cf-4b3e5bab5e97
```

</details>

### Explore The PostgreSQL DB

```sh
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](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)

[httpie]: https://httpie.io/cli
9 changes: 9 additions & 0 deletions databases/diesel-async/diesel.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId", "Clone"]

[migrations_directory]
dir = "/home/alex/CLionProjects/actix-with-async-diesel/migrations"
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.

DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.


-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS
$$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS
$$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE IF EXISTS items;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
-- Your SQL goes here
CREATE TABLE IF NOT EXISTS items
(
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
name VARCHAR NOT NULL
);
Loading
Loading