The minimalistic document archiving platform.
fix(migration): proper iteration for tags normalization migrations (#825)
Corentin Thomasset7c581fa3434c
diff --git a/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.test.ts b/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.test.tsindex 2ac1cb61..5e034ffe 100644--- a/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.test.ts+++ b/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.test.ts@@ -1,6 +1,7 @@import { asc, sql } from 'drizzle-orm';import { describe, expect, test } from 'vitest';import { setupDatabase } from '../../modules/app/database/database';+import { isNil } from '../../modules/shared/utils';import { documentsTagsTable, tagsTable } from '../../modules/tags/tags.table';import { initialSchemaSetupMigration } from './0001-initial-schema-setup.migration';import { caseInsensitiveTagNameUniqConstraintMigration, createTagNameNormalizer } from './0016-case-insensitive-tag-name-uniq-constraint.migration';@@ -246,5 +247,34 @@ describe('0016-case-insensitive-tag-name-uniq-constraint migration', () => {expect(tags.at(0)).toMatchObject({ id: 'tag_1', name: 'Tag One', normalizedName: null });expect(tags.at(1)).toMatchObject({ id: 'tag_2', name: 'Tag One', normalizedName: null });});++ test('processes tags in batches correctly with pagination', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ await initialSchemaSetupMigration.up({ db });++ await db.run(sql`INSERT INTO organizations(id, name, created_at, updated_at) VALUES ('org_1', 'Test Org', 1737936000000, 1737936000000)`);++ for (let i = 1; i <= 500; i++) {+ const name = `Tag ${i}`;+ const id = `tag_${i.toString().padStart(4, '0')}`;++ await db.run(sql`INSERT INTO tags (id, created_at, updated_at, organization_id, name, color, description) VALUES+ (${id}, 1737936000000, 1737936000000, 'org_1', ${name}, '#ff0000', NULL)+ `);+ }++ // Verify all tags are inserted without normalized_name+ const { rows: tagsBeforeMigration } = await db.run(sql`SELECT * FROM tags ORDER BY id`);+ expect(tagsBeforeMigration).toHaveLength(500);+ expect(tagsBeforeMigration.every(tag => isNil(tag.normalizedName))).toBe(true);++ await caseInsensitiveTagNameUniqConstraintMigration.up({ db });++ const tagsAfterMigration = await db.select().from(tagsTable).orderBy(tagsTable.id);+ expect(tagsAfterMigration).toHaveLength(500);++ expect(tagsAfterMigration.every(tag => !isNil(tag.normalizedName))).toBe(true);+ });});});diff --git a/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.ts b/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.tsindex d445d81d..2154bf5f 100644--- a/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.ts+++ b/apps/papra-server/src/migrations/list/0016-case-insensitive-tag-name-uniq-constraint.migration.ts@@ -1,7 +1,7 @@import type { Migration } from '../migrations.types';import { asc, eq, isNull, sql } from 'drizzle-orm';import { nanoid } from 'nanoid';-import { createIterator } from '../../modules/app/database/database.usecases';+import { createBatchedIterator } from '../../modules/app/database/database.usecases';import { createLogger } from '../../modules/shared/logger/logger';import { normalizeTagName } from '../../modules/tags/tags.repository.models';import { tagsTable } from '../../modules/tags/tags.table';@@ -59,14 +59,15 @@ export const caseInsensitiveTagNameUniqConstraintMigration = {const normalizer = createTagNameNormalizer();- const iterator = createIterator({+ const iterator = createBatchedIterator({batchSize: 200,- query: db+ getBatch: async ({ limit }) => db.select().from(tagsTable).where(isNull(tagsTable.normalizedName)).orderBy(asc(tagsTable.id))- .$dynamic(),+ .limit(limit), // No offset as where clause ensures we only get unprocessed rows+});for await (const tag of iterator) {diff --git a/apps/papra-server/src/modules/app/database/database.usecases.test.ts b/apps/papra-server/src/modules/app/database/database.usecases.test.tsindex 7c2af015..7df7908c 100644--- a/apps/papra-server/src/modules/app/database/database.usecases.test.ts+++ b/apps/papra-server/src/modules/app/database/database.usecases.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'vitest';import { usersTable } from '../../users/users.table';import { createInMemoryDatabase } from './database.test-utils';-import { createIterator } from './database.usecases';+import { createBatchedIterator, createIterator } from './database.usecases';const createUsers = ({ count }: { count: number }) => Array.from({ length: count }, (_, i) => ({ id: `usr_${i}`, email: `user-${i}@papra.dev` }));@@ -54,4 +54,56 @@ describe('database usecases', () => {expect(results).to.eql(['usr_0', 'usr_1', 'usr_2', 'usr_3', 'usr_4', 'usr_5', 'usr_6', 'usr_7', 'usr_8', 'usr_9']);});});++ describe('createBatchedIterator', () => {+ test('iterates over all items using the getBatch function', async () => {+ const data = [1, 2, 3, 4, 5];++ const iterator = createBatchedIterator({+ getBatch: async ({ offset, limit }) => data.slice(offset, offset + limit),+ batchSize: 2,+ });++ const results = await Array.fromAsync(iterator);++ expect(results).to.eql([1, 2, 3, 4, 5]);+ });++ test('handles empty collections', async () => {+ const iterator = createBatchedIterator({+ getBatch: async () => [],+ batchSize: 10,+ });++ const results = await Array.fromAsync(iterator);++ expect(results).to.eql([]);+ });++ test('handles collections smaller than batch size', async () => {+ const data = [1, 2, 3];++ const iterator = createBatchedIterator({+ getBatch: async ({ offset, limit }) => data.slice(offset, offset + limit),+ batchSize: 10,+ });++ const results = await Array.fromAsync(iterator);++ expect(results).to.eql([1, 2, 3]);+ });++ test('handles collections that are exact multiples of batch size', async () => {+ const data = [1, 2, 3, 4, 5, 6];++ const iterator = createBatchedIterator({+ getBatch: async ({ offset, limit }) => data.slice(offset, offset + limit),+ batchSize: 3,+ });++ const results = await Array.fromAsync(iterator);++ expect(results).to.eql([1, 2, 3, 4, 5, 6]);+ });+ });});diff --git a/apps/papra-server/src/modules/app/database/database.usecases.ts b/apps/papra-server/src/modules/app/database/database.usecases.tsindex 2e4fb3ba..6b7979de 100644--- a/apps/papra-server/src/modules/app/database/database.usecases.ts+++ b/apps/papra-server/src/modules/app/database/database.usecases.ts@@ -1,20 +1,33 @@import type { SQLiteSelect } from 'drizzle-orm/sqlite-core';import type { ArrayElement } from '../../shared/types';-export async function* createIterator<T extends SQLiteSelect>({+export function createIterator<T extends SQLiteSelect>({query,batchSize = 100,}: { query: T; batchSize?: number }): AsyncGenerator<ArrayElement<T['_']['result']>> {+ return createBatchedIterator({+ getBatch: async ({ offset, limit }) => await query.limit(limit).offset(offset) as ArrayElement<T['_']['result']>[],+ batchSize,+ });+}++export async function* createBatchedIterator<T>({+ getBatch,+ batchSize = 100,+}: {+ getBatch: (args: { offset: number; limit: number }) => Promise<T[]>;+ batchSize?: number;+}): AsyncGenerator<T> {let offset = 0;while (true) {- const results = await query.limit(batchSize).offset(offset);+ const results = await getBatch({ offset, limit: batchSize });if (results.length === 0) {break;}for (const result of results) {- yield result as ArrayElement<T['_']['result']>;+ yield result;}if (results.length < batchSize) {