mirror of
https://github.com/immich-app/immich.git
synced 2025-05-24 01:12:58 -04:00
refactor: database repository (#16593)
* refactor: database repository * fix error reindex check * chore: remove WIP code --------- Co-authored-by: mertalev <101130780+mertalev@users.noreply.github.com>
This commit is contained in:
parent
fe931faf17
commit
2cdbb0a37c
@ -1,8 +1,7 @@
|
|||||||
import { BullModule } from '@nestjs/bullmq';
|
import { BullModule } from '@nestjs/bullmq';
|
||||||
import { Inject, Module, OnModuleDestroy, OnModuleInit, ValidationPipe } from '@nestjs/common';
|
import { Inject, Module, OnModuleDestroy, OnModuleInit, ValidationPipe } from '@nestjs/common';
|
||||||
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE, ModuleRef } from '@nestjs/core';
|
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||||
import { ScheduleModule, SchedulerRegistry } from '@nestjs/schedule';
|
import { ScheduleModule, SchedulerRegistry } from '@nestjs/schedule';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { PostgresJSDialect } from 'kysely-postgres-js';
|
import { PostgresJSDialect } from 'kysely-postgres-js';
|
||||||
import { ClsModule } from 'nestjs-cls';
|
import { ClsModule } from 'nestjs-cls';
|
||||||
import { KyselyModule } from 'nestjs-kysely';
|
import { KyselyModule } from 'nestjs-kysely';
|
||||||
@ -11,7 +10,6 @@ import postgres from 'postgres';
|
|||||||
import { commands } from 'src/commands';
|
import { commands } from 'src/commands';
|
||||||
import { IWorker } from 'src/constants';
|
import { IWorker } from 'src/constants';
|
||||||
import { controllers } from 'src/controllers';
|
import { controllers } from 'src/controllers';
|
||||||
import { entities } from 'src/entities';
|
|
||||||
import { ImmichWorker } from 'src/enum';
|
import { ImmichWorker } from 'src/enum';
|
||||||
import { AuthGuard } from 'src/middleware/auth.guard';
|
import { AuthGuard } from 'src/middleware/auth.guard';
|
||||||
import { ErrorInterceptor } from 'src/middleware/error.interceptor';
|
import { ErrorInterceptor } from 'src/middleware/error.interceptor';
|
||||||
@ -27,7 +25,6 @@ import { teardownTelemetry, TelemetryRepository } from 'src/repositories/telemet
|
|||||||
import { services } from 'src/services';
|
import { services } from 'src/services';
|
||||||
import { AuthService } from 'src/services/auth.service';
|
import { AuthService } from 'src/services/auth.service';
|
||||||
import { CliService } from 'src/services/cli.service';
|
import { CliService } from 'src/services/cli.service';
|
||||||
import { DatabaseService } from 'src/services/database.service';
|
|
||||||
|
|
||||||
const common = [...repositories, ...services, GlobalExceptionFilter];
|
const common = [...repositories, ...services, GlobalExceptionFilter];
|
||||||
|
|
||||||
@ -48,18 +45,6 @@ const imports = [
|
|||||||
BullModule.registerQueue(...bull.queues),
|
BullModule.registerQueue(...bull.queues),
|
||||||
ClsModule.forRoot(cls.config),
|
ClsModule.forRoot(cls.config),
|
||||||
OpenTelemetryModule.forRoot(otel),
|
OpenTelemetryModule.forRoot(otel),
|
||||||
TypeOrmModule.forRootAsync({
|
|
||||||
inject: [ModuleRef],
|
|
||||||
useFactory: (moduleRef: ModuleRef) => {
|
|
||||||
return {
|
|
||||||
...database.config.typeorm,
|
|
||||||
poolErrorHandler: (error) => {
|
|
||||||
moduleRef.get(DatabaseService, { strict: false }).handleConnectionError(error);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
TypeOrmModule.forFeature(entities),
|
|
||||||
KyselyModule.forRoot({
|
KyselyModule.forRoot({
|
||||||
dialect: new PostgresJSDialect({ postgres: postgres(database.config.kysely) }),
|
dialect: new PostgresJSDialect({ postgres: postgres(database.config.kysely) }),
|
||||||
log(event) {
|
log(event) {
|
||||||
|
@ -3,7 +3,6 @@ import { INestApplication } from '@nestjs/common';
|
|||||||
import { Reflector } from '@nestjs/core';
|
import { Reflector } from '@nestjs/core';
|
||||||
import { SchedulerRegistry } from '@nestjs/schedule';
|
import { SchedulerRegistry } from '@nestjs/schedule';
|
||||||
import { Test } from '@nestjs/testing';
|
import { Test } from '@nestjs/testing';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
||||||
import { ClassConstructor } from 'class-transformer';
|
import { ClassConstructor } from 'class-transformer';
|
||||||
import { PostgresJSDialect } from 'kysely-postgres-js';
|
import { PostgresJSDialect } from 'kysely-postgres-js';
|
||||||
import { ClsModule } from 'nestjs-cls';
|
import { ClsModule } from 'nestjs-cls';
|
||||||
@ -14,15 +13,13 @@ import { join } from 'node:path';
|
|||||||
import postgres from 'postgres';
|
import postgres from 'postgres';
|
||||||
import { format } from 'sql-formatter';
|
import { format } from 'sql-formatter';
|
||||||
import { GENERATE_SQL_KEY, GenerateSqlQueries } from 'src/decorators';
|
import { GENERATE_SQL_KEY, GenerateSqlQueries } from 'src/decorators';
|
||||||
import { entities } from 'src/entities';
|
|
||||||
import { repositories } from 'src/repositories';
|
import { repositories } from 'src/repositories';
|
||||||
import { AccessRepository } from 'src/repositories/access.repository';
|
import { AccessRepository } from 'src/repositories/access.repository';
|
||||||
import { ConfigRepository } from 'src/repositories/config.repository';
|
import { ConfigRepository } from 'src/repositories/config.repository';
|
||||||
import { LoggingRepository } from 'src/repositories/logging.repository';
|
import { LoggingRepository } from 'src/repositories/logging.repository';
|
||||||
import { AuthService } from 'src/services/auth.service';
|
import { AuthService } from 'src/services/auth.service';
|
||||||
import { Logger } from 'typeorm';
|
|
||||||
|
|
||||||
export class SqlLogger implements Logger {
|
export class SqlLogger {
|
||||||
queries: string[] = [];
|
queries: string[] = [];
|
||||||
errors: Array<{ error: string | Error; query: string }> = [];
|
errors: Array<{ error: string | Error; query: string }> = [];
|
||||||
|
|
||||||
@ -38,11 +35,6 @@ export class SqlLogger implements Logger {
|
|||||||
logQueryError(error: string | Error, query: string) {
|
logQueryError(error: string | Error, query: string) {
|
||||||
this.errors.push({ error, query });
|
this.errors.push({ error, query });
|
||||||
}
|
}
|
||||||
|
|
||||||
logQuerySlow() {}
|
|
||||||
logSchemaBuild() {}
|
|
||||||
logMigration() {}
|
|
||||||
log() {}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const reflector = new Reflector();
|
const reflector = new Reflector();
|
||||||
@ -94,13 +86,6 @@ class SqlGenerator {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
ClsModule.forRoot(cls.config),
|
ClsModule.forRoot(cls.config),
|
||||||
TypeOrmModule.forRoot({
|
|
||||||
...database.config.typeorm,
|
|
||||||
entities,
|
|
||||||
logging: ['query'],
|
|
||||||
logger: this.sqlLogger,
|
|
||||||
}),
|
|
||||||
TypeOrmModule.forFeature(entities),
|
|
||||||
OpenTelemetryModule.forRoot(otel),
|
OpenTelemetryModule.forRoot(otel),
|
||||||
],
|
],
|
||||||
providers: [...repositories, AuthService, SchedulerRegistry],
|
providers: [...repositories, AuthService, SchedulerRegistry],
|
||||||
|
@ -7,10 +7,6 @@ export const POSTGRES_VERSION_RANGE = '>=14.0.0';
|
|||||||
export const VECTORS_VERSION_RANGE = '>=0.2 <0.4';
|
export const VECTORS_VERSION_RANGE = '>=0.2 <0.4';
|
||||||
export const VECTOR_VERSION_RANGE = '>=0.5 <1';
|
export const VECTOR_VERSION_RANGE = '>=0.5 <1';
|
||||||
|
|
||||||
export const ASSET_FILE_CONFLICT_KEYS = ['assetId', 'type'] as const;
|
|
||||||
export const EXIF_CONFLICT_KEYS = ['assetId'] as const;
|
|
||||||
export const JOB_STATUS_CONFLICT_KEYS = ['assetId'] as const;
|
|
||||||
|
|
||||||
export const NEXT_RELEASE = 'NEXT_RELEASE';
|
export const NEXT_RELEASE = 'NEXT_RELEASE';
|
||||||
export const LIFECYCLE_EXTENSION = 'x-immich-lifecycle';
|
export const LIFECYCLE_EXTENSION = 'x-immich-lifecycle';
|
||||||
export const DEPRECATED_IN_PREFIX = 'This property was deprecated in ';
|
export const DEPRECATED_IN_PREFIX = 'This property was deprecated in ';
|
||||||
|
4
server/src/db.d.ts
vendored
4
server/src/db.d.ts
vendored
@ -4,7 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import type { ColumnType } from 'kysely';
|
import type { ColumnType } from 'kysely';
|
||||||
import { Permission, SyncEntityType } from 'src/enum';
|
import { AssetType, Permission, SyncEntityType } from 'src/enum';
|
||||||
|
|
||||||
export type ArrayType<T> = ArrayTypeImpl<T> extends (infer U)[] ? U[] : ArrayTypeImpl<T>;
|
export type ArrayType<T> = ArrayTypeImpl<T> extends (infer U)[] ? U[] : ArrayTypeImpl<T>;
|
||||||
|
|
||||||
@ -145,7 +145,7 @@ export interface Assets {
|
|||||||
stackId: string | null;
|
stackId: string | null;
|
||||||
status: Generated<AssetsStatusEnum>;
|
status: Generated<AssetsStatusEnum>;
|
||||||
thumbhash: Buffer | null;
|
thumbhash: Buffer | null;
|
||||||
type: string;
|
type: AssetType;
|
||||||
updatedAt: Generated<Timestamp>;
|
updatedAt: Generated<Timestamp>;
|
||||||
updateId: Generated<string>;
|
updateId: Generated<string>;
|
||||||
}
|
}
|
||||||
|
@ -1,61 +0,0 @@
|
|||||||
import { ActivityEntity } from 'src/entities/activity.entity';
|
|
||||||
import { AlbumUserEntity } from 'src/entities/album-user.entity';
|
|
||||||
import { AlbumEntity } from 'src/entities/album.entity';
|
|
||||||
import { APIKeyEntity } from 'src/entities/api-key.entity';
|
|
||||||
import { AssetFaceEntity } from 'src/entities/asset-face.entity';
|
|
||||||
import { AssetFileEntity } from 'src/entities/asset-files.entity';
|
|
||||||
import { AssetJobStatusEntity } from 'src/entities/asset-job-status.entity';
|
|
||||||
import { AssetEntity } from 'src/entities/asset.entity';
|
|
||||||
import { AuditEntity } from 'src/entities/audit.entity';
|
|
||||||
import { ExifEntity } from 'src/entities/exif.entity';
|
|
||||||
import { FaceSearchEntity } from 'src/entities/face-search.entity';
|
|
||||||
import { GeodataPlacesEntity } from 'src/entities/geodata-places.entity';
|
|
||||||
import { LibraryEntity } from 'src/entities/library.entity';
|
|
||||||
import { MemoryEntity } from 'src/entities/memory.entity';
|
|
||||||
import { MoveEntity } from 'src/entities/move.entity';
|
|
||||||
import { NaturalEarthCountriesEntity } from 'src/entities/natural-earth-countries.entity';
|
|
||||||
import { PartnerEntity } from 'src/entities/partner.entity';
|
|
||||||
import { PersonEntity } from 'src/entities/person.entity';
|
|
||||||
import { SessionEntity } from 'src/entities/session.entity';
|
|
||||||
import { SharedLinkEntity } from 'src/entities/shared-link.entity';
|
|
||||||
import { SmartSearchEntity } from 'src/entities/smart-search.entity';
|
|
||||||
import { StackEntity } from 'src/entities/stack.entity';
|
|
||||||
import { SessionSyncCheckpointEntity } from 'src/entities/sync-checkpoint.entity';
|
|
||||||
import { SystemMetadataEntity } from 'src/entities/system-metadata.entity';
|
|
||||||
import { TagEntity } from 'src/entities/tag.entity';
|
|
||||||
import { UserAuditEntity } from 'src/entities/user-audit.entity';
|
|
||||||
import { UserMetadataEntity } from 'src/entities/user-metadata.entity';
|
|
||||||
import { UserEntity } from 'src/entities/user.entity';
|
|
||||||
import { VersionHistoryEntity } from 'src/entities/version-history.entity';
|
|
||||||
|
|
||||||
export const entities = [
|
|
||||||
ActivityEntity,
|
|
||||||
AlbumEntity,
|
|
||||||
AlbumUserEntity,
|
|
||||||
APIKeyEntity,
|
|
||||||
AssetEntity,
|
|
||||||
AssetFaceEntity,
|
|
||||||
AssetFileEntity,
|
|
||||||
AssetJobStatusEntity,
|
|
||||||
AuditEntity,
|
|
||||||
ExifEntity,
|
|
||||||
FaceSearchEntity,
|
|
||||||
GeodataPlacesEntity,
|
|
||||||
NaturalEarthCountriesEntity,
|
|
||||||
MemoryEntity,
|
|
||||||
MoveEntity,
|
|
||||||
PartnerEntity,
|
|
||||||
PersonEntity,
|
|
||||||
SessionSyncCheckpointEntity,
|
|
||||||
SharedLinkEntity,
|
|
||||||
SmartSearchEntity,
|
|
||||||
StackEntity,
|
|
||||||
SystemMetadataEntity,
|
|
||||||
TagEntity,
|
|
||||||
UserEntity,
|
|
||||||
UserAuditEntity,
|
|
||||||
UserMetadataEntity,
|
|
||||||
SessionEntity,
|
|
||||||
LibraryEntity,
|
|
||||||
VersionHistoryEntity,
|
|
||||||
];
|
|
@ -2,6 +2,7 @@ import { MigrationInterface, QueryRunner } from 'typeorm';
|
|||||||
|
|
||||||
export class CreateUserTable1645130759468 implements MigrationInterface {
|
export class CreateUserTable1645130759468 implements MigrationInterface {
|
||||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
|
||||||
await queryRunner.query(`
|
await queryRunner.query(`
|
||||||
create table if not exists users
|
create table if not exists users
|
||||||
(
|
(
|
||||||
|
21
server/src/queries/database.repository.sql
Normal file
21
server/src/queries/database.repository.sql
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
-- NOTE: This file is auto generated by ./sql-generator
|
||||||
|
|
||||||
|
-- DatabaseRepository.getExtensionVersion
|
||||||
|
SELECT
|
||||||
|
default_version as "availableVersion",
|
||||||
|
installed_version as "installedVersion"
|
||||||
|
FROM
|
||||||
|
pg_available_extensions
|
||||||
|
WHERE
|
||||||
|
name = $1
|
||||||
|
|
||||||
|
-- DatabaseRepository.getPostgresVersion
|
||||||
|
SHOW server_version
|
||||||
|
|
||||||
|
-- DatabaseRepository.shouldReindex
|
||||||
|
SELECT
|
||||||
|
idx_status
|
||||||
|
FROM
|
||||||
|
pg_vector_index_stat
|
||||||
|
WHERE
|
||||||
|
indexname = $1
|
@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import { Insertable, Kysely, UpdateResult, Updateable, sql } from 'kysely';
|
import { Insertable, Kysely, UpdateResult, Updateable, sql } from 'kysely';
|
||||||
import { isEmpty, isUndefined, omitBy } from 'lodash';
|
import { isEmpty, isUndefined, omitBy } from 'lodash';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import { ASSET_FILE_CONFLICT_KEYS, EXIF_CONFLICT_KEYS, JOB_STATUS_CONFLICT_KEYS } from 'src/constants';
|
|
||||||
import { AssetFiles, AssetJobStatus, Assets, DB, Exif } from 'src/db';
|
import { AssetFiles, AssetJobStatus, Assets, DB, Exif } from 'src/db';
|
||||||
import { Chunked, ChunkedArray, DummyValue, GenerateSql } from 'src/decorators';
|
import { Chunked, ChunkedArray, DummyValue, GenerateSql } from 'src/decorators';
|
||||||
import {
|
import {
|
||||||
@ -24,7 +23,7 @@ import {
|
|||||||
} from 'src/entities/asset.entity';
|
} from 'src/entities/asset.entity';
|
||||||
import { AssetFileType, AssetOrder, AssetStatus, AssetType } from 'src/enum';
|
import { AssetFileType, AssetOrder, AssetStatus, AssetType } from 'src/enum';
|
||||||
import { AssetSearchOptions, SearchExploreItem, SearchExploreItemSet } from 'src/repositories/search.repository';
|
import { AssetSearchOptions, SearchExploreItem, SearchExploreItemSet } from 'src/repositories/search.repository';
|
||||||
import { anyUuid, asUuid, mapUpsertColumns, unnest } from 'src/utils/database';
|
import { anyUuid, asUuid, removeUndefinedKeys, unnest } from 'src/utils/database';
|
||||||
import { globToSqlPattern } from 'src/utils/misc';
|
import { globToSqlPattern } from 'src/utils/misc';
|
||||||
import { Paginated, PaginationOptions, paginationHelper } from 'src/utils/pagination';
|
import { Paginated, PaginationOptions, paginationHelper } from 'src/utils/pagination';
|
||||||
|
|
||||||
@ -162,7 +161,41 @@ export class AssetRepository {
|
|||||||
.insertInto('exif')
|
.insertInto('exif')
|
||||||
.values(value)
|
.values(value)
|
||||||
.onConflict((oc) =>
|
.onConflict((oc) =>
|
||||||
oc.columns(EXIF_CONFLICT_KEYS).doUpdateSet(() => mapUpsertColumns('exif', value, EXIF_CONFLICT_KEYS)),
|
oc.column('assetId').doUpdateSet((eb) =>
|
||||||
|
removeUndefinedKeys(
|
||||||
|
{
|
||||||
|
description: eb.ref('excluded.description'),
|
||||||
|
exifImageWidth: eb.ref('excluded.exifImageWidth'),
|
||||||
|
exifImageHeight: eb.ref('excluded.exifImageHeight'),
|
||||||
|
fileSizeInByte: eb.ref('excluded.fileSizeInByte'),
|
||||||
|
orientation: eb.ref('excluded.orientation'),
|
||||||
|
dateTimeOriginal: eb.ref('excluded.dateTimeOriginal'),
|
||||||
|
modifyDate: eb.ref('excluded.modifyDate'),
|
||||||
|
timeZone: eb.ref('excluded.timeZone'),
|
||||||
|
latitude: eb.ref('excluded.latitude'),
|
||||||
|
longitude: eb.ref('excluded.longitude'),
|
||||||
|
projectionType: eb.ref('excluded.projectionType'),
|
||||||
|
city: eb.ref('excluded.city'),
|
||||||
|
livePhotoCID: eb.ref('excluded.livePhotoCID'),
|
||||||
|
autoStackId: eb.ref('excluded.autoStackId'),
|
||||||
|
state: eb.ref('excluded.state'),
|
||||||
|
country: eb.ref('excluded.country'),
|
||||||
|
make: eb.ref('excluded.make'),
|
||||||
|
model: eb.ref('excluded.model'),
|
||||||
|
lensModel: eb.ref('excluded.lensModel'),
|
||||||
|
fNumber: eb.ref('excluded.fNumber'),
|
||||||
|
focalLength: eb.ref('excluded.focalLength'),
|
||||||
|
iso: eb.ref('excluded.iso'),
|
||||||
|
exposureTime: eb.ref('excluded.exposureTime'),
|
||||||
|
profileDescription: eb.ref('excluded.profileDescription'),
|
||||||
|
colorspace: eb.ref('excluded.colorspace'),
|
||||||
|
bitsPerSample: eb.ref('excluded.bitsPerSample'),
|
||||||
|
rating: eb.ref('excluded.rating'),
|
||||||
|
fps: eb.ref('excluded.fps'),
|
||||||
|
},
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
@ -177,9 +210,18 @@ export class AssetRepository {
|
|||||||
.insertInto('asset_job_status')
|
.insertInto('asset_job_status')
|
||||||
.values(values)
|
.values(values)
|
||||||
.onConflict((oc) =>
|
.onConflict((oc) =>
|
||||||
oc
|
oc.column('assetId').doUpdateSet((eb) =>
|
||||||
.columns(JOB_STATUS_CONFLICT_KEYS)
|
removeUndefinedKeys(
|
||||||
.doUpdateSet(() => mapUpsertColumns('asset_job_status', values[0], JOB_STATUS_CONFLICT_KEYS)),
|
{
|
||||||
|
duplicatesDetectedAt: eb.ref('excluded.duplicatesDetectedAt'),
|
||||||
|
facesRecognizedAt: eb.ref('excluded.facesRecognizedAt'),
|
||||||
|
metadataExtractedAt: eb.ref('excluded.metadataExtractedAt'),
|
||||||
|
previewAt: eb.ref('excluded.previewAt'),
|
||||||
|
thumbnailAt: eb.ref('excluded.thumbnailAt'),
|
||||||
|
},
|
||||||
|
values[0],
|
||||||
|
),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
@ -936,9 +978,9 @@ export class AssetRepository {
|
|||||||
.insertInto('asset_files')
|
.insertInto('asset_files')
|
||||||
.values(value)
|
.values(value)
|
||||||
.onConflict((oc) =>
|
.onConflict((oc) =>
|
||||||
oc
|
oc.columns(['assetId', 'type']).doUpdateSet((eb) => ({
|
||||||
.columns(ASSET_FILE_CONFLICT_KEYS)
|
path: eb.ref('excluded.path'),
|
||||||
.doUpdateSet(() => mapUpsertColumns('asset_files', value, ASSET_FILE_CONFLICT_KEYS)),
|
})),
|
||||||
)
|
)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
@ -953,9 +995,9 @@ export class AssetRepository {
|
|||||||
.insertInto('asset_files')
|
.insertInto('asset_files')
|
||||||
.values(values)
|
.values(values)
|
||||||
.onConflict((oc) =>
|
.onConflict((oc) =>
|
||||||
oc
|
oc.columns(['assetId', 'type']).doUpdateSet((eb) => ({
|
||||||
.columns(ASSET_FILE_CONFLICT_KEYS)
|
path: eb.ref('excluded.path'),
|
||||||
.doUpdateSet(() => mapUpsertColumns('asset_files', values[0], ASSET_FILE_CONFLICT_KEYS)),
|
})),
|
||||||
)
|
)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,17 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { InjectDataSource } from '@nestjs/typeorm';
|
|
||||||
import AsyncLock from 'async-lock';
|
import AsyncLock from 'async-lock';
|
||||||
import { Kysely, sql } from 'kysely';
|
import { Kysely, sql, Transaction } from 'kysely';
|
||||||
import { InjectKysely } from 'nestjs-kysely';
|
import { InjectKysely } from 'nestjs-kysely';
|
||||||
import semver from 'semver';
|
import semver from 'semver';
|
||||||
import { EXTENSION_NAMES, POSTGRES_VERSION_RANGE, VECTOR_VERSION_RANGE, VECTORS_VERSION_RANGE } from 'src/constants';
|
import { EXTENSION_NAMES, POSTGRES_VERSION_RANGE, VECTOR_VERSION_RANGE, VECTORS_VERSION_RANGE } from 'src/constants';
|
||||||
import { DB } from 'src/db';
|
import { DB } from 'src/db';
|
||||||
|
import { GenerateSql } from 'src/decorators';
|
||||||
import { DatabaseExtension, DatabaseLock, VectorIndex } from 'src/enum';
|
import { DatabaseExtension, DatabaseLock, VectorIndex } from 'src/enum';
|
||||||
import { ConfigRepository } from 'src/repositories/config.repository';
|
import { ConfigRepository } from 'src/repositories/config.repository';
|
||||||
import { LoggingRepository } from 'src/repositories/logging.repository';
|
import { LoggingRepository } from 'src/repositories/logging.repository';
|
||||||
import { ExtensionVersion, VectorExtension, VectorUpdateResult } from 'src/types';
|
import { ExtensionVersion, VectorExtension, VectorUpdateResult } from 'src/types';
|
||||||
import { UPSERT_COLUMNS } from 'src/utils/database';
|
|
||||||
import { isValidInteger } from 'src/validation';
|
import { isValidInteger } from 'src/validation';
|
||||||
import { DataSource, EntityManager, EntityMetadata, QueryRunner } from 'typeorm';
|
import { DataSource } from 'typeorm';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DatabaseRepository {
|
export class DatabaseRepository {
|
||||||
@ -21,9 +20,8 @@ export class DatabaseRepository {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@InjectKysely() private db: Kysely<DB>,
|
@InjectKysely() private db: Kysely<DB>,
|
||||||
@InjectDataSource() private dataSource: DataSource,
|
|
||||||
private logger: LoggingRepository,
|
private logger: LoggingRepository,
|
||||||
configRepository: ConfigRepository,
|
private configRepository: ConfigRepository,
|
||||||
) {
|
) {
|
||||||
this.vectorExtension = configRepository.getEnv().database.vectorExtension;
|
this.vectorExtension = configRepository.getEnv().database.vectorExtension;
|
||||||
this.logger.setContext(DatabaseRepository.name);
|
this.logger.setContext(DatabaseRepository.name);
|
||||||
@ -33,43 +31,24 @@ export class DatabaseRepository {
|
|||||||
await this.db.destroy();
|
await this.db.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
init() {
|
@GenerateSql({ params: [DatabaseExtension.VECTORS] })
|
||||||
for (const metadata of this.dataSource.entityMetadatas) {
|
|
||||||
const table = metadata.tableName as keyof DB;
|
|
||||||
UPSERT_COLUMNS[table] = this.getUpsertColumns(metadata);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async reconnect() {
|
|
||||||
try {
|
|
||||||
if (this.dataSource.isInitialized) {
|
|
||||||
await this.dataSource.destroy();
|
|
||||||
}
|
|
||||||
const { isInitialized } = await this.dataSource.initialize();
|
|
||||||
return isInitialized;
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.error(`Database connection failed: ${error}`);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async getExtensionVersion(extension: DatabaseExtension): Promise<ExtensionVersion> {
|
async getExtensionVersion(extension: DatabaseExtension): Promise<ExtensionVersion> {
|
||||||
const [res]: ExtensionVersion[] = await this.dataSource.query(
|
const { rows } = await sql<ExtensionVersion>`
|
||||||
`SELECT default_version as "availableVersion", installed_version as "installedVersion"
|
SELECT default_version as "availableVersion", installed_version as "installedVersion"
|
||||||
FROM pg_available_extensions
|
FROM pg_available_extensions
|
||||||
WHERE name = $1`,
|
WHERE name = ${extension}
|
||||||
[extension],
|
`.execute(this.db);
|
||||||
);
|
return rows[0] ?? { availableVersion: null, installedVersion: null };
|
||||||
return res ?? { availableVersion: null, installedVersion: null };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getExtensionVersionRange(extension: VectorExtension): string {
|
getExtensionVersionRange(extension: VectorExtension): string {
|
||||||
return extension === DatabaseExtension.VECTORS ? VECTORS_VERSION_RANGE : VECTOR_VERSION_RANGE;
|
return extension === DatabaseExtension.VECTORS ? VECTORS_VERSION_RANGE : VECTOR_VERSION_RANGE;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GenerateSql()
|
||||||
async getPostgresVersion(): Promise<string> {
|
async getPostgresVersion(): Promise<string> {
|
||||||
const [{ server_version: version }] = await this.dataSource.query(`SHOW server_version`);
|
const { rows } = await sql<{ server_version: string }>`SHOW server_version`.execute(this.db);
|
||||||
return version;
|
return rows[0].server_version;
|
||||||
}
|
}
|
||||||
|
|
||||||
getPostgresVersionRange(): string {
|
getPostgresVersionRange(): string {
|
||||||
@ -77,7 +56,7 @@ export class DatabaseRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async createExtension(extension: DatabaseExtension): Promise<void> {
|
async createExtension(extension: DatabaseExtension): Promise<void> {
|
||||||
await this.dataSource.query(`CREATE EXTENSION IF NOT EXISTS ${extension}`);
|
await sql`CREATE EXTENSION IF NOT EXISTS ${sql.raw(extension)}`.execute(this.db);
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateVectorExtension(extension: VectorExtension, targetVersion?: string): Promise<VectorUpdateResult> {
|
async updateVectorExtension(extension: VectorExtension, targetVersion?: string): Promise<VectorUpdateResult> {
|
||||||
@ -93,23 +72,23 @@ export class DatabaseRepository {
|
|||||||
|
|
||||||
const isVectors = extension === DatabaseExtension.VECTORS;
|
const isVectors = extension === DatabaseExtension.VECTORS;
|
||||||
let restartRequired = false;
|
let restartRequired = false;
|
||||||
await this.dataSource.manager.transaction(async (manager) => {
|
await this.db.transaction().execute(async (tx) => {
|
||||||
await this.setSearchPath(manager);
|
await this.setSearchPath(tx);
|
||||||
|
|
||||||
if (isVectors && installedVersion === '0.1.1') {
|
if (isVectors && installedVersion === '0.1.1') {
|
||||||
await this.setExtVersion(manager, DatabaseExtension.VECTORS, '0.1.11');
|
await this.setExtVersion(tx, DatabaseExtension.VECTORS, '0.1.11');
|
||||||
}
|
}
|
||||||
|
|
||||||
const isSchemaUpgrade = semver.satisfies(installedVersion, '0.1.1 || 0.1.11');
|
const isSchemaUpgrade = semver.satisfies(installedVersion, '0.1.1 || 0.1.11');
|
||||||
if (isSchemaUpgrade && isVectors) {
|
if (isSchemaUpgrade && isVectors) {
|
||||||
await this.updateVectorsSchema(manager);
|
await this.updateVectorsSchema(tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
await manager.query(`ALTER EXTENSION ${extension} UPDATE TO '${targetVersion}'`);
|
await sql`ALTER EXTENSION ${sql.raw(extension)} UPDATE TO ${sql.lit(targetVersion)}`.execute(tx);
|
||||||
|
|
||||||
const diff = semver.diff(installedVersion, targetVersion);
|
const diff = semver.diff(installedVersion, targetVersion);
|
||||||
if (isVectors && diff && ['minor', 'major'].includes(diff)) {
|
if (isVectors && diff && ['minor', 'major'].includes(diff)) {
|
||||||
await manager.query('SELECT pgvectors_upgrade()');
|
await sql`SELECT pgvectors_upgrade()`.execute(tx);
|
||||||
restartRequired = true;
|
restartRequired = true;
|
||||||
} else {
|
} else {
|
||||||
await this.reindex(VectorIndex.CLIP);
|
await this.reindex(VectorIndex.CLIP);
|
||||||
@ -122,7 +101,7 @@ export class DatabaseRepository {
|
|||||||
|
|
||||||
async reindex(index: VectorIndex): Promise<void> {
|
async reindex(index: VectorIndex): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.dataSource.query(`REINDEX INDEX ${index}`);
|
await sql`REINDEX INDEX ${sql.raw(index)}`.execute(this.db);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.vectorExtension !== DatabaseExtension.VECTORS) {
|
if (this.vectorExtension !== DatabaseExtension.VECTORS) {
|
||||||
throw error;
|
throw error;
|
||||||
@ -131,29 +110,34 @@ export class DatabaseRepository {
|
|||||||
|
|
||||||
const table = await this.getIndexTable(index);
|
const table = await this.getIndexTable(index);
|
||||||
const dimSize = await this.getDimSize(table);
|
const dimSize = await this.getDimSize(table);
|
||||||
await this.dataSource.manager.transaction(async (manager) => {
|
await this.db.transaction().execute(async (tx) => {
|
||||||
await this.setSearchPath(manager);
|
await this.setSearchPath(tx);
|
||||||
await manager.query(`DROP INDEX IF EXISTS ${index}`);
|
await sql`DROP INDEX IF EXISTS ${sql.raw(index)}`.execute(tx);
|
||||||
await manager.query(`ALTER TABLE ${table} ALTER COLUMN embedding SET DATA TYPE real[]`);
|
await sql`ALTER TABLE ${sql.raw(table)} ALTER COLUMN embedding SET DATA TYPE real[]`.execute(tx);
|
||||||
await manager.query(`ALTER TABLE ${table} ALTER COLUMN embedding SET DATA TYPE vector(${dimSize})`);
|
await sql`ALTER TABLE ${sql.raw(table)} ALTER COLUMN embedding SET DATA TYPE vector(${sql.raw(String(dimSize))})`.execute(
|
||||||
await manager.query(`SET vectors.pgvector_compatibility=on`);
|
tx,
|
||||||
await manager.query(`
|
);
|
||||||
CREATE INDEX IF NOT EXISTS ${index} ON ${table}
|
await sql`SET vectors.pgvector_compatibility=on`.execute(tx);
|
||||||
|
await sql`
|
||||||
|
CREATE INDEX IF NOT EXISTS ${sql.raw(index)} ON ${sql.raw(table)}
|
||||||
USING hnsw (embedding vector_cosine_ops)
|
USING hnsw (embedding vector_cosine_ops)
|
||||||
WITH (ef_construction = 300, m = 16)`);
|
WITH (ef_construction = 300, m = 16)
|
||||||
|
`.execute(tx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GenerateSql({ params: [VectorIndex.CLIP] })
|
||||||
async shouldReindex(name: VectorIndex): Promise<boolean> {
|
async shouldReindex(name: VectorIndex): Promise<boolean> {
|
||||||
if (this.vectorExtension !== DatabaseExtension.VECTORS) {
|
if (this.vectorExtension !== DatabaseExtension.VECTORS) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const query = `SELECT idx_status FROM pg_vector_index_stat WHERE indexname = $1`;
|
const { rows } = await sql<{
|
||||||
const res = await this.dataSource.query(query, [name]);
|
idx_status: string;
|
||||||
return res[0]?.['idx_status'] === 'UPGRADE';
|
}>`SELECT idx_status FROM pg_vector_index_stat WHERE indexname = ${name}`.execute(this.db);
|
||||||
|
return rows[0]?.idx_status === 'UPGRADE';
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message: string = (error as any).message;
|
const message: string = (error as any).message;
|
||||||
if (message.includes('index is not existing')) {
|
if (message.includes('index is not existing')) {
|
||||||
@ -165,44 +149,45 @@ export class DatabaseRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async setSearchPath(manager: EntityManager): Promise<void> {
|
private async setSearchPath(tx: Transaction<DB>): Promise<void> {
|
||||||
await manager.query(`SET search_path TO "$user", public, vectors`);
|
await sql`SET search_path TO "$user", public, vectors`.execute(tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async setExtVersion(manager: EntityManager, extName: DatabaseExtension, version: string): Promise<void> {
|
private async setExtVersion(tx: Transaction<DB>, extName: DatabaseExtension, version: string): Promise<void> {
|
||||||
const query = `UPDATE pg_catalog.pg_extension SET extversion = $1 WHERE extname = $2`;
|
await sql`UPDATE pg_catalog.pg_extension SET extversion = ${version} WHERE extname = ${extName}`.execute(tx);
|
||||||
await manager.query(query, [version, extName]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getIndexTable(index: VectorIndex): Promise<string> {
|
private async getIndexTable(index: VectorIndex): Promise<string> {
|
||||||
const tableQuery = `SELECT relname FROM pg_stat_all_indexes WHERE indexrelname = $1`;
|
const { rows } = await sql<{
|
||||||
const [res]: { relname: string | null }[] = await this.dataSource.manager.query(tableQuery, [index]);
|
relname: string | null;
|
||||||
const table = res?.relname;
|
}>`SELECT relname FROM pg_stat_all_indexes WHERE indexrelname = ${index}`.execute(this.db);
|
||||||
|
const table = rows[0]?.relname;
|
||||||
if (!table) {
|
if (!table) {
|
||||||
throw new Error(`Could not find table for index ${index}`);
|
throw new Error(`Could not find table for index ${index}`);
|
||||||
}
|
}
|
||||||
return table;
|
return table;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async updateVectorsSchema(manager: EntityManager): Promise<void> {
|
private async updateVectorsSchema(tx: Transaction<DB>): Promise<void> {
|
||||||
const extension = DatabaseExtension.VECTORS;
|
const extension = DatabaseExtension.VECTORS;
|
||||||
await manager.query(`CREATE SCHEMA IF NOT EXISTS ${extension}`);
|
await sql`CREATE SCHEMA IF NOT EXISTS ${extension}`.execute(tx);
|
||||||
await manager.query('UPDATE pg_catalog.pg_extension SET extrelocatable = true WHERE extname = $1', [extension]);
|
await sql`UPDATE pg_catalog.pg_extension SET extrelocatable = true WHERE extname = ${extension}`.execute(tx);
|
||||||
await manager.query('ALTER EXTENSION vectors SET SCHEMA vectors');
|
await sql`ALTER EXTENSION vectors SET SCHEMA vectors`.execute(tx);
|
||||||
await manager.query('UPDATE pg_catalog.pg_extension SET extrelocatable = false WHERE extname = $1', [extension]);
|
await sql`UPDATE pg_catalog.pg_extension SET extrelocatable = false WHERE extname = ${extension}`.execute(tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getDimSize(table: string, column = 'embedding'): Promise<number> {
|
private async getDimSize(table: string, column = 'embedding'): Promise<number> {
|
||||||
const res = await this.dataSource.query(`
|
const { rows } = await sql<{ dimsize: number }>`
|
||||||
SELECT atttypmod as dimsize
|
SELECT atttypmod as dimsize
|
||||||
FROM pg_attribute f
|
FROM pg_attribute f
|
||||||
JOIN pg_class c ON c.oid = f.attrelid
|
JOIN pg_class c ON c.oid = f.attrelid
|
||||||
WHERE c.relkind = 'r'::char
|
WHERE c.relkind = 'r'::char
|
||||||
AND f.attnum > 0
|
AND f.attnum > 0
|
||||||
AND c.relname = '${table}'
|
AND c.relname = ${table}
|
||||||
AND f.attname = '${column}'`);
|
AND f.attname = '${column}'
|
||||||
|
`.execute(this.db);
|
||||||
|
|
||||||
const dimSize = res[0]['dimsize'];
|
const dimSize = rows[0]?.dimsize;
|
||||||
if (!isValidInteger(dimSize, { min: 1, max: 2 ** 16 })) {
|
if (!isValidInteger(dimSize, { min: 1, max: 2 ** 16 })) {
|
||||||
throw new Error(`Could not retrieve dimension size`);
|
throw new Error(`Could not retrieve dimension size`);
|
||||||
}
|
}
|
||||||
@ -210,31 +195,32 @@ export class DatabaseRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async runMigrations(options?: { transaction?: 'all' | 'none' | 'each' }): Promise<void> {
|
async runMigrations(options?: { transaction?: 'all' | 'none' | 'each' }): Promise<void> {
|
||||||
await this.dataSource.runMigrations(options);
|
const { database } = this.configRepository.getEnv();
|
||||||
|
const dataSource = new DataSource(database.config.typeorm);
|
||||||
|
|
||||||
|
await dataSource.initialize();
|
||||||
|
await dataSource.runMigrations(options);
|
||||||
|
await dataSource.destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
async withLock<R>(lock: DatabaseLock, callback: () => Promise<R>): Promise<R> {
|
async withLock<R>(lock: DatabaseLock, callback: () => Promise<R>): Promise<R> {
|
||||||
let res;
|
let res;
|
||||||
await this.asyncLock.acquire(DatabaseLock[lock], async () => {
|
await this.asyncLock.acquire(DatabaseLock[lock], async () => {
|
||||||
const queryRunner = this.dataSource.createQueryRunner();
|
await this.db.connection().execute(async (connection) => {
|
||||||
try {
|
|
||||||
await this.acquireLock(lock, queryRunner);
|
|
||||||
res = await callback();
|
|
||||||
} finally {
|
|
||||||
try {
|
try {
|
||||||
await this.releaseLock(lock, queryRunner);
|
await this.acquireLock(lock, connection);
|
||||||
|
res = await callback();
|
||||||
} finally {
|
} finally {
|
||||||
await queryRunner.release();
|
await this.releaseLock(lock, connection);
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return res as R;
|
return res as R;
|
||||||
}
|
}
|
||||||
|
|
||||||
async tryLock(lock: DatabaseLock): Promise<boolean> {
|
tryLock(lock: DatabaseLock): Promise<boolean> {
|
||||||
const queryRunner = this.dataSource.createQueryRunner();
|
return this.db.connection().execute(async (connection) => this.acquireTryLock(lock, connection));
|
||||||
return await this.acquireTryLock(lock, queryRunner);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
isBusy(lock: DatabaseLock): boolean {
|
isBusy(lock: DatabaseLock): boolean {
|
||||||
@ -245,22 +231,18 @@ export class DatabaseRepository {
|
|||||||
await this.asyncLock.acquire(DatabaseLock[lock], () => {});
|
await this.asyncLock.acquire(DatabaseLock[lock], () => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async acquireLock(lock: DatabaseLock, queryRunner: QueryRunner): Promise<void> {
|
private async acquireLock(lock: DatabaseLock, connection: Kysely<DB>): Promise<void> {
|
||||||
return queryRunner.query('SELECT pg_advisory_lock($1)', [lock]);
|
await sql`SELECT pg_advisory_lock(${lock})`.execute(connection);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async acquireTryLock(lock: DatabaseLock, queryRunner: QueryRunner): Promise<boolean> {
|
private async acquireTryLock(lock: DatabaseLock, connection: Kysely<DB>): Promise<boolean> {
|
||||||
const lockResult = await queryRunner.query('SELECT pg_try_advisory_lock($1)', [lock]);
|
const { rows } = await sql<{
|
||||||
return lockResult[0].pg_try_advisory_lock;
|
pg_try_advisory_lock: boolean;
|
||||||
|
}>`SELECT pg_try_advisory_lock(${lock})`.execute(connection);
|
||||||
|
return rows[0].pg_try_advisory_lock;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async releaseLock(lock: DatabaseLock, queryRunner: QueryRunner): Promise<void> {
|
private async releaseLock(lock: DatabaseLock, connection: Kysely<DB>): Promise<void> {
|
||||||
return queryRunner.query('SELECT pg_advisory_unlock($1)', [lock]);
|
await sql`SELECT pg_advisory_unlock(${lock})`.execute(connection);
|
||||||
}
|
|
||||||
|
|
||||||
private getUpsertColumns(metadata: EntityMetadata) {
|
|
||||||
return Object.fromEntries(
|
|
||||||
metadata.ownColumns.map((column) => [column.propertyName, sql<string>`excluded.${sql.ref(column.propertyName)}`]),
|
|
||||||
) as any;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import { ChunkedArray, DummyValue, GenerateSql } from 'src/decorators';
|
|||||||
import { AssetFaceEntity } from 'src/entities/asset-face.entity';
|
import { AssetFaceEntity } from 'src/entities/asset-face.entity';
|
||||||
import { PersonEntity } from 'src/entities/person.entity';
|
import { PersonEntity } from 'src/entities/person.entity';
|
||||||
import { SourceType } from 'src/enum';
|
import { SourceType } from 'src/enum';
|
||||||
import { mapUpsertColumns } from 'src/utils/database';
|
import { removeUndefinedKeys } from 'src/utils/database';
|
||||||
import { Paginated, PaginationOptions } from 'src/utils/pagination';
|
import { Paginated, PaginationOptions } from 'src/utils/pagination';
|
||||||
import { FindOptionsRelations } from 'typeorm';
|
import { FindOptionsRelations } from 'typeorm';
|
||||||
|
|
||||||
@ -417,7 +417,22 @@ export class PersonRepository {
|
|||||||
await this.db
|
await this.db
|
||||||
.insertInto('person')
|
.insertInto('person')
|
||||||
.values(people)
|
.values(people)
|
||||||
.onConflict((oc) => oc.column('id').doUpdateSet(() => mapUpsertColumns('person', people[0], ['id'])))
|
.onConflict((oc) =>
|
||||||
|
oc.column('id').doUpdateSet((eb) =>
|
||||||
|
removeUndefinedKeys(
|
||||||
|
{
|
||||||
|
name: eb.ref('excluded.name'),
|
||||||
|
birthDate: eb.ref('excluded.birthDate'),
|
||||||
|
thumbnailPath: eb.ref('excluded.thumbnailPath'),
|
||||||
|
faceAssetId: eb.ref('excluded.faceAssetId'),
|
||||||
|
isHidden: eb.ref('excluded.isHidden'),
|
||||||
|
isFavorite: eb.ref('excluded.isFavorite'),
|
||||||
|
color: eb.ref('excluded.color'),
|
||||||
|
},
|
||||||
|
people[0],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -404,7 +404,7 @@ export class SearchRepository {
|
|||||||
.where('assets.ownerId', '=', anyUuid(userIds))
|
.where('assets.ownerId', '=', anyUuid(userIds))
|
||||||
.where('assets.isVisible', '=', true)
|
.where('assets.isVisible', '=', true)
|
||||||
.where('assets.isArchived', '=', false)
|
.where('assets.isArchived', '=', false)
|
||||||
.where('assets.type', '=', 'IMAGE')
|
.where('assets.type', '=', AssetType.IMAGE)
|
||||||
.where('assets.deletedAt', 'is', null)
|
.where('assets.deletedAt', 'is', null)
|
||||||
.orderBy('city')
|
.orderBy('city')
|
||||||
.limit(1);
|
.limit(1);
|
||||||
@ -421,7 +421,7 @@ export class SearchRepository {
|
|||||||
.where('assets.ownerId', '=', anyUuid(userIds))
|
.where('assets.ownerId', '=', anyUuid(userIds))
|
||||||
.where('assets.isVisible', '=', true)
|
.where('assets.isVisible', '=', true)
|
||||||
.where('assets.isArchived', '=', false)
|
.where('assets.isArchived', '=', false)
|
||||||
.where('assets.type', '=', 'IMAGE')
|
.where('assets.type', '=', AssetType.IMAGE)
|
||||||
.where('assets.deletedAt', 'is', null)
|
.where('assets.deletedAt', 'is', null)
|
||||||
.whereRef('exif.city', '>', 'cte.city')
|
.whereRef('exif.city', '>', 'cte.city')
|
||||||
.orderBy('city')
|
.orderBy('city')
|
||||||
|
@ -5,7 +5,7 @@ import { DB, UserMetadata as DbUserMetadata, Users } from 'src/db';
|
|||||||
import { DummyValue, GenerateSql } from 'src/decorators';
|
import { DummyValue, GenerateSql } from 'src/decorators';
|
||||||
import { UserMetadata, UserMetadataItem } from 'src/entities/user-metadata.entity';
|
import { UserMetadata, UserMetadataItem } from 'src/entities/user-metadata.entity';
|
||||||
import { UserEntity, withMetadata } from 'src/entities/user.entity';
|
import { UserEntity, withMetadata } from 'src/entities/user.entity';
|
||||||
import { UserStatus } from 'src/enum';
|
import { AssetType, UserStatus } from 'src/enum';
|
||||||
import { asUuid } from 'src/utils/database';
|
import { asUuid } from 'src/utils/database';
|
||||||
|
|
||||||
const columns = [
|
const columns = [
|
||||||
@ -209,11 +209,11 @@ export class UserRepository {
|
|||||||
.select((eb) => [
|
.select((eb) => [
|
||||||
eb.fn
|
eb.fn
|
||||||
.countAll()
|
.countAll()
|
||||||
.filterWhere((eb) => eb.and([eb('assets.type', '=', 'IMAGE'), eb('assets.isVisible', '=', true)]))
|
.filterWhere((eb) => eb.and([eb('assets.type', '=', AssetType.IMAGE), eb('assets.isVisible', '=', true)]))
|
||||||
.as('photos'),
|
.as('photos'),
|
||||||
eb.fn
|
eb.fn
|
||||||
.countAll()
|
.countAll()
|
||||||
.filterWhere((eb) => eb.and([eb('assets.type', '=', 'VIDEO'), eb('assets.isVisible', '=', true)]))
|
.filterWhere((eb) => eb.and([eb('assets.type', '=', AssetType.VIDEO), eb('assets.isVisible', '=', true)]))
|
||||||
.as('videos'),
|
.as('videos'),
|
||||||
eb.fn
|
eb.fn
|
||||||
.coalesce(eb.fn.sum('exif.fileSizeInByte').filterWhere('assets.libraryId', 'is', null), eb.lit(0))
|
.coalesce(eb.fn.sum('exif.fileSizeInByte').filterWhere('assets.libraryId', 'is', null), eb.lit(0))
|
||||||
@ -222,7 +222,9 @@ export class UserRepository {
|
|||||||
.coalesce(
|
.coalesce(
|
||||||
eb.fn
|
eb.fn
|
||||||
.sum('exif.fileSizeInByte')
|
.sum('exif.fileSizeInByte')
|
||||||
.filterWhere((eb) => eb.and([eb('assets.libraryId', 'is', null), eb('assets.type', '=', 'IMAGE')])),
|
.filterWhere((eb) =>
|
||||||
|
eb.and([eb('assets.libraryId', 'is', null), eb('assets.type', '=', AssetType.IMAGE)]),
|
||||||
|
),
|
||||||
eb.lit(0),
|
eb.lit(0),
|
||||||
)
|
)
|
||||||
.as('usagePhotos'),
|
.as('usagePhotos'),
|
||||||
@ -230,7 +232,9 @@ export class UserRepository {
|
|||||||
.coalesce(
|
.coalesce(
|
||||||
eb.fn
|
eb.fn
|
||||||
.sum('exif.fileSizeInByte')
|
.sum('exif.fileSizeInByte')
|
||||||
.filterWhere((eb) => eb.and([eb('assets.libraryId', 'is', null), eb('assets.type', '=', 'VIDEO')])),
|
.filterWhere((eb) =>
|
||||||
|
eb.and([eb('assets.libraryId', 'is', null), eb('assets.type', '=', AssetType.VIDEO)]),
|
||||||
|
),
|
||||||
eb.lit(0),
|
eb.lit(0),
|
||||||
)
|
)
|
||||||
.as('usageVideos'),
|
.as('usageVideos'),
|
||||||
|
@ -384,50 +384,4 @@ describe(DatabaseService.name, () => {
|
|||||||
expect(mocks.database.runMigrations).not.toHaveBeenCalled();
|
expect(mocks.database.runMigrations).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('handleConnectionError', () => {
|
|
||||||
beforeAll(() => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should not override interval', () => {
|
|
||||||
sut.handleConnectionError(new Error('Error'));
|
|
||||||
expect(mocks.logger.error).toHaveBeenCalled();
|
|
||||||
|
|
||||||
sut.handleConnectionError(new Error('foo'));
|
|
||||||
expect(mocks.logger.error).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should reconnect when interval elapses', async () => {
|
|
||||||
mocks.database.reconnect.mockResolvedValue(true);
|
|
||||||
|
|
||||||
sut.handleConnectionError(new Error('error'));
|
|
||||||
await vi.advanceTimersByTimeAsync(5000);
|
|
||||||
|
|
||||||
expect(mocks.database.reconnect).toHaveBeenCalledTimes(1);
|
|
||||||
expect(mocks.logger.log).toHaveBeenCalledWith('Database reconnected');
|
|
||||||
|
|
||||||
await vi.advanceTimersByTimeAsync(5000);
|
|
||||||
expect(mocks.database.reconnect).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should try again when reconnection fails', async () => {
|
|
||||||
mocks.database.reconnect.mockResolvedValueOnce(false);
|
|
||||||
|
|
||||||
sut.handleConnectionError(new Error('error'));
|
|
||||||
await vi.advanceTimersByTimeAsync(5000);
|
|
||||||
|
|
||||||
expect(mocks.database.reconnect).toHaveBeenCalledTimes(1);
|
|
||||||
expect(mocks.logger.warn).toHaveBeenCalledWith(expect.stringContaining('Database connection failed'));
|
|
||||||
|
|
||||||
mocks.database.reconnect.mockResolvedValueOnce(true);
|
|
||||||
await vi.advanceTimersByTimeAsync(5000);
|
|
||||||
expect(mocks.database.reconnect).toHaveBeenCalledTimes(2);
|
|
||||||
expect(mocks.logger.log).toHaveBeenCalledWith('Database reconnected');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { Duration } from 'luxon';
|
|
||||||
import semver from 'semver';
|
import semver from 'semver';
|
||||||
import { EXTENSION_NAMES } from 'src/constants';
|
import { EXTENSION_NAMES } from 'src/constants';
|
||||||
import { OnEvent } from 'src/decorators';
|
import { OnEvent } from 'src/decorators';
|
||||||
@ -54,12 +53,8 @@ const messages = {
|
|||||||
If ${name} ${installedVersion} is compatible with Immich, please ensure the Postgres instance has this available.`,
|
If ${name} ${installedVersion} is compatible with Immich, please ensure the Postgres instance has this available.`,
|
||||||
};
|
};
|
||||||
|
|
||||||
const RETRY_DURATION = Duration.fromObject({ seconds: 5 });
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class DatabaseService extends BaseService {
|
export class DatabaseService extends BaseService {
|
||||||
private reconnection?: NodeJS.Timeout;
|
|
||||||
|
|
||||||
@OnEvent({ name: 'app.bootstrap', priority: BootstrapEventPriority.DatabaseService })
|
@OnEvent({ name: 'app.bootstrap', priority: BootstrapEventPriority.DatabaseService })
|
||||||
async onBootstrap() {
|
async onBootstrap() {
|
||||||
const version = await this.databaseRepository.getPostgresVersion();
|
const version = await this.databaseRepository.getPostgresVersion();
|
||||||
@ -108,30 +103,9 @@ export class DatabaseService extends BaseService {
|
|||||||
if (!database.skipMigrations) {
|
if (!database.skipMigrations) {
|
||||||
await this.databaseRepository.runMigrations();
|
await this.databaseRepository.runMigrations();
|
||||||
}
|
}
|
||||||
this.databaseRepository.init();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
handleConnectionError(error: Error) {
|
|
||||||
if (this.reconnection) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logger.error(`Database disconnected: ${error}`);
|
|
||||||
this.reconnection = setInterval(() => void this.reconnect(), RETRY_DURATION.toMillis());
|
|
||||||
}
|
|
||||||
|
|
||||||
private async reconnect() {
|
|
||||||
const isConnected = await this.databaseRepository.reconnect();
|
|
||||||
if (isConnected) {
|
|
||||||
this.logger.log('Database reconnected');
|
|
||||||
clearInterval(this.reconnection);
|
|
||||||
delete this.reconnection;
|
|
||||||
} else {
|
|
||||||
this.logger.warn(`Database connection failed, retrying in ${RETRY_DURATION.toHuman()}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async createExtension(extension: DatabaseExtension) {
|
private async createExtension(extension: DatabaseExtension) {
|
||||||
try {
|
try {
|
||||||
await this.databaseRepository.createExtension(extension);
|
await this.databaseRepository.createExtension(extension);
|
||||||
|
@ -1,6 +1,4 @@
|
|||||||
import { Expression, RawBuilder, sql, ValueExpression } from 'kysely';
|
import { Expression, sql } from 'kysely';
|
||||||
import { InsertObject } from 'node_modules/kysely/dist/cjs';
|
|
||||||
import { DB } from 'src/db';
|
|
||||||
import { Between, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
|
import { Between, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -17,27 +15,6 @@ export function OptionalBetween<T>(from?: T, to?: T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// populated by the database repository at bootstrap
|
|
||||||
export const UPSERT_COLUMNS = {} as { [T in keyof DB]: { [K in keyof DB[T]]: RawBuilder<unknown> } };
|
|
||||||
|
|
||||||
/** Generates the columns for an upsert statement, excluding the conflict keys.
|
|
||||||
* Assumes that all entries have the same keys. */
|
|
||||||
export function mapUpsertColumns<T extends keyof DB>(
|
|
||||||
table: T,
|
|
||||||
entry: InsertObject<DB, T>,
|
|
||||||
conflictKeys: readonly (keyof DB[T])[],
|
|
||||||
) {
|
|
||||||
const columns = UPSERT_COLUMNS[table] as { [K in keyof DB[T]]: RawBuilder<unknown> };
|
|
||||||
const upsertColumns: Partial<Record<keyof typeof entry, RawBuilder<unknown>>> = {};
|
|
||||||
for (const entryColumn in entry) {
|
|
||||||
if (!conflictKeys.includes(entryColumn as keyof DB[T])) {
|
|
||||||
upsertColumns[entryColumn as keyof typeof entry] = columns[entryColumn as keyof DB[T]];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return upsertColumns as Expand<Record<keyof typeof entry, ValueExpression<DB, T, any>>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const asUuid = (id: string | Expression<string>) => sql<string>`${id}::uuid`;
|
export const asUuid = (id: string | Expression<string>) => sql<string>`${id}::uuid`;
|
||||||
|
|
||||||
export const anyUuid = (ids: string[]) => sql<string>`any(${`{${ids}}`}::uuid[])`;
|
export const anyUuid = (ids: string[]) => sql<string>`any(${`{${ids}}`}::uuid[])`;
|
||||||
@ -46,6 +23,16 @@ export const asVector = (embedding: number[]) => sql<string>`${`[${embedding}]`}
|
|||||||
|
|
||||||
export const unnest = (array: string[]) => sql<Record<string, string>>`unnest(array[${sql.join(array)}]::text[])`;
|
export const unnest = (array: string[]) => sql<Record<string, string>>`unnest(array[${sql.join(array)}]::text[])`;
|
||||||
|
|
||||||
|
export const removeUndefinedKeys = <T extends object>(update: T, template: unknown) => {
|
||||||
|
for (const key in update) {
|
||||||
|
if ((template as T)[key] === undefined) {
|
||||||
|
delete update[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return update;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mainly for type debugging to make VS Code display a more useful tooltip.
|
* Mainly for type debugging to make VS Code display a more useful tooltip.
|
||||||
* Source: https://stackoverflow.com/a/69288824
|
* Source: https://stackoverflow.com/a/69288824
|
||||||
|
@ -53,7 +53,6 @@ const globalSetup = async () => {
|
|||||||
// @ts-expect-error
|
// @ts-expect-error
|
||||||
const dataSource = new DataSource(config);
|
const dataSource = new DataSource(config);
|
||||||
await dataSource.initialize();
|
await dataSource.initialize();
|
||||||
await dataSource.query('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
|
|
||||||
await dataSource.runMigrations();
|
await dataSource.runMigrations();
|
||||||
await dataSource.destroy();
|
await dataSource.destroy();
|
||||||
};
|
};
|
||||||
|
@ -4,9 +4,7 @@ import { Mocked, vitest } from 'vitest';
|
|||||||
|
|
||||||
export const newDatabaseRepositoryMock = (): Mocked<RepositoryInterface<DatabaseRepository>> => {
|
export const newDatabaseRepositoryMock = (): Mocked<RepositoryInterface<DatabaseRepository>> => {
|
||||||
return {
|
return {
|
||||||
init: vitest.fn(),
|
|
||||||
shutdown: vitest.fn(),
|
shutdown: vitest.fn(),
|
||||||
reconnect: vitest.fn(),
|
|
||||||
getExtensionVersion: vitest.fn(),
|
getExtensionVersion: vitest.fn(),
|
||||||
getExtensionVersionRange: vitest.fn(),
|
getExtensionVersionRange: vitest.fn(),
|
||||||
getPostgresVersion: vitest.fn().mockResolvedValue('14.10 (Debian 14.10-1.pgdg120+1)'),
|
getPostgresVersion: vitest.fn().mockResolvedValue('14.10 (Debian 14.10-1.pgdg120+1)'),
|
||||||
|
Loading…
x
Reference in New Issue
Block a user