Skip to content
This repository has been archived by the owner on Oct 3, 2024. It is now read-only.

Commit

Permalink
Fix filtering for multiple targetValues (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
pohlm01 authored Oct 1, 2024
1 parent 42425db commit 564d483
Show file tree
Hide file tree
Showing 12 changed files with 103 additions and 35 deletions.

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

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

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

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

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

28 changes: 28 additions & 0 deletions fixtures/openadr_testsuite_user.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

INSERT INTO "user" (id, reference, description, created, modified)
VALUES ('bl_user',
'bl_test_user',
null,
now(),
now());

-- secret: 1001
INSERT INTO user_credentials (user_id, client_id, client_secret)
VALUES ('bl_user', 'bl_client',
'$argon2id$v=19$m=16,t=2,p=1$YmJkMTJrU0ptMVprYVJLSQ$mu1Fbbt5PzBsE/dJevKazw');

INSERT INTO any_business_user (user_id) VALUES ('bl_user');

INSERT INTO "user" (id, reference, description, created, modified)
VALUES ('ven_user',
'ven_test_user',
null,
now(),
now());

-- secret: 999
INSERT INTO user_credentials (user_id, client_id, client_secret)
VALUES ('ven_user', 'ven_client',
'$argon2id$v=19$m=16,t=2,p=1$RGhDTmVkbEl5cEZDY0Fubg$qPtSCpK6Z5XKQkOLHC/+qg');

INSERT INTO user_ven VALUES ('ven-1', 'ven_user');
9 changes: 6 additions & 3 deletions openadr-vtn/src/api/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use axum::{
Json,
};
use serde::{Deserialize, Serialize};
use tracing::{info, trace};
use tracing::{info, instrument};
use validator::Validate;

use openadr_wire::{
Expand All @@ -23,18 +23,18 @@ use crate::{
jwt::{BusinessUser, User, VENUser},
};

#[instrument(skip(user, report_source))]
pub async fn get_all(
State(report_source): State<Arc<dyn ReportCrud>>,
ValidatedQuery(query_params): ValidatedQuery<QueryParams>,
User(user): User,
) -> AppResponse<Vec<Report>> {
trace!(?query_params);

let reports = report_source.retrieve_all(&query_params, &user).await?;

Ok(Json(reports))
}

#[instrument(skip(user, report_source))]
pub async fn get(
State(report_source): State<Arc<dyn ReportCrud>>,
Path(id): Path<ReportId>,
Expand All @@ -44,6 +44,7 @@ pub async fn get(
Ok(Json(report))
}

#[instrument(skip(user, report_source))]
pub async fn add(
State(report_source): State<Arc<dyn ReportCrud>>,
VENUser(user): VENUser,
Expand All @@ -56,6 +57,7 @@ pub async fn add(
Ok((StatusCode::CREATED, Json(report)))
}

#[instrument(skip(user, report_source))]
pub async fn edit(
State(report_source): State<Arc<dyn ReportCrud>>,
Path(id): Path<ReportId>,
Expand All @@ -69,6 +71,7 @@ pub async fn edit(
Ok(Json(report))
}

#[instrument(skip(user, report_source))]
pub async fn delete(
State(report_source): State<Arc<dyn ReportCrud>>,
// TODO this contradicts the spec, which says that only VENs have write access
Expand Down
6 changes: 5 additions & 1 deletion openadr-vtn/src/data_source/postgres/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,15 @@ impl Crud for PgEventStorage {
JOIN program p on p.id = e.program_id
LEFT JOIN ven_program vp ON p.id = vp.program_id
LEFT JOIN ven v ON v.id = vp.ven_id
LEFT JOIN LATERAL (
SELECT e.id as e_id,
json_array(jsonb_array_elements(e.targets)) <@ $5::jsonb AS target_test )
ON e.id = e_id
WHERE ($1::text IS NULL OR e.program_id like $1)
AND ($2::text[] IS NULL OR e.event_name = ANY($2))
AND ($3::text[] IS NULL OR p.program_name = ANY($3))
AND ($4::text[] IS NULL OR v.ven_name = ANY($4))
AND ($5::jsonb = '[]'::jsonb OR $5::jsonb <@ e.targets)
AND ($5::jsonb = '[]'::jsonb OR target_test)
AND (
($6 AND (vp.ven_id IS NULL OR vp.ven_id = ANY($7)))
OR
Expand Down
6 changes: 5 additions & 1 deletion openadr-vtn/src/data_source/postgres/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,10 +332,14 @@ impl Crud for PgProgramStorage {
LEFT JOIN event e ON p.id = e.program_id
LEFT JOIN ven_program vp ON p.id = vp.program_id
LEFT JOIN ven v ON v.id = vp.ven_id
LEFT JOIN LATERAL (
SELECT p.id as p_id,
json_array(jsonb_array_elements(p.targets)) <@ $4::jsonb AS target_test )
ON p.id = p_id
WHERE ($1::text[] IS NULL OR e.event_name = ANY($1))
AND ($2::text[] IS NULL OR p.program_name = ANY($2))
AND ($3::text[] IS NULL OR v.ven_name = ANY($3))
AND ($4::jsonb = '[]'::jsonb OR $4::jsonb <@ p.targets)
AND ($4::jsonb = '[]'::jsonb OR target_test)
AND (NOT $5 OR v.id IS NULL OR v.id = ANY($6)) -- Filter for VEN ids
GROUP BY p.id
OFFSET $7 LIMIT $8
Expand Down
55 changes: 38 additions & 17 deletions openadr-vtn/src/data_source/postgres/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use openadr_wire::{
Report,
};
use sqlx::PgPool;
use tracing::error;
use tracing::{error, info, trace};

#[async_trait]
impl ReportCrud for PgReportStorage {}
Expand Down Expand Up @@ -105,13 +105,14 @@ impl Crud for PgReportStorage {
.map(|id| id.id)
.collect::<Vec<_>>();

if !user
.ven_ids()
.into_iter()
.any(|user_ven| permitted_vens.contains(&user_ven.to_string()))
if !permitted_vens.is_empty()
&& !user
.ven_ids()
.into_iter()
.any(|user_ven| permitted_vens.contains(&user_ven.to_string()))
{
Err(AppError::NotFound)?
};
}

let program_id = sqlx::query_as!(
PgId,
Expand All @@ -129,7 +130,7 @@ impl Crud for PgReportStorage {
));
}

Ok(sqlx::query_as!(
let report: Report = sqlx::query_as!(
PostgresReport,
r#"
INSERT INTO report (id, created_date_time, modification_date_time, program_id, event_id, client_name, report_name, payload_descriptors, resources)
Expand All @@ -145,7 +146,11 @@ impl Crud for PgReportStorage {
)
.fetch_one(&self.db)
.await?
.try_into()?)
.try_into()?;

info!(report_id = report.id.as_str(), "created report");

Ok(report)
}

async fn retrieve(
Expand All @@ -155,7 +160,7 @@ impl Crud for PgReportStorage {
) -> Result<Self::Type, Self::Error> {
let business_ids = extract_business_ids(user);

Ok(sqlx::query_as!(
let report: Report = sqlx::query_as!(
PostgresReport,
r#"
SELECT r.*
Expand All @@ -173,7 +178,11 @@ impl Crud for PgReportStorage {
)
.fetch_one(&self.db)
.await?
.try_into()?)
.try_into()?;

trace!(report_id = report.id.as_str(), "retrieved report");

Ok(report)
}

async fn retrieve_all(
Expand All @@ -183,7 +192,7 @@ impl Crud for PgReportStorage {
) -> Result<Vec<Self::Type>, Self::Error> {
let business_ids = extract_business_ids(user);

Ok(sqlx::query_as!(
let reports = sqlx::query_as!(
PostgresReport,
r#"
SELECT r.*
Expand All @@ -193,7 +202,7 @@ impl Crud for PgReportStorage {
WHERE ($1::text IS NULL OR $1 like r.program_id)
AND ($2::text IS NULL OR $2 like r.event_id)
AND ($3::text IS NULL OR $3 like r.client_name)
AND (NOT $4 OR v.ven_id IS NULL OR v.ven_id = ANY($5))
AND (NOT $4 OR v.ven_id IS NULL OR v.ven_id = ANY($5))
AND ($6::text[] IS NULL OR p.business_id = ANY($6))
LIMIT $7 OFFSET $8
"#,
Expand All @@ -210,7 +219,11 @@ impl Crud for PgReportStorage {
.await?
.into_iter()
.map(TryInto::try_into)
.collect::<Result<_, _>>()?)
.collect::<Result<Vec<Report>, _>>()?;

trace!("retrieved {} reports", reports.len());

Ok(reports)
}

async fn update(
Expand All @@ -220,7 +233,7 @@ impl Crud for PgReportStorage {
user: &Self::PermissionFilter,
) -> Result<Self::Type, Self::Error> {
let business_ids = extract_business_ids(user);
Ok(sqlx::query_as!(
let report: Report = sqlx::query_as!(
PostgresReport,
r#"
UPDATE report r
Expand Down Expand Up @@ -252,7 +265,11 @@ impl Crud for PgReportStorage {
)
.fetch_one(&self.db)
.await?
.try_into()?)
.try_into()?;

info!(report_id = report.id.as_str(), "updated report");

Ok(report)
}

async fn delete(
Expand All @@ -262,7 +279,7 @@ impl Crud for PgReportStorage {
) -> Result<Self::Type, Self::Error> {
let business_ids = extract_business_ids(user);

Ok(sqlx::query_as!(
let report: Report = sqlx::query_as!(
PostgresReport,
r#"
DELETE FROM report r
Expand All @@ -277,6 +294,10 @@ impl Crud for PgReportStorage {
)
.fetch_one(&self.db)
.await?
.try_into()?)
.try_into()?;

info!(report_id = report.id.as_str(), "deleted report");

Ok(report)
}
}
6 changes: 5 additions & 1 deletion openadr-vtn/src/data_source/postgres/resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,13 @@ impl VenScopedCrud for PgResourceStorage {
r.attributes,
r.targets
FROM resource r
LEFT JOIN LATERAL (
SELECT r.id as r_id,
json_array(jsonb_array_elements(r.targets)) <@ $3::jsonb AS target_test )
ON r.id = r_id
WHERE r.ven_id = $1
AND ($2::text[] IS NULL OR r.resource_name = ANY($2))
AND ($3::jsonb = '[]'::jsonb OR $3::jsonb <@ r.targets)
AND ($3::jsonb = '[]'::jsonb OR target_test)
OFFSET $4 LIMIT $5
"#,
ven_id.as_str(),
Expand Down
Loading

0 comments on commit 564d483

Please sign in to comment.