Skip to content

Commit

Permalink
fix(backend): use insertOne insteadof insert/findOneOrFail combination (
Browse files Browse the repository at this point in the history
#13908)

* fix(backend): use insertOne insteadof insert/findOneOrFail combination

* fix: typo

* fix(backend): inherit mainAlias?

* refactor(backend): use extend

* fix(backend): invalid entityTarget

* fix(backend): fake where

* chore: debug

* chore: debug

* test: log

* fix(backend): column names

* fix(backend): remove dummy from

* revert: log

* fix(backend): position

* fix(backend): automatic aliasing

* chore(backend): alias

* chore(backend): remove from

* fix(backend): type

* fix(backend): avoid pure name

* test(backend): fix type

* chore(backend): use cte

* fix(backend): avoid useless alias

* fix(backend): fix typo

* fix(backend): __disambiguation__

* fix(backend): quote

* chore(backend): t

* chore(backend): accessible

* chore(backend): concrete returning

* fix(backend): quote

* chore: log more

* chore: log metadata

* chore(backend): use raw

* fix(backend): returning column name

* fix(backend): transform

* build(backend): wanna logging

* build(backend): transform empty

* build(backend): build alias

* build(backend): restore name

* chore: return entity

* fix: test case

* test(backend): 204

* chore(backend): log sql

* chore(backend): assert user joined

* fix(backend): typo

* chore(backend): log long sql

* chore(backend): log join

* chore(backend): log join depth null

* chore(backend): joinAttributes

* chore(backend): override createJoinExpression

* chore: join log

* fix(backend): escape

* test(backend): log log

* chore(backend): join gonna success?

* chore(backend): relations

* chore(backend): undefined

* chore(backend): target

* chore(backend): remove log

* chore(backend): log chart update

* chore(backend): log columns

* chore(backend): check hasMetadata

* chore(backend): unshift id when not included

* chore(backend): missing select

* chore(backend): remove debug code
  • Loading branch information
acid-chicken authored Jun 1, 2024
1 parent ecf7945 commit 2b8056a
Show file tree
Hide file tree
Showing 36 changed files with 319 additions and 215 deletions.
4 changes: 2 additions & 2 deletions packages/backend/src/core/AnnouncementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class AnnouncementService {

@bindThis
public async create(values: Partial<MiAnnouncement>, moderator?: MiUser): Promise<{ raw: MiAnnouncement; packed: Packed<'Announcement'> }> {
const announcement = await this.announcementsRepository.insert({
const announcement = await this.announcementsRepository.insertOne({
id: this.idService.gen(),
updatedAt: null,
title: values.title,
Expand All @@ -79,7 +79,7 @@ export class AnnouncementService {
silence: values.silence,
needConfirmationToRead: values.needConfirmationToRead,
userId: values.userId,
}).then(x => this.announcementsRepository.findOneByOrFail(x.identifiers[0]));
});

const packed = await this.announcementEntityService.pack(announcement);

Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/AvatarDecorationService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ export class AvatarDecorationService implements OnApplicationShutdown {

@bindThis
public async create(options: Partial<MiAvatarDecoration>, moderator?: MiUser): Promise<MiAvatarDecoration> {
const created = await this.avatarDecorationsRepository.insert({
const created = await this.avatarDecorationsRepository.insertOne({
id: this.idService.gen(),
...options,
}).then(x => this.avatarDecorationsRepository.findOneByOrFail(x.identifiers[0]));
});

this.globalEventService.publishInternalEvent('avatarDecorationCreated', created);

Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/ClipService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ export class ClipService {
throw new ClipService.TooManyClipsError();
}

const clip = await this.clipsRepository.insert({
const clip = await this.clipsRepository.insertOne({
id: this.idService.gen(),
userId: me.id,
name: name,
isPublic: isPublic,
description: description,
}).then(x => this.clipsRepository.findOneByOrFail(x.identifiers[0]));
});

return clip;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/CustomEmojiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class CustomEmojiService implements OnApplicationShutdown {
localOnly: boolean;
roleIdsThatCanBeUsedThisEmojiAsReaction: MiRole['id'][];
}, moderator?: MiUser): Promise<MiEmoji> {
const emoji = await this.emojisRepository.insert({
const emoji = await this.emojisRepository.insertOne({
id: this.idService.gen(),
updatedAt: new Date(),
name: data.name,
Expand All @@ -82,7 +82,7 @@ export class CustomEmojiService implements OnApplicationShutdown {
isSensitive: data.isSensitive,
localOnly: data.localOnly,
roleIdsThatCanBeUsedThisEmojiAsReaction: data.roleIdsThatCanBeUsedThisEmojiAsReaction,
}).then(x => this.emojisRepository.findOneByOrFail(x.identifiers[0]));
});

if (data.host == null) {
this.localEmojisCache.refresh();
Expand Down
6 changes: 3 additions & 3 deletions packages/backend/src/core/DriveService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export class DriveService {
file.size = size;
file.storedInternal = false;

return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
return await this.driveFilesRepository.insertOne(file);
} else { // use internal storage
const accessKey = randomUUID();
const thumbnailAccessKey = 'thumbnail-' + randomUUID();
Expand Down Expand Up @@ -254,7 +254,7 @@ export class DriveService {
file.md5 = hash;
file.size = size;

return await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
return await this.driveFilesRepository.insertOne(file);
}
}

Expand Down Expand Up @@ -615,7 +615,7 @@ export class DriveService {
file.type = info.type.mime;
file.storedInternal = false;

file = await this.driveFilesRepository.insert(file).then(x => this.driveFilesRepository.findOneByOrFail(x.identifiers[0]));
file = await this.driveFilesRepository.insertOne(file);
} catch (err) {
// duplicate key error (when already registered)
if (isDuplicateKeyValueError(err)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/FederatedInstanceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ export class FederatedInstanceService implements OnApplicationShutdown {
const index = await this.instancesRepository.findOneBy({ host });

if (index == null) {
const i = await this.instancesRepository.insert({
const i = await this.instancesRepository.insertOne({
id: this.idService.gen(),
host,
firstRetrievedAt: new Date(),
}).then(x => this.instancesRepository.findOneByOrFail(x.identifiers[0]));
});

this.federatedInstanceCache.set(host, i);
return i;
Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/RelayService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,11 @@ export class RelayService {

@bindThis
public async addRelay(inbox: string): Promise<MiRelay> {
const relay = await this.relaysRepository.insert({
const relay = await this.relaysRepository.insertOne({
id: this.idService.gen(),
inbox,
status: 'requesting',
}).then(x => this.relaysRepository.findOneByOrFail(x.identifiers[0]));
});

const relayActor = await this.getRelayActor();
const follow = await this.apRendererService.renderFollowRelay(relay, relayActor);
Expand Down
7 changes: 2 additions & 5 deletions packages/backend/src/core/ReversiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ export class ReversiService implements OnApplicationShutdown, OnModuleInit {

@bindThis
private async matched(parentId: MiUser['id'], childId: MiUser['id'], options: { noIrregularRules: boolean; }): Promise<MiReversiGame> {
const game = await this.reversiGamesRepository.insert({
const game = await this.reversiGamesRepository.insertOne({
id: this.idService.gen(),
user1Id: parentId,
user2Id: childId,
Expand All @@ -294,10 +294,7 @@ export class ReversiService implements OnApplicationShutdown, OnModuleInit {
bw: 'random',
isLlotheo: false,
noIrregularRules: options.noIrregularRules,
}).then(x => this.reversiGamesRepository.findOneOrFail({
where: { id: x.identifiers[0].id },
relations: ['user1', 'user2'],
}));
}, { relations: ['user1', 'user2'] });
this.cacheGame(game);

const packed = await this.reversiGameEntityService.packDetail(game);
Expand Down
8 changes: 4 additions & 4 deletions packages/backend/src/core/RoleService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,12 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit {
}
}

const created = await this.roleAssignmentsRepository.insert({
const created = await this.roleAssignmentsRepository.insertOne({
id: this.idService.gen(now),
expiresAt: expiresAt,
roleId: roleId,
userId: userId,
}).then(x => this.roleAssignmentsRepository.findOneByOrFail(x.identifiers[0]));
});

this.rolesRepository.update(roleId, {
lastUsedAt: new Date(),
Expand Down Expand Up @@ -558,7 +558,7 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit {
@bindThis
public async create(values: Partial<MiRole>, moderator?: MiUser): Promise<MiRole> {
const date = new Date();
const created = await this.rolesRepository.insert({
const created = await this.rolesRepository.insertOne({
id: this.idService.gen(date.getTime()),
updatedAt: date,
lastUsedAt: date,
Expand All @@ -576,7 +576,7 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit {
canEditMembersByModerator: values.canEditMembersByModerator,
displayOrder: values.displayOrder,
policies: values.policies,
}).then(x => this.rolesRepository.findOneByOrFail(x.identifiers[0]));
});

this.globalEventService.publishInternalEvent('roleCreated', created);

Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/UserFollowingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ export class UserFollowingService implements OnModuleInit {
followerId: follower.id,
});

const followRequest = await this.followRequestsRepository.insert({
const followRequest = await this.followRequestsRepository.insertOne({
id: this.idService.gen(),
followerId: follower.id,
followeeId: followee.id,
Expand All @@ -531,7 +531,7 @@ export class UserFollowingService implements OnModuleInit {
followeeHost: followee.host,
followeeInbox: this.userEntityService.isRemoteUser(followee) ? followee.inbox : undefined,
followeeSharedInbox: this.userEntityService.isRemoteUser(followee) ? followee.sharedInbox : undefined,
}).then(x => this.followRequestsRepository.findOneByOrFail(x.identifiers[0]));
});

// Publish receiveRequest event
if (this.userEntityService.isLocalUser(followee)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/backend/src/core/activitypub/models/ApNoteService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ export class ApNoteService {

this.logger.info(`register emoji host=${host}, name=${name}`);

return await this.emojisRepository.insert({
return await this.emojisRepository.insertOne({
id: this.idService.gen(),
host,
name,
Expand All @@ -416,7 +416,7 @@ export class ApNoteService {
publicUrl: tag.icon.url,
updatedAt: new Date(),
aliases: [],
}).then(x => this.emojisRepository.findOneByOrFail(x.identifiers[0]));
});
}));
}
}
23 changes: 14 additions & 9 deletions packages/backend/src/core/chart/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import { EntitySchema, LessThan, Between } from 'typeorm';
import { dateUTC, isTimeSame, isTimeBefore, subtractTime, addTime } from '@/misc/prelude/time.js';
import type Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import type { Repository, DataSource } from 'typeorm';
import { MiRepository, miRepository } from '@/models/_.js';
import type { DataSource, Repository } from 'typeorm';

const COLUMN_PREFIX = '___' as const;
const UNIQUE_TEMP_COLUMN_PREFIX = 'unique_temp___' as const;
Expand Down Expand Up @@ -145,10 +146,10 @@ export default abstract class Chart<T extends Schema> {
group: string | null;
}[] = [];
// ↓にしたいけどfindOneとかで型エラーになる
//private repositoryForHour: Repository<RawRecord<T>>;
//private repositoryForDay: Repository<RawRecord<T>>;
private repositoryForHour: Repository<{ id: number; group?: string | null; date: number; }>;
private repositoryForDay: Repository<{ id: number; group?: string | null; date: number; }>;
//private repositoryForHour: Repository<RawRecord<T>> & MiRepository<RawRecord<T>>;
//private repositoryForDay: Repository<RawRecord<T>> & MiRepository<RawRecord<T>>;
private repositoryForHour: Repository<{ id: number; group?: string | null; date: number; }> & MiRepository<{ id: number; group?: string | null; date: number; }>;
private repositoryForDay: Repository<{ id: number; group?: string | null; date: number; }> & MiRepository<{ id: number; group?: string | null; date: number; }>;

/**
* 1日に一回程度実行されれば良いような計算処理を入れる(主にCASCADE削除などアプリケーション側で感知できない変動によるズレの修正用)
Expand Down Expand Up @@ -211,6 +212,10 @@ export default abstract class Chart<T extends Schema> {
} {
const createEntity = (span: 'hour' | 'day'): EntitySchema => new EntitySchema({
name:
span === 'hour' ? `ChartX${name}` :
span === 'day' ? `ChartDayX${name}` :
new Error('not happen') as never,
tableName:
span === 'hour' ? `__chart__${camelToSnake(name)}` :
span === 'day' ? `__chart_day__${camelToSnake(name)}` :
new Error('not happen') as never,
Expand Down Expand Up @@ -271,8 +276,8 @@ export default abstract class Chart<T extends Schema> {
this.logger = logger;

const { hour, day } = Chart.schemaToEntity(name, schema, grouped);
this.repositoryForHour = db.getRepository<{ id: number; group?: string | null; date: number; }>(hour);
this.repositoryForDay = db.getRepository<{ id: number; group?: string | null; date: number; }>(day);
this.repositoryForHour = db.getRepository<{ id: number; group?: string | null; date: number; }>(hour).extend(miRepository as MiRepository<{ id: number; group?: string | null; date: number; }>);
this.repositoryForDay = db.getRepository<{ id: number; group?: string | null; date: number; }>(day).extend(miRepository as MiRepository<{ id: number; group?: string | null; date: number; }>);
}

@bindThis
Expand Down Expand Up @@ -387,11 +392,11 @@ export default abstract class Chart<T extends Schema> {
}

// 新規ログ挿入
log = await repository.insert({
log = await repository.insertOne({
date: date,
...(group ? { group: group } : {}),
...columns,
}).then(x => repository.findOneByOrFail(x.identifiers[0])) as RawRecord<T>;
}) as RawRecord<T>;

this.logger.info(`${this.name + (group ? `:${group}` : '')}(${span}): New commit created`);

Expand Down
Loading

0 comments on commit 2b8056a

Please sign in to comment.