Init commit.

This commit is contained in:
James Pace 2024-02-14 20:06:01 -05:00
commit 0591f445a1
5 changed files with 1845 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
/data

1767
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

13
Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
name = "sqlx-fun"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.79"
serde = "1.0.196"
serde_json = "1.0.113"
sqlx = { version = "0.7.3", features = ["postgres", "json", "runtime-tokio"] }
tokio = { version = "1.36.0", features = ["full"] }

14
run-db.bash Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env bash
DATA_DIR="$PWD/data"
if [ ! -d "$DATA_DIR" ]; then
echo "Making data directory."
mkdir $DATA_DIR
fi
podman run --rm --name test-db --network=host \
-e POSTGRES_USER=postgres \
-e POSTGRES_PASSWORD=devpassword \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-v $DATA_DIR:/var/lib/postgresql/data \
docker.io/library/postgres:latest

49
src/main.rs Normal file
View File

@ -0,0 +1,49 @@
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Connect to the database.
let pool = sqlx::postgres::PgPool::connect("postgresql://postgres:devpassword@localhost/postgres").await?;
// Make the table.
let _ = sqlx::query(
"CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
doc JSONB
);"
).execute(&pool).await?;
// Insert some entries into db.
// Add James.
let james_doc = Doc {
age: 30,
fav_color: "blue".to_owned(),
fav_movie: "Iron Man".to_owned()
};
let james_doc_as_str = serde_json::to_string(&james_doc)?;
let james_add_query = format!(r#"INSERT INTO test (name, doc) VALUES('James', '{}');"#, james_doc_as_str);
let _ = sqlx::query(&james_add_query).execute(&pool).await?;
// Add Dave.
let dave_doc = Doc {
age: 25,
fav_color: "yellow".to_owned(),
fav_movie: "Spiderman".to_owned()
};
let dave_doc_as_str = serde_json::to_string(&dave_doc)?;
let dave_add_query = format!(r#"INSERT INTO test (name, doc) VALUES('Dave', '{}');"#, dave_doc_as_str);
let _ = sqlx::query(&dave_add_query).execute(&pool).await?;
// Get james favorite color.
// Get name based on movie.
// Get james's doc.
// Row based on color.
Ok(())
}
#[derive(Serialize, Deserialize)]
struct Doc {
age: u32,
fav_color: String,
fav_movie: String,
}