Flutter数据库迁移插件needle_orm_migration的使用

Flutter数据库迁移插件needle_orm_migration的使用

Needle Orm Migration 是一个为 Needle ORM 构建的基本数据库迁移框架,并且是从 Angel3 ORM 派生出来的。

使用步骤

1. 添加依赖

在你的 pubspec.yaml 文件中添加 needle_orm_migration 依赖:

dependencies:
  needle_orm_migration: ^x.x.x # 替换为最新版本号

然后运行 flutter pub get 来安装依赖。

2. 创建迁移类

创建迁移类来定义数据库表结构。以下是一个示例:

import 'package:needle_orm_migration/needle_orm_migration.dart';

// 用户表迁移类
class UserMigration implements Migration {
  @override
  void up(Schema schema) {
    // 创建用户表
    schema.create('users', (table) {
      table
        ..serial('id').primaryKey() // 自增主键
        ..varChar('username', length: 32).unique() // 唯一用户名
        ..varChar('password') // 密码字段
        ..boolean('account_confirmed').defaultsTo(false); // 是否确认账户,默认为false
    });
  }

  @override
  void down(Schema schema) {
    // 删除用户表
    schema.drop('users');
  }
}

// 待办事项表迁移类
class TodoMigration implements Migration {
  @override
  void up(Schema schema) {
    // 创建待办事项表
    schema.create('todos', (table) {
      table
        ..serial('id').primaryKey() // 自增主键
        ..integer('user_id').references('users', 'id').onDeleteCascade() // 外键引用用户表的id
        ..varChar('text') // 文本字段
        ..boolean('completed').defaultsTo(false); // 是否完成,默认为false
    });
  }

  @override
  void down(Schema schema) {
    // 删除待办事项表
    schema.drop('todos');
  }
}

3. 运行迁移

在应用启动时运行这些迁移,确保每次应用更新后数据库结构保持一致。以下是一个示例代码:

import 'package:needle_orm_migration/needle_orm_migration.dart';
import 'path_to_your_migrations/user_migration.dart'; // 替换为实际路径
import 'path_to_your_migrations/todo_migration.dart'; // 替换为实际路径

Future<void> main() async {
  final schema = Schema(); // 初始化Schema对象
  
  // 注册迁移类
  await schema.registerMigration(UserMigration());
  await schema.registerMigration(TodoMigration());

  // 运行所有迁移
  await schema.runMigrations();
  
  print("Database migrations completed.");
}

更多关于Flutter数据库迁移插件needle_orm_migration的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据库迁移插件needle_orm_migration的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


needle_orm_migration 是一个用于 Flutter 应用中进行数据库迁移的插件,它通常与 NeedleORM 一起使用。NeedleORM 是一个轻量级的 ORM(对象关系映射)库,旨在简化 Flutter 应用中的数据库操作。

1. 安装依赖

首先,你需要在 pubspec.yaml 文件中添加 needle_orm_migration 的依赖:

dependencies:
  flutter:
    sdk: flutter
  needle_orm: ^0.1.0
  needle_orm_migration: ^0.1.0

然后运行 flutter pub get 来安装依赖。

2. 配置数据库

在使用 needle_orm_migration 之前,你需要配置数据库。通常,你会创建一个 Database 类来管理数据库的连接和迁移。

import 'package:needle_orm/needle_orm.dart';
import 'package:needle_orm_migration/needle_orm_migration.dart';

class MyDatabase extends Database {
  MyDatabase() : super('my_database.db');

  @override
  List<Migration> get migrations => [
        Migration1(),
        Migration2(),
        // 添加更多的迁移类
      ];
}

3. 创建迁移类

每个迁移类都需要继承 Migration 并实现 updown 方法。up 方法用于应用迁移,down 方法用于回滚迁移。

class Migration1 extends Migration {
  @override
  Future<void> up(Database db) async {
    await db.execute('''
      CREATE TABLE users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER
      )
    ''');
  }

  @override
  Future<void> down(Database db) async {
    await db.execute('DROP TABLE users');
  }
}

class Migration2 extends Migration {
  @override
  Future<void> up(Database db) async {
    await db.execute('''
      ALTER TABLE users ADD COLUMN email TEXT
    ''');
  }

  @override
  Future<void> down(Database db) async {
    await db.execute('''
      ALTER TABLE users DROP COLUMN email
    ''');
  }
}

4. 运行迁移

在应用启动时,你可以通过调用 MyDatabasemigrate 方法来运行迁移。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final database = MyDatabase();
  await database.migrate();

  runApp(MyApp());
}

5. 回滚迁移

如果需要回滚到之前的版本,你可以调用 rollback 方法。

await database.rollback();

6. 使用 ORM 进行数据库操作

NeedleORM 提供了一种简单的方式来操作数据库。你可以定义实体类并使用 Repository 来进行 CRUD 操作。

class User {
  int? id;
  String name;
  int age;

  User({this.id, required this.name, required this.age});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'age': age,
    };
  }

  factory User.fromMap(Map<String, dynamic> map) {
    return User(
      id: map['id'],
      name: map['name'],
      age: map['age'],
    );
  }
}

class UserRepository extends Repository<User> {
  UserRepository(Database db) : super(db, 'users');

  @override
  User fromMap(Map<String, dynamic> map) {
    return User.fromMap(map);
  }

  @override
  Map<String, dynamic> toMap(User user) {
    return user.toMap();
  }
}

7. 使用 Repository 进行 CRUD 操作

你可以在应用中使用 UserRepository 来进行数据库操作。

final userRepository = UserRepository(database);

// 插入用户
await userRepository.insert(User(name: 'John Doe', age: 30));

// 查询用户
final users = await userRepository.findAll();

// 更新用户
final user = users.first;
user.name = 'Jane Doe';
await userRepository.update(user);

// 删除用户
await userRepository.delete(user);
回到顶部