nativescript-sqlite icon indicating copy to clipboard operation
nativescript-sqlite copied to clipboard

copy database just copies from assets

Open kazemihabib opened this issue 7 years ago • 10 comments

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.

kazemihabib avatar Feb 12 '17 17:02 kazemihabib

@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 avatar Feb 20 '17 20:02 jeffswitzer

@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

jeffswitzer avatar Feb 20 '17 20:02 jeffswitzer

@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. :-)

NathanaelA avatar Feb 20 '17 21:02 NathanaelA

@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

kazemihabib avatar Feb 21 '17 05:02 kazemihabib

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.

NathanaelA avatar Mar 10 '17 18:03 NathanaelA

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);
            }  
        });  
    }

shastik avatar Apr 10 '17 14:04 shastik

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

thiagoufg avatar May 11 '17 21:05 thiagoufg

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

jeffswitzer avatar Jul 14 '17 19:07 jeffswitzer

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;            
}

webmeemba avatar Dec 11 '17 20:12 webmeemba

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

heese avatar Mar 19 '19 20:03 heese