optimize queries

This commit is contained in:
Brian Cao 2022-06-30 00:22:23 -07:00
parent 3139fe0c6d
commit 3023890cba

View File

@ -21,24 +21,36 @@ export function getDatabase() {
return type;
}
export function getDateStringQuery(data, unit) {
const db = getDatabase();
if (db === POSTGRESQL) {
return `to_char(${data}, '${POSTGRESQL_DATE_FORMATS[unit]}')`;
}
if (db === MYSQL) {
return `DATE_FORMAT(${data}, '${MYSQL_DATE_FORMATS[unit]}')`;
}
}
export function getDateQuery(field, unit, timezone) {
const db = getDatabase();
if (db === POSTGRESQL) {
if (timezone) {
return `to_char(date_trunc('${unit}', ${field} at time zone '${timezone}'), '${POSTGRESQL_DATE_FORMATS[unit]}')`;
return `date_trunc('${unit}', ${field} at time zone '${timezone}')`;
}
return `to_char(date_trunc('${unit}', ${field}), '${POSTGRESQL_DATE_FORMATS[unit]}')`;
return `date_trunc('${unit}', ${field})`;
}
if (db === MYSQL) {
if (timezone) {
const tz = moment.tz(timezone).format('Z');
return `DATE_FORMAT(convert_tz(${field},'+00:00','${tz}'), '${MYSQL_DATE_FORMATS[unit]}')`;
return `convert_tz(${field},'+00:00','${tz}')`;
}
return `DATE_FORMAT(${field}, '${MYSQL_DATE_FORMATS[unit]}')`;
return `${field}`;
}
}
@ -438,7 +450,7 @@ export function getWebsiteStats(website_id, start_at, end_at, filters = {}) {
sum(t.time) as "totaltime"
from (
select pageview.session_id,
${getDateQuery('pageview.created_at', 'hour')},
${getDateQuery('pageview.created_at', 'hour', false, 'date')},
count(*) c,
${getTimestampInterval('pageview.created_at')} as "time"
from pageview
@ -467,8 +479,12 @@ export function getPageviewStats(
const { pageviewQuery, sessionQuery, joinSession } = parseFilters('pageview', filters, params);
return rawQuery(
`
select ${getDateQuery('pageview.created_at', unit, timezone)} t,
`--getPageviewStats
select
${getDateStringQuery('g.t', unit)} as t,
g.y as y
from
(select ${getDateQuery('pageview.created_at', unit, timezone)} t,
count(${count}) y
from pageview
${joinSession}
@ -476,7 +492,7 @@ export function getPageviewStats(
and pageview.created_at between $2 and $3
${pageviewQuery}
${sessionQuery}
group by 1
group by 1) g
order by 1
`,
params,
@ -559,9 +575,10 @@ export function getEventMetrics(
return rawQuery(
`
--getEventMetrics
select
event_value x,
${getDateQuery('created_at', unit, timezone)} t,
${getDateStringQuery(getDateQuery('created_at', unit, timezone), unit)} t,
count(*) y
from event
where website_id=$1