From bb233c8b5915a488c98e7c70361085010117b199 Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:33:14 -0500 Subject: [PATCH 1/2] fix(sync): add updated_at to sl_tags so tag renames and deletions reach the app Migration 0003 adds sl_tags.updated_at (default now(), backfilled from created_at). Every tag write moves it (PUT/DELETE /api/tags/[id], tag update/delete in POST /api/sync), and GET /api/sync pulls tags on updatedAt >= since. Deleting a tag removes its links and moves the touched tasks' updatedAt in the same transaction, so the app realigns their links on the next pull. The user_id ALTERs drizzle-kit re-emitted from the stale 0000 snapshot are dropped from 0003 (0001 applied them); the new snapshot is current. Refs #181 Refs #168 Co-Authored-By: Claude Opus 5.5 --- REVIEW.md | 5 +- web/src/app/api/sync/route.test.ts | 116 +++++ web/src/app/api/sync/route.ts | 28 +- web/src/app/api/tags/[id]/route.ts | 31 +- web/src/db/migrations/0003_tag_updated_at.sql | 6 + web/src/db/migrations/meta/0003_snapshot.json | 417 ++++++++++++++++++ web/src/db/migrations/meta/_journal.json | 7 + web/src/db/schema.ts | 1 + 8 files changed, 593 insertions(+), 18 deletions(-) create mode 100644 web/src/db/migrations/0003_tag_updated_at.sql create mode 100644 web/src/db/migrations/meta/0003_snapshot.json diff --git a/REVIEW.md b/REVIEW.md index 801e8bc..936bb6c 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -113,7 +113,8 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165 - Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts` - Le pull garde le `createdAt` local d'une ligne existante, et le `calendarEventId` d'une tâche (colonne absente du serveur). — `src/services/syncRules.ts` (`pulled*Values`), #149 -- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : le serveur n'a pas d'`updatedAt` sur les étiquettes et renvoie `updated_at` = `created_at`, donc un renommage hors connexion d'étiquette est perdu (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149 +- Dans un pull depuis `SYNC_EPOCH` (première sync, ou après une déconnexion qui remet `lastSyncAt` à null), une liste ou une tâche locale strictement plus récente que le serveur est gardée et remise dans l'outbox (`queueOutboxEntry`, action `update`, écrite même sync éteinte : la première sync tourne avant l'activation, #165). Jamais une étiquette : l'app ne garde pas de date de modification pour les étiquettes, donc un renommage hors connexion d'étiquette reste perdu face au serveur (check smoke « applyTagChange never keeps a local tag »). — `src/services/syncRules.ts` (`keepLocal`), `src/services/syncClient.ts`, #149, #181 +- Une étiquette a un `updatedAt` serveur (migration `0003_tag_updated_at`, rempli par `created_at` pour les lignes existantes) : `GET /api/sync` la tire sur `updatedAt >= since` et renvoie `updated_at` = `updatedAt`. Toute écriture d'une étiquette (`PUT`/`DELETE /api/tags/[id]`, `tag update`/`tag delete` de `POST /api/sync`) avance `updatedAt`. La suppression d'une étiquette retire ses liens `sl_task_tags` et avance `updatedAt` des tâches touchées dans la même transaction, pour que l'app réaligne leurs liens. — `web/src/db/schema.ts`, `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, `web/src/app/api/sync/route.test.ts`, #181 - Après la fusion de la première sync, `initialMerge` tire tout le serveur depuis `SYNC_EPOCH` ; `lastSyncAt` est posé à cette date avant le pull, pour qu'un pull raté se rejoue au `fullSync` suivant (#150). — `src/services/syncClient.ts`, `src/services/syncRules.ts` (`mergeTaskData`) - Une suppression serveur s'applique toujours, même sur une ligne locale plus récente : le protocole n'a pas de restauration. — `src/services/syncClient.ts`, #149 - `src/services/syncRules.ts` reste sans import, pour que `tests/syncRules.test.mjs` le charge par le type stripping de Node (check smoke `syncRules.ts stays import-free`). `src/services/syncSchedule.ts` et `src/services/syncTrigger.ts` suivent la même règle pour `tests/syncSchedule.test.mjs` (check smoke `syncSchedule.ts and syncTrigger.ts stay import-free`). — `tests/smoke.test.cjs`, `tests/syncRules.test.mjs`, `tests/syncSchedule.test.mjs`, #149, #178 @@ -202,7 +203,7 @@ npm run build - **Tests verts, build cassé.** Le smoke test ne charge ni Babel ni Metro : seul l'export Expo prouve le bundle (PR #118). — `STATE.md` (2026-09-25) - **Le Bearer ouvre le middleware.** Une route d'API qui oublie `requireAuth()` n'est pas protégée par le middleware dès que la requête porte un `Bearer`, même invalide. Lire le début de chaque route ajoutée. — `web/src/middleware.ts` - **`...data` dans un `.set()`.** Jusqu'à #142, le code de sync recopiait `data` dans les mises à jour, et un client pouvait écrire `userId`. Une PR qui touche `processOperation` passe `data` par un schéma de `syncData.ts` avant tout `.set()` ou `.values()`, et un `...d` n'y est acceptable que sur la sortie d'un de ces schémas. — `web/src/app/api/sync/route.ts`, #142 -- **Le serveur n'a pas d'`updatedAt` sur les étiquettes.** `createdAt` sert de date de changement au pull : une étiquette renommée n'est pas renvoyée à l'app. — revue de la PR #58, `web/src/app/api/sync/route.ts` +- **Une écriture d'étiquette sans `updatedAt`.** Jusqu'à #181, le serveur n'avait pas d'`updatedAt` sur les étiquettes et le pull les tirait sur `createdAt` : un renommage ou une suppression n'arrivait pas à l'app (revue de la PR #58). Toute écriture ajoutée sur `sl_tags` avance `updatedAt`, sinon elle reste invisible au pull. — `web/src/app/api/sync/route.ts`, `web/src/app/api/tags/[id]/route.ts`, #181 - **Tests de route dépendants de l'ordre.** Chaque test de `web/src/app/api/sync/route.test.ts` crée ses deux comptes neufs par `seed()` et ne lit ni ne modifie jamais les lignes d'un autre test : un test qui suppose l'état laissé par un autre passe dans un ordre et tombe dans un autre, que le mélange permanent finit par tirer. — `web/src/app/api/sync/route.test.ts`, `web/vitest.config.mts`, #148 - **Polling, pas de requêtes vivantes.** Les écrans relisent SQLite toutes les 500 ms ; un état global de tâches ajouté contourne cette convention. — `CLAUDE.md` « Conventions » - **Widget headless.** `widgetState.ts` reste léger (pas de DB, de drizzle ni de date-fns), le smoke test verrouille son graphe d'import ; un import ajouté rallonge le cold start de chaque tap. — `CLAUDE.md` « Widget Android » diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 0871538..1ccbe3a 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -46,6 +46,7 @@ vi.mock('@/lib/idempotency', async (importOriginal) => { const { GET, POST } = await import('./route'); const { POST: postTaskTags } = await import('../tasks/[id]/tags/route'); const { DELETE: deleteTaskTag } = await import('../tasks/[id]/tags/[tagId]/route'); +const { PUT: putTag, DELETE: deleteTag } = await import('../tags/[id]/route'); const { NextRequest } = await import('next/server'); type Op = [entityType: string, action: string, entityId: string, data?: Record]; @@ -807,3 +808,118 @@ describe('POST /api/sync: task and tag creation with an id taken by another acco ])).toEqual(['applied', 'applied']); }); }); + +describe('tags carry an updatedAt that the pull follows (#181)', () => { + const OLD = '2020-01-01T00:00:00.000Z'; + const SINCE = new Date(new Date(OLD).getTime() + 1000).toISOString(); + + // Put the tag and the account's tasks back in the past: only what a write + // moves afterwards comes back in a pull since SINCE. + async function age(userId: string, tagId: string) { + await h.pg.query('update sl_tags set created_at=$1, updated_at=$1 where id=$2', [OLD, tagId]); + await h.pg.query('update sl_tasks set updated_at=$1 where user_id=$2', [OLD, userId]); + } + + type Change = { entity_type: string; entity_id: string; action: string; payload: Record; updated_at: string }; + + async function pull(userId: string): Promise { + h.userId = userId; + const res = await GET(new NextRequest(`http://localhost/api/sync?since=${encodeURIComponent(SINCE)}`)); + expect(res.status).toBe(200); + return (await res.json() as { changes: Change[] }).changes; + } + + function tagChange(changes: Change[], tagId: string) { + return changes.find((c) => c.entity_type === 'tag' && c.entity_id === tagId); + } + + function taskIds(changes: Change[]) { + return changes.filter((c) => c.entity_type === 'task').map((c) => c.entity_id).sort(); + } + + it('the migration backfills updated_at = created_at on existing tags', async () => { + const { PGlite } = await import('electric-sql-pglite'); + const pg = new PGlite(); + const dir = path.join(__dirname, '../../../db/migrations'); + const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort(); + const last = files.findIndex((f) => f.startsWith('0003_')); + expect(last).toBeGreaterThan(0); + const apply = async (f: string) => { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await pg.exec(stmt); + } + }; + for (const f of files.slice(0, last)) await apply(f); + const id = u(); + await pg.query('insert into sl_tags (id, user_id, name, created_at) values ($1, $2, $3, $4)', [id, 'user-old', 'old', OLD]); + await apply(files[last]); + const r = (await pg.query<{ c: Date; u: Date }>('select created_at c, updated_at u from sl_tags where id=$1', [id])).rows[0]; + expect(new Date(r.u).toISOString()).toBe(OLD); + expect(new Date(r.c).toISOString()).toBe(OLD); + await pg.close(); + }); + + it('an untouched tag created before since is not pulled', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + expect(tagChange(await pull(B.userId), B.tag)).toBeUndefined(); + }); + + it('POST /api/sync tag update: the pull sends the new name, updated_at after the creation', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + expect(await push(B.userId, [['tag', 'update', B.tag, { name: 'renamed', color: '#4DB6AC' }]])).toEqual(['applied']); + const c = tagChange(await pull(B.userId), B.tag); + expect(c).toMatchObject({ action: 'update', payload: { name: 'renamed', color: '#4DB6AC', created_at: OLD } }); + expect(c!.updated_at > SINCE).toBe(true); + expect(c!.payload.updated_at).toBe(c!.updated_at); + }); + + it('PUT /api/tags/[id]: the pull sends the new name', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + h.userId = B.userId; + const res = await putTag( + new Request('http://localhost', { method: 'PUT', body: JSON.stringify({ name: 'renamed-web' }) }), + { params: Promise.resolve({ id: B.tag }) }, + ); + expect(res.status).toBe(200); + expect(tagChange(await pull(B.userId), B.tag)).toMatchObject({ action: 'update', payload: { name: 'renamed-web' } }); + }); + + it('POST /api/sync tag delete: the pull sends delete, the links are gone, the touched tasks come back', async () => { + const { B } = await seed(); + // B.tag on B.task (seed) and on B.sub; B.parent stays without it + expect(await push(B.userId, [['taskTag', 'create', B.sub, { tagId: B.tag }]])).toEqual(['applied']); + await age(B.userId, B.tag); + expect(await push(B.userId, [['tag', 'delete', B.tag, { id: B.tag }]])).toEqual(['applied']); + const changes = await pull(B.userId); + expect(tagChange(changes, B.tag)?.action).toBe('delete'); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [B.tag])).toEqual({ c: 0 }); + expect(taskIds(changes)).toEqual([B.task, B.sub].sort()); + expect(changes.filter((c) => c.entity_type === 'task_tag' && c.payload.tag_id === B.tag)).toEqual([]); + }); + + it('DELETE /api/tags/[id]: the pull sends delete, the links are gone, the touched tasks come back', async () => { + const { B } = await seed(); + await age(B.userId, B.tag); + h.userId = B.userId; + const res = await deleteTag(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: B.tag }) }); + expect(res.status).toBe(200); + const changes = await pull(B.userId); + expect(tagChange(changes, B.tag)?.action).toBe('delete'); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [B.tag])).toEqual({ c: 0 }); + expect(taskIds(changes)).toEqual([B.task]); + }); + + it('DELETE /api/tags/[id] on another account\'s tag: 404, its tag, links and tasks untouched', async () => { + const { A, B } = await seed(); + await age(A.userId, A.tag); + h.userId = B.userId; + const res = await deleteTag(new Request('http://localhost', { method: 'DELETE' }), { params: Promise.resolve({ id: A.tag }) }); + expect(res.status).toBe(404); + expect(await row('select deleted_at from sl_tags where id=$1', [A.tag])).toEqual({ deleted_at: null }); + expect(await row('select count(*)::int c from sl_task_tags where tag_id=$1', [A.tag])).toEqual({ c: 1 }); + expect(taskIds(await pull(A.userId))).toEqual([]); + }); +}); diff --git a/web/src/app/api/sync/route.ts b/web/src/app/api/sync/route.ts index 87a8396..e61fe6a 100644 --- a/web/src/app/api/sync/route.ts +++ b/web/src/app/api/sync/route.ts @@ -49,7 +49,7 @@ export async function GET(request: NextRequest) { db .select() .from(slTags) - .where(and(eq(slTags.userId, auth.userId), gte(slTags.createdAt, sinceDate))), + .where(and(eq(slTags.userId, auth.userId), gte(slTags.updatedAt, sinceDate))), ]); // Get task-tag relations for the affected tasks @@ -121,9 +121,9 @@ export async function GET(request: NextRequest) { name: tag.name, color: tag.color, created_at: tag.createdAt.toISOString(), - updated_at: tag.createdAt.toISOString(), + updated_at: tag.updatedAt.toISOString(), }, - updated_at: tag.createdAt.toISOString(), + updated_at: tag.updatedAt.toISOString(), }); } @@ -335,16 +335,28 @@ async function processOperation(op: SyncOperation, userId: string, ctx: RequestC } else if (action === 'update') { const d = tagUpdateData.parse(data); await verifyTagOwnership(entityId, userId); - // Tags have no updatedAt: skip when nothing is left to write + // Nothing left to write: no change, so updatedAt does not move either if (d.name === undefined && d.color === undefined) break; await db.update(slTags) - .set(d) + .set({ ...d, updatedAt: now }) .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); } else if (action === 'delete') { await verifyTagOwnership(entityId, userId); - await db.update(slTags) - .set({ deletedAt: now }) - .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); + // Same transaction as DELETE /api/tags/[id] (#181): the tag's + // updatedAt brings the delete to the pull, and the tasks that lose a + // link come back in it too, so the app aligns their links. + await db.transaction(async (tx) => { + await tx.update(slTags) + .set({ deletedAt: now, updatedAt: now }) + .where(and(eq(slTags.id, entityId), eq(slTags.userId, userId))); + await tx.update(slTasks) + .set({ updatedAt: now }) + .where(and( + eq(slTasks.userId, userId), + inArray(slTasks.id, tx.select({ id: slTaskTags.taskId }).from(slTaskTags).where(eq(slTaskTags.tagId, entityId))), + )); + await tx.delete(slTaskTags).where(eq(slTaskTags.tagId, entityId)); + }); } break; } diff --git a/web/src/app/api/tags/[id]/route.ts b/web/src/app/api/tags/[id]/route.ts index dfa7af5..8ca7bcc 100644 --- a/web/src/app/api/tags/[id]/route.ts +++ b/web/src/app/api/tags/[id]/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from 'next/server'; import { db } from '@/db/client'; -import { slTags } from '@/db/schema'; -import { eq, and } from 'drizzle-orm'; +import { slTags, slTasks, slTaskTags } from '@/db/schema'; +import { eq, and, inArray } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { notifyUserChanged } from '@/lib/ws'; @@ -22,7 +22,7 @@ export async function PUT( const [updated] = await db .update(slTags) - .set(body.data) + .set({ ...body.data, updatedAt: new Date() }) .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) .returning(); @@ -45,11 +45,26 @@ export async function DELETE( const { id } = await params; - const [deleted] = await db - .update(slTags) - .set({ deletedAt: new Date() }) - .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) - .returning(); + // Same transaction as POST /api/sync tag delete (#181): the tag's updatedAt + // brings the delete to the app's pull, and the tasks that lose a link come + // back in it too, so the app aligns their links. + const now = new Date(); + const deleted = await db.transaction(async (tx) => { + const [tag] = await tx + .update(slTags) + .set({ deletedAt: now, updatedAt: now }) + .where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId))) + .returning({ id: slTags.id }); + if (!tag) return null; + await tx.update(slTasks) + .set({ updatedAt: now }) + .where(and( + eq(slTasks.userId, auth.userId), + inArray(slTasks.id, tx.select({ id: slTaskTags.taskId }).from(slTaskTags).where(eq(slTaskTags.tagId, id))), + )); + await tx.delete(slTaskTags).where(eq(slTaskTags.tagId, id)); + return tag; + }); if (!deleted) { return NextResponse.json({ error: 'Not found' }, { status: 404 }); diff --git a/web/src/db/migrations/0003_tag_updated_at.sql b/web/src/db/migrations/0003_tag_updated_at.sql new file mode 100644 index 0000000..5ae0e1d --- /dev/null +++ b/web/src/db/migrations/0003_tag_updated_at.sql @@ -0,0 +1,6 @@ +-- Tags get an updatedAt so that GET /api/sync pulls renames, colour changes +-- and deletions (#181). The user_id ALTERs that drizzle-kit re-emitted from +-- the stale 0000 snapshot were dropped: 0001 already applied them. +ALTER TABLE "sl_tags" ADD COLUMN "updated_at" timestamp with time zone DEFAULT now() NOT NULL;--> statement-breakpoint +-- Existing tags: their last known change is their creation. +UPDATE "sl_tags" SET "updated_at" = "created_at"; diff --git a/web/src/db/migrations/meta/0003_snapshot.json b/web/src/db/migrations/meta/0003_snapshot.json new file mode 100644 index 0000000..a80a8b5 --- /dev/null +++ b/web/src/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,417 @@ +{ + "id": "f15d185b-4478-4cdf-91b9-e281f16fdb3f", + "prevId": "a1bf2951-6318-42a2-adbb-758a703deb0b", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.sl_lists": { + "name": "sl_lists", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_inbox": { + "name": "is_inbox", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_lists_user": { + "name": "idx_sl_lists_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tags": { + "name": "sl_tags", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'#4A90A4'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tags_user": { + "name": "idx_sl_tags_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_task_tags": { + "name": "sl_task_tags", + "schema": "", + "columns": { + "task_id": { + "name": "task_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "tag_id": { + "name": "tag_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sl_task_tags_task_id_sl_tasks_id_fk": { + "name": "sl_task_tags_task_id_sl_tasks_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sl_task_tags_tag_id_sl_tags_id_fk": { + "name": "sl_task_tags_tag_id_sl_tags_id_fk", + "tableFrom": "sl_task_tags", + "tableTo": "sl_tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "sl_task_tags_task_id_tag_id_pk": { + "name": "sl_task_tags_task_id_tag_id_pk", + "columns": [ + "task_id", + "tag_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sl_tasks": { + "name": "sl_tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "completed": { + "name": "completed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "due_date": { + "name": "due_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "list_id": { + "name": "list_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "recurrence": { + "name": "recurrence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_sl_tasks_user": { + "name": "idx_sl_tasks_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_list": { + "name": "idx_sl_tasks_list", + "columns": [ + { + "expression": "list_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_sl_tasks_parent": { + "name": "idx_sl_tasks_parent", + "columns": [ + { + "expression": "parent_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sl_tasks_list_id_sl_lists_id_fk": { + "name": "sl_tasks_list_id_sl_lists_id_fk", + "tableFrom": "sl_tasks", + "tableTo": "sl_lists", + "columnsFrom": [ + "list_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/web/src/db/migrations/meta/_journal.json b/web/src/db/migrations/meta/_journal.json index 5fd5c09..f21ecc8 100644 --- a/web/src/db/migrations/meta/_journal.json +++ b/web/src/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1775649600000, "tag": "0002_cleanup_duplicate_inboxes", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1793673039382, + "tag": "0003_tag_updated_at", + "breakpoints": true } ] } \ No newline at end of file diff --git a/web/src/db/schema.ts b/web/src/db/schema.ts index 02fedc7..7eec89e 100644 --- a/web/src/db/schema.ts +++ b/web/src/db/schema.ts @@ -43,6 +43,7 @@ export const slTags = pgTable('sl_tags', { name: text('name').notNull(), color: text('color').notNull().default('#4A90A4'), createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), deletedAt: timestamp('deleted_at', { withTimezone: true }), }, (table) => [ index('idx_sl_tags_user').on(table.userId), -- 2.52.0 From acaad3ba6a6b6755dbe1aaf1e5c0dae3357e171b Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:38:09 -0500 Subject: [PATCH 2/2] test(sync): give the migration backfill test room to boot its own PGlite Refs #181 Co-Authored-By: Claude Opus 5.5 --- web/src/app/api/sync/route.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/app/api/sync/route.test.ts b/web/src/app/api/sync/route.test.ts index 1ccbe3a..7ed54a1 100644 --- a/web/src/app/api/sync/route.test.ts +++ b/web/src/app/api/sync/route.test.ts @@ -857,7 +857,7 @@ describe('tags carry an updatedAt that the pull follows (#181)', () => { expect(new Date(r.u).toISOString()).toBe(OLD); expect(new Date(r.c).toISOString()).toBe(OLD); await pg.close(); - }); + }, 30_000); // a second PGlite instance boots in seconds, over the 5 s default it('an untouched tag created before since is not pulled', async () => { const { B } = await seed(); -- 2.52.0