Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepopulate Realm database with data?

I have a file of data scraped from the web, that was generated using python script.
How can I load it into my Realm react native database?
I have stumbled upon ideas that it can be loaded from JSON file without any modifications, is it possible, how to do this?

How can I specify path to the file in react native? How can I parse a file in react native?

Update: Could you suggest me the general work flow for work with data in React Native? I haven't found useful manuals for that.
I wonder, should I parse files from React native (generic scripts), in this case how to specify path to them, or should I work with them in the specific platform (from Andriod /iOS project)?

like image 772
spin_eight Avatar asked Jan 21 '18 10:01

spin_eight


People also ask

How do I delete all data from a Realm?

The right way of deleting your entire Realm (schema) is to use : Realm realm = Realm. getDefaultInstance(); realm. beginTransaction(); // delete all realm objects realm.

Is Realm database SQL or NoSQL?

The Realm database is an open-source, easy-to-use alternative to Core Data and SQLite. It's a non-relational, NoSQL database that allows you to set up relationships between different objects. Realm is far younger than SQLite; nonetheless, it's widely popular among developers around the globe.


1 Answers

Finally I came out with the valid workflow for providing repopulated database.
1. Convert your data to json format, as json files can be imported directly using node's npm require method. (I had file in csv format, and wrote python script to convert it into json), so your file should look like this:

{"key0": ["property0", "property1"], "key1": ["property0", "property1"]...}

actually you create json file having schema of your database in mind, example file will map to the following schema:

const MyDBSchema = {
    name: 'MyEntity',
    primaryKey: 'key',
    properties: {
      key:  'string',
      property0: 'string',
      property1: 'int',
      property2: 'int',
      property3: 'int'
    }
};

as you can see, I load properties: property0, property1 from son file, other properties are initialized when I create database.
2. Create you database for the first time:
this includes database generation and selection of place where to put it (be careful on where to put it, as there are limited choices here).
The key element here is that we create database only once, only if there is no database, we use RNFS module for that.
We algorithm is fairly strait forward: if file exists - open it, otherwise create and open it.

export async function openDB() {
    realm = await Realm.open({
        path: RNFS.DocumentDirectoryPath + '/myDBname.realm',
        schema: [MySchema],

    });
    RNFS.exists(RNFS.DocumentDirectoryPath + '/myDBname.realm').then(exists => {
        if(!exists) {
          createDB(realm);
        }
    });
    return realm;
}

Database creation is described on the Realm's web page, in any case here is my code snippet for that, so you could see how it maps to the overall picture:

let entities = require('../../data/myJsonFileForDB');
export function createDB(realm){
try {
    console.log("Creating DB");
    console.log("db path:" + realm.path);
    realm.write(() => {
        for (let entity in entities) {
            let property0 = entities['property0'][0];
            let property1 = parseInt(entities['property0'][1]);
            realm.create('myEntity', 
              {
                property0: property0,
                property1: property1,
                property2: 0,
                property3: 0,
              }, true);
          }
        });
    } catch (error) {
      console.log(error)
        console.log("Error on creation");
    }
};
like image 189
spin_eight Avatar answered Sep 18 '22 18:09

spin_eight