Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server): use prisma #8033

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion server/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@ RUN npm ci && \
rm -rf node_modules/@img/sharp-libvips* && \
rm -rf node_modules/@img/sharp-linuxmusl-x64
COPY server .

WORKDIR /usr/src/app/server
RUN npm run prisma:generate

WORKDIR /usr/src/app
ENV PATH="${PATH}:/usr/src/app/bin" \
IMMICH_ENV=development \
NVIDIA_DRIVER_CAPABILITIES=all \
NVIDIA_VISIBLE_DEVICES=all
ENTRYPOINT ["tini", "--", "/bin/sh"]


FROM dev AS prod

RUN npm run build
Expand Down
3,791 changes: 3,236 additions & 555 deletions server/package-lock.json

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"typeorm:schema:drop": "typeorm query -d ./dist/database.config.js 'DROP schema public cascade; CREATE schema public;'",
"typeorm:schema:reset": "npm run typeorm:schema:drop && npm run typeorm:migrations:run",
"sql:generate": "node ./dist/utils/sql.js",
"email:dev": "email dev -p 3050 --dir src/emails"
"email:dev": "email dev -p 3050 --dir src/emails",
"prisma:generate": "prisma generate --schema=./src/prisma/schema.prisma"
},
"dependencies": {
"@nestjs/bullmq": "^10.0.1",
Expand All @@ -48,6 +49,7 @@
"@opentelemetry/context-async-hooks": "^1.24.0",
"@opentelemetry/exporter-prometheus": "^0.51.0",
"@opentelemetry/sdk-node": "^0.51.0",
"@prisma/client": "^5.11.0",
"@react-email/components": "^0.0.17",
"@socket.io/postgres-adapter": "^0.3.1",
"archiver": "^7.0.0",
Expand All @@ -67,6 +69,7 @@
"ioredis": "^5.3.2",
"joi": "^17.10.0",
"js-yaml": "^4.1.0",
"kysely": "^0.27.3",
"lodash": "^4.17.21",
"luxon": "^3.4.2",
"mnemonist": "^0.39.8",
Expand All @@ -77,6 +80,7 @@
"openid-client": "^5.4.3",
"pg": "^8.11.3",
"picomatch": "^4.0.0",
"prisma-extension-kysely": "^2.1.0",
"react-email": "^2.1.2",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
Expand Down Expand Up @@ -119,6 +123,8 @@
"mock-fs": "^5.2.0",
"prettier": "^3.0.2",
"prettier-plugin-organize-imports": "^3.2.3",
"prisma": "^5.14.0",
"prisma-kysely": "^1.8.0",
"rimraf": "^5.0.1",
"source-map-support": "^0.5.21",
"sql-formatter": "^15.0.0",
Expand Down
22 changes: 11 additions & 11 deletions server/src/database.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import { DatabaseExtension } from 'src/interfaces/database.interface';
import { DataSource } from 'typeorm';
import { PostgresConnectionOptions } from 'typeorm/driver/postgres/PostgresConnectionOptions.js';

const url = process.env.DB_URL;
const urlOrParts = url
? { url }
: {
host: process.env.DB_HOSTNAME || 'database',
port: Number.parseInt(process.env.DB_PORT || '5432'),
username: process.env.DB_USERNAME || 'postgres',
password: process.env.DB_PASSWORD || 'postgres',
database: process.env.DB_DATABASE_NAME || 'immich',
};
let url = process.env.DB_URL;
if (!url) {
const host = process.env.DB_HOSTNAME || 'database';
const port = Number.parseInt(process.env.DB_PORT || '5432');
const username = process.env.DB_USERNAME || 'postgres';
const password = process.env.DB_PASSWORD || 'postgres';
const database = process.env.DB_DATABASE_NAME || 'immich';
url = `postgres://${username}:${password}@${host}:${port}/${database}`;
process.env.DB_URL = url;
}

/* eslint unicorn/prefer-module: "off" -- We can fix this when migrating to ESM*/
export const databaseConfig: PostgresConnectionOptions = {
Expand All @@ -23,7 +23,7 @@ export const databaseConfig: PostgresConnectionOptions = {
synchronize: false,
connectTimeoutMS: 10_000, // 10 seconds
parseInt8: true,
...urlOrParts,
url,
};

/**
Expand Down
13 changes: 0 additions & 13 deletions server/src/dtos/duplicate.dto.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,6 @@
import { groupBy } from 'lodash';
import { AssetResponseDto } from 'src/dtos/asset-response.dto';

export class DuplicateResponseDto {
duplicateId!: string;
assets!: AssetResponseDto[];
}

export function mapDuplicateResponse(assets: AssetResponseDto[]): DuplicateResponseDto[] {
const result = [];

const grouped = groupBy(assets, (a) => a.duplicateId);

for (const [duplicateId, assets] of Object.entries(grouped)) {
result.push({ duplicateId, assets });
}

return result;
}
58 changes: 28 additions & 30 deletions server/src/interfaces/asset.interface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Prisma } from '@prisma/client';
import { AssetOrder } from 'src/entities/album.entity';
import { AssetJobStatusEntity } from 'src/entities/asset-job-status.entity';
import { AssetEntity, AssetType } from 'src/entities/asset.entity';
import { ExifEntity } from 'src/entities/exif.entity';
import { ReverseGeocodeResult } from 'src/interfaces/metadata.interface';
import { AssetSearchOptions, SearchExploreItem } from 'src/interfaces/search.interface';
import { Paginated, PaginationOptions } from 'src/utils/pagination';
import { FindOptionsOrder, FindOptionsRelations, FindOptionsSelect } from 'typeorm';

export type AssetStats = Record<AssetType, number>;

Expand Down Expand Up @@ -80,22 +80,6 @@ export interface TimeBucketItem {
count: number;
}

export type AssetCreate = Pick<
AssetEntity,
| 'deviceAssetId'
| 'ownerId'
| 'libraryId'
| 'deviceId'
| 'type'
| 'originalPath'
| 'fileCreatedAt'
| 'localDateTime'
| 'fileModifiedAt'
| 'checksum'
| 'originalFileName'
> &
Partial<AssetEntity>;

export type AssetWithoutRelations = Omit<
AssetEntity,
| 'livePhotoVideo'
Expand All @@ -108,10 +92,27 @@ export type AssetWithoutRelations = Omit<
| 'sharedLinks'
| 'smartInfo'
| 'smartSearch'
| 'stack'
| 'tags'
>;

export type AssetUpdateOptions = Pick<AssetWithoutRelations, 'id'> & Partial<AssetWithoutRelations>;
export type AssetCreate = Pick<
AssetEntity,
| 'deviceAssetId'
| 'ownerId'
| 'libraryId'
| 'deviceId'
| 'type'
| 'originalPath'
| 'fileCreatedAt'
| 'localDateTime'
| 'fileModifiedAt'
| 'checksum'
| 'originalFileName'
> &
Partial<AssetWithoutRelations>;

export type AssetUpdateOptions = Pick<AssetEntity, 'id'> & Partial<AssetWithoutRelations>;

export type AssetUpdateAllOptions = Omit<Partial<AssetWithoutRelations>, 'id'>;

Expand Down Expand Up @@ -151,28 +152,25 @@ export interface AssetUpdateDuplicateOptions {
duplicateIds: string[];
}

export interface AssetDuplicateGroup {
duplicateId: string;
assets: AssetEntity[];
}

export type AssetPathEntity = Pick<AssetEntity, 'id' | 'originalPath' | 'isOffline'>;

export const IAssetRepository = 'IAssetRepository';

export interface IAssetRepository {
create(asset: AssetCreate): Promise<AssetEntity>;
getByIds(
ids: string[],
relations?: FindOptionsRelations<AssetEntity>,
select?: FindOptionsSelect<AssetEntity>,
): Promise<AssetEntity[]>;
getByIds(ids: string[], relations?: Prisma.AssetsInclude): Promise<AssetEntity[]>;
getByIdsWithAllRelations(ids: string[]): Promise<AssetEntity[]>;
getByDayOfYear(ownerIds: string[], monthDay: MonthDay): Promise<AssetEntity[]>;
getByChecksum(libraryId: string, checksum: Buffer): Promise<AssetEntity | null>;
getUploadAssetIdByChecksum(ownerId: string, checksum: Buffer): Promise<string | undefined>;
getByAlbumId(pagination: PaginationOptions, albumId: string): Paginated<AssetEntity>;
getByUserId(pagination: PaginationOptions, userId: string, options?: AssetSearchOptions): Paginated<AssetEntity>;
getById(
id: string,
relations?: FindOptionsRelations<AssetEntity>,
order?: FindOptionsOrder<AssetEntity>,
): Promise<AssetEntity | null>;
getById(id: string, relations?: Prisma.AssetsInclude): Promise<AssetEntity | null>;
getWithout(pagination: PaginationOptions, property: WithoutProperty): Paginated<AssetEntity>;
getWith(pagination: PaginationOptions, property: WithProperty, libraryId?: string): Paginated<AssetEntity>;
getRandom(userId: string, count: number): Promise<AssetEntity[]>;
Expand All @@ -185,7 +183,7 @@ export interface IAssetRepository {
getAllByDeviceId(userId: string, deviceId: string): Promise<string[]>;
updateAll(ids: string[], options: Partial<AssetUpdateAllOptions>): Promise<void>;
updateDuplicates(options: AssetUpdateDuplicateOptions): Promise<void>;
update(asset: AssetUpdateOptions): Promise<void>;
update(asset: AssetUpdateOptions): Promise<AssetEntity>;
remove(asset: AssetEntity): Promise<void>;
softDeleteAll(ids: string[]): Promise<void>;
restoreAll(ids: string[]): Promise<void>;
Expand All @@ -198,7 +196,7 @@ export interface IAssetRepository {
upsertJobStatus(...jobStatus: Partial<AssetJobStatusEntity>[]): Promise<void>;
getAssetIdByCity(userId: string, options: AssetExploreFieldOptions): Promise<SearchExploreItem<string>>;
getAssetIdByTag(userId: string, options: AssetExploreFieldOptions): Promise<SearchExploreItem<string>>;
getDuplicates(options: AssetBuilderOptions): Promise<AssetEntity[]>;
getDuplicates(userIds: string[]): Promise<AssetDuplicateGroup[]>;
getAllForUserFullSync(options: AssetFullSyncOptions): Promise<AssetEntity[]>;
getChangedDeltaSync(options: AssetDeltaSyncOptions): Promise<AssetEntity[]>;
}
2 changes: 1 addition & 1 deletion server/src/interfaces/search.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export type SmartSearchOptions = SearchDateOptions &
export interface FaceEmbeddingSearch extends SearchEmbeddingOptions {
hasPerson?: boolean;
numResults: number;
maxDistance?: number;
maxDistance: number;
}

export interface AssetDuplicateSearch {
Expand Down
1 change: 1 addition & 0 deletions server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Worker } from 'node:worker_threads';
import { ImmichAdminModule } from 'src/app.module';
import { LogLevel } from 'src/config';
import { getWorkers } from 'src/utils/workers';

const immichApp = process.argv[2] || process.env.IMMICH_APP;

if (process.argv[2] === immichApp) {
Expand Down
32 changes: 32 additions & 0 deletions server/src/prisma/find-non-deleted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Prisma } from '@prisma/client';

const excludeDeleted = ({ args, query }: { args: any; query: any }) => {
if (args.where === undefined) {
args.where = { deletedAt: null };
} else if (
args.where.deletedAt === undefined &&
!args.where.OR?.some(({ deletedAt }: any) => deletedAt !== undefined) &&
!args.where.AND?.some(({ deletedAt }: any) => deletedAt !== undefined)
) {
args.where.deletedAt = null;
}

return query(args);
};

const findNonDeleted = {
findFirst: excludeDeleted,
findFirstOrThrow: excludeDeleted,
findMany: excludeDeleted,
findUnique: excludeDeleted,
findUniqueOrThrow: excludeDeleted,
};

export const findNonDeletedExtension = Prisma.defineExtension({
query: {
albums: findNonDeleted,
assets: findNonDeleted,
libraries: findNonDeleted,
users: findNonDeleted,
},
});