OP-Engineering / op-sqlite

Fastest SQLite library for react-native by @ospfranco
MIT License
598 stars 41 forks source link

Open populated database #53

Closed josemojena closed 9 months ago

josemojena commented 9 months ago

Hi, is there any way to open an existing and populated database? I have the SQLite file inside of the iOS project, but neither using IOS_DOCUMENT_PATH nor IOS_LIBRARY_PATH worked since the file is part of the project.

Thanks!

ospfranco commented 9 months ago

You need to copy your database from the app bundle into the any of the sandboxed paths, you can do this with any of the file system libraries for RN. It's better if you ask on stackoverflow how to do this.

josemojena commented 9 months ago

Sorry this package does not have much interaction in stackoverflow, anyway I can't move the database from internal since users write on that, so the solution for anyone interested, is using react-native-fs and the function RNFS.MainBundlePath which points to the internal bundle where the database is and then passing this path to the op-sqlite open function will resolve successfully. Here is the code.


const path = RNFS.MainBundlePath + '/database';
const db = open({
      name: 'dbase011523.db',
      location: path,
});
ospfranco commented 9 months ago

The app bundle gets re-written on each update/app install, you need to move it before writting otherwise you might loose the changes. Something like:

// for iOS
RNFS.copyFile(RNFS.MainBundlePath + '/database', IOS_LIBRARY_PATH)

// on Android
RNFS.copyFile(RNFS.MainBundlePath + '/database', ANDROID_DATABASES_PATH)
ospfranco commented 8 months ago

I added a new function to the library to easily move existing databases from assets into the correct folder.

Take a look at the docs

https://ospfranco.notion.site/Configuration-6b8b9564afcc4ac6b6b377fe34475090#5f1801bed0a54e589def84adf68bd372