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

View File

@ -8,39 +8,39 @@ package com.windchat.im.storage.dao.config;
*/ */
public interface JdbcConst { 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-------------------- // ----------------------MASTER--------------------
String MYSQL_HOST = "openzaly.mysql.host"; String MYSQL_HOST = "windchat.mysql.host";
String MYSQL_PORT = "openzaly.mysql.port"; String MYSQL_PORT = "windchat.mysql.port";
String MYSQL_DB = "openzaly.mysql.database"; String MYSQL_DB = "windchat.mysql.database";
String MYSQL_USER_NAME = "openzaly.mysql.username"; String MYSQL_USER_NAME = "windchat.mysql.username";
String MYSQL_PASSWORD = "openzaly.mysql.password"; String MYSQL_PASSWORD = "windchat.mysql.password";
String MYSQL_INITIAL_SIZE = "openzaly.mysql.initial-size"; String MYSQL_INITIAL_SIZE = "windchat.mysql.initial-size";
String MYSQL_MAX_SIZE = "openzaly.mysql.max-size"; String MYSQL_MAX_SIZE = "windchat.mysql.max-size";
String MYSQL_MAX_IDLE = "openzaly.mysql.max-idle"; String MYSQL_MAX_IDLE = "windchat.mysql.max-idle";
String MYSQL_USE_UNICODE = "openzaly.mysql.useUnicode"; String MYSQL_USE_UNICODE = "windchat.mysql.useUnicode";
String MYSQL_CHARACTER_ENCODING = "openzaly.mysql.characterEncoding"; String MYSQL_CHARACTER_ENCODING = "windchat.mysql.characterEncoding";
String MYSQL_VERIFY_SERVER_CERTIFICATE = "openzaly.mysql.verifyServerCertificate"; String MYSQL_VERIFY_SERVER_CERTIFICATE = "windchat.mysql.verifyServerCertificate";
String MYSQL_USE_SSL = "openzaly.mysql.useSSL"; String MYSQL_USE_SSL = "windchat.mysql.useSSL";
// ----------------------SLAVE-------------------- // ----------------------SLAVE--------------------
String MYSQL_SLAVE_HOST = "openzaly.mysql.slave.host"; String MYSQL_SLAVE_HOST = "windchat.mysql.slave.host";
String MYSQL_SLAVE_PORT = "openzaly.mysql.slave.port"; String MYSQL_SLAVE_PORT = "windchat.mysql.slave.port";
String MYSQL_SLAVE_DB = "openzaly.mysql.slave.database"; String MYSQL_SLAVE_DB = "windchat.mysql.slave.database";
String MYSQL_SLAVE_USER_NAME = "openzaly.mysql.slave.username"; String MYSQL_SLAVE_USER_NAME = "windchat.mysql.slave.username";
String MYSQL_SLAVE_PASSWORD = "openzaly.mysql.slave.password"; String MYSQL_SLAVE_PASSWORD = "windchat.mysql.slave.password";
String MYSQL_SLAVE_INITIAL_SIZE = "openzaly.mysql.slave.initial-size"; String MYSQL_SLAVE_INITIAL_SIZE = "windchat.mysql.slave.initial-size";
String MYSQL_SLAVE_MAX_SIZE = "openzaly.mysql.slave.max-size"; String MYSQL_SLAVE_MAX_SIZE = "windchat.mysql.slave.max-size";
String MYSQL_SLAVE_MAX_IDLE = "openzaly.mysql.slave.max-idle"; String MYSQL_SLAVE_MAX_IDLE = "windchat.mysql.slave.max-idle";
String MYSQL_SLAVE_USE_UNICODE = "openzaly.mysql.slave.useUnicode"; String MYSQL_SLAVE_USE_UNICODE = "windchat.mysql.slave.useUnicode";
String MYSQL_SLAVE_CHARACTER_ENCODING = "openzaly.mysql.slave.characterEncoding"; String MYSQL_SLAVE_CHARACTER_ENCODING = "windchat.mysql.slave.characterEncoding";
String MYSQL_SLAVE_VERIFY_SERVER_CERTIFICATE = "openzaly.mysql.slave.verifyServerCertificate"; String MYSQL_SLAVE_VERIFY_SERVER_CERTIFICATE = "windchat.mysql.slave.verifyServerCertificate";
String MYSQL_SLAVE_USE_SSL = "openzaly.mysql.slave.useSSL"; 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")); int maxIdle = Integer.valueOf(trimToNull(pro, JdbcConst.MYSQL_MAX_IDLE, "60"));
cpds.setMaxIdleTime(maxIdle);// 最大空闲时间 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 { public static java.sql.Connection getConnection() throws SQLException {

View File

@ -54,7 +54,7 @@ public class C3P0PoolSlaveManager extends AbstractPoolManager {
cpdsList.add(cpds); 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

@ -18,96 +18,97 @@ import com.windchat.im.storage.util.SqlLog;
/** /**
* 启动mysql的情形下需要获取一个连接建数据库建表操作只有在初始化数据库情况下才使用 * 启动mysql的情形下需要获取一个连接建数据库建表操作只有在初始化数据库情况下才使用
* *
* @author Sam{@link an.guoyue254@gmail.com} * @author Sam{@link an.guoyue254@gmail.com}
* @since 2018-06-07 16:18:11 * @since 2018-06-07 16:18:11
*/ */
public class InitDatabaseConnection extends AbstractPoolManager { public class InitDatabaseConnection extends AbstractPoolManager {
private static final String OPENZALY_MYSQL_SQL = "openzaly-mysql.sql"; private static final String WINDCHAT_MYSQL_SQL = "windchat-mysql.sql";
private static Connection conn; private static Connection conn;
public static void init(Properties prop) throws Exception { public static void init(Properties prop) throws Exception {
try { try {
initAndGetConnection(prop); initAndGetConnection(prop);
} finally { } finally {
closeInitConnection(); closeInitConnection();
} }
} }
public static Connection initAndGetConnection(Properties prop) throws Exception { public static Connection initAndGetConnection(Properties prop) throws Exception {
Connection conn = initConnection(prop); Connection conn = initConnection(prop);
String dbName = trimToNull(prop, JdbcConst.MYSQL_DB); String dbName = trimToNull(prop, JdbcConst.MYSQL_DB);
createAndUseDatabase(conn, dbName); createAndUseDatabase(conn, dbName);
initDatabaseTable(conn); initDatabaseTable(conn);
return conn; return conn;
} }
private static Connection initConnection(Properties pro) throws Exception { private static Connection initConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver" // "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrlWithoutDBName(pro); String jdbcUrl = getJdbcUrlWithoutDBName(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME); String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD); String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER); Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password); conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate(); conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn; return conn;
} }
// 获取单独一个连接迁移数据库使用 // 获取单独一个连接迁移数据库使用
public static Connection getConnection(Properties pro) throws Exception { public static Connection getConnection(Properties pro) throws Exception {
// "com.mysql.cj.jdbc.Driver" // "com.mysql.cj.jdbc.Driver"
String jdbcUrl = getJdbcUrl(pro); String jdbcUrl = getJdbcUrl(pro);
String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME); String userName = trimToNull(pro, JdbcConst.MYSQL_USER_NAME);
String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD); String password = trimToNull(pro, JdbcConst.MYSQL_PASSWORD);
Class.forName(MYSQL_JDBC_DRIVER); Class.forName(MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection(jdbcUrl, userName, password); conn = DriverManager.getConnection(jdbcUrl, userName, password);
conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate(); conn.prepareStatement("SET NAMES utf8mb4;").executeUpdate();
return conn; return conn;
} }
public static void closeInitConnection() { public static void closeInitConnection() {
try { try {
if (conn != null) if (conn != null) {
conn.close(); conn.close();
} catch (Exception e) { }
SqlLog.error("close mysql init connection error", e); } catch (Exception e) {
} SqlLog.error("close mysql init connection error", e);
} }
}
private static void createAndUseDatabase(Connection conn, String dbName) throws SQLException { private static void createAndUseDatabase(Connection conn, String dbName) throws SQLException {
if (StringUtils.isEmpty(dbName)) { if (StringUtils.isEmpty(dbName)) {
throw new SQLException("openzaly team need designated database name,but now it's " + 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 createSql = "CREATE DATABASE IF NOT EXISTS " + dbName + " CHARACTER SET utf8mb4;";
String useSql = "use " + dbName; String useSql = "use " + dbName;
conn.prepareStatement(createSql).executeUpdate(); conn.prepareStatement(createSql).executeUpdate();
conn.prepareStatement(useSql).executeUpdate(); conn.prepareStatement(useSql).executeUpdate();
} }
private static void initDatabaseTable(Connection conn) throws SQLException { private static void initDatabaseTable(Connection conn) throws SQLException {
try { try {
// 生成临时sql文件加载数据库sql执行脚本, // 生成临时sql文件加载数据库sql执行脚本,
File sqlFile = new File(OPENZALY_MYSQL_SQL); File sqlFile = new File(WINDCHAT_MYSQL_SQL);
if (!sqlFile.exists()) { if (!sqlFile.exists()) {
FileUtils.writeResourceToFile("/" + OPENZALY_MYSQL_SQL, sqlFile); FileUtils.writeResourceToFile("/" + WINDCHAT_MYSQL_SQL, sqlFile);
} }
// 初始化数据库表 // 初始化数据库表
File file = new File(OPENZALY_MYSQL_SQL); File file = new File(WINDCHAT_MYSQL_SQL);
if (!file.exists()) { if (!file.exists()) {
throw new FileNotFoundException("init mysql with sql script file is not exists"); throw new FileNotFoundException("init mysql with sql script file is not exists");
} }
FileSystemResource rc = new FileSystemResource(file); FileSystemResource rc = new FileSystemResource(file);
EncodedResource encodeRes = new EncodedResource(rc, "GBK"); EncodedResource encodeRes = new EncodedResource(rc, "GBK");
ScriptUtils.executeSqlScript(conn, encodeRes); ScriptUtils.executeSqlScript(conn, encodeRes);
SqlLog.info("openzaly init mysql database with sql-script finish"); SqlLog.info("windchat init mysql database with sql-script finish");
file.delete(); file.delete();
} catch (Exception e) { } catch (Exception e) {
throw new SQLException(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 int SITE_DB_VERSION = SQLConst.SITE_DB_VERSION_10;
private static String sqliteDriverName = "org.sqlite.JDBC"; private static String sqliteDriverName = "org.sqlite.JDBC";
private static Connection sqlitConnection = null; 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() { private SQLiteJDBCManager() {
@ -61,7 +61,7 @@ public class SQLiteJDBCManager {
loadDatabaseDriver(config.getDbDir()); loadDatabaseDriver(config.getDbDir());
if (getDbVersion() < SITE_DB_VERSION) { 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

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