Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unhandled Exception: Instance of 'ConnectionClosedException' #2771

Closed
heshaShawky opened this issue Dec 6, 2023 · 1 comment
Closed

Unhandled Exception: Instance of 'ConnectionClosedException' #2771

heshaShawky opened this issue Dec 6, 2023 · 1 comment

Comments

@heshaShawky
Copy link

Describe the bug

I am trying to make a bulk insertion on database using isolate, so based on docs did this but getting the following error

E/flutter ( 4398): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Instance of 'ConnectionClosedException'
E/flutter ( 4398): #0      DriftCommunication.request (package:drift/src/remote/communication.dart:113:66)
E/flutter ( 4398): #1      _RemoteQueryExecutor.ensureOpen (package:drift/src/remote/client_impl.dart:158:10)
E/flutter ( 4398): #2      Batch._commit (package:drift/src/runtime/api/batch.dart:190:26)
E/flutter ( 4398): #3      DatabaseConnectionUser.batch (package:drift/src/runtime/api/connection_user.dart:525:20)
E/flutter ( 4398): #4      CategoriesDAO.insertDefaultCategories.<anonymous closure> (package:mizaniti/src/database/dao/categories_dao.dart:123:18)
E/flutter ( 4398): #5      ComputeWithDriftIsolate.computeWithDatabase.<anonymous closure> (package:drift/isolate.dart:331:33)
E/flutter ( 4398): <asynchronous suspension>
E/flutter ( 4398): #6      _RemoteRunner._run (dart:isolate:1023:18)
E/flutter ( 4398): <asynchronous suspension>
E/flutter ( 4398): 
D/EGL_emulation( 4398): app_time_stats: avg=50.61ms min=3.25ms max=708.63ms count=20
D/ProfileInstaller( 4398): Installing profile for com.example.mizaniti

My code:

@DriftDatabase(
    tables: [SettingsTable, WalletsTable, TransactionsTable, CategoriesTable],
    daos: [SettingsDAO, WalletsDAO, TransactionsDAO, CategoriesDAO])
class AppDatabase extends _$AppDatabase {
  AppDatabase([QueryExecutor? executor]) : super(executor ?? _openConnection());

  @override
  int get schemaVersion => 1;

  @override
  MigrationStrategy get migration => MigrationStrategy(
        beforeOpen: (details) async {
          if (details.wasCreated) {
            // preloading settings
            await into(settingsTable).insert(
              SettingsData(
                id: 1,
                details: SettingsDetails.empty(),
              ),
            );

            CategoriesDAO.insertDefaultCategories(this);
          }
        },
      );
}

LazyDatabase _openConnection() {
  // the LazyDatabase util lets us find the right location for the file async.
  return LazyDatabase(() async {
    // put the database file, called db.sqlite here, into the documents folder
    // for your app.
    final dbFolder = await getApplicationDocumentsDirectory();
    final file = File(p.join(dbFolder.path, 'db.sqlite'));
    return NativeDatabase.createInBackground(file, logStatements: true);
  });
}
@lazySingleton
@DriftAccessor(tables: [CategoriesTable])
class CategoriesDAO extends DatabaseAccessor<AppDatabase>
    with _$CategoriesDAOMixin {
  CategoriesDAO(AppDatabase attachedDatabase) : super(attachedDatabase);

  

  static Future<void> insertDefaultCategories(AppDatabase database) async {
    await database.computeWithDatabase(
      computation: (database) async {
        // Expensive computation that runs on its own isolate but talks to the
        // main database.

        final categories = categoryList;

        database.batch((batch) => batch.insertAll(
            database.categoriesTable, categories,
            mode: InsertMode.insertOrReplace));
      },
      connect: (connection) {
        // This function is responsible for creating a second instance of your
        // database class with a short-lived [connection].
        // For this to work, your database class needs to have a constructor that
        // allows taking a connection as described above.
        return AppDatabase(connection);
      },
    );
  }
}
@simolus3
Copy link
Owner

simolus3 commented Dec 6, 2023

The connection gets closed after the callback completes, so you need to await the database.batch call in insertDefaultCategories.

@simolus3 simolus3 closed this as completed Dec 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants