Consider a NestJS migration that adds a new column to an existing table. What will be the state of the database after running this migration?
import { MigrationInterface, QueryRunner } from 'typeorm'; export class AddAgeColumn1680000000000 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE users ADD COLUMN age int`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE users DROP COLUMN age`); } }
Think about what the up method does in a migration.
The up method runs the SQL to add the new column. This changes the database schema by adding the 'age' column to the 'users' table.
Identify the migration code snippet that will cause a syntax error when executed.
Check the SQL syntax for adding a column.
Option A is missing the keyword COLUMN after ADD, which is required in SQL to add a new column.
Given the migration below, why does running the down method cause an error?
import { MigrationInterface, QueryRunner } from 'typeorm'; export class RenameUsernameToUser1680000000001 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE users RENAME COLUMN username TO user`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`ALTER TABLE users RENAME COLUMN user TO username`); } }
Think about the state of the database after the up method runs.
After the up method, the column 'username' is renamed to 'user'. The down method tries to rename 'username' again, but it no longer exists, causing an error.
This migration creates a new table. What will the database contain after running up?
import { MigrationInterface, QueryRunner } from 'typeorm'; export class CreateProductsTable1680000000002 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`CREATE TABLE products (id int PRIMARY KEY, name varchar(100), price decimal)`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE products`); } }
Check the SQL syntax for creating tables and column definitions.
The up method creates a table named 'products' with the specified columns and types. The SQL syntax is correct.
Why is the down method important in a migration class?
Think about what happens if you want to undo a migration.
The down method provides instructions to undo the changes made by up. This is essential for safely rolling back migrations if needed.