Skip to content

Commit

Permalink
add daydiff function query
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscao633 committed Aug 15, 2023
1 parent 27226d1 commit 979ea33
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
13 changes: 13 additions & 0 deletions lib/prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ function getAddMinutesQuery(field: string, minutes: number): string {
}
}

function getDayDiffQuery(field1: string, field2: string): string {
const db = getDatabaseType(process.env.DATABASE_URL);

if (db === POSTGRESQL) {
return `${field1}::date - ${field2}::date`;
}

if (db === MYSQL) {
return `DATEDIFF(${field1}, ${field2});`;
}
}

function getDateQuery(field: string, unit: string, timezone?: string): string {
const db = getDatabaseType();

Expand Down Expand Up @@ -180,6 +192,7 @@ function getPageFilters(filters: SearchFilter<any>): [
export default {
...prisma,
getAddMinutesQuery,
getDayDiffQuery,
getDateQuery,
getTimestampIntervalQuery,
getFilterQuery,
Expand Down
7 changes: 5 additions & 2 deletions queries/analytics/reports/getRetention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async function relationalQuery(
}[]
> {
const { startDate, endDate } = dateRange;
const { getDateQuery, rawQuery } = prisma;
const { getDateQuery, getDayDiffQuery, rawQuery } = prisma;
const timezone = 'utc';
const unit = 'day';

Expand All @@ -49,7 +49,10 @@ async function relationalQuery(
user_activities AS (
select distinct
w.session_id,
(${getDateQuery('created_at', unit, timezone)}::date - c.cohort_date::date) as day_number
(${getDayDiffQuery(
getDateQuery('created_at', unit, timezone),
'c.cohort_date',
)}) as day_number
from website_event w
join cohort_items c
on w.session_id = c.session_id
Expand Down

0 comments on commit 979ea33

Please sign in to comment.