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

Using moor_ffi with existing database #346

Closed
abahnj opened this issue Jan 20, 2020 · 3 comments
Closed

Using moor_ffi with existing database #346

abahnj opened this issue Jan 20, 2020 · 3 comments
Labels
backend-native Related to NativeDatabase question Further information is requested

Comments

@abahnj
Copy link

abahnj commented Jan 20, 2020

I would like to enquire if it is possible to use moor with an existing sqlite database file as your documentation doesn't mention if it is supported. Any help would be greatly appreciated

@simolus3 simolus3 added backend-native Related to NativeDatabase question Further information is requested labels Jan 20, 2020
@simolus3
Copy link
Owner

moor_ffi should support that, yes. I've added some documentation for existing databases here (it will go to the live website with the next moor release).

Please let me know if the docs help or if you need more info, I'm always looking for ways to improve the documentation.

@abahnj
Copy link
Author

abahnj commented Jan 20, 2020

I was able to get it to work using the below code... Thanks a lot for your help and for the great work on moor. Any thoughts or optimization suggestions?

LazyDatabase _openConnection() {
  // after
  return LazyDatabase(() async {
    var databasesPath = await getApplicationDocumentsDirectory();
    var path = join(databasesPath.path, 'confession.db');

    final file = File(path);
    if (!file.existsSync()) {
      // copy the file from an asset, or network, or any other source
      // Should happen only the first time you launch your application
      print('Creating new copy from asset');

      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}

      // Copy from asset
      var data =
          await rootBundle.load(join('assets', 'database', 'confession.db'));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Write and flush the bytes written
      await file.writeAsBytes(bytes, flush: true);
    } else {
      print('Opening existing database');
    }
    return VmDatabase(file);
  });
}

@simolus3
Copy link
Owner

Looks good! If you're in an async function you can replace file.existsSync() with await file.exists() - but it doesn't make much of a difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend-native Related to NativeDatabase question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants