1 parent
78346795eb
commit
d05d9c4f34
73 files changed
+1262
-161
No files matched your search
+261
-2
@@ -234,11 +234,25 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
|
||||
const cohortFilters = Object.fromEntries(
|
||||
Object.entries(filters).filter(([key]) => key.startsWith('cohort_')),
|
||||
);
|
||||
const {
|
||||
sql: eventPropertyFilterQuery,
|
||||
params: eventPropertyFilterParams,
|
||||
} = getEventPropertyFilterQuery((filters as QueryFilters).eventPropertyFilters, filters.timezone);
|
||||
const {
|
||||
sql: sessionPropertyFilterQuery,
|
||||
params: sessionPropertyFilterParams,
|
||||
} = getSessionPropertyFilterQuery((filters as QueryFilters).sessionPropertyFilters, filters.timezone);
|
||||
|
||||
return {
|
||||
filterQuery: getFilterQuery(filters, options),
|
||||
filterQuery: [getFilterQuery(filters, options), eventPropertyFilterQuery, sessionPropertyFilterQuery]
|
||||
.filter(Boolean)
|
||||
.join('\n'),
|
||||
dateQuery: getDateQuery(filters),
|
||||
queryParams: getQueryParams(filters),
|
||||
queryParams: {
|
||||
...getQueryParams(filters),
|
||||
...eventPropertyFilterParams,
|
||||
...sessionPropertyFilterParams,
|
||||
},
|
||||
cohortQuery: getCohortQuery(cohortFilters),
|
||||
excludeBounceQuery: getExcludeBounceQuery(filters),
|
||||
};
|
||||
@@ -368,6 +382,251 @@ function getPropertyFilterQuery(
|
||||
return { sql: parts.join('\n'), params };
|
||||
}
|
||||
|
||||
function getEventPropertyFilterQuery(
|
||||
filters: PropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
if (!filters.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
const clauses: string[] = [];
|
||||
const keyRefs: string[] = [];
|
||||
const params: Record<string, any> = {};
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, index) => {
|
||||
const keyParam = `epf_key_${index}`;
|
||||
const valParam = `epf_val_${index}`;
|
||||
params[keyParam] = propertyName;
|
||||
keyRefs.push(`{${keyParam}:String}`);
|
||||
|
||||
let condition: string;
|
||||
|
||||
switch (dataType) {
|
||||
case DATA_TYPE.number: {
|
||||
const col = 'number_value';
|
||||
params[valParam] = parseFloat(value) || 0;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.equals]: `${col} = {${valParam}:Float64}`,
|
||||
[OPERATORS.notEquals]: `${col} != {${valParam}:Float64}`,
|
||||
[OPERATORS.greaterThan]: `${col} > {${valParam}:Float64}`,
|
||||
[OPERATORS.lessThan]: `${col} < {${valParam}:Float64}`,
|
||||
[OPERATORS.greaterThanEquals]: `${col} >= {${valParam}:Float64}`,
|
||||
[OPERATORS.lessThanEquals]: `${col} <= {${valParam}:Float64}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${col} = {${valParam}:Float64}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.date: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
const dateCol = timezone
|
||||
? `toDate(toTimezone(date_value, {timezone:String}))`
|
||||
: `toDate(toTimezone(date_value, 'UTC'))`;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.before]: `${dateCol} < {${valParam}:Date}`,
|
||||
[OPERATORS.after]: `${dateCol} > {${valParam}:Date}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${dateCol} = {${valParam}:Date}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.array: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `has(JSONExtract(ifNull(string_value, '[]'), 'Array(String)'), {${valParam}:String})`
|
||||
: `not has(JSONExtract(ifNull(string_value, '[]'), 'Array(String)'), {${valParam}:String})`;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const col = 'string_value';
|
||||
|
||||
if (EQUALITY_OPERATORS.includes(operator)) {
|
||||
const vals = value.split(',').filter(Boolean);
|
||||
|
||||
if (!vals.length) return;
|
||||
|
||||
params[valParam] = vals;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.equals ? OPERATORS.equals : OPERATORS.notEquals,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
} else if (REGEX_OPERATORS.includes(operator)) {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.regex ? OPERATORS.regex : OPERATORS.notRegex,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
} else {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.contains ? OPERATORS.contains : OPERATORS.doesNotContain,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
clauses.push(
|
||||
`max(if(data_key = {${keyParam}:String} and data_type = ${dataType} and ${condition}, 1, 0)) = 1`,
|
||||
);
|
||||
});
|
||||
|
||||
if (!clauses.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
return {
|
||||
sql: `and website_event.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 in (${keyRefs.join(', ')})
|
||||
group by event_id
|
||||
having ${clauses.join('\n and ')}
|
||||
)`,
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
function getSessionPropertyFilterQuery(
|
||||
filters: PropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
if (!filters.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
const clauses: string[] = [];
|
||||
const keyRefs: string[] = [];
|
||||
const params: Record<string, any> = {};
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, index) => {
|
||||
const keyParam = `spf_key_${index}`;
|
||||
const valParam = `spf_val_${index}`;
|
||||
params[keyParam] = propertyName;
|
||||
keyRefs.push(`{${keyParam}:String}`);
|
||||
|
||||
let condition: string;
|
||||
|
||||
switch (dataType) {
|
||||
case DATA_TYPE.number: {
|
||||
const col = 'number_value';
|
||||
params[valParam] = parseFloat(value) || 0;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.equals]: `${col} = {${valParam}:Float64}`,
|
||||
[OPERATORS.notEquals]: `${col} != {${valParam}:Float64}`,
|
||||
[OPERATORS.greaterThan]: `${col} > {${valParam}:Float64}`,
|
||||
[OPERATORS.lessThan]: `${col} < {${valParam}:Float64}`,
|
||||
[OPERATORS.greaterThanEquals]: `${col} >= {${valParam}:Float64}`,
|
||||
[OPERATORS.lessThanEquals]: `${col} <= {${valParam}:Float64}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${col} = {${valParam}:Float64}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.date: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
const dateCol = timezone
|
||||
? `toDate(toTimezone(date_value, {timezone:String}))`
|
||||
: `toDate(toTimezone(date_value, 'UTC'))`;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.before]: `${dateCol} < {${valParam}:Date}`,
|
||||
[OPERATORS.after]: `${dateCol} > {${valParam}:Date}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${dateCol} = {${valParam}:Date}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.array: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `has(JSONExtract(ifNull(string_value, '[]'), 'Array(String)'), {${valParam}:String})`
|
||||
: `not has(JSONExtract(ifNull(string_value, '[]'), 'Array(String)'), {${valParam}:String})`;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const col = 'string_value';
|
||||
|
||||
if (EQUALITY_OPERATORS.includes(operator)) {
|
||||
const vals = value.split(',').filter(Boolean);
|
||||
|
||||
if (!vals.length) return;
|
||||
|
||||
params[valParam] = vals;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.equals ? OPERATORS.equals : OPERATORS.notEquals,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
} else if (REGEX_OPERATORS.includes(operator)) {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.regex ? OPERATORS.regex : OPERATORS.notRegex,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
} else {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition = mapFilter(
|
||||
col,
|
||||
operator === OPERATORS.contains ? OPERATORS.contains : OPERATORS.doesNotContain,
|
||||
valParam,
|
||||
'String',
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
clauses.push(
|
||||
`max(if(data_key = {${keyParam}:String} and data_type = ${dataType} and ${condition}, 1, 0)) = 1`,
|
||||
);
|
||||
});
|
||||
|
||||
if (!clauses.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
return {
|
||||
sql: `and tuple(website_event.website_id, website_event.session_id) in (
|
||||
select website_id, session_id
|
||||
from session_data final
|
||||
where website_id = {websiteId:UUID}
|
||||
and data_key in (${keyRefs.join(', ')})
|
||||
group by website_id, session_id
|
||||
having ${clauses.join('\n and ')}
|
||||
)`,
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
async function pagedRawQuery(
|
||||
query: string,
|
||||
queryParams: Record<string, any>,
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { DATA_TYPE, OPERATORS } from './constants';
|
||||
import {
|
||||
parseSessionPropertyFilters,
|
||||
parseUniversalEventPropertyFilters,
|
||||
serializeSessionPropertyFilters,
|
||||
serializeUniversalEventPropertyFilters,
|
||||
} from './params';
|
||||
|
||||
describe('session property filter params', () => {
|
||||
test('serializes and parses session property filters', () => {
|
||||
const filters = [
|
||||
{
|
||||
propertyName: 'user.id',
|
||||
dataType: DATA_TYPE.string,
|
||||
operator: OPERATORS.equals,
|
||||
value: 'abc.123,xyz',
|
||||
},
|
||||
{
|
||||
propertyName: 'created at',
|
||||
dataType: DATA_TYPE.date,
|
||||
operator: OPERATORS.before,
|
||||
value: '2026-07-01',
|
||||
},
|
||||
];
|
||||
|
||||
const params = serializeSessionPropertyFilters(filters);
|
||||
|
||||
expect(params).toEqual({
|
||||
spf0: '1.eq.user%2Eid.abc.123,xyz',
|
||||
spf1: '4.bf.created%20at.2026-07-01',
|
||||
});
|
||||
expect(parseSessionPropertyFilters(params)).toEqual(filters);
|
||||
});
|
||||
|
||||
test('ignores malformed session property filters', () => {
|
||||
expect(
|
||||
parseSessionPropertyFilters({
|
||||
spf0: 'eq.user%2Eid.value',
|
||||
spf1: '1.unknown.email.value',
|
||||
spf2: '1.eq',
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test('serializes and parses universal event property filters', () => {
|
||||
const filters = [
|
||||
{
|
||||
propertyName: 'plan.id',
|
||||
dataType: DATA_TYPE.string,
|
||||
operator: OPERATORS.equals,
|
||||
value: 'pro,team',
|
||||
},
|
||||
];
|
||||
|
||||
const params = serializeUniversalEventPropertyFilters(filters);
|
||||
|
||||
expect(params).toEqual({
|
||||
epf0: '1.eq.plan%2Eid.pro,team',
|
||||
});
|
||||
expect(parseUniversalEventPropertyFilters(params)).toEqual(filters);
|
||||
});
|
||||
|
||||
test('ignores malformed universal event property filters', () => {
|
||||
expect(
|
||||
parseUniversalEventPropertyFilters({
|
||||
epf0: 'eq.plan%2Eid.value',
|
||||
epf1: '1.unknown.email.value',
|
||||
epf2: '1.eq',
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
+111
-1
@@ -1,8 +1,18 @@
|
||||
import { DATA_TYPE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
|
||||
import type { Filter, Operator, PropertyFilter, QueryFilters, QueryOptions } from '@/lib/types';
|
||||
import type {
|
||||
Filter,
|
||||
Operator,
|
||||
PropertyFilter,
|
||||
QueryFilters,
|
||||
QueryOptions,
|
||||
EventPropertyFilter,
|
||||
SessionPropertyFilter,
|
||||
} from '@/lib/types';
|
||||
|
||||
const VALID_OPERATORS: Operator[] = Object.values(OPERATORS);
|
||||
const VALID_EVENT_DATA_TYPES = Object.values(DATA_TYPE);
|
||||
const EVENT_PROPERTY_FILTER_PARAM = /^epf\d+$/;
|
||||
const SESSION_PROPERTY_FILTER_PARAM = /^spf\d+$/;
|
||||
|
||||
function isValidEventDataType(value: number): value is (typeof VALID_EVENT_DATA_TYPES)[number] {
|
||||
return VALID_EVENT_DATA_TYPES.includes(value as (typeof VALID_EVENT_DATA_TYPES)[number]);
|
||||
@@ -108,6 +118,18 @@ function getPropertyFilterPrefix(key: string, prefixes: string[]) {
|
||||
return prefixes.find(prefix => key.startsWith(`${prefix}_`));
|
||||
}
|
||||
|
||||
function decodePropertyName(value: string) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function encodePropertyName(value: string) {
|
||||
return encodeURIComponent(value).replaceAll('.', '%2E');
|
||||
}
|
||||
|
||||
export function parsePropertyFilters(
|
||||
query: Record<string, any>,
|
||||
prefixes: string[] = ['pf'],
|
||||
@@ -156,6 +178,76 @@ export function parseEventPropertyFilters(query: Record<string, any>) {
|
||||
return parsePropertyFilters(query, ['pf']);
|
||||
}
|
||||
|
||||
export function parseUniversalEventPropertyFilters(
|
||||
query: Record<string, any>,
|
||||
): EventPropertyFilter[] {
|
||||
return Object.entries(query).flatMap(([key, val]) => {
|
||||
if (!EVENT_PROPERTY_FILTER_PARAM.test(key)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stringValue = String(val);
|
||||
const match = stringValue.match(/^(\d+)\.([^.]+)\.([^.]+)\.(.*)$/);
|
||||
const explicitDataType = match ? Number(match[1]) : undefined;
|
||||
const operator = resolveOperator(match?.[2]);
|
||||
const propertyName = match?.[3] ? decodePropertyName(match[3]) : undefined;
|
||||
const value = match?.[4];
|
||||
|
||||
if (
|
||||
!propertyName ||
|
||||
!operator ||
|
||||
explicitDataType === undefined ||
|
||||
!isValidEventDataType(explicitDataType) ||
|
||||
value === undefined
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
propertyName,
|
||||
dataType: explicitDataType,
|
||||
operator,
|
||||
value,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function parseSessionPropertyFilters(query: Record<string, any>): SessionPropertyFilter[] {
|
||||
return Object.entries(query).flatMap(([key, val]) => {
|
||||
if (!SESSION_PROPERTY_FILTER_PARAM.test(key)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stringValue = String(val);
|
||||
const match = stringValue.match(/^(\d+)\.([^.]+)\.([^.]+)\.(.*)$/);
|
||||
const explicitDataType = match ? Number(match[1]) : undefined;
|
||||
const operator = resolveOperator(match?.[2]);
|
||||
const propertyName = match?.[3] ? decodePropertyName(match[3]) : undefined;
|
||||
const value = match?.[4];
|
||||
|
||||
if (
|
||||
!propertyName ||
|
||||
!operator ||
|
||||
explicitDataType === undefined ||
|
||||
!isValidEventDataType(explicitDataType) ||
|
||||
value === undefined
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
propertyName,
|
||||
dataType: explicitDataType,
|
||||
operator,
|
||||
value,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function serializePropertyFilters(
|
||||
filters: PropertyFilter[],
|
||||
prefix = 'pf',
|
||||
@@ -176,3 +268,21 @@ export function serializePropertyFilters(
|
||||
export function serializeEventPropertyFilters(filters: PropertyFilter[]) {
|
||||
return serializePropertyFilters(filters, 'pf');
|
||||
}
|
||||
|
||||
export function serializeUniversalEventPropertyFilters(filters: EventPropertyFilter[]) {
|
||||
return Object.fromEntries(
|
||||
filters.map((filter, index) => [
|
||||
`epf${index}`,
|
||||
`${filter.dataType}.${filter.operator}.${encodePropertyName(filter.propertyName)}.${filter.value}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
export function serializeSessionPropertyFilters(filters: SessionPropertyFilter[]) {
|
||||
return Object.fromEntries(
|
||||
filters.map((filter, index) => [
|
||||
`spf${index}`,
|
||||
`${filter.dataType}.${filter.operator}.${encodePropertyName(filter.propertyName)}.${filter.value}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
+268
-2
@@ -309,6 +309,14 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
|
||||
const cohortFilters = Object.fromEntries(
|
||||
Object.entries(filters).filter(([key]) => key.startsWith('cohort_')),
|
||||
);
|
||||
const {
|
||||
sql: eventPropertyFilterQuery,
|
||||
params: eventPropertyFilterParams,
|
||||
} = getEventPropertyFilterQuery((filters as QueryFilters).eventPropertyFilters, filters.timezone);
|
||||
const {
|
||||
sql: sessionPropertyFilterQuery,
|
||||
params: sessionPropertyFilterParams,
|
||||
} = getSessionPropertyFilterQuery((filters as QueryFilters).sessionPropertyFilters, filters.timezone);
|
||||
|
||||
return {
|
||||
joinSessionQuery:
|
||||
@@ -316,8 +324,14 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
|
||||
? `inner join session on website_event.session_id = session.session_id and website_event.website_id = session.website_id`
|
||||
: '',
|
||||
dateQuery: getDateQuery(filters),
|
||||
filterQuery: getFilterQuery(filters, options),
|
||||
queryParams: getQueryParams(filters),
|
||||
filterQuery: [getFilterQuery(filters, options), eventPropertyFilterQuery, sessionPropertyFilterQuery]
|
||||
.filter(Boolean)
|
||||
.join('\n'),
|
||||
queryParams: {
|
||||
...getQueryParams(filters),
|
||||
...eventPropertyFilterParams,
|
||||
...sessionPropertyFilterParams,
|
||||
},
|
||||
cohortQuery: getCohortQuery(cohortFilters),
|
||||
excludeBounceQuery: getExcludeBounceQuery(filters),
|
||||
};
|
||||
@@ -450,6 +464,258 @@ function getPropertyFilterQuery(
|
||||
return { sql: parts.join('\n'), params };
|
||||
}
|
||||
|
||||
function getEventPropertyFilterQuery(
|
||||
filters: PropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
if (!filters.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
const clauses: string[] = [];
|
||||
const keyRefs: string[] = [];
|
||||
const params: Record<string, any> = {};
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, index) => {
|
||||
const keyParam = `epf_key_${index}`;
|
||||
const valParam = `epf_val_${index}`;
|
||||
params[keyParam] = propertyName;
|
||||
keyRefs.push(`{{${keyParam}}}`);
|
||||
|
||||
let condition: string;
|
||||
|
||||
switch (dataType) {
|
||||
case DATA_TYPE.number: {
|
||||
const col = 'cast(number_value as decimal)';
|
||||
params[valParam] = parseFloat(value) || 0;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.equals]: `${col} = {{${valParam}}}`,
|
||||
[OPERATORS.notEquals]: `${col} != {{${valParam}}}`,
|
||||
[OPERATORS.greaterThan]: `${col} > {{${valParam}}}`,
|
||||
[OPERATORS.lessThan]: `${col} < {{${valParam}}}`,
|
||||
[OPERATORS.greaterThanEquals]: `${col} >= {{${valParam}}}`,
|
||||
[OPERATORS.lessThanEquals]: `${col} <= {{${valParam}}}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${col} = {{${valParam}}}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.date: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
const dateCol =
|
||||
timezone && !isUtcTimezone(timezone)
|
||||
? `(date_value at time zone {{timezone}})::date`
|
||||
: `(date_value at time zone 'utc')::date`;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.before]: `${dateCol} < {{${valParam}::date}}`,
|
||||
[OPERATORS.after]: `${dateCol} > {{${valParam}::date}}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${dateCol} = {{${valParam}::date}}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.array: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `exists (
|
||||
select 1
|
||||
from jsonb_array_elements_text(coalesce(string_value, '[]')::jsonb) as array_item(value)
|
||||
where array_item.value = {{${valParam}}}
|
||||
)`
|
||||
: `not exists (
|
||||
select 1
|
||||
from jsonb_array_elements_text(coalesce(string_value, '[]')::jsonb) as array_item(value)
|
||||
where array_item.value = {{${valParam}}}
|
||||
)`;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const col = 'string_value';
|
||||
|
||||
if (EQUALITY_OPERATORS.includes(operator)) {
|
||||
const vals = value.split(',').filter(Boolean);
|
||||
|
||||
if (!vals.length) return;
|
||||
|
||||
params[valParam] = vals;
|
||||
condition =
|
||||
operator === OPERATORS.equals
|
||||
? `${col} = ANY({{${valParam}}})`
|
||||
: `${col} != ALL({{${valParam}}})`;
|
||||
} else if (REGEX_OPERATORS.includes(operator)) {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.regex
|
||||
? `${col} ~* {{${valParam}}}`
|
||||
: `${col} !~* {{${valParam}}}`;
|
||||
} else {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = `%${value}%`;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `${col} ilike {{${valParam}}}`
|
||||
: `${col} not ilike {{${valParam}}}`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
clauses.push(
|
||||
`bool_or(data_key = {{${keyParam}}} and data_type = ${dataType} and ${condition})`,
|
||||
);
|
||||
});
|
||||
|
||||
if (!clauses.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
return {
|
||||
sql: `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 in (${keyRefs.join(', ')})
|
||||
group by website_event_id
|
||||
having ${clauses.join('\n and ')}
|
||||
)`,
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
function getSessionPropertyFilterQuery(
|
||||
filters: PropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
if (!filters.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
const clauses: string[] = [];
|
||||
const keyRefs: string[] = [];
|
||||
const params: Record<string, any> = {};
|
||||
|
||||
filters.forEach(({ propertyName, dataType, operator, value }, index) => {
|
||||
const keyParam = `spf_key_${index}`;
|
||||
const valParam = `spf_val_${index}`;
|
||||
params[keyParam] = propertyName;
|
||||
keyRefs.push(`{{${keyParam}}}`);
|
||||
|
||||
let condition: string;
|
||||
|
||||
switch (dataType) {
|
||||
case DATA_TYPE.number: {
|
||||
const col = 'cast(number_value as decimal)';
|
||||
params[valParam] = parseFloat(value) || 0;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.equals]: `${col} = {{${valParam}}}`,
|
||||
[OPERATORS.notEquals]: `${col} != {{${valParam}}}`,
|
||||
[OPERATORS.greaterThan]: `${col} > {{${valParam}}}`,
|
||||
[OPERATORS.lessThan]: `${col} < {{${valParam}}}`,
|
||||
[OPERATORS.greaterThanEquals]: `${col} >= {{${valParam}}}`,
|
||||
[OPERATORS.lessThanEquals]: `${col} <= {{${valParam}}}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${col} = {{${valParam}}}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.date: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
const dateCol =
|
||||
timezone && !isUtcTimezone(timezone)
|
||||
? `(date_value at time zone {{timezone}})::date`
|
||||
: `(date_value at time zone 'utc')::date`;
|
||||
const opMap: Record<string, string> = {
|
||||
[OPERATORS.before]: `${dateCol} < {{${valParam}::date}}`,
|
||||
[OPERATORS.after]: `${dateCol} > {{${valParam}::date}}`,
|
||||
};
|
||||
condition = opMap[operator] ?? `${dateCol} = {{${valParam}::date}}`;
|
||||
break;
|
||||
}
|
||||
case DATA_TYPE.array: {
|
||||
if (!value) return;
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `exists (
|
||||
select 1
|
||||
from jsonb_array_elements_text(coalesce(string_value, '[]')::jsonb) as array_item(value)
|
||||
where array_item.value = {{${valParam}}}
|
||||
)`
|
||||
: `not exists (
|
||||
select 1
|
||||
from jsonb_array_elements_text(coalesce(string_value, '[]')::jsonb) as array_item(value)
|
||||
where array_item.value = {{${valParam}}}
|
||||
)`;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const col = 'string_value';
|
||||
|
||||
if (EQUALITY_OPERATORS.includes(operator)) {
|
||||
const vals = value.split(',').filter(Boolean);
|
||||
|
||||
if (!vals.length) return;
|
||||
|
||||
params[valParam] = vals;
|
||||
condition =
|
||||
operator === OPERATORS.equals
|
||||
? `${col} = ANY({{${valParam}}})`
|
||||
: `${col} != ALL({{${valParam}}})`;
|
||||
} else if (REGEX_OPERATORS.includes(operator)) {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = value;
|
||||
condition =
|
||||
operator === OPERATORS.regex
|
||||
? `${col} ~* {{${valParam}}}`
|
||||
: `${col} !~* {{${valParam}}}`;
|
||||
} else {
|
||||
if (!value) return;
|
||||
|
||||
params[valParam] = `%${value}%`;
|
||||
condition =
|
||||
operator === OPERATORS.contains
|
||||
? `${col} ilike {{${valParam}}}`
|
||||
: `${col} not ilike {{${valParam}}}`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
clauses.push(
|
||||
`bool_or(data_key = {{${keyParam}}} and data_type = ${dataType} and ${condition})`,
|
||||
);
|
||||
});
|
||||
|
||||
if (!clauses.length) {
|
||||
return { sql: '', params: {} };
|
||||
}
|
||||
|
||||
return {
|
||||
sql: `and exists (
|
||||
select 1
|
||||
from session_data
|
||||
where website_id = website_event.website_id
|
||||
and session_id = website_event.session_id
|
||||
and data_key in (${keyRefs.join(', ')})
|
||||
group by website_id, session_id
|
||||
having ${clauses.join('\n and ')}
|
||||
)`,
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
async function executeRawQuery(
|
||||
sql: string,
|
||||
data: Record<string, any>,
|
||||
|
||||
+13
-2
@@ -4,7 +4,11 @@ import { checkAuth } from '@/lib/auth';
|
||||
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
|
||||
import { getAllowedUnits, getMinimumUnit, maxDate, parseDateRange } from '@/lib/date';
|
||||
import { fetchAccount, fetchWebsite } from '@/lib/load';
|
||||
import { filtersArrayToObject } from '@/lib/params';
|
||||
import {
|
||||
filtersArrayToObject,
|
||||
parseSessionPropertyFilters,
|
||||
parseUniversalEventPropertyFilters,
|
||||
} from '@/lib/params';
|
||||
import { badRequest, unauthorized } from '@/lib/response';
|
||||
import type { QueryFilters } from '@/lib/types';
|
||||
import { getWebsiteSegment } from '@/queries/prisma';
|
||||
@@ -32,7 +36,10 @@ export async function parseRequest(
|
||||
|
||||
// Re-add dynamic params stripped by Zod schema: suffixed filter params (browser1, os2)
|
||||
for (const key of Object.keys(rawQuery)) {
|
||||
if ((/\d+$/.test(key) || /^pf_/.test(key)) && !(key in query)) {
|
||||
if (
|
||||
(/\d+$/.test(key) || /^pf_/.test(key) || /^epf\d+$/.test(key) || /^spf\d+$/.test(key)) &&
|
||||
!(key in query)
|
||||
) {
|
||||
query[key] = rawQuery[key];
|
||||
}
|
||||
}
|
||||
@@ -114,6 +121,8 @@ export async function getQueryFilters(
|
||||
): Promise<QueryFilters> {
|
||||
const dateRange = getRequestDateRange(params);
|
||||
const filters = getRequestFilters(params);
|
||||
const eventPropertyFilters = parseUniversalEventPropertyFilters(params);
|
||||
const sessionPropertyFilters = parseSessionPropertyFilters(params);
|
||||
|
||||
let match = params?.match;
|
||||
|
||||
@@ -169,6 +178,8 @@ export async function getQueryFilters(
|
||||
...filters,
|
||||
match,
|
||||
minDuration: params?.minDuration,
|
||||
eventPropertyFilters,
|
||||
sessionPropertyFilters,
|
||||
page: params?.page,
|
||||
pageSize: params?.pageSize ? params?.pageSize || DEFAULT_PAGE_SIZE : undefined,
|
||||
orderBy: params?.orderBy,
|
||||
|
||||
@@ -48,6 +48,7 @@ export interface PropertyFilter {
|
||||
}
|
||||
|
||||
export type EventPropertyFilter = PropertyFilter;
|
||||
export type SessionPropertyFilter = PropertyFilter;
|
||||
|
||||
export interface Filter {
|
||||
name: string;
|
||||
@@ -126,6 +127,8 @@ export interface QueryFilters
|
||||
SegmentParams {
|
||||
minDuration?: number;
|
||||
cohortFilters?: QueryFilters;
|
||||
eventPropertyFilters?: EventPropertyFilter[];
|
||||
sessionPropertyFilters?: SessionPropertyFilter[];
|
||||
}
|
||||
|
||||
export interface DateParams {
|
||||
|
||||
Reference in new issue
Block a user