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