mirror of
https://github.com/launchbadge/sqlx
synced 2024-11-10 14:34:19 +00:00
Merge pull request #91 from Ace4896/todos-postgres-example
Add TODOs CLI Example for Postgres
This commit is contained in:
commit
7233caa579
5 changed files with 153 additions and 1 deletions
|
@ -3,7 +3,8 @@ members = [
|
|||
".",
|
||||
"sqlx-core",
|
||||
"sqlx-macros",
|
||||
"examples/realworld-postgres"
|
||||
"examples/realworld-postgres",
|
||||
"examples/todos-postgres",
|
||||
]
|
||||
|
||||
[package]
|
||||
|
|
13
examples/todos-postgres/Cargo.toml
Normal file
13
examples/todos-postgres/Cargo.toml
Normal file
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "todos-postgres"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
workspace = "../../"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
async-std = { version = "1.4.0", features = [ "attributes" ] }
|
||||
futures = "0.3"
|
||||
paw = "1.0"
|
||||
sqlx = { version = "0.2", features = ["postgres"] }
|
||||
structopt = { version = "0.3", features = ["paw"] }
|
29
examples/todos-postgres/README.md
Normal file
29
examples/todos-postgres/README.md
Normal file
|
@ -0,0 +1,29 @@
|
|||
# TODOs Example
|
||||
|
||||
## Usage
|
||||
|
||||
Declare the database URL:
|
||||
|
||||
```
|
||||
export DATABASE_URL="postgres://postgres@localhost/todos"
|
||||
```
|
||||
|
||||
Create the database:
|
||||
|
||||
```
|
||||
createdb -U postgres todos
|
||||
```
|
||||
|
||||
Load the database schema:
|
||||
|
||||
```
|
||||
psql -d "$DATABASE_URL" -f ./schema.sql
|
||||
```
|
||||
|
||||
Run:
|
||||
|
||||
- Add a todo: `cargo run -- add "todo description"`
|
||||
- Complete a todo: `cargo run -- done <todo id>`
|
||||
- List all todos: `cargo run`
|
||||
|
||||
|
5
examples/todos-postgres/schema.sql
Normal file
5
examples/todos-postgres/schema.sql
Normal file
|
@ -0,0 +1,5 @@
|
|||
CREATE TABLE IF NOT EXISTS todos (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
description TEXT NOT NULL,
|
||||
done BOOLEAN NOT NULL DEFAULT FALSE
|
||||
);
|
104
examples/todos-postgres/src/main.rs
Normal file
104
examples/todos-postgres/src/main.rs
Normal file
|
@ -0,0 +1,104 @@
|
|||
use sqlx::PgPool;
|
||||
use std::env;
|
||||
use structopt::StructOpt;
|
||||
|
||||
#[derive(StructOpt)]
|
||||
struct Args {
|
||||
#[structopt(subcommand)]
|
||||
cmd: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt)]
|
||||
enum Command {
|
||||
Add { description: String },
|
||||
Done { id: i64 },
|
||||
}
|
||||
|
||||
#[async_std::main]
|
||||
#[paw::main]
|
||||
async fn main(args: Args) -> anyhow::Result<()> {
|
||||
let mut pool = PgPool::new(&env::var("DATABASE_URL")?).await?;
|
||||
|
||||
match args.cmd {
|
||||
Some(Command::Add { description }) => {
|
||||
println!("Adding new todo with description '{}'", &description);
|
||||
let todo_id = add_todo(&pool, &description).await?;
|
||||
println!("Added new todo with id {}", todo_id);
|
||||
}
|
||||
Some(Command::Done { id }) => {
|
||||
println!("Marking todo {} as done", id);
|
||||
if complete_todo(&pool, id).await? {
|
||||
println!("Todo {} is marked as done", id);
|
||||
} else {
|
||||
println!("Invalid id {}", id);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!("Printing list of all todos");
|
||||
list_todos(&mut pool).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_todo(pool: &PgPool, description: &str) -> anyhow::Result<i64> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let rec = sqlx::query!(
|
||||
"
|
||||
INSERT INTO todos ( description )
|
||||
VALUES ( $1 )
|
||||
RETURNING id
|
||||
",
|
||||
description
|
||||
)
|
||||
.fetch_one(&mut tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(rec.id)
|
||||
}
|
||||
|
||||
async fn complete_todo(pool: &PgPool, id: i64) -> anyhow::Result<bool> {
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let rows_affected = sqlx::query!(
|
||||
"
|
||||
UPDATE todos
|
||||
SET done = TRUE
|
||||
WHERE id = $1
|
||||
",
|
||||
id
|
||||
)
|
||||
.execute(&mut tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(rows_affected > 0)
|
||||
}
|
||||
|
||||
async fn list_todos(pool: &mut PgPool) -> anyhow::Result<()> {
|
||||
let recs = sqlx::query!(
|
||||
"
|
||||
SELECT id, description, done
|
||||
FROM todos
|
||||
ORDER BY id
|
||||
"
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
for rec in recs {
|
||||
println!(
|
||||
"- [{}] {}: {}",
|
||||
if rec.done { "x" } else { " " },
|
||||
rec.id,
|
||||
&rec.description,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
Loading…
Reference in a new issue