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

fix: Metadata filtering #56

Merged
merged 5 commits into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export const UpsertMetadataGroupDialog: React.FC<{

<DialogContent>
<DialogHeader>
<DialogTitle>{create ? "Create" : "Edit"} Label Group</DialogTitle>
<DialogTitle>{create ? "Create" : "Edit"} Metadata Group</DialogTitle>
</DialogHeader>

<Form {...form}>
Expand Down Expand Up @@ -219,7 +219,7 @@ export const UpsertMetadataGroupDialog: React.FC<{
setInput("");
}}
>
Add Label
Add Key
</Button>
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import {

export const CombinationsTable: React.FC<{
workspaceSlug: string;
groups: Array<{ targets: number } & Record<string, string>>;
groups: Array<{
targets: number;
metadata: Record<string, string>;
}>;
}> = ({ workspaceSlug, groups }) => {
const router = useRouter();
return (
Expand All @@ -26,21 +29,21 @@ export const CombinationsTable: React.FC<{
</TableHeader>
<TableBody>
{groups.map((group, idx) => {
const { targets, ...combinations } = group;
const { targets, metadata } = group;
return (
<TableRow
key={idx}
className="cursor-pointer"
onClick={() =>
router.push(
`/${workspaceSlug}/targets?combinations=${encodeURIComponent(
JSON.stringify(combinations),
JSON.stringify(metadata),
)}`,
)
}
>
<TableCell>
{Object.entries(combinations).map(([key, value]) => (
{Object.entries(metadata).map(([key, value]) => (
<div key={key} className="text-nowrap font-mono text-xs">
<span className="text-red-400">{key}:</span>{" "}
<span className="text-green-300">{value}</span>
Expand Down
21 changes: 14 additions & 7 deletions apps/webservice/src/app/[workspaceSlug]/(targets)/targets/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import type { ComparisonCondition } from "@ctrlplane/validators/targets";
import { useEffect, useMemo, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useSearchParams } from "next/navigation";
import { capitalCase } from "change-case";
import _ from "lodash";
import { TbCategory, TbTag, TbTarget, TbX } from "react-icons/tb";
Expand Down Expand Up @@ -38,7 +38,6 @@ export default function TargetsPage({
const workspace = api.workspace.bySlug.useQuery(params.workspaceSlug);
const { filters, removeFilter, addFilters, clearFilters, updateFilter } =
useFilters<TargetFilter>();
const router = useRouter();
const searchParams = useSearchParams();
const combination: Record<string, string> = useMemo(() => {
const combinations = searchParams.get("combinations");
Expand All @@ -47,11 +46,19 @@ export default function TargetsPage({

useEffect(() => {
if (Object.keys(combination).length === 0) return;
const metadataFilter = filters.find((f) => f.key === "metadata");
if (!_.isEqual(metadataFilter?.value, combination))
addFilters([{ key: "metadata", value: combination }]);
router.replace(`/${params.workspaceSlug}/targets`);
}, [combination, filters, addFilters, router, params.workspaceSlug]);

console.log("combination", { combination });
const cond = {
operator: "and" as const,
conditions: Object.entries(combination).map(([key, value]) => ({
key,
value,
operator: "equals" as const,
})),
};
if (!filters.some((f) => f.key === "metadata" && _.isEqual(f.value, cond)))
addFilters([{ key: "metadata", value: cond }]);
}, [combination, filters, addFilters, params.workspaceSlug]);

const targetsAll = api.target.byWorkspaceId.list.useQuery(
{ workspaceId: workspace.data?.id ?? "" },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ export const CreateReleaseDialog: React.FC<{
<FormItem className="col-span-1">
<Select value={value} onValueChange={onChange}>
<SelectTrigger className="h-8 text-sm">
<SelectValue placeholder="Label Group" />
<SelectValue placeholder="Metadata Group" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
Expand Down
35 changes: 22 additions & 13 deletions packages/api/src/router/target-metadata-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,29 +65,38 @@ export const targetMetadataGroupRouter = createTRPCRouter({

if (group == null) throw new Error("Group not found");

const groups = await ctx.db
const targetMetadataAgg = ctx.db
.select({
targets: sql<number>`count(distinct ${target.id})`.mapWith(Number),
...Object.fromEntries(
group.keys.map((k) => [
k,
sql.raw(`"target_metadata"."value"`).as(k),
]),
),
id: target.id,
metadata: sql<Record<string, string>>`jsonb_object_agg(
${targetMetadata}.key,
${targetMetadata}.value
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

${targetMetadata.key}

work?

)`.as("metadata"),
})
.from(target)
.innerJoin(targetMetadata, eq(targetMetadata.targetId, target.id))
.where(
.leftJoin(
targetMetadata,
and(
eq(target.id, targetMetadata.targetId),
inArray(targetMetadata.key, group.keys),
eq(target.workspaceId, group.workspaceId),
),
)
.groupBy(targetMetadata.value);
.where(eq(target.workspaceId, group.workspaceId))
.groupBy(target.id)
.as("target_metadata_agg");

const groups = await ctx.db
.with(targetMetadataAgg)
.select({
metadata: targetMetadataAgg.metadata,
targets: sql<number>`COUNT(*)`.as("targets"),
})
.from(targetMetadataAgg)
.groupBy(targetMetadataAgg.metadata);

return {
...group,
groups: groups as Array<{ targets: number } & Record<string, string>>,
groups,
};
}),

Expand Down
4 changes: 0 additions & 4 deletions packages/db/src/schema/target-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,4 @@ export const targetMetadataGroup = pgTable("target_metadata_group", {
keys: text("keys").array().notNull(),
});

export const targetMetadataGroupKeys = pgTable("target_metadata_group_keys", {
id: uuid("id").primaryKey().defaultRandom(),
});

export type TargetMetadataGroup = InferSelectModel<typeof targetMetadataGroup>;
Loading