乐闻世界logo
搜索文章和话题

How to deal with SQLite migrations in React-Native using TypeORM?

1个答案

1

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.

bash
npm 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.

typescript
import {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:

bash
typeorm migration:create -n UserMigration

This creates a new migration file in the specified migration folder. Edit this file to define the database schema changes.

typescript
import {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.

typescript
import {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.

typescript
await 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.

2024年7月31日 00:43 回复

你的答案