Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Some SQL query optimisations

Blue Mousead328d4fb757
diff --git a/src/analytics/analytics.module.ts b/src/analytics/analytics.module.ts
index c5cf3c8ea..b208527e7 100644
--- a/src/analytics/analytics.module.ts
+++ b/src/analytics/analytics.module.ts
@@ -1,7 +1,5 @@
import { Module, forwardRef } from '@nestjs/common'
-import { TypeOrmModule } from '@nestjs/typeorm'
-import { Analytics } from './entities/analytics.entity'
import { AnalyticsService } from './analytics.service'
import { AnalyticsController } from './analytics.controller'
import { UserModule } from '../user/user.module'
@@ -10,7 +8,6 @@ import { ProjectModule } from '../project/project.module'
@Module({
imports: [
- TypeOrmModule.forFeature([Analytics]),
forwardRef(() => UserModule),
AppLoggerModule,
ProjectModule,
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index 3810b9d22..07698ce30 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -11,8 +11,6 @@ import * as utc from 'dayjs/plugin/utc'
import {
Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,
} from '@nestjs/common'
-import { InjectRepository } from '@nestjs/typeorm'
-import { Repository } from 'typeorm'
import { ACCOUNT_PLANS } from '../user/entities/user.entity'
import {
@@ -20,7 +18,6 @@ import {
UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisUserCountKey,
redisProjectCountCacheTimeout,
} from '../common/constants'
-import { Analytics } from './entities/analytics.entity'
import { PageviewsDTO } from './dto/pageviews.dto'
import { EventsDTO } from './dto/events.dto'
import { ProjectService } from '../project/project.service'
@@ -32,44 +29,18 @@ dayjs.extend(utc)
@Injectable()
export class AnalyticsService {
constructor(
- @InjectRepository(Analytics)
- private analyticsRepository: Repository<Analytics>,
private readonly projectService: ProjectService,
) { }
- count(): Promise<number> {
- return this.analyticsRepository.count()
- }
-
- async create(project: PageviewsDTO | Analytics): Promise<PageviewsDTO | Analytics> {
- return this.analyticsRepository.save(project)
- }
-
- async update(id: string, eventsDTO: PageviewsDTO): Promise<any> {
- return this.analyticsRepository.update(id, eventsDTO)
- }
-
- async delete(id: string): Promise<any> {
- return this.analyticsRepository.delete(id)
- }
-
- findOne(id: string): Promise<Analytics | null> {
- return this.analyticsRepository.findOne(id)
- }
-
- findOneWhere(where: Record<string, unknown>): Promise<Analytics> {
- return this.analyticsRepository.findOne({ where })
- }
-
- findWhere(where: Record<string, unknown>): Promise<Analytics[]> {
- return this.analyticsRepository.find({ where })
- }
-
async getRedisProject(pid: string): Promise<Project | null> {
const pidKey = getRedisProjectKey(pid)
let project = await redis.get(pidKey)
+
if (_isEmpty(project)) {
- project = await this.projectService.findOneWithRelations(pid)
+ project = await this.projectService.findOne(pid, {
+ relations: ['admin'],
+ select: ['origins', 'active', 'admin']
+ })
if (_isEmpty(project)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
await redis.set(pidKey, JSON.stringify(project), 'EX', redisProjectCacheTimeout)
} else {
diff --git a/src/analytics/entities/analytics.entity.ts b/src/analytics/entities/analytics.entity.ts
deleted file mode 100644
index 0e0c9116c..000000000
--- a/src/analytics/entities/analytics.entity.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, ManyToOne } from 'typeorm'
-import { ApiProperty } from '@nestjs/swagger'
-
-import { Project } from '../../project/entity/project.entity'
-
-@Entity()
-export class Analytics {
- @PrimaryGeneratedColumn('uuid')
- id: string
-
- @Column('varchar', { length: 11 })
- pid: string
-
- // @ApiProperty({ type: () => Project })
- // @ManyToOne(() => Project, proj => proj.id)
- // pid: Project
-
- @Column('varchar', {
- length: 64,
- nullable: true,
- })
- tz: string
-
- @Column('varchar', {
- length: 500,
- nullable: true,
- }) // maybe it should be 2083? https://support.microsoft.com/uk-ua/topic/maximum-url-length-is-2-083-characters-in-internet-explorer-174e7c8a-6666-f4e0-6fd6-908b53c12246
- pg: string
-
- @Column('varchar', {
- length: 8,
- nullable: true,
- })
- lc: string
-
- @Column('varchar', {
- length: 500,
- nullable: true,
- }) // same question as pg
- ref: string
-
- @Column('varchar', {
- length: 32,
- nullable: true,
- })
- br: string // browser name
-
- @Column('varchar', {
- length: 32,
- nullable: true,
- })
- os: string // OS name
-
- @Column('varchar', {
- length: 32,
- nullable: true,
- })
- dv: string // device type [desktop, console, mobile, tablet, smarttv, wearable, embedded]
-
- @Column('varchar', {
- length: 100,
- nullable: true,
- })
- so: string
-
- @Column('varchar', {
- length: 100,
- nullable: true,
- })
- me: string
-
- @Column('varchar', {
- length: 100,
- nullable: true,
- })
- ca: string
-
- @Column({ nullable: true })
- lt: number // load time
-
- @CreateDateColumn()
- created: Date;
-}
diff --git a/src/app.module.ts b/src/app.module.ts
index a60aac831..af7acbaa7 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -8,7 +8,6 @@ import { UserModule } from './user/user.module'
import { AnalyticsModule } from './analytics/analytics.module'
import { User } from './user/entities/user.entity'
import { Project } from './project/entity/project.entity'
-import { Analytics } from './analytics/entities/analytics.entity'
import { ProjectModule } from './project/project.module'
import { MailerModule } from './mailer/mailer.module'
import { ActionTokensModule } from './action-tokens/action-tokens.module'
@@ -26,7 +25,7 @@ import { TaskManagerModule } from './task-manager/task-manager.module'
password: process.env.MYSQL_ROOT_PASSWORD,
database: process.env.MYSQL_DATABASE,
synchronize: true,
- entities: [User, ActionToken, Project, Analytics],
+ entities: [User, ActionToken, Project],
}),
ScheduleModule.forRoot(),
TaskManagerModule,
@@ -40,4 +39,3 @@ import { TaskManagerModule } from './task-manager/task-manager.module'
})
export class AppModule {}
-
diff --git a/src/project/project.service.ts b/src/project/project.service.ts
index e8c815a1d..2c3128a23 100644
--- a/src/project/project.service.ts
+++ b/src/project/project.service.ts
@@ -56,8 +56,8 @@ export class ProjectService {
return this.projectsRepository.findOne(id, { relations: ['admin'] })
}
- findOne(id: string): Promise<Project | null> {
- return this.projectsRepository.findOne(id)
+ findOne(id: string, params: Object = {}): Promise<Project | null> {
+ return this.projectsRepository.findOne(id, params)
}
findWhere(where: Record<string, unknown>): Promise<Project[]> {
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 5294ebaa6..95e39b7ea 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -7,7 +7,6 @@ import * as _isNull from 'lodash/isNull'
import * as _join from 'lodash/join'
import * as _size from 'lodash/size'
import * as _map from 'lodash/map'
-import * as _keys from 'lodash/keys'
import { MailerService } from '../mailer/mailer.service'
import { UserService } from '../user/user.service'
@@ -58,9 +57,13 @@ export class TaskManagerService {
// EVERY SUNDAY AT 2:30 AM
@Cron('30 02 * * 0')
async weeklyReportsHandler(): Promise<void> {
- const users = await this.userService.findWhereWithRelations({
- reportFrequency: ReportFrequency.Weekly,
- }, ['projects'])
+ const users = await this.userService.find({
+ where: {
+ reportFrequency: ReportFrequency.Weekly,
+ },
+ relations: ['projects'],
+ select: ['email'],
+ })
const now = dayjs.utc().format('DD.MM.YYYY')
const weekAgo = dayjs.utc().subtract(1, 'w').format('DD.MM.YYYY')
const date = `${weekAgo} - ${now}`
@@ -90,9 +93,13 @@ export class TaskManagerService {
// ON THE FIRST DAY OF EVERY MONTH AT 2 AM
@Cron('0 02 1 * *')
async monthlyReportsHandler(): Promise<void> {
- const users = await this.userService.findWhereWithRelations({
- reportFrequency: ReportFrequency.Weekly,
- }, ['projects'])
+ const users = await this.userService.find({
+ where: {
+ reportFrequency: ReportFrequency.Monthly,
+ },
+ relations: ['projects'],
+ select: ['email'],
+ })
const now = dayjs.utc().format('DD.MM.YYYY')
const weekAgo = dayjs.utc().subtract(1, 'M').format('DD.MM.YYYY')
const date = `${weekAgo} - ${now}`
diff --git a/src/user/user.service.ts b/src/user/user.service.ts
index 7516a70b9..a99672130 100644
--- a/src/user/user.service.ts
+++ b/src/user/user.service.ts
@@ -56,6 +56,10 @@ export class UserService {
})
}
+ find(params: object): Promise<User[]> {
+ return this.usersRepository.find(params)
+ }
+
findWhere(where: Record<string, unknown>): Promise<User[]> {
return this.usersRepository.find({ where })
}