數據庫升級筆記

http://jinnianshilongnian.iteye.com/blog/2022468 ? Realm數據庫系列教程

http://www.easydone.cn/2015/11/13數據庫greendao升級筆記

packagexcxin.filexpert.orm.dao.base;

importandroid.content.ContentValues;

importandroid.content.Context;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.provider.MediaStore;

importandroid.text.TextUtils;

importandroid.util.Log;

importjava.io.File;

importjava.util.ArrayList;

importjava.util.Arrays;

importjava.util.List;

importde.greenrobot.dao.AbstractDao;

importde.greenrobot.dao.internal.DaoConfig;

importde.greenrobot.dao.query.QueryBuilder;

importxcxin.filexpert.assistant.constant.DataConstant;

importxcxin.filexpert.assistant.constant.SettingConstant;

importxcxin.filexpert.assistant.utils.FileUtils;

importxcxin.filexpert.assistant.utils.PreferenceUtils;

importxcxin.filexpert.assistant.utils.TimeUtils;

importxcxin.filexpert.assistant.utils.TmpFolderUtils;

importxcxin.filexpert.model.implement.local.tool.recyclebin.RecycleUtils;

importxcxin.filexpert.orm.helper.implement.SafeBoxHelper;

/**

* Created by liucheng on 2015/10/16

*/

public classDBCore {

private static finalStringDEFAULT_DB_NAME="FileExpert.db";

private staticDaoMasterdaoMaster;

private staticDaoSessiondaoSession;

private staticContextmContext;

private staticStringDB_NAME;

//Befor Table Columns

public final staticStringDATA= MediaStore.Files.FileColumns.DATA;

public final staticStringTITLE= MediaStore.Files.FileColumns.TITLE;

public final staticStringSIZE= MediaStore.Files.FileColumns.SIZE;

//Befor Tables

public static finalStringSEARCH_HISTORY="search_history";

public static finalStringROOT_FILE="root_file";

public static finalStringTABLE_MUSIC_PLAY="music_play";

public static finalStringNAVIGATION="navigation";

public static finalStringSETTING="setting";

public static finalStringAPPS="apps";

public static finalStringAPKS="apks";

public static finalStringGCLOUD_ACCOUNT="gcloud_account";

public static finalStringGCLOUD_FILE="gcloud_file";

public static finalStringWIFI_DEVICE="wifi_device";

public static finalStringTASK_DOWNLOAD="task_download";

public static finalStringTHREAD_DOWNLOAD="thread_download";

public static finalStringSTATISTICS="statistics";

public static finalStringSPLASH="splash";

public static finalStringSYNC_SETTING="sync_setting";

public static finalStringFILEANALYSIS="file_analysis";

public static finalStringRECOMMEND="recommend";

public static finalStringMAIN_CUSTOMER="main_customer";

public static finalStringFAVORITE="favorite";

public static finalStringLABELFIlE="label_file";

public static finalStringLABEL="label";

public static finalStringRecycle_BIN="recycle";

public static finalStringSYNC_DATA="sync_data";

public static finalStringSYNC_HISTORY="sync_history";

public static finalStringSEARCH_FILE="search";

public static finalStringTABLE_SETTING="setting";

public static finalStringLOCAL_FILE="local_file";

public static voidinitDB(Context context) {

init(context,DEFAULT_DB_NAME);

}

public static voidinit(Context context,String dbName) {

if(context ==null) {

throw newIllegalArgumentException("context can't be null");

}

enableQueryBuilderLog();

mContext= context.getApplicationContext();

DB_NAME= dbName;

}

public staticDaoMastergetDaoMaster() {

if(daoMaster==null) {

DaoMaster.OpenHelper helper =newFeOpenHelper(mContext,DB_NAME, null);

daoMaster=newDaoMaster(helper.getWritableDatabase());

}

returndaoMaster;

}

public staticDaoSessiongetDaoSession() {

if(daoSession==null) {

if(daoMaster==null) {

daoMaster=getDaoMaster();

}

daoSession=daoMaster.newSession();

}

returndaoSession;

}

public static voidenableQueryBuilderLog() {

QueryBuilder.LOG_SQL=false;

QueryBuilder.LOG_VALUES=false;

}

private static classFeOpenHelperextendsDaoMaster.OpenHelper {

publicFeOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory) {

super(context,name,factory);

}

@Override

public voidonUpgrade(SQLiteDatabase db, intoldVersion, intnewVersion) {

Log.e("nizi","==== oldVersion ?"+ oldVersion +"newVersion "+ newVersion);

try{

if(oldVersion <=10) {

dropAllTable(db);

}

if(oldVersion >=11&& oldVersion <=17) {

//delete unavailable table

dropV7UnavailableTable(db);

//table:Label

upgradeLableTable(db);

//table:labelFile

upgradeLableFileTable(db);

//table:favorate

restoreFavorateToLableFile(db);

RecycleUtils.updateRecycleData(db);

}

}catch(Exception e) {

e.printStackTrace();

}finally{

//version 17 need's newTables

DaoMaster.createAllTables(db, true);

}

if(PreferenceUtils.getPrefBoolean(SettingConstant.FIRST_USE_SAFEBOX,SettingConstant.FIRST_USE_SAFEBOX_DEFAULT_VALUE)) {

SafeBoxHelper.getHelper();

}

}

}

private staticArrayListneedDropBasicTables() {

ArrayList tableList =newArrayList<>();

tableList.add(APKS);

tableList.add(APPS);

tableList.add(FILEANALYSIS);

tableList.add(GCLOUD_ACCOUNT);

tableList.add(GCLOUD_FILE);

tableList.add(TABLE_MUSIC_PLAY);

tableList.add(MAIN_CUSTOMER);

tableList.add(NAVIGATION);

tableList.add(RECOMMEND);

tableList.add(ROOT_FILE);

tableList.add(SEARCH_HISTORY);

tableList.add(SETTING);

tableList.add(SPLASH);

tableList.add(STATISTICS);

tableList.add(SYNC_SETTING);

tableList.add(TASK_DOWNLOAD);

tableList.add(THREAD_DOWNLOAD);

tableList.add(WIFI_DEVICE);

returntableList;

}

private static voiddropV7UnavailableTable(SQLiteDatabase db) {

ArrayList tableList =needDropBasicTables();

for(inti =0,z = tableList.size();i < z;i++) {

String tableName = tableList.get(i);

db.execSQL("DROP TABLE IF EXISTS "+ tableName);

Log.e("nizi","dropV7UnavailableTable "+ tableName +" success");

}

}

private static voiddropAllTable(SQLiteDatabase db) {

ArrayList tableList =needDropBasicTables();

tableList.add(WIFI_DEVICE);

tableList.add(LABELFIlE);

tableList.add(LABEL);

tableList.add(Recycle_BIN);

tableList.add(SYNC_DATA);

tableList.add(SYNC_HISTORY);

tableList.add(SEARCH_FILE);

tableList.add(TABLE_SETTING);

tableList.add(LOCAL_FILE);

for(inti =0,z = tableList.size();i < z;i++) {

String tableName = tableList.get(i);

db.execSQL("DROP TABLE IF EXISTS "+ tableName);

Log.e("nizi","dropAllTable "+ tableName +" success");

}

}

private static voidupgradeLableTable(SQLiteDatabase db) {

try{

db.beginTransaction();

String tempTableName = LabelDao.TABLENAME+"_temp";

String sqlAlter ="ALTER TABLE "+ LabelDao.TABLENAME+" RENAME TO "+ tempTableName;

db.execSQL(sqlAlter);

// 2,創建新表.

LabelDao.createTable(db, true);

// 3,遷移數據

String sql ="INSERT INTO "+ LabelDao.TABLENAME

+" SELECT * ?FROM "+ tempTableName;

db.execSQL(sql);

// 4,刪除舊表

sql ="DROP TABLE IF EXISTS "+ tempTableName;

db.execSQL(sql);

db.setTransactionSuccessful();

Log.d("nizi","upgradeLableTable success------");

}catch(Exception e) {

e.printStackTrace();

}finally{

db.endTransaction();

}

}

private static voidupgradeLableFileTable(SQLiteDatabase db) {

try{

db.beginTransaction();

String tempTableName = LabelFileDao.TABLENAME+"_temp";

String sqlAlter ="ALTER TABLE "+ LabelFileDao.TABLENAME+" RENAME TO "+ tempTableName;

db.execSQL(sqlAlter);

// 2,創建新表.

LabelFileDao.createTable(db, true);

// 3,遷移數據

String sql ="INSERT INTO "+ LabelFileDao.TABLENAME

+"("+ LabelFileDao.Properties.Name.columnName+","

+ LabelFileDao.Properties.Path.columnName+","

+ LabelFileDao.Properties.Size.columnName+","

+ LabelFileDao.Properties.Date_modified.columnName+","

+ LabelFileDao.Properties.LabelId.columnName+","

+ LabelFileDao.Properties.Mime_type.columnName+","

+ LabelFileDao.Properties.Is_file.columnName+")"

+" SELECT "+TITLE+","+DATA+","+SIZE+","

+ LabelFileDao.Properties.Date_modified.name+","

+ LabelFileDao.Properties.LabelId.name+","

+ LabelFileDao.Properties.Mime_type.name+","

+ LabelFileDao.Properties.Is_file.name+

" FROM "+ tempTableName;

db.execSQL(sql);

// 4,刪除舊表

sql ="DROP TABLE IF EXISTS "+ tempTableName;

db.execSQL(sql);

db.setTransactionSuccessful();

Log.d("nizi","upgradeLableFile Table success------");

}catch(Exception e) {

e.printStackTrace();

}finally{

db.endTransaction();

}

}

private static voidrestoreFavorateToLableFile(SQLiteDatabase db) {

List files =newArrayList<>();

Cursor beforFiles = db.query(FAVORITE, newString[]{MediaStore.Files.FileColumns.DATA}, null, null, null, null, null);

if(beforFiles !=null&& beforFiles.getCount() >0) {

while(beforFiles.moveToNext()) {

String data = beforFiles.getString(0);

if(data !=null) {

files.add(newFile(data));

}

}

beforFiles.close();

booleanresult =false;

try{

ContentValues cv =newContentValues();

cv.put(LabelDao.Properties.LabelType.columnName,DataConstant.LABEL_DEFAUL_FAV_NAME);

cv.put(LabelDao.Properties.LabelColor.columnName,DataConstant.LABEL_DEFAUL_FAV_COLOR);

cv.put(LabelDao.Properties.Date_modified.columnName,TimeUtils.getCurrentTime());

if(db.insert(LabelDao.TABLENAME, null,cv) != -1) {

Log.d("nizi"," insert ?"+ LabelDao.TABLENAME+" SUCCESS ");

result =true;

}else{

Log.d("nizi"," insert ?"+ LabelDao.TABLENAME+" fail ");

}

}catch(Exception e) {

e.printStackTrace();

}finally{

if(result) {

String selectSql ="select * from "+ LabelDao.TABLENAME+" where "+ LabelDao.Properties.LabelType.columnName+" = '"

+ DataConstant.LABEL_DEFAUL_FAV_NAME+"' and "+ LabelDao.Properties.LabelColor.columnName+" = "+ DataConstant.LABEL_DEFAUL_FAV_COLOR;

Cursor cur = db.rawQuery(selectSql, null);

if(cur !=null&& cur.getCount() ==1) {

cur.moveToFirst();

intlableId = cur.getInt(cur.getColumnIndex(LabelDao.Properties.Id.columnName));

Log.d("nizi"," select ? "+ LabelDao.TABLENAME+" curId ?"+ lableId);

cur.close();

try{

if(files.size() >0) {

db.beginTransaction();

for(File file : files) {

ContentValues cv =newContentValues();

cv.put(LabelFileDao.Properties.LabelId.columnName,lableId);

cv.put(LabelFileDao.Properties.Path.columnName,file.getPath());

cv.put(LabelFileDao.Properties.Name.columnName,file.getName());

cv.put(LabelFileDao.Properties.Size.columnName,file.length());

cv.put(LabelFileDao.Properties.Date_modified.columnName,file.lastModified());

cv.put(LabelFileDao.Properties.Is_file.columnName,!file.isDirectory());

cv.put(LabelFileDao.Properties.Mime_type.columnName,FileUtils.getMiMeType(file.getName()));

db.insert(LabelFileDao.TABLENAME, null,cv);

}

db.execSQL("DROP TABLE IF EXISTS "+FAVORITE);

Log.d("nizi"," generate favorate data ok ?");

db.setTransactionSuccessful();

}

}catch(Exception e) {

e.printStackTrace();

}finally{

db.endTransaction();

}

}else{

Log.d("nizi"," select ? "+ LabelDao.TABLENAME+" curId ?null");

}

}

}

}else{

db.execSQL("DROP TABLE IF EXISTS "+FAVORITE);

Log.d("nizi"," DROP TABLE IF EXISTS FAVORITE OK ");

return;

}

}

private staticStringgetTypeByClass(Class type) {

if(type.equals(String.class)) {

return"TEXT";

}

if(type.equals(Long.class) || type.equals(Integer.class) || type.equals(long.class)) {

return"INTEGER";

}

if(type.equals(Boolean.class)) {

return"BOOLEAN";

}

return null;

}

private staticListgetColumns(SQLiteDatabase db,String tableName) {

List columns =newArrayList<>();

Cursor cursor =null;

try{

cursor = db.rawQuery("SELECT * FROM "+ tableName +" limit 1", null);

if(cursor !=null) {

columns =newArrayList<>(Arrays.asList(cursor.getColumnNames()));

}

}catch(Exception e) {

Log.v(tableName,e.getMessage(),e);

e.printStackTrace();

}finally{

if(cursor !=null)

cursor.close();

}

returncolumns;

}

private static booleantableIsExist(SQLiteDatabase db,String tableName) {

booleanresult =false;

if(tableName ==null) {

return false;

}

Cursor cursor =null;

try{

String sql ="SELECT COUNT(*) FROM sqlite_master where type ='table' and name ='"+ tableName.trim() +"' ";

cursor = db.rawQuery(sql, null);

if(cursor.moveToNext()) {

intcount = cursor.getInt(0);

if(count >0) {

result =true;

}

}

}catch(Exception e) {

e.printStackTrace();

}finally{

if(cursor !=null) {

cursor.close();

}

}

returnresult;

}

private static voidgenerateTempTables(SQLiteDatabase db,Class>... daoClasses) {

for(Class> daoClass : daoClasses) {

DaoConfig daoConfig =newDaoConfig(db,daoClass);

String divider ="";

String tableName = daoConfig.tablename;

String tempTableName = daoConfig.tablename.concat("_TEMP");

ArrayList properties =newArrayList<>();

StringBuilder createTableStringBuilder =newStringBuilder();

createTableStringBuilder.append("CREATE TABLE ").append(tempTableName).append(" (");

for(intj =0;j < daoConfig.properties.length;j++) {

String columnName = daoConfig.properties[j].columnName;

if(getColumns(db,tableName).contains(columnName)) {

properties.add(columnName);

String type =null;

try{

type =getTypeByClass(daoConfig.properties[j].type);

}catch(Exception exception) {

exception.printStackTrace();

}

createTableStringBuilder.append(divider).append(columnName).append(" ").append(type);

if(daoConfig.properties[j].primaryKey) {

createTableStringBuilder.append(" PRIMARY KEY");

}

divider =",";

}

}

createTableStringBuilder.append(");");

db.execSQL(createTableStringBuilder.toString());

StringBuilder insertTableStringBuilder =newStringBuilder();

insertTableStringBuilder.append("INSERT INTO ").append(tempTableName).append(" (");

insertTableStringBuilder.append(TextUtils.join(",",properties));

insertTableStringBuilder.append(") SELECT ");

insertTableStringBuilder.append(TextUtils.join(",",properties));

insertTableStringBuilder.append(" FROM ").append(tableName).append(";");

db.execSQL(insertTableStringBuilder.toString());

}

}

private static voidrestoreData(SQLiteDatabase db,Class>... daoClasses) {

for(Class> daoClass : daoClasses) {

DaoConfig daoConfig =newDaoConfig(db,daoClass);

String tableName = daoConfig.tablename;

String tempTableName = daoConfig.tablename.concat("_TEMP");

ArrayList properties =newArrayList<>();

for(intj =0;j < daoConfig.properties.length;j++) {

String columnName = daoConfig.properties[j].columnName;

if(getColumns(db,tempTableName).contains(columnName)) {

properties.add(columnName);

}

}

StringBuilder insertTableStringBuilder =newStringBuilder();

insertTableStringBuilder.append("INSERT INTO ").append(tableName).append(" (");

insertTableStringBuilder.append(TextUtils.join(",",properties));

insertTableStringBuilder.append(") SELECT ");

insertTableStringBuilder.append(TextUtils.join(",",properties));

insertTableStringBuilder.append(" FROM ").append(tempTableName).append(";");

StringBuilder dropTableStringBuilder =newStringBuilder();

dropTableStringBuilder.append("DROP TABLE ").append(tempTableName);

db.execSQL(insertTableStringBuilder.toString());

db.execSQL(dropTableStringBuilder.toString());

}

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,238評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,430評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,134評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,893評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,653評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,136評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,212評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,372評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,888評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,738評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,482評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,179評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,588評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,829評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,610評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,916評論 2 372

推薦閱讀更多精彩內容