umami/lib/prisma.ts

135 lines
3.5 KiB
TypeScript
Raw Normal View History

2022-12-27 06:51:16 +01:00
import prisma from '@umami/prisma-client';
2022-08-26 07:04:32 +02:00
import moment from 'moment-timezone';
2022-12-27 06:51:16 +01:00
import { MYSQL, POSTGRESQL, getDatabaseType } from 'lib/db';
2023-08-04 22:18:30 +02:00
import { FILTER_COLUMNS, IGNORED_FILTERS, SESSION_COLUMNS } from './constants';
import { loadWebsite } from './load';
import { maxDate } from './date';
import { QueryFilters } from './types';
2022-08-28 06:38:35 +02:00
const MYSQL_DATE_FORMATS = {
minute: '%Y-%m-%d %H:%i:00',
hour: '%Y-%m-%d %H:00:00',
day: '%Y-%m-%d',
month: '%Y-%m-01',
year: '%Y-01-01',
};
const POSTGRESQL_DATE_FORMATS = {
minute: 'YYYY-MM-DD HH24:MI:00',
hour: 'YYYY-MM-DD HH24:00:00',
day: 'YYYY-MM-DD',
month: 'YYYY-MM-01',
year: 'YYYY-01-01',
};
2022-08-27 07:43:31 +02:00
2023-07-25 23:54:56 +02:00
function getAddMinutesQuery(field: string, minutes: number): string {
2023-05-09 08:46:58 +02:00
const db = getDatabaseType(process.env.DATABASE_URL);
if (db === POSTGRESQL) {
return `${field} + interval '${minutes} minute'`;
}
if (db === MYSQL) {
return `DATE_ADD(${field}, interval ${minutes} minute)`;
}
}
2022-12-27 06:51:16 +01:00
function getDateQuery(field: string, unit: string, timezone?: string): string {
2023-07-25 08:06:16 +02:00
const db = getDatabaseType();
2022-08-26 07:04:32 +02:00
if (db === POSTGRESQL) {
if (timezone) {
return `to_char(date_trunc('${unit}', ${field} at time zone '${timezone}'), '${POSTGRESQL_DATE_FORMATS[unit]}')`;
}
return `to_char(date_trunc('${unit}', ${field}), '${POSTGRESQL_DATE_FORMATS[unit]}')`;
}
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 `date_format(${field}, '${MYSQL_DATE_FORMATS[unit]}')`;
}
}
2023-07-25 08:06:16 +02:00
function getTimestampIntervalQuery(field: string): string {
const db = getDatabaseType();
2022-08-27 06:29:26 +02:00
if (db === POSTGRESQL) {
return `floor(extract(epoch from max(${field}) - min(${field})))`;
}
if (db === MYSQL) {
return `floor(unix_timestamp(max(${field})) - unix_timestamp(min(${field})))`;
}
}
2023-08-02 23:21:13 +02:00
function getFilterQuery(filters = {}): string {
2022-08-26 07:04:32 +02:00
const query = Object.keys(filters).reduce((arr, key) => {
const filter = filters[key];
2023-08-04 22:18:30 +02:00
if (filter !== undefined && !IGNORED_FILTERS.includes(key)) {
2023-04-02 00:44:30 +02:00
const column = FILTER_COLUMNS[key] || key;
2023-07-31 20:42:47 +02:00
arr.push(`and ${column}={{${key}}}`);
2022-08-26 07:04:32 +02:00
}
2023-08-04 09:51:52 +02:00
if (key === 'referrer') {
arr.push(
2023-08-04 22:18:30 +02:00
'and (website_event.referrer_domain != {{websiteDomain}} or website_event.referrer_domain is null)',
2023-08-04 09:51:52 +02:00
);
}
2022-08-26 07:04:32 +02:00
return arr;
}, []);
return query.join('\n');
}
2023-08-04 22:18:30 +02:00
async function parseFilters(websiteId, filters: QueryFilters & { [key: string]: any } = {}) {
const website = await loadWebsite(websiteId);
2023-07-25 23:54:56 +02:00
return {
2023-08-02 23:21:13 +02:00
joinSession: Object.keys(filters).find(key => SESSION_COLUMNS[key])
? `inner join session on website_event.session_id = session.session_id`
: '',
filterQuery: getFilterQuery(filters),
2023-08-04 22:18:30 +02:00
params: {
...filters,
websiteId,
startDate: maxDate(filters.startDate, website.resetAt),
websiteDomain: website.domain,
},
2023-07-25 23:54:56 +02:00
};
}
2023-07-25 08:06:16 +02:00
async function rawQuery(sql: string, data: object): Promise<any> {
const db = getDatabaseType();
const params = [];
2022-08-26 07:04:32 +02:00
if (db !== POSTGRESQL && db !== MYSQL) {
return Promise.reject(new Error('Unknown database.'));
}
2023-07-29 03:30:02 +02:00
2023-07-25 18:43:51 +02:00
const query = sql?.replaceAll(/\{\{\s*(\w+)(::\w+)?\s*}}/g, (...args) => {
2023-07-25 08:06:16 +02:00
const [, name, type] = args;
params.push(data[name]);
return db === MYSQL ? '?' : `$${params.length}${type ?? ''}`;
});
2022-08-26 07:04:32 +02:00
2023-07-25 08:06:16 +02:00
return prisma.rawQuery(query, params);
2022-08-26 07:04:32 +02:00
}
2022-08-27 07:43:31 +02:00
export default {
2022-12-27 06:51:16 +01:00
...prisma,
2023-05-09 08:46:58 +02:00
getAddMinutesQuery,
2022-08-27 07:43:31 +02:00
getDateQuery,
2023-07-25 08:06:16 +02:00
getTimestampIntervalQuery,
2022-08-27 07:43:31 +02:00
getFilterQuery,
parseFilters,
rawQuery,
};