use connection with foreign keys enabled

This commit is contained in:
Joe Ardent 2023-04-28 13:42:43 -07:00
parent fdf2b1e910
commit 358eddd4a1

View file

@ -1,18 +1,3 @@
//! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! Run with
//!
//! ```not_rust
//! cargo run -p example-sqlx-postgres
//! ```
//!
//! Test with curl:
//!
//! ```not_rust
//! curl 127.0.0.1:3000
//! curl -X POST 127.0.0.1:3000
//! ```
use std::{net::SocketAddr, time::Duration}; use std::{net::SocketAddr, time::Duration};
use axum::{ use axum::{
@ -22,11 +7,8 @@ use axum::{
routing::get, routing::get,
Router, Router,
}; };
use sqlx::{ use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions}, // use tokio::net::TcpListener;
types::uuid::adapter::Hyphenated,
};
use tokio::net::TcpListener;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
#[tokio::main] #[tokio::main]
@ -34,19 +16,29 @@ async fn main() {
tracing_subscriber::registry() tracing_subscriber::registry()
.with( .with(
tracing_subscriber::EnvFilter::try_from_default_env() tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_tokio_postgres=debug".into()), .unwrap_or_else(|_| "ww_main=debug".into()),
) )
.with(tracing_subscriber::fmt::layer()) .with(tracing_subscriber::fmt::layer())
.init(); .init();
let db_connection_str = std::env::var("DATABASE_URL") let db_filename = {
.unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string()); std::env::var("DATABASE_FILE").unwrap_or_else(|_| {
let home =
std::env::var("HOME").expect("Could not determine $HOME for finding db file");
format!("{home}/.witch-watch.db")
})
};
let conn_opts = SqliteConnectOptions::new()
.foreign_keys(true)
.auto_vacuum(sqlx::sqlite::SqliteAutoVacuum::Incremental)
.filename(&db_filename);
// setup connection pool // setup connection pool
let pool = SqlitePoolOptions::new() let pool = SqlitePoolOptions::new()
.max_connections(5) .max_connections(5)
.connect_timeout(Duration::from_secs(3)) .connect_timeout(Duration::from_secs(3))
.connect(&db_connection_str) .connect_with(conn_opts)
.await .await
.expect("can't connect to database"); .expect("can't connect to database");
@ -59,9 +51,9 @@ async fn main() {
.with_state(pool); .with_state(pool);
// run it with hyper // run it with hyper
let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); //let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
//axum::serve(listener, app).await.unwrap(); //axum::serve(listener, app).await.unwrap();
tracing::info!("binding to 0.0.0.0:3000");
axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000))) axum::Server::bind(&SocketAddr::from(([0, 0, 0, 0], 3000)))
.serve(app.into_make_service()) .serve(app.into_make_service())
.await .await
@ -72,7 +64,7 @@ async fn main() {
async fn using_connection_pool_extractor( async fn using_connection_pool_extractor(
State(pool): State<SqlitePool>, State(pool): State<SqlitePool>,
) -> Result<String, (StatusCode, String)> { ) -> Result<String, (StatusCode, String)> {
sqlx::query_scalar("select 'hello world from pg'") sqlx::query_scalar("select 'hello world from sqlite get'")
.fetch_one(&pool) .fetch_one(&pool)
.await .await
.map_err(internal_error) .map_err(internal_error)
@ -103,7 +95,7 @@ async fn using_connection_extractor(
DatabaseConnection(conn): DatabaseConnection, DatabaseConnection(conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> { ) -> Result<String, (StatusCode, String)> {
let mut conn = conn; let mut conn = conn;
sqlx::query_scalar("select 'hello world from pg'") sqlx::query_scalar("select 'hello world from sqlite post'")
.fetch_one(&mut conn) .fetch_one(&mut conn)
.await .await
.map_err(internal_error) .map_err(internal_error)