add event-data property filtering

This commit is contained in:
Francis Cao committed 2026-04-24 11:39:40 -07:00
1 parent cf2ab575ba
commit 77dda7268e
25 files changed
+748 -122

No files matched your search

+76 -2
View File
@@ -1,10 +1,10 @@
import { CLICKHOUSE } from '@/lib/db';
import { type ClickHouseClient, createClient } from '@clickhouse/client';
import { formatInTimeZone } from 'date-fns-tz';
import debug from 'debug';
import { CLICKHOUSE } from '@/lib/db';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from './constants';
import { filtersObjectToArray } from './params';
import type { QueryFilters, QueryOptions } from './types';
import type { EventPropertyFilter, QueryFilters, QueryOptions } from './types';
export const CLICKHOUSE_DATE_FORMATS = {
utc: '%Y-%m-%dT%H:%i:%SZ',
@@ -235,6 +235,79 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
};
}
function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
sql: string;
params: Record<string, any>;
} {
if (!filters.length) return { sql: '', params: {} };
const parts: string[] = [];
const params: Record<string, any> = {};
filters.forEach(({ propertyName, dataType, operator, value }, i) => {
const keyParam = `epf_key_${i}`;
const valParam = `epf_val_${i}`;
params[keyParam] = propertyName;
const isNumeric = dataType === 2;
const col = isNumeric ? 'number_value' : 'string_value';
let condition: string;
if (isNumeric) {
params[valParam] = parseFloat(value) || 0;
const opMap: Record<string, string> = {
eq: `${col} = {${valParam}:Float64}`,
neq: `${col} != {${valParam}:Float64}`,
gt: `${col} > {${valParam}:Float64}`,
lt: `${col} < {${valParam}:Float64}`,
gte: `${col} >= {${valParam}:Float64}`,
lte: `${col} <= {${valParam}:Float64}`,
};
condition = opMap[operator] ?? `${col} = {${valParam}:Float64}`;
} else if (operator === 'eq' || operator === 'neq') {
const vals = value.split(',').filter(Boolean);
if (!vals.length) return;
params[valParam] = vals;
condition = mapFilter(
col,
operator === 'eq' ? OPERATORS.equals : OPERATORS.notEquals,
valParam,
'String',
);
} else if (operator === 'regex' || operator === 'notRegex') {
if (!value) return;
params[valParam] = value;
condition = mapFilter(
col,
operator === 'regex' ? OPERATORS.regex : OPERATORS.notRegex,
valParam,
'String',
);
} else {
if (!value) return;
params[valParam] = value;
condition = mapFilter(
col,
operator === 'c' ? OPERATORS.contains : OPERATORS.doesNotContain,
valParam,
'String',
);
}
parts.push(`and event_id in (
select event_id
from event_data
where website_id = {websiteId:UUID}
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
and data_key = {${keyParam}:String}
and data_type = ${dataType}
and ${condition}
)`);
});
return { sql: parts.join('\n'), params };
}
async function pagedRawQuery(
query: string,
queryParams: Record<string, any>,
@@ -321,6 +394,7 @@ export default {
getDateSQL,
getSearchSQL,
getFilterQuery,
getEventPropertyFilterQuery,
getUTCString,
parseFilters,
pagedRawQuery,
+29 -1
View File
@@ -1,5 +1,5 @@
import { FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
import type { Filter, QueryFilters, QueryOptions } from '@/lib/types';
import type { EventPropertyFilter, Filter, QueryFilters, QueryOptions } from '@/lib/types';
export function parseFilterValue(param: any) {
if (typeof param === 'string') {
@@ -88,3 +88,31 @@ export function filtersArrayToObject(filters: Filter[]) {
return obj;
}, {});
}
export function parseEventPropertyFilters(query: Record<string, any>): EventPropertyFilter[] {
return Object.entries(query)
.filter(([key]) => /^epf_/.test(key))
.flatMap(([key, val]) => {
const dotIndex = (val as string).indexOf('.');
if (dotIndex < 1) return [];
const withoutPrefix = key.slice(4); // strip "epf_"
const propertyName = withoutPrefix.replace(/\d+$/, ''); // strip trailing index digits
const operator = (val as string).slice(0, dotIndex);
const value = (val as string).slice(dotIndex + 1);
const isNumeric =
['gt', 'lt', 'gte', 'lte'].includes(operator) ||
(['eq', 'neq'].includes(operator) && value !== '' && !Number.isNaN(Number(value)));
return [{ propertyName, dataType: isNumeric ? 2 : 1, operator, value }];
});
}
export function serializeEventPropertyFilters(filters: EventPropertyFilter[]): Record<string, string> {
const counts: Record<string, number> = {};
return Object.fromEntries(
filters.map(f => {
const n = counts[f.propertyName] ?? 0;
counts[f.propertyName] = n + 1;
return [`epf_${f.propertyName}${n > 0 ? n : ''}`, `${f.operator}.${f.value}`];
}),
);
}
+65 -2
View File
@@ -1,10 +1,10 @@
import { PrismaClient } from '@/generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { readReplicas } from '@prisma/extension-read-replicas';
import debug from 'debug';
import { PrismaClient } from '@/generated/prisma/client';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS, SESSION_COLUMNS } from './constants';
import { filtersObjectToArray } from './params';
import type { Operator, QueryFilters, QueryOptions } from './types';
import type { EventPropertyFilter, Operator, QueryFilters, QueryOptions } from './types';
const log = debug('umami:prisma');
@@ -252,6 +252,68 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
};
}
function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
sql: string;
params: Record<string, any>;
} {
if (!filters.length) return { sql: '', params: {} };
const parts: string[] = [];
const params: Record<string, any> = {};
filters.forEach(({ propertyName, dataType, operator, value }, i) => {
const keyParam = `epf_key_${i}`;
const valParam = `epf_val_${i}`;
params[keyParam] = propertyName;
const isNumeric = dataType === 2;
const col = isNumeric ? 'cast(number_value as decimal)' : 'string_value';
let condition: string;
if (isNumeric) {
params[valParam] = parseFloat(value) || 0;
const opMap: Record<string, string> = {
eq: `${col} = {{${valParam}}}`,
neq: `${col} != {{${valParam}}}`,
gt: `${col} > {{${valParam}}}`,
lt: `${col} < {{${valParam}}}`,
gte: `${col} >= {{${valParam}}}`,
lte: `${col} <= {{${valParam}}}`,
};
condition = opMap[operator] ?? `${col} = {{${valParam}}}`;
} else if (operator === 'eq' || operator === 'neq') {
const vals = value.split(',').filter(Boolean);
if (!vals.length) return;
params[valParam] = vals;
condition =
operator === 'eq'
? `${col} = ANY({{${valParam}::text[]}})`
: `${col} != ALL({{${valParam}::text[]}})`;
} else if (operator === 'regex' || operator === 'notRegex') {
if (!value) return;
params[valParam] = value;
condition = operator === 'regex' ? `${col} ~* {{${valParam}}}` : `${col} !~* {{${valParam}}}`;
} else {
if (!value) return;
params[valParam] = `%${value}%`;
condition =
operator === 'c' ? `${col} ilike {{${valParam}}}` : `${col} not ilike {{${valParam}}}`;
}
parts.push(`and website_event.event_id in (
select website_event_id
from event_data
where website_id = {{websiteId::uuid}}
and created_at between {{startDate}} and {{endDate}}
and data_key = {{${keyParam}}}
and data_type = ${dataType}
and ${condition}
)`);
});
return { sql: parts.join('\n'), params };
}
async function rawQuery(sql: string, data: Record<string, any>, name?: string): Promise<any> {
if (process.env.LOG_QUERY) {
log('QUERY:\n', sql);
@@ -426,6 +488,7 @@ export default {
getDateSQL,
getDateWeeklySQL,
getFilterQuery,
getEventPropertyFilterQuery,
getSearchParameters,
getTimestampDiffSQL,
getSearchSQL,
+4 -4
View File
@@ -1,5 +1,3 @@
import { startOfMonth, subMonths } from 'date-fns';
import { z } from 'zod';
import { checkAuth } from '@/lib/auth';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
import { getAllowedUnits, getMinimumUnit, maxDate, parseDateRange } from '@/lib/date';
@@ -8,6 +6,8 @@ import { filtersArrayToObject } from '@/lib/params';
import { badRequest, unauthorized } from '@/lib/response';
import type { QueryFilters } from '@/lib/types';
import { getWebsiteSegment } from '@/queries/prisma';
import { startOfMonth, subMonths } from 'date-fns';
import { z } from 'zod';
export async function parseRequest(
request: Request,
@@ -30,9 +30,9 @@ export async function parseRequest(
} else if (isGet) {
query = result.data;
// Re-add suffixed filter params (e.g., browser1, os2) stripped by Zod schema
// Re-add dynamic params stripped by Zod schema: suffixed filter params (browser1, os2)
for (const key of Object.keys(rawQuery)) {
if (/\d+$/.test(key) && !(key in query)) {
if ((/\d+$/.test(key) || /^epf_/.test(key)) && !(key in query)) {
query[key] = rawQuery[key];
}
}
+7
View File
@@ -30,6 +30,13 @@ export interface Auth {
};
}
export interface EventPropertyFilter {
propertyName: string;
dataType: number;
operator: string;
value: string;
}
export interface Filter {
name: string;
operator: Operator;