Database

Learn How to Safely Use dropSchema in TypeORM for Database Cleanup


Overview

TypeORM’s dropSchema option allows you to remove all tables from your database, which has the overall effect of emptying your schema. It will mainly come in handy while developing or testing an application where an old state of the database no longer serves any purpose.

How It Works

Once the option dropSchema is set to true, the following actions are performed when the ORM is synchronized with the database

  1. All database tables are deleted.

  2. Associated tables, columns, indexes, and relationships are removed.

  3. If dropSchema is set to true and synchronize is set to false, then it will not remove any tables. However, if both options are set to true, then the existing tables will be deleted and the schema will be constructed according to the entity definitions.

Example:

import { DataSource } from 'typeorm';import { User } from './entities/User';const dataSource = new DataSource({  type: 'postgres',  host: 'localhost',  port: 5432,  username: 'postgres',  password: 'password',  database: 'test_db',  synchronize: true,  // Recreate schema after dropping  dropSchema: true,   // Drop all tables  entities: [User],});dataSource  .initialize()  .then(() => console.log('Schema dropped and recreated'))  .catch((error) => console.log('Error: ', error)); 

When to Use dropSchema

  • Development: During application development, a schema can be reset quickly without having to use a full reset option.
  • Testing: Remove all database information between individual tests to guarantee a clean environment for each test case.
  • Database Reset: Remove all information stored in the database so that a new schema can be created.

Risks

  • Data Loss: All Data will be lost and will no longer be retrievable.
  • Avoid Production Setups: Never use dropSchema in a production environment because it will permanently remove critical business data from the database.

Best Practices

  • Utilize in Multi-User Development and Testing Environment: It is advised to use dropSchema on non-production sites where multiple users can test the system.
  • Always Save Important Data: It is always advisable to make a copy of important data before removing database tables with dropSchema.

 Ready to transform your business with our technology solutions? Contact Us Now!

0

Database

Related Center Of Excellence