rename openzaly to windchat

This commit is contained in:
an.guoyue 2019-12-31 17:22:19 +08:00
parent d98575d0d2
commit 116a18b97a
9 changed files with 451 additions and 450 deletions

View File

@ -1,12 +1,12 @@
/**
* Copyright 2018-2028 Akaxin Group
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@ -48,96 +48,96 @@ import com.windchat.im.storage.util.MigrateUtils;
* @since 2018-01-31 12:15:15
*/
public class DataSourceManager {
private static final Logger logger = LoggerFactory.getLogger(DataSourceManager.class);
private static final Logger logger = LoggerFactory.getLogger(DataSourceManager.class);
private static final String OPENZALY_DATABASE_CONFIG = "openzaly-server.config";
private static final String WINDCHAT_DATABASE_CONFIG = "windchat-server.config";
private DataSourceManager() {
}
private DataSourceManager() {
}
// server启动初始化数据库
public static void init(DBConfig config)
throws InitDatabaseException, UpgradeDatabaseException, NeedInitMysqlException {
try {
DBType dbType = DBType.PERSONAL;
Properties pro = loadDatabaseConfig(OPENZALY_DATABASE_CONFIG);
if (pro != null && pro.size() > 0) {
// get edition from config file
String edition = MysqlManager.trimToNull(pro, JdbcConst.OPENZALY_EDITION);
if (StringUtils.isNotEmpty(edition)) {
dbType = DBType.getDBType(edition);
}
}
config.setDb(dbType);
logger.info("load database config finish databaseType:{}", dbType);
// server启动初始化数据库
public static void init(DBConfig config)
throws InitDatabaseException, UpgradeDatabaseException, NeedInitMysqlException {
try {
DBType dbType = DBType.PERSONAL;
Properties pro = loadDatabaseConfig(WINDCHAT_DATABASE_CONFIG);
if (pro != null && pro.size() > 0) {
// get edition from config file
String edition = MysqlManager.trimToNull(pro, JdbcConst.WINDCHAT_EDITION);
if (StringUtils.isNotEmpty(edition)) {
dbType = DBType.getDBType(edition);
}
}
config.setDb(dbType);
logger.info("load database config finish databaseType:{}", dbType);
switch (dbType) {
case PERSONAL:
System.setProperty("database", dbType.getName());
SQLiteJDBCManager.initSqliteDB(config);
PrepareSiteConfigData.init(config);// 初始化数据库中初始数据
break;
case TEAM:
System.setProperty("database", dbType.getName());
MysqlManager.initMysqlDB(pro); // 初始化数据库以及数据库连接
PrepareSiteConfigData.init(config);// 初始化数据库中初始数据
break;
}
} catch (SQLException e) {
throw new InitDatabaseException("init database error", e);
}
}
switch (dbType) {
case PERSONAL:
System.setProperty("database", dbType.getName());
SQLiteJDBCManager.initSqliteDB(config);
PrepareSiteConfigData.init(config);// 初始化数据库中初始数据
break;
case TEAM:
System.setProperty("database", dbType.getName());
MysqlManager.initMysqlDB(pro); // 初始化数据库以及数据库连接
PrepareSiteConfigData.init(config);// 初始化数据库中初始数据
break;
}
} catch (SQLException e) {
throw new InitDatabaseException("init database error", e);
}
}
// 初始化生成mysql的配置文件
public static void initMysqlConfig() throws FileNotFoundException, IOException {
// 生成配置文件
File configFile = new File(OPENZALY_DATABASE_CONFIG);
if (!configFile.exists()) {
FileUtils.writeResourceToFile("/" + OPENZALY_DATABASE_CONFIG, configFile);
}
}
// 初始化生成mysql的配置文件
public static void initMysqlConfig() throws FileNotFoundException, IOException {
// 生成配置文件
File configFile = new File(WINDCHAT_DATABASE_CONFIG);
if (!configFile.exists()) {
FileUtils.writeResourceToFile("/" + WINDCHAT_DATABASE_CONFIG, configFile);
}
}
// 手动升级数据库
public static int upgradeDB(DBConfig config) throws UpgradeDatabaseException {
try {
switch (config.getDb()) {
case PERSONAL:
return SQLiteUpgrade.doUpgrade(config, true);
case TEAM:
throw new UpgradeDatabaseException("database upgrade can't support mysql");
}
} catch (SQLException e) {
throw new UpgradeDatabaseException("upgrade database error", e);
}
return 0;
}
// 手动升级数据库
public static int upgradeDB(DBConfig config) throws UpgradeDatabaseException {
try {
switch (config.getDb()) {
case PERSONAL:
return SQLiteUpgrade.doUpgrade(config, true);
case TEAM:
throw new UpgradeDatabaseException("database upgrade can't support mysql");
}
} catch (SQLException e) {
throw new UpgradeDatabaseException("upgrade database error", e);
}
return 0;
}
// 迁移数据库把sqlite迁移至mysql数据库
public static void migrateDB() throws MigrateDatabaseException, NeedInitMysqlException {
// 加载配置文件中的数据库配置
Properties prop = loadDatabaseConfig(OPENZALY_DATABASE_CONFIG);
MigrateUtils.sqlite2Mysql(prop);
}
// 迁移数据库把sqlite迁移至mysql数据库
public static void migrateDB() throws MigrateDatabaseException, NeedInitMysqlException {
// 加载配置文件中的数据库配置
Properties prop = loadDatabaseConfig(WINDCHAT_DATABASE_CONFIG);
MigrateUtils.sqlite2Mysql(prop);
}
public static Properties loadDatabaseConfig(String configPath) {
Properties properties = null;
InputStream inputStream = null;
try {
properties = new Properties();
inputStream = new FileInputStream(configPath);
properties.load(inputStream);
} catch (Exception e) {
logger.error("load database config fail,openzaly will use sqlite database,cause={}", e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("close db config inputstream error", e);
}
}
return properties;
}
public static Properties loadDatabaseConfig(String configPath) {
Properties properties = null;
InputStream inputStream = null;
try {
properties = new Properties();
inputStream = new FileInputStream(configPath);
properties.load(inputStream);
} catch (Exception e) {
logger.error("load database config fail,WindChat will use sqlite database,cause={}", e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error("close db config inputstream error", e);
}
}
return properties;
}
}

View File

@ -8,39 +8,39 @@ package com.windchat.im.storage.dao.config;
*/
public interface JdbcConst {
String OPENZALY_EDITION = "openzaly.edition";
String WINDCHAT_EDITION = "windchat.edition";
String SQLITE_URL = "openzaly.sqlite.url";
String SQLITE_URL = "windchat.sqlite.url";
// ----------------------MASTER--------------------
String MYSQL_HOST = "openzaly.mysql.host";
String MYSQL_PORT = "openzaly.mysql.port";
String MYSQL_DB = "openzaly.mysql.database";
String MYSQL_HOST = "windchat.mysql.host";
String MYSQL_PORT = "windchat.mysql.port";
String MYSQL_DB = "windchat.mysql.database";
String MYSQL_USER_NAME = "openzaly.mysql.username";
String MYSQL_PASSWORD = "openzaly.mysql.password";
String MYSQL_INITIAL_SIZE = "openzaly.mysql.initial-size";
String MYSQL_MAX_SIZE = "openzaly.mysql.max-size";
String MYSQL_MAX_IDLE = "openzaly.mysql.max-idle";
String MYSQL_USER_NAME = "windchat.mysql.username";
String MYSQL_PASSWORD = "windchat.mysql.password";
String MYSQL_INITIAL_SIZE = "windchat.mysql.initial-size";
String MYSQL_MAX_SIZE = "windchat.mysql.max-size";
String MYSQL_MAX_IDLE = "windchat.mysql.max-idle";
String MYSQL_USE_UNICODE = "openzaly.mysql.useUnicode";
String MYSQL_CHARACTER_ENCODING = "openzaly.mysql.characterEncoding";
String MYSQL_VERIFY_SERVER_CERTIFICATE = "openzaly.mysql.verifyServerCertificate";
String MYSQL_USE_SSL = "openzaly.mysql.useSSL";
String MYSQL_USE_UNICODE = "windchat.mysql.useUnicode";
String MYSQL_CHARACTER_ENCODING = "windchat.mysql.characterEncoding";
String MYSQL_VERIFY_SERVER_CERTIFICATE = "windchat.mysql.verifyServerCertificate";
String MYSQL_USE_SSL = "windchat.mysql.useSSL";
// ----------------------SLAVE--------------------
String MYSQL_SLAVE_HOST = "openzaly.mysql.slave.host";
String MYSQL_SLAVE_PORT = "openzaly.mysql.slave.port";
String MYSQL_SLAVE_DB = "openzaly.mysql.slave.database";
String MYSQL_SLAVE_HOST = "windchat.mysql.slave.host";
String MYSQL_SLAVE_PORT = "windchat.mysql.slave.port";
String MYSQL_SLAVE_DB = "windchat.mysql.slave.database";
String MYSQL_SLAVE_USER_NAME = "openzaly.mysql.slave.username";
String MYSQL_SLAVE_PASSWORD = "openzaly.mysql.slave.password";
String MYSQL_SLAVE_INITIAL_SIZE = "openzaly.mysql.slave.initial-size";
String MYSQL_SLAVE_MAX_SIZE = "openzaly.mysql.slave.max-size";
String MYSQL_SLAVE_MAX_IDLE = "openzaly.mysql.slave.max-idle";
String MYSQL_SLAVE_USER_NAME = "windchat.mysql.slave.username";
String MYSQL_SLAVE_PASSWORD = "windchat.mysql.slave.password";
String MYSQL_SLAVE_INITIAL_SIZE = "windchat.mysql.slave.initial-size";
String MYSQL_SLAVE_MAX_SIZE = "windchat.mysql.slave.max-size";
String MYSQL_SLAVE_MAX_IDLE = "windchat.mysql.slave.max-idle";
String MYSQL_SLAVE_USE_UNICODE = "openzaly.mysql.slave.useUnicode";
String MYSQL_SLAVE_CHARACTER_ENCODING = "openzaly.mysql.slave.characterEncoding";
String MYSQL_SLAVE_VERIFY_SERVER_CERTIFICATE = "openzaly.mysql.slave.verifyServerCertificate";
String MYSQL_SLAVE_USE_SSL = "openzaly.mysql.slave.useSSL";
String MYSQL_SLAVE_USE_UNICODE = "windchat.mysql.slave.useUnicode";
String MYSQL_SLAVE_CHARACTER_ENCODING = "windchat.mysql.slave.characterEncoding";
String MYSQL_SLAVE_VERIFY_SERVER_CERTIFICATE = "windchat.mysql.slave.verifyServerCertificate";
String MYSQL_SLAVE_USE_SSL = "windchat.mysql.slave.useSSL";
}

View File

@ -36,7 +36,7 @@ public class C3P0PoolManager extends AbstractPoolManager {
int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_IDLE, "60"));
cpds.setMaxIdleTime(maxIdle);// 最大空闲时间
SqlLog.info("openzaly init mysql master connection pool cpds={}", cpds);
SqlLog.info("windchat init mysql master connection pool cpds={}", cpds);
}
public static java.sql.Connection getConnection() throws SQLException {

View File

@ -54,7 +54,7 @@ public class C3P0PoolSlaveManager extends AbstractPoolManager {
cpdsList.add(cpds);
SqlLog.info("openzaly init mysql slave connection pool cpds={}", cpds.toString());
SqlLog.info("windchat init mysql slave connection pool cpds={}", cpds.toString());
}
}

View File

@ -24,90 +24,91 @@ import com.windchat.im.storage.util.SqlLog;
*/
public class InitDatabaseConnection extends AbstractPoolManager {
private static final String OPENZALY_MYSQL_SQL = "openzaly-mysql.sql";
private static Connection conn;
private static final String WINDCHAT_MYSQL_SQL = "windchat-mysql.sql";
private static Connection conn;
public static void init(Properties prop) throws Exception {
try {
initAndGetConnection(prop);
} finally {
closeInitConnection();
}
}
public static void init(Properties prop) throws Exception {
try {
initAndGetConnection(prop);
} finally {
closeInitConnection();
}
}
public static Connection initAndGetConnection(Properties prop) throws Exception {
Connection conn = initConnection(prop);
String dbName = trimToNull(prop, JdbcConst.MYSQL_DB);
createAndUseDatabase(conn, dbName);
initDatabaseTable(conn);
return conn;
}
public static Connection initAndGetConnection(Properties prop) throws Exception {
Connection conn = initConnection(prop);
String dbName = trimToNull(prop, JdbcConst.MYSQL_DB);
createAndUseDatabase(conn, dbName);
initDatabaseTable(conn);
return conn;
}
private static Connection initConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrlWithoutDBName(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn;
}
private static Connection initConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrlWithoutDBName(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn;
}
// 获取单独一个连接迁移数据库使用
public static Connection getConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrl(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn;
}
// 获取单独一个连接迁移数据库使用
public static Connection getConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrl(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn;
}
public static void closeInitConnection() {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
SqlLog.error("close mysql init connection error", e);
}
}
public static void closeInitConnection() {
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
SqlLog.error("close mysql init connection error", e);
}
}
private static void createAndUseDatabase(Connection conn, String dbName) throws SQLException {
if (StringUtils.isEmpty(dbName)) {
throw new SQLException("openzaly team need designated database name,but now it's " + dbName);
}
String createSql = "CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4;";
String useSql = "use " + dbName;
conn.prepareStatement(createSql).executeUpdate();
conn.prepareStatement(useSql).executeUpdate();
}
private static void createAndUseDatabase(Connection conn, String dbName) throws SQLException {
if (StringUtils.isEmpty(dbName)) {
throw new SQLException("windchat team need designated database name,but now it's " + dbName);
}
String createSql = "CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4;";
String useSql = "use " + dbName;
conn.prepareStatement(createSql).executeUpdate();
conn.prepareStatement(useSql).executeUpdate();
}
private static void initDatabaseTable(Connection conn) throws SQLException {
try {
// 生成临时sql文件加载数据库sql执行脚本,
File sqlFile = new File(OPENZALY_MYSQL_SQL);
if (!sqlFile.exists()) {
FileUtils.writeResourceToFile("/" + OPENZALY_MYSQL_SQL, sqlFile);
}
private static void initDatabaseTable(Connection conn) throws SQLException {
try {
// 生成临时sql文件加载数据库sql执行脚本,
File sqlFile = new File(WINDCHAT_MYSQL_SQL);
if (!sqlFile.exists()) {
FileUtils.writeResourceToFile("/" + WINDCHAT_MYSQL_SQL, sqlFile);
}
// 初始化数据库表
File file = new File(OPENZALY_MYSQL_SQL);
if (!file.exists()) {
throw new FileNotFoundException("init mysql with sql script file is not exists");
}
// 初始化数据库表
File file = new File(WINDCHAT_MYSQL_SQL);
if (!file.exists()) {
throw new FileNotFoundException("init mysql with sql script file is not exists");
}
FileSystemResource rc = new FileSystemResource(file);
EncodedResource encodeRes = new EncodedResource(rc, "GBK");
ScriptUtils.executeSqlScript(conn, encodeRes);
SqlLog.info("openzaly init mysql database with sql-script finish");
FileSystemResource rc = new FileSystemResource(file);
EncodedResource encodeRes = new EncodedResource(rc, "GBK");
ScriptUtils.executeSqlScript(conn, encodeRes);
SqlLog.info("windchat init mysql database with sql-script finish");
file.delete();
} catch (Exception e) {
throw new SQLException(e);
}
}
file.delete();
} catch (Exception e) {
throw new SQLException(e);
}
}
}

View File

@ -47,7 +47,7 @@ public class SQLiteJDBCManager {
private static int SITE_DB_VERSION = SQLConst.SITE_DB_VERSION_10;
private static String sqliteDriverName = "org.sqlite.JDBC";
private static Connection sqlitConnection = null;
private static final String DB_FILE_PATH = "openzalyDB.sqlite3";
private static final String DB_FILE_PATH = "windchatDB.sqlite3";
private SQLiteJDBCManager() {
@ -61,7 +61,7 @@ public class SQLiteJDBCManager {
loadDatabaseDriver(config.getDbDir());
if (getDbVersion() < SITE_DB_VERSION) {
throw new UpgradeDatabaseException("openzaly-server need to upgrade before run it");
throw new UpgradeDatabaseException("windchat-server need to upgrade before run it");
}
}

View File

@ -34,292 +34,292 @@ import com.windchat.im.storage.util.SqlLog;
* @since 2018-06-28 11:47:07
*/
public class SQLiteUpgrade {
private static final Logger logger = LoggerFactory.getLogger(SQLiteUpgrade.class);
private static final Logger logger = LoggerFactory.getLogger(SQLiteUpgrade.class);
private static final String DB_FILE_PATH = "openzalyDB.sqlite3";
private static final String OPENZALY_SQLITE_SQL = "openzaly-sqlite.sql";
private static final String DB_FILE_PATH = "windchatDB.sqlite3";
private static final String WINDCHAT_SQLITE_SQL = "windchat-sqlite.sql";
private SQLiteUpgrade() {
}
private SQLiteUpgrade() {
}
public static int doUpgrade(DBConfig config) throws SQLException, UpgradeDatabaseException {
return upgradeSqliteDB(config, false);
}
public static int doUpgrade(DBConfig config) throws SQLException, UpgradeDatabaseException {
return upgradeSqliteDB(config, false);
}
public static int doUpgrade(DBConfig config, boolean clear) throws SQLException, UpgradeDatabaseException {
return upgradeSqliteDB(config, clear);
}
public static int doUpgrade(DBConfig config, boolean clear) throws SQLException, UpgradeDatabaseException {
return upgradeSqliteDB(config, clear);
}
// upgrade db,return current db user-version
private static int upgradeSqliteDB(DBConfig config, boolean clear) throws SQLException, UpgradeDatabaseException {
// 数据库文件
File file = new File(config.getDbDir(), DB_FILE_PATH);
// upgrade db,return current db user-version
private static int upgradeSqliteDB(DBConfig config, boolean clear) throws SQLException, UpgradeDatabaseException {
// 数据库文件
File file = new File(config.getDbDir(), DB_FILE_PATH);
if (!file.exists()) {
SqlLog.info("openzaly start with first init sqlite database");
SQLiteJDBCManager.loadDatabaseDriver(config.getDbDir());
doInitWork(SQLiteJDBCManager.getConnection());
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_11);
} else {
SQLiteJDBCManager.loadDatabaseDriver(config.getDbDir());
if (clear) {
SQLiteUnique.clearUnique(SQLiteJDBCManager.getConnection());
}
doUpgradeWork(config);
}
if (!file.exists()) {
SqlLog.info("windchat start with first init sqlite database");
SQLiteJDBCManager.loadDatabaseDriver(config.getDbDir());
doInitWork(SQLiteJDBCManager.getConnection());
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_11);
} else {
SQLiteJDBCManager.loadDatabaseDriver(config.getDbDir());
if (clear) {
SQLiteUnique.clearUnique(SQLiteJDBCManager.getConnection());
}
doUpgradeWork(config);
}
return SQLiteJDBCManager.getDbVersion();
}
return SQLiteJDBCManager.getDbVersion();
}
/**
* 通过sql脚本初始化数据库表
*
* @param conn
* @throws SQLException
*/
private static void doInitWork(Connection conn) throws SQLException {
try {
// 生成临时sql文件加载数据库sql执行脚本,
File sqlFile = new File(OPENZALY_SQLITE_SQL);
if (!sqlFile.exists()) {
FileUtils.writeResourceToFile("/" + OPENZALY_SQLITE_SQL, sqlFile);
}
/**
* 通过sql脚本初始化数据库表
*
* @param conn
* @throws SQLException
*/
private static void doInitWork(Connection conn) throws SQLException {
try {
// 生成临时sql文件加载数据库sql执行脚本,
File sqlFile = new File(WINDCHAT_SQLITE_SQL);
if (!sqlFile.exists()) {
FileUtils.writeResourceToFile("/" + WINDCHAT_SQLITE_SQL, sqlFile);
}
// 初始化数据库表
File file = new File(OPENZALY_SQLITE_SQL);
if (!file.exists()) {
throw new FileNotFoundException("init mysql with sql script file is not exists");
}
// 初始化数据库表
File file = new File(WINDCHAT_SQLITE_SQL);
if (!file.exists()) {
throw new FileNotFoundException("init mysql with sql script file is not exists");
}
FileSystemResource rc = new FileSystemResource(file);
EncodedResource encodeRes = new EncodedResource(rc, "GBK");
ScriptUtils.executeSqlScript(conn, encodeRes);
SqlLog.info("openzaly init sqlite with sql-script finish");
FileSystemResource rc = new FileSystemResource(file);
EncodedResource encodeRes = new EncodedResource(rc, "GBK");
ScriptUtils.executeSqlScript(conn, encodeRes);
SqlLog.info("windchat init sqlite with sql-script finish");
file.delete();
} catch (Exception e) {
throw new SQLException(e);
}
}
file.delete();
} catch (Exception e) {
throw new SQLException(e);
}
}
private static void doUpgradeWork(DBConfig config) throws UpgradeDatabaseException, SQLException {
int times = 5;
while (true) {
// 做一个简单的频率控制防止升级出现死循环
if (times-- <= 0) {
break;
}
private static void doUpgradeWork(DBConfig config) throws UpgradeDatabaseException, SQLException {
int times = 5;
while (true) {
// 做一个简单的频率控制防止升级出现死循环
if (times-- <= 0) {
break;
}
int dbVersion = SQLiteJDBCManager.getDbVersion();
if (dbVersion < 9) {
// 1.首先备份
String fileName = backupDatabaseFile(config.getDbDir(), dbVersion);
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
// 2.升级
if (upgrade0_9(dbVersion)) {
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_9);
} else {
logger.error("upgrade user-version {} -> {} error.", dbVersion, SQLConst.SITE_DB_VERSION_9);
// db rename to original db file
restoreDatabase(fileName);
}
continue;
} else if (dbVersion == 9) {
// 0.9.5 upgrade from 9 to 10
// 1.首先备份
String fileName = backupDatabaseFile(config.getDbDir(), dbVersion);
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
// 2.升级
if (upgrade9_10(dbVersion)) {
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_10);
} else {
logger.error("upgrade user-version {} -> {} error.", dbVersion, SQLConst.SITE_DB_VERSION_10);
// db rename to original db file
restoreDatabase(fileName);
}
int dbVersion = SQLiteJDBCManager.getDbVersion();
if (dbVersion < 9) {
// 1.首先备份
String fileName = backupDatabaseFile(config.getDbDir(), dbVersion);
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
// 2.升级
if (upgrade0_9(dbVersion)) {
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_9);
} else {
logger.error("upgrade user-version {} -> {} error.", dbVersion, SQLConst.SITE_DB_VERSION_9);
// db rename to original db file
restoreDatabase(fileName);
}
continue;
} else if (dbVersion == 9) {
// 0.9.5 upgrade from 9 to 10
// 1.首先备份
String fileName = backupDatabaseFile(config.getDbDir(), dbVersion);
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
if (StringUtils.isEmpty(fileName)) {
throw new UpgradeDatabaseException("backup database file before upgrade error");
}
// 2.升级
if (upgrade9_10(dbVersion)) {
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_10);
} else {
logger.error("upgrade user-version {} -> {} error.", dbVersion, SQLConst.SITE_DB_VERSION_10);
// db rename to original db file
restoreDatabase(fileName);
}
} else if (dbVersion == 10) {
doInitWork(SQLiteJDBCManager.getConnection());
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_11);
}
} else if (dbVersion == 10) {
doInitWork(SQLiteJDBCManager.getConnection());
SQLiteJDBCManager.setDbVersion(SQLConst.SITE_DB_VERSION_11);
}
break;
}
}
break;
}
}
private static String backupDatabaseFile(String dbDir, int oldVersion) {
String filePath = "./";
try {
String dbFileName = SQLiteJDBCManager.getDbFileName();
if (StringUtils.isNotEmpty(dbDir)) {
filePath = dbDir;
}
File file = new File(filePath, dbFileName);// original db file
String bkFileName = dbFileName + ".backup." + oldVersion + "." + System.currentTimeMillis();
File backupFile = new File(filePath, bkFileName);
if (!backupFile.exists()) {
new FileOutputStream(backupFile).close();
}
FileOutputStream fos = new FileOutputStream(backupFile);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
try {
byte[] buffer = new byte[1024];
int bytesLen = 0;
while ((bytesLen = bis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesLen);
}
} finally {
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
}
private static String backupDatabaseFile(String dbDir, int oldVersion) {
String filePath = "./";
try {
String dbFileName = SQLiteJDBCManager.getDbFileName();
if (StringUtils.isNotEmpty(dbDir)) {
filePath = dbDir;
}
File file = new File(filePath, dbFileName);// original db file
String bkFileName = dbFileName + ".backup." + oldVersion + "." + System.currentTimeMillis();
File backupFile = new File(filePath, bkFileName);
if (!backupFile.exists()) {
new FileOutputStream(backupFile).close();
}
FileOutputStream fos = new FileOutputStream(backupFile);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
try {
byte[] buffer = new byte[1024];
int bytesLen = 0;
while ((bytesLen = bis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesLen);
}
} finally {
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.close();
}
}
return backupFile.getAbsolutePath();
} catch (FileNotFoundException e) {
logger.error("backup db file error,fileUrl=" + filePath, e);
} catch (IOException e) {
logger.error("backup db file IOException.fileUrl=" + filePath, e);
}
return backupFile.getAbsolutePath();
} catch (FileNotFoundException e) {
logger.error("backup db file error,fileUrl=" + filePath, e);
} catch (IOException e) {
logger.error("backup db file IOException.fileUrl=" + filePath, e);
}
return null;
}
return null;
}
private static boolean upgrade0_9(int oldVersion) {
String sql1 = "alter table " + SQLConst.SITE_USER_PROFILE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_PROFILE);
String sql2 = "alter table " + SQLConst.SITE_USER_FRIEND + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_FRIEND);
String sql3 = "alter table " + SQLConst.SITE_USER_DEVICE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_DEVICE);
private static boolean upgrade0_9(int oldVersion) {
String sql1 = "alter table " + SQLConst.SITE_USER_PROFILE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_PROFILE);
String sql2 = "alter table " + SQLConst.SITE_USER_FRIEND + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_FRIEND);
String sql3 = "alter table " + SQLConst.SITE_USER_DEVICE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_DEVICE);
boolean result = false;
List<String> upgradeSqls = Arrays.asList(sql1, sql2, sql3);
try {
Connection conn = SQLiteJDBCManager.getConnection();
conn.setAutoCommit(false);
try {
// 1.rename
for (String sql : upgradeSqls) {
PreparedStatement pst = conn.prepareStatement(sql);
int res = pst.executeUpdate();
logger.info("rename database table result={} sql:{}", res, sql);
if (pst != null) {
pst.close();
}
}
// 2.check all tables
doInitWork(conn);
boolean result = false;
List<String> upgradeSqls = Arrays.asList(sql1, sql2, sql3);
try {
Connection conn = SQLiteJDBCManager.getConnection();
conn.setAutoCommit(false);
try {
// 1.rename
for (String sql : upgradeSqls) {
PreparedStatement pst = conn.prepareStatement(sql);
int res = pst.executeUpdate();
logger.info("rename database table result={} sql:{}", res, sql);
if (pst != null) {
pst.close();
}
}
// 2.check all tables
doInitWork(conn);
// 3. migrate
String migSql1 = "INSERT INTO " + SQLConst.SITE_USER_PROFILE
+ "(id,site_user_id,global_user_id,user_id_pubk,user_name,user_photo,phone_id,user_status,mute,register_time) select id,site_user_id,global_user_id,user_id_pubk,user_name,user_photo,phone_id,user_status,mute,register_time from "
+ getTempTable(oldVersion, SQLConst.SITE_USER_PROFILE);
// 3. migrate
String migSql1 = "INSERT INTO " + SQLConst.SITE_USER_PROFILE
+ "(id,site_user_id,global_user_id,user_id_pubk,user_name,user_photo,phone_id,user_status,mute,register_time) select id,site_user_id,global_user_id,user_id_pubk,user_name,user_photo,phone_id,user_status,mute,register_time from "
+ getTempTable(oldVersion, SQLConst.SITE_USER_PROFILE);
String migSql2 = "INSERT INTO " + SQLConst.SITE_USER_FRIEND
+ "(id,site_user_id,site_friend_id,relation,mute,add_time) select id,site_user_id,site_friend_id,relation,mute,add_time from "
+ getTempTable(oldVersion, SQLConst.SITE_USER_FRIEND);
String migSql2 = "INSERT INTO " + SQLConst.SITE_USER_FRIEND
+ "(id,site_user_id,site_friend_id,relation,mute,add_time) select id,site_user_id,site_friend_id,relation,mute,add_time from "
+ getTempTable(oldVersion, SQLConst.SITE_USER_FRIEND);
String migSql3 = "INSERT INTO " + SQLConst.SITE_USER_DEVICE
+ "(id,site_user_id,device_id,user_device_pubk,user_token,device_name,active_time,add_time) SELECT id,site_user_id,device_id,user_device_pubk,user_token,device_name,active_time,add_time FROM "
+ getTempTable(oldVersion, SQLConst.SITE_USER_DEVICE);
Map<Integer, String> sqlMap = new HashMap<Integer, String>() {
/**
*
*/
private static final long serialVersionUID = 1438260552099272302L;
String migSql3 = "INSERT INTO " + SQLConst.SITE_USER_DEVICE
+ "(id,site_user_id,device_id,user_device_pubk,user_token,device_name,active_time,add_time) SELECT id,site_user_id,device_id,user_device_pubk,user_token,device_name,active_time,add_time FROM "
+ getTempTable(oldVersion, SQLConst.SITE_USER_DEVICE);
Map<Integer, String> sqlMap = new HashMap<Integer, String>() {
/**
*
*/
private static final long serialVersionUID = 1438260552099272302L;
{
put(1, migSql1);
put(2, migSql2);
put(3, migSql3);
}
};
for (int sqlIndex : sqlMap.keySet()) {
String sql_mig = sqlMap.get(sqlIndex);
PreparedStatement pst = conn.prepareStatement(sql_mig);
int res = pst.executeUpdate();
logger.info("migrate database table result={} sql:{}", res, sql_mig);
if (pst != null) {
pst.close();
}
}
result = true;// 兼容失败情况这里不能使用成功个数
} catch (Exception e) {
logger.error("upgrade to execute sql error", e);
}
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
logger.error("rename database table to upgrade error.", e);
}
{
put(1, migSql1);
put(2, migSql2);
put(3, migSql3);
}
};
for (int sqlIndex : sqlMap.keySet()) {
String sql_mig = sqlMap.get(sqlIndex);
PreparedStatement pst = conn.prepareStatement(sql_mig);
int res = pst.executeUpdate();
logger.info("migrate database table result={} sql:{}", res, sql_mig);
if (pst != null) {
pst.close();
}
}
result = true;// 兼容失败情况这里不能使用成功个数
} catch (Exception e) {
logger.error("upgrade to execute sql error", e);
}
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
logger.error("rename database table to upgrade error.", e);
}
return result;
}
return result;
}
private static boolean upgrade9_10(int oldVersion) {
String sql = "ALTER TABLE " + SQLConst.SITE_USER_MESSAGE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_MESSAGE);
private static boolean upgrade9_10(int oldVersion) {
String sql = "ALTER TABLE " + SQLConst.SITE_USER_MESSAGE + " RENAME TO "
+ getTempTable(oldVersion, SQLConst.SITE_USER_MESSAGE);
boolean result = false;
try {
Connection conn = SQLiteJDBCManager.getConnection();
// 1.rename
PreparedStatement pst = conn.prepareStatement(sql);
int res = pst.executeUpdate();
logger.info("rename database table result={} sql:{}", res, sql);
boolean result = false;
try {
Connection conn = SQLiteJDBCManager.getConnection();
// 1.rename
PreparedStatement pst = conn.prepareStatement(sql);
int res = pst.executeUpdate();
logger.info("rename database table result={} sql:{}", res, sql);
if (pst != null) {
pst.close();
}
if (pst != null) {
pst.close();
}
// 2.check all tables
doInitWork(conn);
// 2.check all tables
doInitWork(conn);
// 3. migrate
String sql_mig = "INSERT INTO " + SQLConst.SITE_USER_MESSAGE
+ "(id,site_user_id,msg_id,send_user_id,receive_user_id,msg_type,content,device_id,ts_key,msg_time) "
+ "SELECT id,site_user_id,msg_id,send_user_id,site_user_id,msg_type,content,device_id,ts_key,msg_time FROM "
+ getTempTable(oldVersion, SQLConst.SITE_USER_MESSAGE);
// 3. migrate
String sql_mig = "INSERT INTO " + SQLConst.SITE_USER_MESSAGE
+ "(id,site_user_id,msg_id,send_user_id,receive_user_id,msg_type,content,device_id,ts_key,msg_time) "
+ "SELECT id,site_user_id,msg_id,send_user_id,site_user_id,msg_type,content,device_id,ts_key,msg_time FROM "
+ getTempTable(oldVersion, SQLConst.SITE_USER_MESSAGE);
PreparedStatement pst2 = conn.prepareStatement(sql_mig);
int res2 = pst2.executeUpdate();
logger.info("migrate database table result={} sql:{}", res2, sql_mig);
if (pst2 != null) {
pst2.close();
}
result = true;// 兼容失败情况这里不能使用成功个数
} catch (SQLException e) {
logger.error("execute database table to upgrade error.", e);
}
PreparedStatement pst2 = conn.prepareStatement(sql_mig);
int res2 = pst2.executeUpdate();
logger.info("migrate database table result={} sql:{}", res2, sql_mig);
if (pst2 != null) {
pst2.close();
}
result = true;// 兼容失败情况这里不能使用成功个数
} catch (SQLException e) {
logger.error("execute database table to upgrade error.", e);
}
return result;
}
return result;
}
private static String getTempTable(int oldVersion, String tableName) {
return "temp_" + oldVersion + "_" + tableName;
}
private static String getTempTable(int oldVersion, String tableName) {
return "temp_" + oldVersion + "_" + tableName;
}
private static void restoreDatabase(String filePath) throws UpgradeDatabaseException {
File backupFile = new File(filePath);
if (!backupFile.exists()) {
throw new UpgradeDatabaseException("backup file cannot find");
}
String dbPath = backupFile.getParent();
File dbFile = new File(dbPath, SQLiteJDBCManager.getDbFileName());
if (dbFile.exists()) {
dbFile.delete();
}
backupFile.renameTo(dbFile);
}
private static void restoreDatabase(String filePath) throws UpgradeDatabaseException {
File backupFile = new File(filePath);
if (!backupFile.exists()) {
throw new UpgradeDatabaseException("backup file cannot find");
}
String dbPath = backupFile.getParent();
File dbFile = new File(dbPath, SQLiteJDBCManager.getDbFileName());
if (dbFile.exists()) {
dbFile.delete();
}
backupFile.renameTo(dbFile);
}
}