Skip to content
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
138 changes: 7 additions & 131 deletions src/catalog/backends/sql/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,53 +12,18 @@
//
// SPDX-License-Identifier: Apache-2.0

use sea_orm::DatabaseConnection;
use sea_orm::entity::*;
use sea_orm::query::*;
use serde_json::Value;
use tracing::error;

use crate::catalog::backends::error::{CatalogDatabaseError, db_err};
use crate::catalog::backends::error::CatalogDatabaseError;
use crate::catalog::types::*;
use crate::config::Config;
use crate::db::entity::{prelude::Service as DbService, service as db_service};
use crate::db::entity::service as db_service;

pub async fn get<I: AsRef<str>>(
_conf: &Config,
db: &DatabaseConnection,
id: I,
) -> Result<Option<Service>, CatalogDatabaseError> {
let select = DbService::find_by_id(id.as_ref());
mod get;
mod list;

let entry: Option<db_service::Model> = select
.one(db)
.await
.map_err(|err| db_err(err, "fetching service by ID"))?;
entry.map(TryInto::try_into).transpose()
}

pub async fn list(
_conf: &Config,
db: &DatabaseConnection,
params: &ServiceListParameters,
) -> Result<Vec<Service>, CatalogDatabaseError> {
let mut select = DbService::find();

if let Some(typ) = &params.r#type {
select = select.filter(db_service::Column::Type.eq(typ));
}

let db_services: Vec<db_service::Model> = select
.all(db)
.await
.map_err(|err| db_err(err, "fetching services"))?;
let results: Result<Vec<Service>, _> = db_services
.into_iter()
.map(TryInto::<Service>::try_into)
.collect();

results
}
pub use get::get;
pub use list::list;

impl TryFrom<db_service::Model> for Service {
type Error = CatalogDatabaseError;
Expand Down Expand Up @@ -86,103 +51,14 @@ impl TryFrom<db_service::Model> for Service {

#[cfg(test)]
mod tests {
use sea_orm::{DatabaseBackend, MockDatabase, Transaction};
use serde_json::json;

use crate::config::Config;
use crate::db::entity::service;

use super::*;

fn get_service_mock(id: String) -> service::Model {
pub(super) fn get_service_mock(id: String) -> service::Model {
service::Model {
id: id.clone(),
r#type: Some("type".into()),
enabled: true,
extra: Some(r#"{"name": "srv"}"#.to_string()),
}
}

#[tokio::test]
async fn test_get() {
// Create MockDatabase with mock query results
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([
// First query result - select user itself
vec![get_service_mock("1".into())],
])
.into_connection();
let config = Config::default();
assert_eq!(
get(&config, &db, "1").await.unwrap().unwrap(),
Service {
id: "1".into(),
r#type: Some("type".into()),
enabled: true,
name: Some("srv".into()),
extra: Some(json!({"name": "srv"})),
}
);

// Checking transaction log
assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service" WHERE "service"."id" = $1 LIMIT $2"#,
["1".into(), 1u64.into()]
),]
);
}

#[tokio::test]
async fn test_list() {
// Create MockDatabase with mock query results
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![get_service_mock("1".into())]])
.append_query_results([vec![get_service_mock("1".into())]])
.into_connection();
let config = Config::default();
assert!(
list(&config, &db, &ServiceListParameters::default())
.await
.is_ok()
);
assert_eq!(
list(
&config,
&db,
&ServiceListParameters {
r#type: Some("type".into()),
name: Some("service_name".into())
}
)
.await
.unwrap(),
vec![Service {
id: "1".into(),
r#type: Some("type".into()),
enabled: true,
name: Some("srv".into()),
extra: Some(json!({"name": "srv"})),
}]
);

// Checking transaction log
assert_eq!(
db.into_transaction_log(),
[
Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service""#,
[]
),
Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service" WHERE "service"."type" = $1"#,
["type".into()]
),
]
);
}
}
77 changes: 77 additions & 0 deletions src/catalog/backends/sql/service/get.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
use sea_orm::DatabaseConnection;
use sea_orm::entity::*;

use crate::catalog::backends::error::{CatalogDatabaseError, db_err};
use crate::catalog::types::*;
use crate::config::Config;
use crate::db::entity::{prelude::Service as DbService, service as db_service};

pub async fn get<I: AsRef<str>>(
_conf: &Config,
db: &DatabaseConnection,
id: I,
) -> Result<Option<Service>, CatalogDatabaseError> {
let select = DbService::find_by_id(id.as_ref());

let entry: Option<db_service::Model> = select
.one(db)
.await
.map_err(|err| db_err(err, "fetching service by ID"))?;
entry.map(TryInto::try_into).transpose()
}

#[cfg(test)]
mod tests {
use sea_orm::{DatabaseBackend, MockDatabase, Transaction};
use serde_json::json;

use crate::config::Config;

use super::super::tests::get_service_mock;
use super::*;

#[tokio::test]
async fn test_get() {
// Create MockDatabase with mock query results
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([
// First query result - select user itself
vec![get_service_mock("1".into())],
])
.into_connection();
let config = Config::default();
assert_eq!(
get(&config, &db, "1").await.unwrap().unwrap(),
Service {
id: "1".into(),
r#type: Some("type".into()),
enabled: true,
name: Some("srv".into()),
extra: Some(json!({"name": "srv"})),
}
);

// Checking transaction log
assert_eq!(
db.into_transaction_log(),
[Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service" WHERE "service"."id" = $1 LIMIT $2"#,
["1".into(), 1u64.into()]
),]
);
}
}
107 changes: 107 additions & 0 deletions src/catalog/backends/sql/service/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

use sea_orm::DatabaseConnection;
use sea_orm::entity::*;
use sea_orm::query::*;

use crate::catalog::backends::error::{CatalogDatabaseError, db_err};
use crate::catalog::types::*;
use crate::config::Config;
use crate::db::entity::{prelude::Service as DbService, service as db_service};

pub async fn list(
_conf: &Config,
db: &DatabaseConnection,
params: &ServiceListParameters,
) -> Result<Vec<Service>, CatalogDatabaseError> {
let mut select = DbService::find();

if let Some(typ) = &params.r#type {
select = select.filter(db_service::Column::Type.eq(typ));
}

let db_services: Vec<db_service::Model> = select
.all(db)
.await
.map_err(|err| db_err(err, "fetching services"))?;
let results: Result<Vec<Service>, _> = db_services
.into_iter()
.map(TryInto::<Service>::try_into)
.collect();

results
}

#[cfg(test)]
mod tests {
use sea_orm::{DatabaseBackend, MockDatabase, Transaction};
use serde_json::json;

use crate::config::Config;

use super::super::tests::get_service_mock;
use super::*;

#[tokio::test]
async fn test_list() {
// Create MockDatabase with mock query results
let db = MockDatabase::new(DatabaseBackend::Postgres)
.append_query_results([vec![get_service_mock("1".into())]])
.append_query_results([vec![get_service_mock("1".into())]])
.into_connection();
let config = Config::default();
assert!(
list(&config, &db, &ServiceListParameters::default())
.await
.is_ok()
);
assert_eq!(
list(
&config,
&db,
&ServiceListParameters {
r#type: Some("type".into()),
name: Some("service_name".into())
}
)
.await
.unwrap(),
vec![Service {
id: "1".into(),
r#type: Some("type".into()),
enabled: true,
name: Some("srv".into()),
extra: Some(json!({"name": "srv"})),
}]
);

// Checking transaction log
assert_eq!(
db.into_transaction_log(),
[
Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service""#,
[]
),
Transaction::from_sql_and_values(
DatabaseBackend::Postgres,
r#"SELECT "service"."id", "service"."type", "service"."enabled", "service"."extra" FROM "service" WHERE "service"."type" = $1"#,
["type".into()]
),
]
);
}
}
Loading