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

refactor/nanocld: namespace repository #730

Merged
merged 2 commits into from
Dec 19, 2023
Merged
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
2 changes: 1 addition & 1 deletion bin/nanocld/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,6 @@ async fn main() -> std::io::Result<()> {
}
}
}
log::info!("shutdown");
log::info!("main: shutdown");
Ok(())
}
60 changes: 2 additions & 58 deletions bin/nanocld/src/models/namespace.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
use std::sync::Arc;

use diesel::prelude::*;
use ntex::rt::JoinHandle;
use serde::{Serialize, Deserialize};

use nanocl_error::io::{IoError, IoResult};

use nanocl_stubs::{generic::GenericFilter, namespace::NamespacePartial};

use crate::{utils, schema::namespaces};
use nanocl_stubs::namespace::NamespacePartial;

use super::{Pool, Repository};
use crate::schema::namespaces;

/// This structure represent the namespace in the database.
/// A namespace is a group of cargo or virtual machine that share the same network.
Expand Down Expand Up @@ -46,52 +39,3 @@ impl From<&NamespacePartial> for NamespaceDb {
}
}
}

impl Repository for NamespaceDb {
type Table = namespaces::table;
type Item = NamespaceDb;
type UpdateItem = NamespaceDb;

fn find_one(
filter: &GenericFilter,
pool: &Pool,
) -> JoinHandle<IoResult<Self::Item>> {
log::trace!("NamespaceDb::find_one: {filter:?}");
// let r#where = filter.r#where.to_owned().unwrap_or_default();
let query = namespaces::dsl::namespaces
.order(namespaces::dsl::created_at.desc())
.into_boxed();
let pool = Arc::clone(pool);
ntex::rt::spawn_blocking(move || {
let mut conn = utils::store::get_pool_conn(&pool)?;
let item = query
.get_result::<Self>(&mut conn)
.map_err(Self::map_err_context)?;
Ok::<_, IoError>(item)
})
}

fn find(
filter: &GenericFilter,
pool: &Pool,
) -> JoinHandle<IoResult<Vec<Self::Item>>> {
log::trace!("NamespaceDb::find: {filter:?}");
// let r#where = filter.r#where.to_owned().unwrap_or_default();
let mut query = namespaces::dsl::namespaces
.order(namespaces::dsl::created_at.desc())
.into_boxed();
let limit = filter.limit.unwrap_or(100);
query = query.limit(limit as i64);
if let Some(offset) = filter.offset {
query = query.offset(offset as i64);
}
let pool = Arc::clone(pool);
ntex::rt::spawn_blocking(move || {
let mut conn = utils::store::get_pool_conn(&pool)?;
let items = query
.get_results::<Self>(&mut conn)
.map_err(Self::map_err_context)?;
Ok::<_, IoError>(items)
})
}
}
23 changes: 1 addition & 22 deletions bin/nanocld/src/repositories/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,7 @@ impl RepositoryUpdate for CargoDb {
type UpdateItem = CargoUpdateDb;
}

impl RepositoryDelete for CargoDb {
fn get_del_query(
filter: &GenericFilter,
) -> diesel::query_builder::BoxedDeleteStatement<
'static,
diesel::pg::Pg,
<Self as diesel::associations::HasTable>::Table,
>
where
Self: diesel::associations::HasTable,
{
let r#where = filter.r#where.to_owned().unwrap_or_default();
let mut query = diesel::delete(cargoes::dsl::cargoes).into_boxed();
if let Some(value) = r#where.get("key") {
gen_where4string!(query, cargoes::dsl::key, value);
}
if let Some(value) = r#where.get("name") {
gen_where4string!(query, cargoes::dsl::name, value);
}
query
}
}
impl RepositoryDelByPk for CargoDb {}

impl RepositoryReadWithSpec for CargoDb {
type Output = Cargo;
Expand Down
57 changes: 30 additions & 27 deletions bin/nanocld/src/repositories/generic/delete.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,30 @@
use std::sync::Arc;

use diesel::{prelude::*, associations::HasTable, query_dsl, query_builder};
use ntex::rt::JoinHandle;
use diesel::{prelude::*, associations::HasTable, query_dsl, query_builder};

use nanocl_error::io::IoResult;

use nanocl_stubs::generic::GenericFilter;

use crate::{utils, models::Pool};

pub trait RepositoryDelete: super::RepositoryBase {
fn get_del_query(
filter: &GenericFilter,
) -> diesel::query_builder::BoxedDeleteStatement<
'static,
diesel::pg::Pg,
<Self as diesel::associations::HasTable>::Table,
>
pub trait RepositoryDelByPk: super::RepositoryBase {
fn del_by_pk<Pk>(
pk: &Pk,
pool: &Pool,
) -> JoinHandle<IoResult<()>>
where
Self: diesel::associations::HasTable;

fn del_by_pk<Pk>(
pk: &Pk,
pool: &Pool,
) -> JoinHandle<IoResult<()>>
where
Self: Sized + HasTable,
Pk: ToOwned + ?Sized + std::fmt::Display,
<Pk as ToOwned>::Owned: Send + 'static,
Self::Table: query_dsl::methods::FindDsl<<Pk as ToOwned>::Owned> + HasTable<Table = Self::Table>,
diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned>: query_builder::IntoUpdateTarget,
query_builder::DeleteStatement<
<diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned> as HasTable>::Table,
<diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned> as query_builder::IntoUpdateTarget>::WhereClause,
>: query_builder::QueryFragment<diesel::pg::Pg> + query_builder::QueryId,
{
Self: Sized + HasTable,
Pk: ToOwned + ?Sized + std::fmt::Display,
<Pk as ToOwned>::Owned: Send + 'static,
Self::Table: query_dsl::methods::FindDsl<<Pk as ToOwned>::Owned> + HasTable<Table = Self::Table>,
diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned>: query_builder::IntoUpdateTarget,
query_builder::DeleteStatement<
<diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned> as HasTable>::Table,
<diesel::helper_types::Find<Self::Table, <Pk as ToOwned>::Owned> as query_builder::IntoUpdateTarget>::WhereClause,
>: query_builder::QueryFragment<diesel::pg::Pg> + query_builder::QueryId,
{
log::trace!("{}::delete_by_pk: {pk}", Self::get_name());
let pool = Arc::clone(pool);
let pk = pk.to_owned();
Expand All @@ -46,6 +36,18 @@ pub trait RepositoryDelete: super::RepositoryBase {
Ok(())
})
}
}

pub trait RepositoryDelBy: super::RepositoryBase {
fn gen_del_query(
filter: &GenericFilter,
) -> diesel::query_builder::BoxedDeleteStatement<
'static,
diesel::pg::Pg,
<Self as diesel::associations::HasTable>::Table,
>
where
Self: diesel::associations::HasTable;

fn del_by(
filter: &GenericFilter,
Expand All @@ -56,10 +58,11 @@ pub trait RepositoryDelete: super::RepositoryBase {
<Self as diesel::associations::HasTable>::Table: diesel::query_builder::QueryId + 'static,
<<Self as diesel::associations::HasTable>::Table as diesel::QuerySource>::FromClause: diesel::query_builder::QueryFragment<diesel::pg::Pg>,
{
log::trace!("{}::delete_by: {filter:?}", Self::get_name());
let pool = Arc::clone(pool);
let filter = filter.clone();
ntex::rt::spawn_blocking(move || {
let query = Self::get_del_query(&filter);
let query = Self::gen_del_query(&filter);
let mut conn = utils::store::get_pool_conn(&pool)?;
query.execute(&mut conn).map_err(Self::map_err)?;
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions bin/nanocld/src/repositories/generic/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub trait RepositoryUpdate: super::RepositoryBase {
) -> JoinHandle<IoResult<Self>>
where
T: Into<Self::UpdateItem>,
Pk: ToOwned + ?Sized,
Pk: ToOwned + ?Sized + std::fmt::Display,
<Pk as ToOwned>::Owned: Send + 'static,
Self: Sized + Send + associations::HasTable + 'static,
<Self as associations::HasTable>::Table: diesel::query_dsl::methods::FindDsl<<Pk as ToOwned>::Owned> + associations::HasTable<Table = Self::Table>,
Expand All @@ -33,7 +33,7 @@ pub trait RepositoryUpdate: super::RepositoryBase {
>:
diesel::query_builder::AsQuery + diesel::query_dsl::LoadQuery<'static, diesel::pg::PgConnection, Self>,
{
log::trace!("{}::update_by_pk", Self::get_name());
log::trace!("{}::update_by_pk: {pk}", Self::get_name());
let pool = Arc::clone(pool);
let pk = pk.to_owned();
let values = values.into();
Expand Down
1 change: 1 addition & 0 deletions bin/nanocld/src/repositories/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod cargo;
mod process;
mod namespace;

pub mod generic;
30 changes: 30 additions & 0 deletions bin/nanocld/src/repositories/namespace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use diesel::prelude::*;
use nanocl_stubs::generic::GenericFilter;

use crate::{models::NamespaceDb, schema::namespaces};

use super::generic::*;

impl RepositoryBase for NamespaceDb {}

impl RepositoryCreate for NamespaceDb {}

impl RepositoryDelByPk for NamespaceDb {}

impl RepositoryRead for NamespaceDb {
type Output = NamespaceDb;
type Query = namespaces::BoxedQuery<'static, diesel::pg::Pg>;

fn gen_read_query(filter: &GenericFilter, is_multiple: bool) -> Self::Query {
let mut query = namespaces::dsl::namespaces.into_boxed();
if is_multiple {
query = query.order(namespaces::dsl::created_at.desc());
let limit = filter.limit.unwrap_or(100);
query = query.limit(limit as i64);
if let Some(offset) = filter.offset {
query = query.offset(offset as i64);

Check warning on line 25 in bin/nanocld/src/repositories/namespace.rs

View check run for this annotation

Codecov / codecov/patch

bin/nanocld/src/repositories/namespace.rs#L25

Added line #L25 was not covered by tests
}
}

Check warning on line 27 in bin/nanocld/src/repositories/namespace.rs

View check run for this annotation

Codecov / codecov/patch

bin/nanocld/src/repositories/namespace.rs#L27

Added line #L27 was not covered by tests
query
}
}
14 changes: 8 additions & 6 deletions bin/nanocld/src/repositories/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,15 @@ impl RepositoryBase for ProcessDb {}

impl RepositoryCreate for ProcessDb {}

impl RepositoryUpdate for ProcessDb {
type UpdateItem = ProcessUpdateDb;
}

impl RepositoryDelByPk for ProcessDb {}

/// Implement delete_by_pk and delete_by_id for ProcessDb
impl RepositoryDelete for ProcessDb {
fn get_del_query(
impl RepositoryDelBy for ProcessDb {
fn gen_del_query(
filter: &GenericFilter,
) -> diesel::query_builder::BoxedDeleteStatement<
'static,
Expand Down Expand Up @@ -86,10 +92,6 @@ impl RepositoryRead for ProcessDb {
}
}

impl RepositoryUpdate for ProcessDb {
type UpdateItem = ProcessUpdateDb;
}

impl ProcessDb {
pub(crate) async fn find_by_kind_key(
kind_key: &str,
Expand Down
15 changes: 10 additions & 5 deletions bin/nanocld/src/services/namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ use ntex::web;

use nanocl_error::http::{HttpResult, HttpError};

use nanocl_stubs::generic::{GenericFilter, GenericListQuery};
use nanocl_stubs::namespace::NamespacePartial;
use nanocl_stubs::{
generic::{GenericFilter, GenericListQuery},
namespace::NamespacePartial,
};

use crate::utils;
use crate::models::{DaemonState, Repository, NamespaceDb};
use crate::{
utils,
models::{DaemonState, NamespaceDb},
repositories::generic::RepositoryRead,
};

/// List namespaces
#[cfg_attr(feature = "dev", utoipa::path(
Expand Down Expand Up @@ -92,7 +97,7 @@ pub(crate) async fn delete_namespace(
state: web::types::State<DaemonState>,
path: web::types::Path<(String, String)>,
) -> HttpResult<web::HttpResponse> {
NamespaceDb::find_by_pk(&path.1, &state.pool).await??;
NamespaceDb::read_by_pk(&path.1, &state.pool).await??;
utils::namespace::delete_by_name(&path.1, &state).await?;
Ok(web::HttpResponse::Accepted().into())
}
Expand Down
4 changes: 2 additions & 2 deletions bin/nanocld/src/utils/cargo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ pub(crate) async fn list(
})?
.r#where("namespace_name", GenericClause::Eq(namespace.clone()));
// ensure namespace exists
NamespaceDb::find_by_pk(&namespace, &state.pool).await??;
NamespaceDb::read_by_pk(&namespace, &state.pool).await??;
let cargoes = CargoDb::read_with_spec(&filter, &state.pool).await??;
let mut cargo_summaries = Vec::new();
for cargo in cargoes {
Expand Down Expand Up @@ -528,7 +528,7 @@ pub(crate) async fn delete_by_namespace(
namespace: &str,
state: &DaemonState,
) -> HttpResult<()> {
let namespace = NamespaceDb::find_by_pk(namespace, &state.pool).await??;
let namespace = NamespaceDb::read_by_pk(namespace, &state.pool).await??;
let cargoes =
CargoDb::find_by_namespace(&namespace.name, &state.pool).await?;
cargoes
Expand Down
Loading
Loading