Skip to content

Commit

Permalink
Merge pull request #56 from friendbear/develop
Browse files Browse the repository at this point in the history
PostgreSQL
  • Loading branch information
friendbear authored Sep 1, 2023
2 parents 289d059 + 04f3bc9 commit 2684dde
Show file tree
Hide file tree
Showing 24 changed files with 340 additions and 115 deletions.
46 changes: 33 additions & 13 deletions Cargo.lock

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

24 changes: 0 additions & 24 deletions practice_collection/postgres/src/pool_2.rs

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "postgres"
name = "postgresql"
version = "0.1.0"
edition = "2021"

Expand All @@ -13,4 +13,10 @@ once_cell = "1.18.0"

postgres = "0.19.7"
r2d2 = "0.8.10"
r2d2_postgres = "0.18.1"
r2d2_postgres = "0.18.1"

tokio ={ version = "1.24.1", features = ["full"] }
tokio-postgres = "0.7.1"
proc-macro2 = "1.0.49"
async-trait = "0.1.61"
yaml-rust = "0.4.5"
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,16 @@ class Product {
}
ProductRepository ..> Repository~T,PK,UPD~
ProductRepository ..> Product
```

## QA

[[cargo clippy warning]arning: this `MutexGuard` is held across an `await` point](https://users.rust-lang.org/t/cargo-clippy-warning-arning-this-mutexguard-is-held-across-an-await-point/99225)

```rust
let config;
{
let params = CONNECT_PARAMS.lock().unwrap(); // params lock here.
config = params.connect_string().clone();
} // params drop here.
```
11 changes: 11 additions & 0 deletions practice_collection/postgresql/resources/sql.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
product:
select_all: SELECT id, name, price, category_id FROM product
select_by_id: SELECT id, name, price, category_id FROM product WHERE id = $1
insert: INSERT INTO product VALUES(nextval('product_seq'), $1, $2, $3)
update_by_id: UPDATE product SET name=$1, price=#2, category_id=$3 WHERE id = $4
delete_by_id: DELETE FROM product WHERE id = $1
product_category:
select_all: SELECT id, name FROM product_category
select_by_id: SELECT id, name FROM FROM product_category
insert: INSERT INTO product_category VALUES(nextval('product_category_seq')), $1)
delete_by_id: DELETE FROM product_category WHERE id = $1
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,11 @@ CREATE SEQUENCE product_seq
INCREMENT 1
MINVALUE 10
MAXVALUE 100000
CYCLE;
CYCLE;

CREATE SEQUENCE product_category_seq
START 10
INCREMENT 1
MINVALUE 10
MAXVALUE 100000
CYCLE;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use postgres::{Client, NoTls, Config};
use crate::params::ConnectParams;
use postgres::{Client, Config, NoTls};

/// データベース接続機能の実装
#[allow(dead_code)]
Expand Down Expand Up @@ -36,7 +36,7 @@ mod tests {
5432,
"rust_sample".to_owned(),
"postgres".to_owned(),
"admin".to_owned()
"admin".to_owned(),
);
match super::PostgresSampleClient::simple_connect(params.clone()) {
Ok(client) => {
Expand All @@ -53,4 +53,4 @@ mod tests {
Err(err) => println!("{}", err),
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ pub struct Product {
price: i32,
category_id: i32,
product_category: Option<Vec<ProductCategory>>,
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
mod params;
mod connect;
mod transaction;
mod entities;
mod repository;
mod product_repository;
mod product_category_repository;
mod manager;
mod params;
mod pool_1;
mod pool_2;
mod manager;
mod product_category_repository;
mod product_repository;
mod repository;
mod tokio_connect;
mod tokio_product_repository;
mod tokio_repository;
mod tokio_transaction;
mod transaction;
pub mod sql;
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
use r2d2::PooledConnection;
use anyhow::Result;
use crate::pool_1::SAMPLE_POOL_1;
use anyhow::Result;
use r2d2::PooledConnection;
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
/// ConnectionManager
pub struct SamplePoolManager;
impl SamplePoolManager {
Expand All @@ -19,10 +19,10 @@ impl SamplePoolManager {
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use crate::product_repository::ProductRepository;
use crate::repository::Repository;
use crate::transaction::TransactionUtil;
use crate::product_repository::ProductRepository;
use std::thread;

#[ignore = "Not connection database"]
#[test]
Expand All @@ -38,4 +38,4 @@ mod tests {
assert_eq!(product.get_name(), "はしちゃん");
Ok(())
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ pub struct ConnectParams {
}
impl ConnectParams {
pub fn connect_string(&self) -> String {
format!("host={} port={} dbname={} user={} password={}",
self.host, self.port, self.dbname, self.user, self.password)
format!(
"host={} port={} dbname={} user={} password={}",
self.host, self.port, self.dbname, self.user, self.password
)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use std::sync::Mutex;
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
use r2d2_postgres::r2d2::Pool;
use once_cell::sync::Lazy;
use r2d2_postgres::r2d2::Pool;
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
use std::sync::Mutex;

#[allow(dead_code)]
// Connecttion String
static CONNECTION_STR: &str = "host=localhost port=5432 dbname=rust_sample user=postgres password=admin";
static CONNECTION_STR: &str =
"host=localhost port=5432 dbname=rust_sample user=postgres password=admin";
#[allow(dead_code)]
// Create Connection Pool
pub static SAMPLE_POOL_1: Lazy<Mutex<Pool<PostgresConnectionManager<NoTls>>>> =
Lazy::new(|| {
pub static SAMPLE_POOL_1: Lazy<Mutex<Pool<PostgresConnectionManager<NoTls>>>> = Lazy::new(|| {
let config = CONNECTION_STR.parse().unwrap();
// create connection manager
let manager = PostgresConnectionManager::new(config, NoTls);
// create pool
let pool = r2d2::Pool::new(manager).unwrap();
Mutex::new(pool)
});
});
24 changes: 24 additions & 0 deletions practice_collection/postgresql/src/pool_2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use once_cell::sync::Lazy;
use r2d2_postgres::r2d2::Pool;
use r2d2_postgres::{postgres::NoTls, PostgresConnectionManager};
use std::sync::Mutex;
use std::time::Duration;

#[allow(dead_code)]
// connection str
static CONNECTION_STR: &str =
"host=localhost port=5432 dbname=rust_sample user=postgres password=admin";

#[allow(dead_code)]
// create connection pool
pub static SAMPLE_POOL_2: Lazy<Mutex<Pool<PostgresConnectionManager<NoTls>>>> = Lazy::new(|| {
let config = CONNECTION_STR.parse().unwrap();
let manager = PostgresConnectionManager::new(config, NoTls);
let pool = r2d2::Pool::builder()
.max_size(30)
.min_idle(Some(1))
.connection_timeout(Duration::from_secs_f32(60.0))
.build(manager)
.unwrap();
Mutex::new(pool)
});
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use postgres::Transaction;
use postgres::types::Type;
use anyhow::{Result, Error};
use crate::entities::{Product, ProductCategory};
use anyhow::{Error, Result};
use postgres::types::Type;
use postgres::Transaction;

#[allow(dead_code)]
pub struct ProductCategoryRepository<'a, 'b>(pub &'a mut Transaction<'b>);
impl ProductCategoryRepository<'_,'_> {
impl ProductCategoryRepository<'_, '_> {
#[allow(dead_code)]
pub fn select_by_id_join_product(&mut self, id: i32) -> Result<ProductCategory> {
let sql = r#"
Expand All @@ -26,9 +26,15 @@ impl ProductCategoryRepository<'_,'_> {
product_category.set_id(row.get("idc_id"));
product_category.set_name(row.get("c_name"));
}
products.push(Product::new(row.get("id"), row.get("name"), row.get("price"), row.get("category_id"), None));
products.push(Product::new(
row.get("id"),
row.get("name"),
row.get("price"),
row.get("category_id"),
None,
));
}
product_category.set_products(Some(products));
Ok(product_category)
}
}
}
Loading

0 comments on commit 2684dde

Please sign in to comment.