⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(custom-fields): bound migrations and clear persisted drafts
Tin50d1e6191fe9
diff --git a/apps/api/src/custom-field/controllers/update-custom-field.ts b/apps/api/src/custom-field/controllers/update-custom-field.tsindex a7417916b..05d53da74 100644--- a/apps/api/src/custom-field/controllers/update-custom-field.ts+++ b/apps/api/src/custom-field/controllers/update-custom-field.ts@@ -1,4 +1,4 @@-import { eq, sql } from "drizzle-orm";+import { and, asc, eq, gt, sql } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {@@ -121,28 +121,42 @@ export default async function updateCustomField(const needsMigration = oldOptions.some((option) => replacements.get(option) !== option,);- const values = needsMigration- ? await tx- .select()- .from(customFieldValueTable)- .where(eq(customFieldValueTable.fieldId, id))- .for("update")- : [];- const changed = values- .map((row) => ({- id: row.id,- before: row.value,- value: transform(row.value),- }))- .filter((row) => row.before !== row.value);- // Batch updates preserve simultaneous renames (including swaps) without a query per task.- for (let i = 0; i < changed.length; i += 500) {- const rows = changed- .slice(i, i + 500)- .map((row) => sql`(${row.id}::text, ${row.value}::text)`);- await tx.execute(sql`UPDATE ${customFieldValueTable} AS target SET value = changes.value- FROM (VALUES ${sql.join(rows, sql`, `)}) AS changes(id, value)- WHERE target.id = changes.id`);+ // Keep application memory bounded while the definition lock serializes assignments.+ let cursor: string | undefined;+ while (needsMigration) {+ const values = await tx+ .select({+ id: customFieldValueTable.id,+ value: customFieldValueTable.value,+ })+ .from(customFieldValueTable)+ .where(+ and(+ eq(customFieldValueTable.fieldId, id),+ cursor ? gt(customFieldValueTable.id, cursor) : undefined,+ ),+ )+ .orderBy(asc(customFieldValueTable.id))+ .limit(500)+ .for("update");+ const last = values.at(-1);+ if (!last) break;+ const changed = values+ .map((row) => ({+ id: row.id,+ before: row.value,+ value: transform(row.value),+ }))+ .filter((row) => row.before !== row.value);+ if (changed.length) {+ const rows = changed.map(+ (row) => sql`(${row.id}::text, ${row.value}::text)`,+ );+ await tx.execute(sql`UPDATE ${customFieldValueTable} AS target SET value = changes.value+ FROM (VALUES ${sql.join(rows, sql`, `)}) AS changes(id, value)+ WHERE target.id = changes.id`);+ }+ cursor = last.id;}options = newOptions;}diff --git a/apps/web/src/components/shared/modals/create-task-modal.test.tsx b/apps/web/src/components/shared/modals/create-task-modal.test.tsxindex 32ece308b..4c0f624c6 100644--- a/apps/web/src/components/shared/modals/create-task-modal.test.tsx+++ b/apps/web/src/components/shared/modals/create-task-modal.test.tsx@@ -32,6 +32,10 @@ function createWrapper() {}const useLocation = vi.fn();+const setCustomFieldValue = vi.fn(async () => ({}));+vi.mock("@/hooks/mutations/custom-field/use-set-custom-field-value", () => ({+ default: () => ({ mutateAsync: setCustomFieldValue }),+}));const deleteTask = vi.fn(async () => {});const updateTask = vi.fn(async (input: Record<string, unknown>) => input);const setProject = vi.fn();@@ -195,6 +199,45 @@ describe("CreateTaskModal", () => {},);+ it("clears hidden dropdown selections in an already persisted upload draft", async () => {+ useLocation.mockReturnValue({+ pathname: "/dashboard/workspace/workspace-1/project/project-1/board",+ });+ customFields = [+ {+ id: "people",+ name: "People",+ type: "dropdown",+ options: ["Former", "Current"],+ hiddenOptions: [],+ defaultValue: "Former",+ required: false,+ },+ ];+ const view = render(<CreateTaskModal open onClose={vi.fn()} />, {+ wrapper: createWrapper(),+ });+ enterTitle();+ await act(async () => {+ await ensureTaskId?.();+ });+ customFields = customFields.map((field) => ({+ ...field,+ hiddenOptions: ["Former"],+ defaultValue: "",+ }));+ view.rerender(<CreateTaskModal open onClose={vi.fn()} />);+ await act(async () => {+ submit();+ });+ expect(updateTask).toHaveBeenCalled();+ expect(setCustomFieldValue).toHaveBeenCalledWith({+ taskId: "task-1",+ fieldId: "people",+ value: "",+ });+ });+it("keeps unsaved input while discard confirmation is open", async () => {useLocation.mockReturnValue({pathname: "/dashboard/workspace/workspace-1/project/project-1/board",diff --git a/apps/web/src/components/shared/modals/create-task-modal.tsx b/apps/web/src/components/shared/modals/create-task-modal.tsxindex fef4678a2..b6f2c36b3 100644--- a/apps/web/src/components/shared/modals/create-task-modal.tsx+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx@@ -634,13 +634,11 @@ function CreateTaskModalContent({if (currentDraft) {for (const [fieldId, value] of Object.entries(customFieldValues)) {- if (value) {- await setCustomFieldValue({- taskId: savedTask.id,- fieldId,- value: String(value),- });- }+ await setCustomFieldValue({+ taskId: savedTask.id,+ fieldId,+ value: String(value),+ });}}diff --git a/tests/api-integration/custom-field-edit.test.ts b/tests/api-integration/custom-field-edit.test.tsindex 4b71c64f4..b4b3db623 100644--- a/tests/api-integration/custom-field-edit.test.ts+++ b/tests/api-integration/custom-field-edit.test.ts@@ -115,6 +115,51 @@ describe("custom field editing", () => {},);+ it.each([false, true])(+ "migrates bounded batches atomically (late invalid value: %s)",+ async (invalid) => {+ const { project, task, field, update } = await fixture();+ const tasks = await db+ .insert(schema.taskTable)+ .values(+ Array.from({ length: 501 }, (_, index) => ({+ projectId: project.id,+ title: "Batch task",+ number: index + 2,+ status: task.status,+ columnId: task.columnId,+ })),+ )+ .returning({ id: schema.taskTable.id });+ await db.insert(schema.customFieldValueTable).values(+ tasks.map((item, index) => ({+ id: `batch-${String(index).padStart(4, "0")}`,+ taskId: item.id,+ fieldId: field.id,+ value: invalid && index === 500 ? '["Unused"]' : '["Alice","Bob"]',+ })),+ );+ const response = await update({+ options: [+ { originalValue: "Alice", value: "Bob" },+ { originalValue: "Bob", value: "Alice" },+ ],+ });+ expect(response.status).toBe(invalid ? 400 : 200);+ const values = await db+ .select({ value: schema.customFieldValueTable.value })+ .from(schema.customFieldValueTable)+ .where(eq(schema.customFieldValueTable.fieldId, field.id));+ expect(values).toHaveLength(502);+ expect(+ values.filter(+ (row) =>+ row.value === (invalid ? '["Alice","Bob"]' : '["Bob","Alice"]'),+ ),+ ).toHaveLength(invalid ? 501 : 502);+ },+ );+it("handles simultaneous swaps without collapsing selections", async () => {const { update, readValue } = await fixture();expect(