react-native-sqlite-storage icon indicating copy to clipboard operation
react-native-sqlite-storage copied to clipboard

Is it possible import database from sql file

Open pwin519 opened this issue 3 years ago • 3 comments

I am trying import the sql file into database that it opened. But I cannot find the method on the document. I think a solution is executing sql in plain text. Any answer here?

Many Thanks!

pwin519 avatar Mar 04 '21 08:03 pwin519

@pwin519 did you find any solution?

NisargTailor avatar Aug 28 '21 09:08 NisargTailor

My idea is fetching the content from sql file. Then we will execute this sql content.

fetch('query.sql')
  .then(response => response.text())
  .then(query => {
  	console.log(query);
        this.db.transaction(txn => {
           txn.executeSql(query, args, callback);
        });
  });

thanhzusu avatar Jun 17 '22 02:06 thanhzusu

It is possible, but requires a little bit of workaround...

Firstly, you would need to install the package react-native-fs, since you can't really access the file system like you can with node.js module fs.

Unfortunately, you have to also duplicate your SQL file into either android or ios folder (depending what platform you are targeting to) so that the file can be bundled together and allow react-native-fs to import this file.

The process for android is creating the file in this structure

├── __tests__
├── android
│   └── app
│     └── src
│      └── main
│       └── assets
│        └── query.sql
├── src
...

For ios, I believe all you have to do is create an assets folder inside ios but I may be wrong. Found a StackOverflow answer that describes the process here

Once you've created this file, you can then access the file by importing react-native-fs and using the readFileAssets function

import fs from "react-native-fs";

const sqlFile = fs.readFileAssets("query.sql")

db.transaction((tx) => {
  tx.executeSql(sqlFile);
});

I assume that you can also create a file structure inside assets folder. You can imagine the path starting from assets file.

silvabacc avatar Jan 22 '23 01:01 silvabacc