Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

optimize queries

Brian Cao3023890cbaae
diff --git a/lib/queries.js b/lib/queries.js
index 0e93244e7..9a165d130 100644
--- a/lib/queries.js
+++ b/lib/queries.js
@@ -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,16 +479,20 @@ export function getPageviewStats(
const { pageviewQuery, sessionQuery, joinSession } = parseFilters('pageview', filters, params);
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
+ `--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}
+ where pageview.website_id=$1
+ and pageview.created_at between $2 and $3
+ ${pageviewQuery}
+ ${sessionQuery}
+ 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