Skip to content

Commit

Permalink
Server: Fixed owner_id migration for SQLite
Browse files Browse the repository at this point in the history
  • Loading branch information
laurent22 committed Oct 27, 2021
1 parent b0e3e1b commit f1c4d35
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions packages/server/src/migrations/20211027112530_item_owner.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,42 @@
import { Knex } from 'knex';
import { DbConnection } from '../db';
import { DbConnection, isPostgres } from '../db';

export async function up(db: DbConnection): Promise<any> {
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();
Expand Down

0 comments on commit f1c4d35

Please sign in to comment.