AddNameToUsersMigration: fix can't work when db already has users

This commit is contained in:
Alice Gaudon 2021-01-25 16:22:51 +01:00
parent 4817563dc1
commit 8b98c8cc59

View File

@ -4,13 +4,24 @@ import User from "../models/User";
import UserNameComponent from "../models/UserNameComponent";
import MagicLink from "../models/MagicLink";
import MagicLinkUserNameComponent from "../models/MagicLinkUserNameComponent";
import {nanoid} from "nanoid";
export default class AddNameToUsersMigration extends Migration {
public async install(): Promise<void> {
await this.query(`ALTER TABLE users
ADD COLUMN name VARCHAR(64) UNIQUE NOT NULL`);
ADD COLUMN name VARCHAR(64) NOT NULL`);
await this.query(`ALTER TABLE magic_links
ADD COLUMN username VARCHAR(64) DEFAULT NULL`);
// Give every user a random name
const users = await User.select().get(this.getCurrentConnection());
await Promise.all(users.map(user => {
user.name = nanoid();
return user.save(this.getCurrentConnection());
}));
await this.query(`ALTER TABLE users
ADD CONSTRAINT UNIQUE (name)`);
}
public async rollback(): Promise<void> {