route to view or raw table based on filters

This commit is contained in:
Francis Cao 2025-07-15 16:26:03 -07:00
parent 2dcb9e21bd
commit 954404f8df
7 changed files with 102 additions and 26 deletions

View file

@ -1,4 +1,5 @@
import clickhouse from '@/lib/clickhouse';
import { EVENT_COLUMNS } from '@/lib/constants';
import { CLICKHOUSE, getDatabaseType, POSTGRESQL, PRISMA, runQuery } from '@/lib/db';
import prisma from '@/lib/prisma';
import { PageParams, QueryFilters } from '@/lib/types';
@ -77,8 +78,45 @@ async function clickhouseQuery(websiteId: string, filters: QueryFilters, pagePar
const { params, dateQuery, filterQuery, cohortQuery } = await parseFilters(websiteId, filters);
const { search } = pageParams;
return pagedQuery(
`
let sql = '';
if (EVENT_COLUMNS.some(item => Object.keys(filters).includes(item))) {
sql = `
select
session_id as id,
website_id as websiteId,
browser,
os,
device,
screen,
language,
country,
region,
city,
${getDateStringSQL('min(created_at)')} as firstAt,
${getDateStringSQL('max(created_at)')} as lastAt,
uniq(visit_id) as visits,
sumIf(views, event_type = 1) as views,
lastAt as createdAt
from website_event
${cohortQuery}
where website_id = {websiteId:UUID}
${dateQuery}
${filterQuery}
${
search
? `and ((positionCaseInsensitive(distinct_id, {search:String}) > 0)
or (positionCaseInsensitive(city, {search:String}) > 0)
or (positionCaseInsensitive(browser, {search:String}) > 0)
or (positionCaseInsensitive(os, {search:String}) > 0)
or (positionCaseInsensitive(device, {search:String}) > 0))`
: ''
}
group by session_id, website_id, browser, os, device, screen, language, country, region, city
order by lastAt desc
`;
} else {
sql = `
select
session_id as id,
website_id as websiteId,
@ -111,8 +149,8 @@ async function clickhouseQuery(websiteId: string, filters: QueryFilters, pagePar
}
group by session_id, website_id, browser, os, device, screen, language, country, region, city
order by lastAt desc
`,
{ ...params, search },
pageParams,
);
`;
}
return pagedQuery(sql, { ...params, search }, pageParams);
}