Merge pull request #1245 from umami-software/brian/um-13-query-optimizations

Brian/um 13 query optimizations
This commit is contained in:
Mike Cao 2022-07-04 17:35:41 -07:00 committed by GitHub
commit b2f1dd4386
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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
@ -468,15 +480,19 @@ export function getPageviewStats(
return rawQuery(
`
select ${getDateQuery('pageview.created_at', unit, timezone)} t,
count(${count}) y
from pageview
${joinSession}
where pageview.website_id=$1
and pageview.created_at between $2 and $3
${pageviewQuery}
${sessionQuery}
group by 1
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}
where pageview.website_id=$1
and pageview.created_at between $2 and $3
${pageviewQuery}
${sessionQuery}
group by 1) g
order by 1
`,
params,
@ -561,7 +577,7 @@ export function 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