Skip to content
This repository has been archived by the owner on Jul 7, 2022. It is now read-only.

copy database just copies from assets #37

Open
kazemihabib opened this issue Feb 12, 2017 · 10 comments
Open

copy database just copies from assets #37

kazemihabib opened this issue Feb 12, 2017 · 10 comments

Comments

@kazemihabib
Copy link

kazemihabib commented Feb 12, 2017

hi,
the copyDatabase just copies the database from assets (Android I didn't check ios) but there are situations that we need to copy it from sdcard to database folder (like downloading it from server).
I know we can copy do it manually, but if copyDatabase supports that it would be really good.

@jeffswitzer
Copy link

@kazemihabib I also ran into this problem (on android) of trying to download a database from a remote server and then call copyDatabase on the downloaded file but even though the file has been downloaded to the apps directory copyDatabase doesn't find it. I posted my code snippit in this github issue. couple questions: are the assets folder and app folder 2 different locations? How did you get around this by copying manually? If I instead embed the sqlite file in the apps folder before building the app then the copyDatabase call works.

@jeffswitzer
Copy link

jeffswitzer commented Feb 20, 2017

@NathanaelA is the path that copyDatabase() tries to copy from the same as fs.knownFolders.currentApp().path? On my system that resolves to /data/data/org.nativescript.myappname/files/app

@NathanaelA
Copy link
Owner

NathanaelA commented Feb 20, 2017

@jeffswitzer - Yes. The copy from path is the root of the app which is that path.

The copyDatabase is really just designed to be a very simple helper for those who include the database as part of the built in app; so that it can be installed in the place that it needs to be. It is not a general purpose routine. :-)

@kazemihabib
Copy link
Author

@jeffswitzer I didn't implement it yet , but I know it's possible for example:http://stackoverflow.com/questions/22531789/copy-database-from-sdcard-to-data-data-packagename-databases-folder

@NathanaelA
Copy link
Owner

I am willing to accept a pull request that implements this functionality; or you can contract with me or another contractor to add this feature.

@shastik
Copy link

shastik commented Apr 10, 2017

Hi everyone,

I tried @kazemihabib solution and it works.

I have a custom db service (db.service.ts) (did not overloaded nativescript-sqlite library).

I use Angular2

I have to use Android DownloadManager to download DB file. http.getFile is not ready to download large files.

Here is my code: (maybe it will help to someone)

    let dm = new DownloadManager();
    dm.downloadFile("https://database_to_download/database_name.db", function(result,uri) {
      if (result) {                  
         uri = uri.replace('file://','');
         self.copyDatabaseAndroid(databaseName, uri, self.getDatabaseName());                        
         self.initialize(self.getDatabaseName(), true);
      }
      resolve(true);
                    

      dm.unregisterBroadcast();
    })   

    /**
     * gets the current application context
     * @returns {*}
     * @private
     */
    _getContext() {

        if (app.android.context) {
            return (app.android.context);
        }
        var ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null);
        if (ctx) return ctx;

        ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null);
        return ctx;
    }
    

    copyDatabaseAndroid(name, currentDBPath, oldName) {
                
        if (name.indexOf('/')) {
            name = name.substring(name.indexOf('/')+1);
        }
        //noinspection JSUnresolvedFunction
        var dbname = this._getContext().getDatabasePath(name).getAbsolutePath();
        var path = dbname.substr(0, dbname.lastIndexOf('/') + 1);

        if (oldName != 'church_service.db') {
            var olddbname = this._getContext().getDatabasePath(oldName).getAbsolutePath();
            var oldpath = olddbname.substr(0, olddbname.lastIndexOf('/') + 1);
            try {
                var javaFile = new java.io.File(oldpath);
                if (javaFile.exists()) {
                    javaFile.delete();
                    console.log('Delete old db file success');
                } else {
                    console.log('Old db file not found', oldpath);
                }
            } catch (err) {
                console.info('Delete old db error', err);
            }
        }

        // Create "databases" folder if it is missing.  This causes issues on Emulators if it is missing
        // So we create it if it is missing

        try {
            var javaFile = new java.io.File(path);
            if (!javaFile.exists()) {
                //noinspection JSUnresolvedFunction
                javaFile.mkdirs();
                //noinspection JSUnresolvedFunction
                javaFile.setReadable(true);
                //noinspection JSUnresolvedFunction
                javaFile.setWritable(true);
            }
        }
        catch (err) {
            console.info("SQLITE - COPYDATABASE - Creating DB Folder Error", err);
        }

        var backupDBPath = path + '/' + name;

        var currentDB = new java.io.File(currentDBPath);
        var backupDB = new java.io.File(backupDBPath);
        var success = false;
        try {
                var source = new java.io.FileInputStream(currentDB).getChannel();
                var destination = new java.io.FileOutputStream(backupDB).getChannel();
                destination.transferFrom(source, 0, source.size());
                source.close();
                destination.close();
                console.log('DB exported');
                success = true;
                //Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
            } catch(err) {
                console.info('Copy DB error', err);
            }

        return success;            
    }

    public initialize(databaseName: string = '', reInitialize: boolean = false) {
        return new Promise((resolve, reject) => {
            if (!this.isInitialized || reInitialize) {

                console.log('initializeDB');

                if (!databaseName) {
                    databaseName = this.getDatabaseName();
                }

                this.setDatabaseName(databaseName);
                
                if (!Sqlite.exists(databaseName)) {
                    Sqlite.copyDatabase(databaseName);
                }        
                (new Sqlite(databaseName))
                .then(db => {         
                    console.log('open database: ', databaseName);                                    
                    this.database = db;  
                    this.isInitialized = true;   
                    this.database.resultType(Sqlite.RESULTSASOBJECT);
                    this.queryBuilderService.setDatabase(this.database);

                    resolve(true);
                            
                }, error => {
                    console.log("OPEN DB ERROR", error);
                })                    
                .then(db => {
                });   

            } else {
                resolve(true);
            }  
        });  
    }

@thiagoufg
Copy link

I'd also like to have it copied from the SD card, or even accessed from there, without needing to copy it to the folder /data/data/org.nativescript.myappname/files/app

@jeffswitzer
Copy link

@kazemihabib @shastik thanks much... finally just got back to this and the above code helped me to get it working.

@webmeemba
Copy link

Hi, I need help with copyDatabaseAndroid(name, currentDBPath, oldName).

(angular)Me code is the next:

component.ts

var filePath = fs.path.join(fs.knownFolders.currentApp().path, "init2.db");

http.getFile("http://meemba-webs.com.ar/beeorder/init2.db", filePath).then(downloadedFile => {
this.service.setDB(dbName, filePath)
})

service.ts

public setDB(name, path) : void{
console.log('name:'); console.log(name);
if (!sqlite.exists(name)) {
this.copyDatabaseAndroid(name, path, name);
};

   new sqlite(name, function(err, db) {
        if (!err) {
          this.database = db;
        }
   });     
}

private copyDatabaseAndroid(name, currentDBPath, oldName) {

    if (name.indexOf('/')) {
        name = name.substring(name.indexOf('/')+1);
    }
    //noinspection JSUnresolvedFunction
    var dbname = this._getContext().getDatabasePath(name).getAbsolutePath();
    var path = dbname.substr(0, dbname.lastIndexOf('/') + 1);

    if (oldName != 'church_service.db') {
        var olddbname = this._getContext().getDatabasePath(oldName).getAbsolutePath();
        var oldpath = olddbname.substr(0, olddbname.lastIndexOf('/') + 1);
        try {
            var javaFile = new java.io.File(oldpath);
            if (javaFile.exists()) {
                javaFile.delete();
                console.log('Delete old db file success');
            } else {
                console.log('Old db file not found', oldpath);
            }
        } catch (err) {
            console.info('Delete old db error', err);
        }
    }

    // Create "databases" folder if it is missing.  This causes issues on Emulators if it is missing
    // So we create it if it is missing

    try {
        var javaFile = new java.io.File(path);
        if (!javaFile.exists()) {
            //noinspection JSUnresolvedFunction
            javaFile.mkdirs();
            //noinspection JSUnresolvedFunction
            javaFile.setReadable(true);
            //noinspection JSUnresolvedFunction
            javaFile.setWritable(true);
        }
    }
    catch (err) {
        console.info("SQLITE - COPYDATABASE - Creating DB Folder Error", err);
    }

    var backupDBPath = path + '/' + name;

    var currentDB = new java.io.File(currentDBPath);
    var backupDB = new java.io.File(backupDBPath);
    var success = false;
    try {
            var source = new java.io.FileInputStream(currentDB).getChannel();
            var destination = new java.io.FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            console.log('DB exported');
            success = true;
            //Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
        } catch(err) {
            console.info('Copy DB error', err);
        }

    return success;            
}

@heese
Copy link

heese commented Mar 19, 2019

I read this thread first but could not easily extract the key source code. I found another post showing very concise source code (also notice the comment later about checking for the existence of the folder). Maybe, this will help other people facing this issue.

https://discourse.nativescript.org/t/downloading-and-using-an-sqlite-db-file-where-does-it-go/6567/4

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

7 participants