umami/src/queries/analytics/getValues.ts

83 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-08-08 22:29:59 +00:00
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
2023-10-13 16:31:53 +00:00
export async function getValues(
2024-03-27 00:31:16 +00:00
...args: [websiteId: string, column: string, startDate: Date, endDate: Date, search: string]
2023-10-13 16:31:53 +00:00
) {
2023-08-08 22:29:59 +00:00
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
2024-03-27 00:31:16 +00:00
async function relationalQuery(
websiteId: string,
column: string,
startDate: Date,
endDate: Date,
search: string,
) {
const { rawQuery, getSearchQuery } = prisma;
2024-03-27 00:31:16 +00:00
let searchQuery = '';
if (search) {
searchQuery = getSearchQuery(column);
2024-03-27 00:31:16 +00:00
}
2023-08-08 22:29:59 +00:00
return rawQuery(
`
2024-03-27 00:31:16 +00:00
select ${column} as "value", count(*)
2023-08-08 22:29:59 +00:00
from website_event
inner join session
on session.session_id = website_event.session_id
where website_event.website_id = {{websiteId::uuid}}
2023-10-13 17:01:23 +00:00
and website_event.created_at between {{startDate}} and {{endDate}}
2024-03-27 00:31:16 +00:00
${searchQuery}
group by 1
order by 2 desc
limit 10
2023-08-08 22:29:59 +00:00
`,
2023-10-13 16:31:53 +00:00
{
websiteId,
startDate,
endDate,
2024-03-27 00:31:16 +00:00
search: `%${search}%`,
2023-10-13 16:31:53 +00:00
},
2023-08-08 22:29:59 +00:00
);
}
2024-03-27 00:31:16 +00:00
async function clickhouseQuery(
websiteId: string,
column: string,
startDate: Date,
endDate: Date,
search: string,
) {
2023-08-08 22:29:59 +00:00
const { rawQuery } = clickhouse;
2024-03-27 00:31:16 +00:00
let searchQuery = '';
if (search) {
searchQuery = `and positionCaseInsensitive(${column}, {search:String}) > 0`;
}
2023-08-08 22:29:59 +00:00
return rawQuery(
`
2024-03-27 00:31:16 +00:00
select ${column} as value, count(*)
2023-08-08 22:29:59 +00:00
from website_event
where website_id = {websiteId:UUID}
2023-10-13 16:31:53 +00:00
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
2024-03-27 00:31:16 +00:00
${searchQuery}
group by 1
order by 2 desc
limit 10
2023-08-08 22:29:59 +00:00
`,
2023-10-13 16:31:53 +00:00
{
websiteId,
startDate,
endDate,
2024-03-27 00:31:16 +00:00
search,
2023-10-13 16:31:53 +00:00
},
2023-08-08 22:29:59 +00:00
);
}