Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: breakdowns on cohorts

Carl-Gerhard Lindesvärdda3c9b288dae
diff --git a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
index e0adc4d53..9cd2e37aa 100644
--- a/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
+++ b/apps/start/src/components/report/sidebar/PropertiesCombobox.tsx
@@ -40,6 +40,7 @@ interface PropertiesComboboxProps {
include?: string[];
mode?: 'events' | 'profile';
showCohorts?: boolean;
+ isBreakdown?: boolean;
}
function SearchHeader({
@@ -76,6 +77,7 @@ export function PropertiesCombobox({
exclude = [],
include = [],
showCohorts = false,
+ isBreakdown = false,
}: PropertiesComboboxProps) {
const { projectId } = useAppParams();
const trpc = useTRPC();
@@ -209,7 +211,15 @@ export function PropertiesCombobox({
className="group justify-between gap-2"
onClick={(e) => {
e.preventDefault();
- handleStateChange('cohort');
+ if (isBreakdown) {
+ handleSelect({
+ value: 'cohort',
+ label: 'Cohorts',
+ description: 'All cohorts',
+ });
+ } else {
+ handleStateChange('cohort');
+ }
}}
>
Cohorts
diff --git a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
index e5c7ec92e..5ebc1c23f 100644
--- a/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
+++ b/apps/start/src/components/report/sidebar/ReportBreakdowns.tsx
@@ -39,6 +39,8 @@ export function ReportBreakdowns() {
<div className="flex items-center gap-2 p-2 px-4">
<ColorSquare>{index}</ColorSquare>
<PropertiesCombobox
+ isBreakdown
+ showCohorts
onSelect={(action) => {
dispatch(
changeBreakdown({
@@ -58,7 +60,7 @@ export function ReportBreakdowns() {
>
<div className="row w-full gap-2 items-center">
<SplitIcon className="size-4" />
- {item.name}
+ {item.name === 'cohort' ? 'Cohorts' : item.name}
</div>
<ChevronsUpDownIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
@@ -72,6 +74,7 @@ export function ReportBreakdowns() {
<PropertiesCombobox
showCohorts
+ isBreakdown
onSelect={(action) => {
dispatch(
addBreakdown({
diff --git a/packages/db/src/services/chart.service.ts b/packages/db/src/services/chart.service.ts
index 626b6bd9d..7a4aa2cf0 100644
--- a/packages/db/src/services/chart.service.ts
+++ b/packages/db/src/services/chart.service.ts
@@ -71,6 +71,41 @@ export function extractCohortId(breakdownName: string): string | null {
return null;
}
+export function isAllCohortsBreakdown(breakdownName: string): boolean {
+ return breakdownName === 'cohort';
+}
+
+export async function fetchProjectCohorts(
+ projectId: string,
+): Promise<CohortMetadata[]> {
+ return db.cohort.findMany({
+ where: { projectId },
+ select: { id: true, name: true },
+ });
+}
+
+export function buildAllCohortsMembershipQuery(
+ projectId: string,
+): string {
+ return `
+ SELECT profile_id, cohort_id
+ FROM ${TABLE_NAMES.cohort_members} FINAL
+ WHERE project_id = ${sqlstring.escape(projectId)}
+ `;
+}
+
+export function buildAllCohortsLabelExpr(
+ cohorts: CohortMetadata[],
+ alias = '_all_cohorts',
+): string {
+ if (cohorts.length === 0) {
+ return "'Unknown'";
+ }
+ const ids = cohorts.map((c) => sqlstring.escape(c.id)).join(', ');
+ const names = cohorts.map((c) => sqlstring.escape(c.name)).join(', ');
+ return `transform(${alias}.cohort_id, [${ids}], [${names}], 'Unknown')`;
+}
+
export function collectCohortIds(
filters: IChartEventFilter[],
breakdowns: IChartBreakdown[],
@@ -243,9 +278,24 @@ export async function getChartSql({
with: addCte,
} = createSqlBuilder();
+ const hasAllCohortsBreakdown = breakdowns.some((b) =>
+ isAllCohortsBreakdown(b.name),
+ );
+ const allCohorts = hasAllCohortsBreakdown
+ ? await fetchProjectCohorts(projectId)
+ : [];
+
const cohortIds = collectCohortIds(event.filters, breakdowns);
const cohortMetadata = await fetchCohortsMetadata(cohortIds);
+ // Add CTE + JOIN for "all cohorts" breakdown
+ if (hasAllCohortsBreakdown) {
+ addCte('_all_cohorts', buildAllCohortsMembershipQuery(projectId));
+ sb.joins._all_cohorts =
+ 'INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id';
+ }
+
+ // Add individual cohort CTEs (for single-cohort filters)
for (const cohortId of cohortIds) {
addCte(
getCohortCteName(cohortId),
@@ -426,12 +476,17 @@ export async function getChartSql({
breakdowns.forEach((breakdown, index) => {
// Breakdowns start at label_1 (label_0 is reserved for event name)
const key = `label_${index + 1}`;
- const breakdownCohortId = extractCohortId(breakdown.name);
- const breakdownCohortName = breakdownCohortId
- ? cohortMetadata.get(breakdownCohortId)?.name
- : undefined;
- sb.select[key] =
- `${getSelectPropertyKey(breakdown.name, projectId, breakdownCohortId ?? undefined, breakdownCohortName)} as ${key}`;
+
+ if (isAllCohortsBreakdown(breakdown.name)) {
+ sb.select[key] = `${buildAllCohortsLabelExpr(allCohorts)} as ${key}`;
+ } else {
+ const breakdownCohortId = extractCohortId(breakdown.name);
+ const breakdownCohortName = breakdownCohortId
+ ? cohortMetadata.get(breakdownCohortId)?.name
+ : undefined;
+ sb.select[key] =
+ `${getSelectPropertyKey(breakdown.name, projectId, breakdownCohortId ?? undefined, breakdownCohortName)} as ${key}`;
+ }
sb.groupBy[key] = `${key}`;
});
@@ -496,6 +551,10 @@ export async function getChartSql({
const inlineCohortJoinsSql = cohortIds
.map((id) => buildInlineCohortJoin(id, projectId, 'e'))
.join(' ');
+ // Inline all-cohorts join for use in _uc CTE (can't reference CTEs from nested CTEs)
+ const inlineAllCohortsJoin = hasAllCohortsBreakdown
+ ? `INNER JOIN (${buildAllCohortsMembershipQuery(projectId)}) AS _all_cohorts ON _all_cohorts.profile_id = e.profile_id `
+ : '';
if (breakdowns.length > 0) {
// Pre-compute unique counts per breakdown group in a CTE, then JOIN it.
@@ -504,6 +563,9 @@ export async function getChartSql({
// which resolve in the subquery's scope, making the condition a tautology.
// 2. Correlated subqueries aren't supported on distributed/remote tables.
const ucSelectParts: string[] = breakdowns.map((breakdown, index) => {
+ if (isAllCohortsBreakdown(breakdown.name)) {
+ return `${buildAllCohortsLabelExpr(allCohorts)} as _uc_label_${index + 1}`;
+ }
const bId = extractCohortId(breakdown.name);
const bName = bId ? cohortMetadata.get(bId)?.name : undefined;
const propertyKey = getSelectPropertyKey(
@@ -524,11 +586,14 @@ export async function getChartSql({
addCte(
'_uc',
- `SELECT ${ucSelectParts.join(', ')} FROM ${TABLE_NAMES.events} e ${subqueryGroupJoins}${profilesJoinRef ? `${profilesJoinRef} ` : ''}${inlineCohortJoinsSql ? `${inlineCohortJoinsSql} ` : ''}${ucWhere} GROUP BY ${ucGroupByParts.join(', ')}`
+ `SELECT ${ucSelectParts.join(', ')} FROM ${TABLE_NAMES.events} e ${subqueryGroupJoins}${profilesJoinRef ? `${profilesJoinRef} ` : ''}${inlineCohortJoinsSql ? `${inlineCohortJoinsSql} ` : ''}${inlineAllCohortsJoin}${ucWhere} GROUP BY ${ucGroupByParts.join(', ')}`
);
const ucJoinConditions = breakdowns
.map((b, index) => {
+ if (isAllCohortsBreakdown(b.name)) {
+ return `_uc._uc_label_${index + 1} = ${buildAllCohortsLabelExpr(allCohorts)}`;
+ }
const bId = extractCohortId(b.name);
const bName = bId ? cohortMetadata.get(bId)?.name : undefined;
const propertyKey = getSelectPropertyKey(
@@ -574,9 +639,24 @@ export async function getAggregateChartSql({
}) {
const { sb, join, getJoins, with: addCte, getSql } = createSqlBuilder();
+ const hasAllCohortsBreakdown = breakdowns.some((b) =>
+ isAllCohortsBreakdown(b.name),
+ );
+ const allCohorts = hasAllCohortsBreakdown
+ ? await fetchProjectCohorts(projectId)
+ : [];
+
const cohortIds = collectCohortIds(event.filters, breakdowns);
const cohortMetadata = await fetchCohortsMetadata(cohortIds);
+ // Add CTE + JOIN for "all cohorts" breakdown
+ if (hasAllCohortsBreakdown) {
+ addCte('_all_cohorts', buildAllCohortsMembershipQuery(projectId));
+ sb.joins._all_cohorts =
+ 'INNER JOIN _all_cohorts ON _all_cohorts.profile_id = e.profile_id';
+ }
+
+ // Add individual cohort CTEs (for single-cohort filters)
for (const cohortId of cohortIds) {
addCte(
getCohortCteName(cohortId),
@@ -718,12 +798,17 @@ export async function getAggregateChartSql({
breakdowns.forEach((breakdown, index) => {
// Breakdowns start at label_1 (label_0 is reserved for event name)
const key = `label_${index + 1}`;
- const breakdownCohortId = extractCohortId(breakdown.name);
- const breakdownCohortName = breakdownCohortId
- ? cohortMetadata.get(breakdownCohortId)?.name
- : undefined;
- sb.select[key] =
- `${getSelectPropertyKey(breakdown.name, projectId, breakdownCohortId ?? undefined, breakdownCohortName)} as ${key}`;
+
+ if (isAllCohortsBreakdown(breakdown.name)) {
+ sb.select[key] = `${buildAllCohortsLabelExpr(allCohorts)} as ${key}`;
+ } else {
+ const breakdownCohortId = extractCohortId(breakdown.name);
+ const breakdownCohortName = breakdownCohortId
+ ? cohortMetadata.get(breakdownCohortId)?.name
+ : undefined;
+ sb.select[key] =
+ `${getSelectPropertyKey(breakdown.name, projectId, breakdownCohortId ?? undefined, breakdownCohortName)} as ${key}`;
+ }
sb.groupBy[key] = `${key}`;
});