mirror of
https://github.com/benjamin-wilson/public-pool.git
synced 2026-09-29 09:05:06 -07:00
raw query
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
|
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
|
||||||
import { DataSource, EntityManager, Repository } from 'typeorm';
|
import { DataSource, Repository } from 'typeorm';
|
||||||
|
|
||||||
import { ClientStatisticsEntity } from './client-statistics.entity';
|
import { ClientStatisticsEntity } from './client-statistics.entity';
|
||||||
|
|
||||||
@@ -19,28 +19,31 @@ export class ClientStatisticsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async save(clientStatistic: Partial<ClientStatisticsEntity>) {
|
public async save(clientStatistic: Partial<ClientStatisticsEntity>) {
|
||||||
// Use transaction to ensure atomicity
|
await this.dataSource.transaction(async (entityManager) => {
|
||||||
await this.dataSource.transaction(async (entityManager: EntityManager) => {
|
const query = `
|
||||||
// Attempt to update the existing record
|
UPDATE client_statistics_entity
|
||||||
const updateResult = await entityManager
|
SET shares = shares + $1, accepted_count = accepted_count + 1
|
||||||
.createQueryBuilder()
|
WHERE address = $2 AND client_name = $3 AND session_id = $4 AND time = $5
|
||||||
.update(ClientStatisticsEntity)
|
RETURNING *;`;
|
||||||
.set({
|
|
||||||
shares: () => `"shares" + ${clientStatistic.shares}`,
|
|
||||||
acceptedCount: () => `"acceptedCount" + 1`
|
|
||||||
})
|
|
||||||
.where('address = :address AND clientName = :clientName AND sessionId = :sessionId AND time = :time', {
|
|
||||||
address: clientStatistic.address,
|
|
||||||
clientName: clientStatistic.clientName,
|
|
||||||
sessionId: clientStatistic.sessionId,
|
|
||||||
time: clientStatistic.time
|
|
||||||
})
|
|
||||||
.execute();
|
|
||||||
|
|
||||||
// Check if the update affected any rows
|
const parameters = [
|
||||||
if (updateResult.affected === 0) {
|
clientStatistic.shares || 0, // Ensure a default value for shares
|
||||||
// If no rows were updated, insert a new record
|
clientStatistic.address,
|
||||||
await entityManager.insert(ClientStatisticsEntity, clientStatistic);
|
clientStatistic.clientName,
|
||||||
|
clientStatistic.sessionId,
|
||||||
|
clientStatistic.time
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await entityManager.query(query, parameters);
|
||||||
|
|
||||||
|
if (result.length === 0) {
|
||||||
|
await entityManager.insert(ClientStatisticsEntity, clientStatistic);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Handle errors
|
||||||
|
console.error('Error during transaction:', error);
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user