Using TypeORM to handle SQLite migrations in a React Native project involves several key steps. I will explain each step in detail and provide code examples or operational instructions.
Step 1: Installation and Configuration of TypeORM
First, ensure that typeorm and react-native-sqlite-storage are installed in your React Native project. TypeORM depends on this library for handling SQLite databases.
bashnpm install typeorm react-native-sqlite-storage
Next, configure TypeORM in your project, typically within a dedicated database configuration file. For example, create a database.ts file to initialize the database connection.
typescriptimport {createConnection} from 'typeorm'; import {User} from './entities/User'; export const databaseInitializer = async () => { await createConnection({ type: 'react-native', database: 'test.db', location: 'default', logging: ['error', 'query', 'schema'], synchronize: false, entities: [ User, ], migrations: ['src/migration/**/*.ts'], cli: { migrationsDir: 'src/migration', }, }); };
Step 2: Creating Migrations
Migrations in TypeORM are scripts for managing database schema changes. You can manually create migration files or generate them using the TypeORM CLI.
To generate a migration, run the following command:
bashtypeorm migration:create -n UserMigration
This creates a new migration file in the specified migration folder. Edit this file to define the database schema changes.
typescriptimport {MigrationInterface, QueryRunner} from "typeorm"; export class UserMigration implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar NOT NULL)`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "user"`); } }
Step 3: Executing Migrations
Once your migration files are prepared, execute migrations during application startup to update the database schema.
typescriptimport {databaseInitializer} from './database'; const startApp = async () => { await databaseInitializer(); await connection.runMigrations(); // Other initialization code here }; startApp();
Step 4: Rolling Back Migrations (Optional)
TypeORM supports rolling back migrations if necessary, which can be achieved by calling the undoLastMigration method.
typescriptawait connection.undoLastMigration();
Summary
Handling SQLite database migrations with TypeORM involves setting up TypeORM and its dependencies, writing migration scripts, and executing them at the appropriate time. This approach helps you effectively manage database schema changes in your React Native application.