From f1c4d35ef3df42155fe9f2d9f6cb4b18360fe471 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Wed, 27 Oct 2021 16:31:19 +0100 Subject: [PATCH] Server: Fixed owner_id migration for SQLite --- .../migrations/20211027112530_item_owner.ts | 39 +++++++++++++++---- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/packages/server/src/migrations/20211027112530_item_owner.ts b/packages/server/src/migrations/20211027112530_item_owner.ts index 8d17cfedf..c023da782 100644 --- a/packages/server/src/migrations/20211027112530_item_owner.ts +++ b/packages/server/src/migrations/20211027112530_item_owner.ts @@ -1,17 +1,42 @@ import { Knex } from 'knex'; -import { DbConnection } from '../db'; +import { DbConnection, isPostgres } from '../db'; export async function up(db: DbConnection): Promise { await db.schema.alterTable('items', (table: Knex.CreateTableBuilder) => { table.string('owner_id', 32).defaultTo('').notNullable(); }); - await db.raw(` - UPDATE items - SET owner_id = user_items.user_id - FROM user_items - WHERE user_items.item_id = items.id - `); + if (isPostgres(db)) { + await db.raw(` + UPDATE items + SET owner_id = user_items.user_id + FROM user_items + WHERE user_items.item_id = items.id + `); + } else { + // Very inefficient way to set the owner_id but SQLite is probably not + // used with very large dataset. + + interface Row { + id: string; + user_id: string; + } + + while (true) { + const items: Row[] = await + db('items') + .join('user_items', 'items.id', 'user_items.item_id') + .select(['items.id', 'user_items.user_id']) + .where('owner_id', '=', '') + .limit(10000); + + if (!items.length) break; + + for (const item of items) { + await db('items').update({ owner_id: item.user_id }).where('id', '=', item.id); + } + } + } await db.schema.alterTable('items', (table: Knex.CreateTableBuilder) => { table.string('owner_id', 32).notNullable().alter();