SQLite
 sql >> Database >  >> RDS >> SQLite

Impossibile copiare db precreato dagli asset

Hai una serie di problemi, supponendo che tu voglia sostituire un database preesistente esistente con un'altra copia.

Il problema che stai affrontando è che poiché esiste un database, la copia non procederà, ad esempio il checkDatabase() restituirà true.

Se dovessi semplicemente invocare il copyDatabase() quindi il database verrebbe copiato ogni volta che viene eseguita l'app, il che sarebbe inefficiente e distruttivo se il database può essere modificato dall'utente.

Quello che devi fare è avere un indicatore, che può essere testato, per vedere se il database preesistente è stato modificato. Esistono vari modi, ma il modo più probabile/comune sarebbe utilizzare la versione_utente di SQLite . Questo è un valore intero e viene spesso utilizzato per aggiornare il database corrente tramite onUpgrade metodo.

Nell'ambito dell'apertura del database, SQLiteOpenHelper (e quindi una sua sottoclasse) confronta la user_version memorizzata nel database con il numero di versione fornito (4° parametro alla super chiamata SQLiteOpenHelper) e se quest'ultimo è maggiore del valore memorizzato nella database, quindi viene chiamato il metodo onUpgrade. (se è il contrario, allora onDowngrade verrà chiamato e senza che venga codificato si verifica un'eccezione).

La user_version può essere impostata nel tool di gestione SQLite user the SQL PRAGMA user_version = n .

Un altro problema è che da Android 9, il database viene aperto in modalità WAL (Write-Ahead Logging) per impostazione predefinita. Il codice sopra utilizzando this.getReadableDatabase(); risulta nella creazione dei file -shm e -wal. La loro esistenza si traduce in un errore intrappolato (poiché non corrispondono al database copiato) che quindi provoca la creazione di un database vuoto (teoricamente utilizzabile) da parte di SQLiteOpenHelper, che sostanzialmente cancella il database copiato (credo che questo sia ciò che accade ).

Il motivo per cui this.getReadableDatabase(); è stato utilizzato è per aggirare il problema che quando non ci sono dati dell'app, i database la cartella/directory non esiste e l'utilizzo di quanto sopra la crea. Il modo corretto è creare la directory/cartella del database se non esiste. Pertanto i file -wal e -shm non vengono creati.

Quello che segue è un esempio di DatabseHelper che risolve i problemi e consente inoltre di copiare versioni modificate del database preesistente in base alla modifica di user_version.

public class DBHelperV001 extends SQLiteOpenHelper {

    public static final String DBNAME = "test.db"; //<<<<<<<<<< obviously change accordingly

    //
    private static int db_user_version, asset_user_version, user_version_offset = 60, user_version_length = 4;
    private static String stck_trc_msg = " (see stack-trace above)";
    private static String sqlite_ext_journal = "-journal";
    private static String sqlite_ext_shm = "-shm";
    private static String sqlite_ext_wal = "-wal";
    private static int copy_buffer_size = 1024 * 8; //Copy data in 8k chucks, change if wanted.

    SQLiteDatabase mDB;

    /**
     *  Instantiate the DBHelper, copying the databse from the asset folder if no DB exists
     *  or if the user_version is greater than the user_version of the current database.
     *  NOTE The pre-existing database copied into the assets folder MUST have the user version set
     *  to 1 or greater. If the user_version in the assets folder is increased above the
     *
     * @param context
     */
    public DBHelperV001(Context context) {

        // Note get the version according to the asset file
        // avoid having to maintain the version number passed
        super(context, DBNAME, null, setUserVersionFromAsset(context,DBNAME));
        if (!ifDbExists(context,DBNAME)) {
            copyDBFromAssets(context, DBNAME,DBNAME);
        } else {
            setUserVersionFromAsset(context,DBNAME);
            setUserVersionFromDB(context,DBNAME);
            if (asset_user_version > db_user_version) {
                copyDBFromAssets(context,DBNAME,DBNAME);
            }
        }
        // Force open (and hence copy attempt) when constructing helper
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    /**
     * Check to see if the databse file exists
     * @param context   The Context
     * @param dbname    The databse name
     * @return          true id database file exists, else false
     */
    private static boolean ifDbExists(Context context, String dbname) {
        File db = context.getDatabasePath(dbname);
        if (db.exists()) return true;
        if (!db.getParentFile().exists()) {
            db.getParentFile().mkdirs();
        }
        return false;
    }

    /**
     * set the db_user_version according to the user_version obtained from the current database file
     * @param context   The Context
     * @param dbname    The database (file) name
     * @return          The user_version
     */
    private static int setUserVersionFromDB(Context context, String dbname) {
        File db = context.getDatabasePath(dbname);
        InputStream is;
        try {
            is = new FileInputStream(db);
        } catch (IOException e) {
            throw new RuntimeException("IOError Opening " + db.getPath() + " as an InputStream" + stck_trc_msg);
        }
        db_user_version = getUserVersion(is);
        Log.d("DATABASEUSERVERSION","Obtained user_version from current DB, it is " + String.valueOf(db_user_version)); //TODO remove for live App
        return db_user_version;
    }

    /**
     * set the asset_user_version according to the user_version from the asset file
     * @param context
     * @param assetname
     * @return
     */
    private static int setUserVersionFromAsset(Context context, String assetname) {
        InputStream is;
        try {
            is = context.getAssets().open(assetname);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("IOError Getting asset " + assetname + " as an InputStream" + stck_trc_msg);
        }
        asset_user_version = getUserVersion(is);
        Log.d("ASSETUSERVERSION","Obtained user_version from asset, it is " + String.valueOf(asset_user_version)); //TODO remove for Live App
        return asset_user_version;
    }

    /**
     * Retrieve SQLite user_version from the provied InputStream
     * @param is    The InputStream
     * @return      the user_version
     */
    private static int getUserVersion(InputStream is) {
        String ioerrmsg = "Reading DB header bytes(60-63) ";
        int rv;
        byte[] buffer = new byte[user_version_length];
        byte[] header = new byte[64];
        try {
            is.skip(user_version_offset);
            is.read(buffer,0,user_version_length);
            ByteBuffer bb = ByteBuffer.wrap(buffer);
            rv = ByteBuffer.wrap(buffer).getInt();
            ioerrmsg = "Closing DB ";
            is.close();
            return rv;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("IOError " + ioerrmsg + stck_trc_msg);
        }
    }

    /**
     * Copy the database file from the assets 
     * Note backup of existing files may not be required
     * @param context   The Context
     * @param dbname    The database (file)name
     * @param assetname The asset name (may therefore be different but )
     */
    private static void copyDBFromAssets(Context context, String dbname, String assetname) {
        String tag = "COPYDBFROMASSETS";
        Log.d(tag,"Copying Database from assets folder");
        String backup_base = "bkp_" + String.valueOf(System.currentTimeMillis());
        String ioerrmsg = "Opening Asset " + assetname;

        // Prepare Files that could be used
        File db = context.getDatabasePath(dbname);
        File dbjrn = new File(db.getPath() + sqlite_ext_journal);
        File dbwal = new File(db.getPath() + sqlite_ext_wal);
        File dbshm = new File(db.getPath() + sqlite_ext_shm);
        File dbbkp = new File(db.getPath() + backup_base);
        File dbjrnbkp = new File(db.getPath() + backup_base);
        File dbwalbkp = new File(db.getPath() + backup_base);
        File dbshmbkp = new File(db.getPath() + backup_base);
        byte[] buffer = new byte[copy_buffer_size];
        int bytes_read = 0;
        int total_bytes_read = 0;
        int total_bytes_written = 0;

        // Backup existing sqlite files
        if (db.exists()) {
            db.renameTo(dbbkp);
            dbjrn.renameTo(dbjrnbkp);
            dbwal.renameTo(dbwalbkp);
            dbshm.renameTo(dbshmbkp);
        }
        // ALWAYS delete the additional sqlite log files
        dbjrn.delete();
        dbwal.delete();
        dbshm.delete();

        //Attempt the copy
        try {
            ioerrmsg = "Open InputStream for Asset " + assetname;
            InputStream is = context.getAssets().open(assetname);
            ioerrmsg = "Open OutputStream for Databse " + db.getPath();
            OutputStream os = new FileOutputStream(db);
            ioerrmsg = "Read/Write Data";
             while((bytes_read = is.read(buffer)) > 0) {
                 total_bytes_read = total_bytes_read + bytes_read;
                 os.write(buffer,0,bytes_read);
                 total_bytes_written = total_bytes_written + bytes_read;
             }
             ioerrmsg = "Flush Written data";
             os.flush();
             ioerrmsg = "Close DB OutputStream";
             os.close();
             ioerrmsg = "Close Asset InputStream";
             is.close();
             Log.d(tag,"Databsse copied from the assets folder. " + String.valueOf(total_bytes_written) + " bytes were copied.");
             // Delete the backups
             dbbkp.delete();
             dbjrnbkp.delete();
             dbwalbkp.delete();
             dbshmbkp.delete();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("IOError attempting to " + ioerrmsg + stck_trc_msg);
        }
    }
}

Esempio di utilizzo

Considera i seguenti file di asset (database sqlite) (avviso in quanto l'app fallirebbe ) :-

Quindi ci sono due database (barra identica la versione_utente impostata utilizzando PRAGMA user_version = 1 e PRAGMA user_version = 2 rispettivamente/in base ai nomi dei file) Per la nuovissima app, esegui per la prima volta l'app (cioè disinstallata), quindi file test.dbV1 viene rinominato in test.db e viene utilizzata la seguente attività :-

public class MainActivity extends AppCompatActivity {

    DBHelperV001 mDbhlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDbhlpr = new DBHelperV001(this);
        DatabaseUtils.dumpCursor(
                mDbhlpr.getWritableDatabase().query(
                        "sqlite_master",
                        null,null,null,null,null,null
                )
        );
    }
}
  • Questo crea semplicemente un'istanza di Database Helper (che copierà o utilizzerà il database) e quindi esegue il dump della tabella sqlite_master.

Il registro contiene :-

04-02 12:55:36.258 644-644/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 1
04-02 12:55:36.258 644-644/aaa.so55441840 D/COPYDBFROMASSETS: Copying Database from assets folder
04-02 12:55:36.262 644-644/aaa.so55441840 D/COPYDBFROMASSETS: Databsse copied from the assets folder. 69632 bytes were copied.
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: >>>>> Dumping cursor [email protected]
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out: 0 {
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out:    type=table
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out:    name=android_metadata
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out:    tbl_name=android_metadata
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out:    rootpage=3
04-02 12:55:36.265 644-644/aaa.so55441840 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: }
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out: 1 {
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out:    type=table
04-02 12:55:36.266 644-644/aaa.so55441840 I/System.out:    name=shops
..........

Quando viene introdotta la nuova versione del DB, che ha una versione_utente di 2

  • cioè test.db che era test.dbV1 viene rinominato in test.dbV1 E poi,
    • (cancellandolo di fatto)
  • test.dbV2 viene quindi rinominato test.db
    • (introducendo di fatto il nuovo file di asset) quindi :-

E l'app viene quindi rieseguita, quindi il registro contiene:-

04-02 13:04:25.044 758-758/? D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:04:25.046 758-758/? D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:04:25.046 758-758/? D/DATABASEUSERVERSION: Obtained user_version from current DB, it is 1
04-02 13:04:25.047 758-758/? D/COPYDBFROMASSETS: Copying Database from assets folder
04-02 13:04:25.048 758-758/? D/COPYDBFROMASSETS: Databsse copied from the assets folder. 69632 bytes were copied.
04-02 13:04:25.051 758-758/? I/System.out: >>>>> Dumping cursor [email protected]
04-02 13:04:25.052 758-758/? I/System.out: 0 {
04-02 13:04:25.052 758-758/? I/System.out:    type=table
04-02 13:04:25.052 758-758/? I/System.out:    name=android_metadata
04-02 13:04:25.052 758-758/? I/System.out:    tbl_name=android_metadata
04-02 13:04:25.052 758-758/? I/System.out:    rootpage=3
04-02 13:04:25.052 758-758/? I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
04-02 13:04:25.052 758-758/? I/System.out: }
04-02 13:04:25.052 758-758/? I/System.out: 1 {
04-02 13:04:25.052 758-758/? I/System.out:    type=table
04-02 13:04:25.052 758-758/? I/System.out:    name=shops

Infine, con un'esecuzione successiva, ovvero nessun asset aggiornato, il registro mostra :-

04-02 13:05:50.197 840-840/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:05:50.198 840-840/aaa.so55441840 D/ASSETUSERVERSION: Obtained user_version from asset, it is 2
04-02 13:05:50.198 840-840/aaa.so55441840 D/DATABASEUSERVERSION: Obtained user_version from current DB, it is 2
04-02 13:05:50.201 840-840/aaa.so55441840 I/System.out: >>>>> Dumping cursor [email protected]
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: 0 {
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    type=table
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    name=android_metadata
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    tbl_name=android_metadata
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    rootpage=3
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: }
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out: 1 {
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    type=table
04-02 13:05:50.202 840-840/aaa.so55441840 I/System.out:    name=shops

ovvero nessuna copia eseguita in quanto la risorsa è effettivamente la stessa