Add Property filters for booleans, dates, arrays
This commit is contained in:
1 parent
877945e721
commit
9da332c489
21 files changed
+499
-163
No files matched your search
+76
-44
@@ -2,7 +2,7 @@ import { CLICKHOUSE } from '@/lib/db';
|
||||
import { type ClickHouseClient, createClient } from '@clickhouse/client';
|
||||
import { formatInTimeZone } from 'date-fns-tz';
|
||||
import debug from 'debug';
|
||||
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from './constants';
|
||||
import { DATA_TYPE, DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from './constants';
|
||||
import { filtersObjectToArray } from './params';
|
||||
import type { EventPropertyFilter, Operator, QueryFilters, QueryOptions } from './types';
|
||||
|
||||
@@ -238,7 +238,10 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
|
||||
function getEventPropertyFilterQuery(
|
||||
filters: EventPropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
@@ -252,49 +255,78 @@ function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
|
||||
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> = {
|
||||
[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}`;
|
||||
} else 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',
|
||||
);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
parts.push(`and event_id in (
|
||||
|
||||
@@ -113,6 +113,10 @@ export function normalizeTimezone(timezone: string): string {
|
||||
return TIMEZONE_MAPPINGS[timezone] || timezone;
|
||||
}
|
||||
|
||||
export function getMaxSelectableDate(now = new Date()) {
|
||||
return max([endOfYear(now), addMonths(now, 6)]);
|
||||
}
|
||||
|
||||
export function isValidTimezone(timezone: string) {
|
||||
try {
|
||||
const normalizedTimezone = normalizeTimezone(timezone);
|
||||
|
||||
+25
-20
@@ -1,14 +1,8 @@
|
||||
import { FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
|
||||
import { DATA_TYPE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
|
||||
import type { EventPropertyFilter, Filter, Operator, QueryFilters, QueryOptions } from '@/lib/types';
|
||||
|
||||
const VALID_OPERATORS: Operator[] = Object.values(OPERATORS);
|
||||
const NUMERIC_EVENT_PROPERTY_OPERATORS: Operator[] = [
|
||||
OPERATORS.greaterThan,
|
||||
OPERATORS.lessThan,
|
||||
OPERATORS.greaterThanEquals,
|
||||
OPERATORS.lessThanEquals,
|
||||
];
|
||||
const EQUALITY_OPERATORS: Operator[] = [OPERATORS.equals, OPERATORS.notEquals];
|
||||
const VALID_EVENT_DATA_TYPES = Object.values(DATA_TYPE);
|
||||
|
||||
function resolveOperator(value?: string): Operator | undefined {
|
||||
if (!value) {
|
||||
@@ -110,22 +104,33 @@ export function parseEventPropertyFilters(query: Record<string, any>): EventProp
|
||||
return Object.entries(query)
|
||||
.filter(([key]) => /^epf_/.test(key))
|
||||
.flatMap(([key, val]) => {
|
||||
const dotIndex = (val as string).indexOf('.');
|
||||
if (dotIndex < 1) return [];
|
||||
const stringValue = String(val);
|
||||
const withoutPrefix = key.slice(4); // strip "epf_"
|
||||
const propertyName = withoutPrefix.replace(/\d+$/, ''); // strip trailing index digits
|
||||
const rawOperator = (val as string).slice(0, dotIndex);
|
||||
const prefixedDotMatch = stringValue.match(/^(\d+)\.([^.]+)\.(.*)$/);
|
||||
const untypedDotMatch = stringValue.match(/^([^.]+)\.(.*)$/);
|
||||
const explicitDataType = prefixedDotMatch ? Number(prefixedDotMatch[1]) : undefined;
|
||||
const rawOperator = prefixedDotMatch ? prefixedDotMatch[2] : untypedDotMatch?.[1];
|
||||
const operator = resolveOperator(rawOperator);
|
||||
if (!operator) {
|
||||
|
||||
if (!operator || (explicitDataType !== undefined && !VALID_EVENT_DATA_TYPES.includes(explicitDataType))) {
|
||||
return [];
|
||||
}
|
||||
const value = (val as string).slice(dotIndex + 1);
|
||||
const isNumeric =
|
||||
NUMERIC_EVENT_PROPERTY_OPERATORS.includes(operator) ||
|
||||
(EQUALITY_OPERATORS.includes(operator) &&
|
||||
value !== '' &&
|
||||
!Number.isNaN(Number(value)));
|
||||
return [{ propertyName, dataType: isNumeric ? 2 : 1, operator, value }];
|
||||
|
||||
const value = prefixedDotMatch ? prefixedDotMatch[3] : untypedDotMatch?.[2];
|
||||
|
||||
if (value === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
propertyName,
|
||||
dataType: explicitDataType ?? DATA_TYPE.string,
|
||||
operator,
|
||||
value,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -135,7 +140,7 @@ export function serializeEventPropertyFilters(filters: EventPropertyFilter[]): R
|
||||
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}`];
|
||||
return [`epf_${f.propertyName}${n > 0 ? n : ''}`, `${f.dataType}.${f.operator}.${f.value}`];
|
||||
}),
|
||||
);
|
||||
}
|
||||
+85
-38
@@ -2,7 +2,7 @@ import { PrismaClient } from '@/generated/prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { readReplicas } from '@prisma/extension-read-replicas';
|
||||
import debug from 'debug';
|
||||
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS, SESSION_COLUMNS } from './constants';
|
||||
import { DATA_TYPE, DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS, SESSION_COLUMNS } from './constants';
|
||||
import { filtersObjectToArray } from './params';
|
||||
import type { EventPropertyFilter, Operator, QueryFilters, QueryOptions } from './types';
|
||||
|
||||
@@ -44,6 +44,10 @@ const DATE_STRING_FORMATS = {
|
||||
second: 'YYYY-MM-DD"T"HH24:MI:SS',
|
||||
};
|
||||
|
||||
function isUtcTimezone(timezone?: string) {
|
||||
return timezone?.toLowerCase() === 'utc';
|
||||
}
|
||||
|
||||
function getAddIntervalQuery(field: string, interval: string): string {
|
||||
return `${field} + interval '${interval}'`;
|
||||
}
|
||||
@@ -57,7 +61,7 @@ function getCastColumnQuery(field: string, type: string): string {
|
||||
}
|
||||
|
||||
function getDateSQL(field: string, unit: string, timezone?: string): string {
|
||||
if (timezone && timezone !== 'utc') {
|
||||
if (timezone && !isUtcTimezone(timezone)) {
|
||||
return `to_char(date_trunc('${unit}', ${field} at time zone '${timezone}'), '${DATE_FORMATS[unit]}')`;
|
||||
}
|
||||
|
||||
@@ -65,7 +69,7 @@ function getDateSQL(field: string, unit: string, timezone?: string): string {
|
||||
}
|
||||
|
||||
function getDateStringSQL(field: string, unit: keyof typeof DATE_STRING_FORMATS = 'utc', timezone?: string): string {
|
||||
if (timezone && timezone !== 'utc') {
|
||||
if (timezone && !isUtcTimezone(timezone)) {
|
||||
return `to_char(${field} at time zone '${timezone}', '${DATE_STRING_FORMATS[unit]}')`;
|
||||
}
|
||||
|
||||
@@ -269,7 +273,10 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
|
||||
function getEventPropertyFilterQuery(
|
||||
filters: EventPropertyFilter[] = [],
|
||||
timezone?: string,
|
||||
): {
|
||||
sql: string;
|
||||
params: Record<string, any>;
|
||||
} {
|
||||
@@ -283,41 +290,81 @@ function getEventPropertyFilterQuery(filters: EventPropertyFilter[] = []): {
|
||||
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> = {
|
||||
[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}}}`;
|
||||
} else 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}::text[]}})`
|
||||
: `${col} != ALL({{${valParam}::text[]}})`;
|
||||
} 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}}}`;
|
||||
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}::text[]}})`
|
||||
: `${col} != ALL({{${valParam}::text[]}})`;
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
|
||||
parts.push(`and website_event.event_id in (
|
||||
|
||||
Reference in new issue
Block a user