[ref]同步

This commit is contained in:
shi_jq 2025-03-13 10:45:13 +08:00
parent fbfa28fc2e
commit b8c1101693
613 changed files with 26004 additions and 31078 deletions

View File

@ -20,7 +20,10 @@ bool CDbKingbaseApi::doAfterOpen()
* SET search_path TO ISCS6000_FSNH;-- * SET search_path TO ISCS6000_FSNH;--
* ALTER database ISCS6000_FSNH SET search_path TO ISCS6000_FSNH,$USER, public;-- * ALTER database ISCS6000_FSNH SET search_path TO ISCS6000_FSNH,$USER, public;--
*/ */
QString sSql = "SET search_path TO iscs6000;"; /* 为以后搜索方便,保留此注释
* QString sSql = QString("SET search_path TO %1;").arg(EMS_DEFAULT_DATABASE) ;
*/
QString sSql = QString("SET search_path TO %1;").arg(m_objDbPara.getDatabaseName()) ;
if ( !execute(sSql) ) if ( !execute(sSql) )
return false; return false;

View File

@ -1,161 +1,161 @@
#include "CDbMySQLApi.h" #include "CDbMySQLApi.h"
using namespace iot_dbms; using namespace iot_dbms;
CDbMySQLApi::CDbMySQLApi() CDbMySQLApi::CDbMySQLApi()
: CDbBaseApi_impl() : CDbBaseApi_impl()
{ {
} }
CDbMySQLApi::CDbMySQLApi( const CDbPara& objDbPara ) CDbMySQLApi::CDbMySQLApi( const CDbPara& objDbPara )
: CDbBaseApi_impl( objDbPara ) : CDbBaseApi_impl( objDbPara )
{ {
} }
CDbMySQLApi::~CDbMySQLApi() CDbMySQLApi::~CDbMySQLApi()
{ {
} }
QString CDbMySQLApi::getDriverStr() const QString CDbMySQLApi::getDriverStr() const
{ {
return QString( "QMYSQL" ); return QString( "QMYSQL" );
} }
void CDbMySQLApi::setConnectOptions() void CDbMySQLApi::setConnectOptions()
{ {
// model_studio 调用存储过程的时候会导致超过60s无返回故不设置超时参数todo 应该让它优化 // model_studio 调用存储过程的时候会导致超过60s无返回故不设置超时参数todo 应该让它优化
QString sAppName = QCoreApplication::applicationName().toLower(); QString sAppName = QCoreApplication::applicationName().toLower();
if ( sAppName=="model_studio" || sAppName=="db_manager" ) if ( sAppName=="model_studio" || sAppName=="db_manager" )
return; return;
//< 经实验setConnectOptions()必须一次性设置不可分多行再次执行setConnectOptions()会覆盖掉之前的 //< 经实验setConnectOptions()必须一次性设置不可分多行再次执行setConnectOptions()会覆盖掉之前的
//< 在此参数下60%网络丢包率环境测试9474次打开数据库 //< 在此参数下60%网络丢包率环境测试9474次打开数据库
//< 526次大于61秒其中70~79秒47次80~89秒4次90秒1次112秒1次 //< 526次大于61秒其中70~79秒47次80~89秒4次90秒1次112秒1次
//< 因此极端情况下可能触发死锁检测默认3分钟自杀todo 可以考虑增加死锁检测默认值到5分钟 //< 因此极端情况下可能触发死锁检测默认3分钟自杀todo 可以考虑增加死锁检测默认值到5分钟
m_pDb->setConnectOptions("MYSQL_OPT_CONNECT_TIMEOUT=10;MYSQL_OPT_READ_TIMEOUT=60;MYSQL_OPT_WRITE_TIMEOUT=60"); m_pDb->setConnectOptions("MYSQL_OPT_CONNECT_TIMEOUT=10;MYSQL_OPT_READ_TIMEOUT=60;MYSQL_OPT_WRITE_TIMEOUT=60;MYSQL_OPT_RECONNECT=1");
} }
bool CDbMySQLApi::doAfterOpen() bool CDbMySQLApi::doAfterOpen()
{ {
QString sSql = "use " + m_objDbPara.getDatabaseName(); QString sSql = "use " + m_objDbPara.getDatabaseName();
if ( !execute(sSql) ) if ( !execute(sSql) )
{ {
return false; return false;
} }
if ( !execute("set names 'utf8'") ) if ( !execute("set names 'utf8'") )
{ {
return false; return false;
} }
//< 历史原因有些表的长度超长在MySQL5时代可以的但现在不行报错如下 //< 历史原因有些表的长度超长在MySQL5时代可以的但现在不行报错如下
//< SQL EXECUTE ERROR, REASON:Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline. //< SQL EXECUTE ERROR, REASON:Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline.
//< 执行此设置以作兼容在MySQL5上是默认OFF的 //< 执行此设置以作兼容在MySQL5上是默认OFF的
execute("SET SESSION innodb_strict_mode = 'OFF'"); execute("SET SESSION innodb_strict_mode = 'OFF'");
return true; return true;
} }
bool CDbMySQLApi::needReconnect() bool CDbMySQLApi::needReconnect()
{ {
if ( 2006 == m_nErrorNum ) if ( 2006 == m_nErrorNum )
{ {
// 2006错误MySQL server has gone away与服务器连接中断 // 2006错误MySQL server has gone away与服务器连接中断
return true; return true;
} }
if ( 2013 == m_nErrorNum ) if ( 2013 == m_nErrorNum )
{ {
// 2013错误Lost connection to MySQL server during query // 2013错误Lost connection to MySQL server during query
return true; return true;
} }
return false; return false;
} }
bool CDbMySQLApi::drop( const QString& sTableName ) bool CDbMySQLApi::drop( const QString& sTableName )
{ {
if ( !isOpen() ) if ( !isOpen() )
return false; return false;
m_sLastSql = QString( "drop table if exists %1;" ) m_sLastSql = QString( "drop table if exists %1;" )
.arg( addQuoteMarks(sTableName) ); .arg( addQuoteMarks(sTableName) );
QSqlQuery objQuery( m_sLastSql, *m_pDb ); QSqlQuery objQuery( m_sLastSql, *m_pDb );
m_sErrorStr = objQuery.lastError().text(); m_sErrorStr = objQuery.lastError().text();
m_nErrorNum = objQuery.lastError().number(); m_nErrorNum = objQuery.lastError().number();
return objQuery.isActive(); return objQuery.isActive();
} }
QString CDbMySQLApi::addQuoteMarks( const QString& sStr ) const QString CDbMySQLApi::addQuoteMarks( const QString& sStr ) const
{ {
QString strDest( sStr.trimmed() ); QString strDest( sStr.trimmed() );
if ( !strDest.startsWith("`") ) if ( !strDest.startsWith("`") )
strDest = QString("`%1").arg(strDest); strDest = QString("`%1").arg(strDest);
if ( !strDest.endsWith("`") ) if ( !strDest.endsWith("`") )
strDest = QString("%1`").arg(strDest); strDest = QString("%1`").arg(strDest);
return strDest; return strDest;
} }
QString CDbMySQLApi::convertQuoteMarks( const QString& sStr ) const QString CDbMySQLApi::convertQuoteMarks( const QString& sStr ) const
{ {
QString sTmp = sStr; QString sTmp = sStr;
sTmp = sTmp.replace("\\","\\\\"); /* \ -> \\ */ sTmp = sTmp.replace("\\","\\\\"); /* \ -> \\ */
sTmp = sTmp.replace("'","\\'"); /* ' -> \' */ sTmp = sTmp.replace("'","\\'"); /* ' -> \' */
//sTmp = sTmp.replace("\"","\\\""); //sTmp = sTmp.replace("\"","\\\"");
return sTmp; return sTmp;
} }
QString CDbMySQLApi::convertToSqlString( const QDateTime& dt ) const QString CDbMySQLApi::convertToSqlString( const QDateTime& dt ) const
{ {
QString strDateTime = dt.toString( "yyyy-MM-dd hh:mm:ss" ); QString strDateTime = dt.toString( "yyyy-MM-dd hh:mm:ss" );
strDateTime = QString( "\'%1\'" ).arg( strDateTime ); strDateTime = QString( "\'%1\'" ).arg( strDateTime );
return strDateTime; return strDateTime;
} }
QString CDbMySQLApi::getHostName() QString CDbMySQLApi::getHostName()
{ {
QString sHostName = ""; QString sHostName = "";
if ( m_pDb != NULL && m_pDb->isOpen() ) if ( m_pDb != NULL && m_pDb->isOpen() )
{ {
QSqlQuery objQuery = m_pDb->exec("select @@global.hostname"); QSqlQuery objQuery = m_pDb->exec("select @@global.hostname");
m_sErrorStr = objQuery.lastError().text(); m_sErrorStr = objQuery.lastError().text();
m_nErrorNum = objQuery.lastError().number(); m_nErrorNum = objQuery.lastError().number();
if ( objQuery.next()) if ( objQuery.next())
sHostName = objQuery.value( 0 ).toString(); sHostName = objQuery.value( 0 ).toString();
} }
return sHostName; return sHostName;
} }
bool CDbMySQLApi::lockTable( const QString& sTabelName ) bool CDbMySQLApi::lockTable( const QString& sTabelName )
{ {
if ( m_pDb != NULL && m_pDb->isOpen() && sTabelName.size()>0 ) if ( m_pDb != NULL && m_pDb->isOpen() && sTabelName.size()>0 )
{ {
QSqlQuery objQuery = m_pDb->exec("LOCK TABLES "+sTabelName+" WRITE"); QSqlQuery objQuery = m_pDb->exec("LOCK TABLES "+sTabelName+" WRITE");
m_sErrorStr = objQuery.lastError().text(); m_sErrorStr = objQuery.lastError().text();
m_nErrorNum = objQuery.lastError().number(); m_nErrorNum = objQuery.lastError().number();
return objQuery.isActive(); return objQuery.isActive();
} }
return false; return false;
} }
bool CDbMySQLApi::unlockTable() bool CDbMySQLApi::unlockTable()
{ {
if ( m_pDb != NULL && m_pDb->isOpen() ) if ( m_pDb != NULL && m_pDb->isOpen() )
{ {
QSqlQuery objQuery = m_pDb->exec("UNLOCK TABLES"); QSqlQuery objQuery = m_pDb->exec("UNLOCK TABLES");
m_sErrorStr = objQuery.lastError().text(); m_sErrorStr = objQuery.lastError().text();
m_nErrorNum = objQuery.lastError().number(); m_nErrorNum = objQuery.lastError().number();
return objQuery.isActive(); return objQuery.isActive();
} }
return false; return false;
} }

View File

@ -21,7 +21,10 @@ bool CDbOpenGaussApi::doAfterOpen()
* SET search_path TO ISCS6000_FSNH;-- * SET search_path TO ISCS6000_FSNH;--
* ALTER database ISCS6000_FSNH SET search_path TO ISCS6000_FSNH,$USER, public;-- * ALTER database ISCS6000_FSNH SET search_path TO ISCS6000_FSNH,$USER, public;--
*/ */
QString sSql = "SET search_path TO iscs6000;"; /*为以后搜索方便,保留此注释
* QString sSql = QString("SET search_path TO %1;").arg(EMS_DEFAULT_DATABASE) ;
*/
QString sSql = QString("SET search_path TO %1;").arg(m_objDbPara.getDatabaseName()) ;
if ( !execute(sSql) ) if ( !execute(sSql) )
return false; return false;

View File

@ -19,8 +19,6 @@
#define CONNECTION_NAME PROCESS_NAME #define CONNECTION_NAME PROCESS_NAME
#define DATABASE_NAME "iscs6000"
#define TSDB_DB_NAME "iscs6000"
#define DB_FILE_NAME "db_export.sql" #define DB_FILE_NAME "db_export.sql"
#define TSDB_FILE_NAME "tsdb_export.sql.gz" #define TSDB_FILE_NAME "tsdb_export.sql.gz"
@ -79,7 +77,11 @@ bool CDumpUtils::getDbConn(const CDbHisCfg &dbCfg,iot_dbms::CDbBaseApi &objDb)
objPara.setPort(3306); objPara.setPort(3306);
objPara.setDbType(iot_dbms::EDbType::DB_MYSQL); objPara.setDbType(iot_dbms::EDbType::DB_MYSQL);
} }
objPara.setDatabaseName(DATABASE_NAME);
/* 为以后搜索方便,保留此注释
* objPara.setDatabaseName(EMS_DEFAULT_DATABASE);
*/
objPara.setDatabaseName(dbCfg.strDbName);
objDb.setDbPara(objPara); objDb.setDbPara(objPara);
bool ok = objDb.open(); bool ok = objDb.open();
@ -90,6 +92,11 @@ bool CDumpUtils::getDbConn(const CDbHisCfg &dbCfg,iot_dbms::CDbBaseApi &objDb)
//获取首链接连接 //获取首链接连接
{ {
iot_public::CSysInfoInterfacePtr ptrSysInfo; iot_public::CSysInfoInterfacePtr ptrSysInfo;
if(!iot_public::createSysInfoInstance(ptrSysInfo))
{
LOGERROR( "createSysInfoInstance 返回失败" );
return false;
}
iot_public::SDatabaseInfo stFirstConnectInfo; //数据库连接信息 iot_public::SDatabaseInfo stFirstConnectInfo; //数据库连接信息
std::vector<iot_public::SDatabaseInfo> vecLocalDbInfo; std::vector<iot_public::SDatabaseInfo> vecLocalDbInfo;
std::vector<iot_public::SDatabaseInfo> vecRemoteDbInfo; std::vector<iot_public::SDatabaseInfo> vecRemoteDbInfo;
@ -180,8 +187,11 @@ bool CDumpUtils::doBackup(const CDbHisCfg &dbCfg)
qint64 expired_days_timestamp = expired_days.toMSecsSinceEpoch(); qint64 expired_days_timestamp = expired_days.toMSecsSinceEpoch();
//==================================================================== //====================================================================
/* 为以后搜索方便,保留此注释
* hismng.exportHisPartV2(objDb.getDatabase(),"127.0.0.1",EMS_DEFAULT_DATABASE,0,expired_days_timestamp,dbFilePath,tsdbFilePath);
*/
iot_dbms::CHisMngApi hismng; iot_dbms::CHisMngApi hismng;
hismng.exportHisPartV2(objDb.getDatabase(),"127.0.0.1",TSDB_DB_NAME,0,expired_days_timestamp,dbFilePath,tsdbFilePath); hismng.exportHisPartV2(objDb.getDatabase(),"127.0.0.1",objDb.getDbPara().getDatabaseName(),0,expired_days_timestamp,dbFilePath,tsdbFilePath);
//< 生成配置 //< 生成配置
LOGINFO("start to generate config"); LOGINFO("start to generate config");
@ -211,7 +221,10 @@ bool CDumpUtils::doBackup(const CDbHisCfg &dbCfg)
//< 数据库 //< 数据库
entry.setAttribute("databaseName", DATABASE_NAME); /* 为以后搜索方便,保留此注释
* entry.setAttribute("databaseName", EMS_DEFAULT_DATABASE);
*/
entry.setAttribute("databaseName", objDb.getDbPara().getDatabaseName());
//< 备份名称 //< 备份名称
entry.setAttribute("configName", QDateTime::currentDateTime().toString(QObject::tr("yyyy年M月d日h时m分s秒"))); entry.setAttribute("configName", QDateTime::currentDateTime().toString(QObject::tr("yyyy年M月d日h时m分s秒")));
@ -252,7 +265,10 @@ bool CDumpUtils::doClean(const CDbHisCfg &dbCfg, bool isAll)
//==================================================================== //====================================================================
iot_dbms::CHisMngApi hismng; iot_dbms::CHisMngApi hismng;
hismng.delHis(objDb.getDatabase(),"127.0.0.1",TSDB_DB_NAME,expired_days_timestamp); /* 为以后搜索方便,保留此注释
* hismng.delHis(objDb.getDatabase(),"127.0.0.1",EMS_DEFAULT_DATABASE,expired_days_timestamp);
*/
hismng.delHisV2(objDb.getDatabase(),"127.0.0.1",objDb.getDbPara().getDatabaseName(),expired_days_timestamp);
QString logPath = QCoreApplication::applicationDirPath() + "/../../log/"; QString logPath = QCoreApplication::applicationDirPath() + "/../../log/";
// 清理日志 // 清理日志

View File

@ -52,6 +52,7 @@ bool CDbHisCfg::loadFromFile()
strUsername = node.attribute("username"); strUsername = node.attribute("username");
strPasswd = node.attribute("passwd"); strPasswd = node.attribute("passwd");
strDbType = node.attribute("dbType"); strDbType = node.attribute("dbType");
strDbName = node.attribute("dbName");
} }
} }

View File

@ -13,9 +13,15 @@ public:
int nTrigWeekDay = 7; // 在星期几触发 int nTrigWeekDay = 7; // 在星期几触发
int nTrigHour = 1; // 触发小时数 24小时制 int nTrigHour = 1; // 触发小时数 24小时制
int nTrigMin = 0; // 触发分钟数 int nTrigMin = 0; // 触发分钟数
QString strUsername = "root"; /* 为方便检索,暂时保留此注释,同时为避免出错,取消默认参数
QString strPasswd = "kbdct@0755"; * QString strUsername = "root";
QString strDbType = "QMYSQL"; * QString strPasswd = EMS_DEFAULT_PASSWD;
* QString strDbType = "QMYSQL";
*/
QString strUsername = "";
QString strPasswd = "";
QString strDbType = "";
QString strDbName = "";
int nTrigType = 1; int nTrigType = 1;
int nTrigAction = 1; int nTrigAction = 1;
int nTrigVolume = 90; int nTrigVolume = 90;

View File

@ -31,7 +31,7 @@ win32-msvc:contains(QMAKE_HOST.arch, x86_64){
LIBS += -lboost_system -lboost_filesystem \ LIBS += -lboost_system -lboost_filesystem \
-llog4cplus -lpub_logger_api \ -llog4cplus -lpub_logger_api \
-lpub_utility_api -ldb_his_mng_api -ldb_base_api -lpub_utility_api -ldb_his_mng_api -ldb_base_api -lpub_sysinfo_api
HEADERS += \ HEADERS += \
CDumpUtils.h \ CDumpUtils.h \

View File

@ -2,7 +2,7 @@
CChunkedJsonHandler::CChunkedJsonHandler(QString strFilePath): CChunkedJsonHandler::CChunkedJsonHandler(const QString &strDbName,const QString &strFilePath):
state_(kExpectObjectStart), state_(kExpectObjectStart),
nIndex(0), nIndex(0),
m_gGzipOs(strFilePath) m_gGzipOs(strFilePath)
@ -13,7 +13,7 @@ CChunkedJsonHandler::CChunkedJsonHandler(QString strFilePath):
return ; return ;
} }
genDMLHeader(m_gGzipOs); genDMLHeader(strDbName,m_gGzipOs);
} }
@ -259,11 +259,12 @@ bool CChunkedJsonHandler::RawNumber(const Ch *str, SizeType length, bool copy){
} }
} }
void CChunkedJsonHandler::genDMLHeader(CChunkedJsonHandler::CGZipOStream &os) void CChunkedJsonHandler::genDMLHeader(const QString &strDbName,CChunkedJsonHandler::CGZipOStream &os)
{ {
/* 为以后搜索方便,保留此注释 EMS_DEFAULT_DATABASE */
os << "# DDL\n" os << "# DDL\n"
<< "CREATE DATABASE iscs6000 WITH NAME autogen\n"; << "CREATE DATABASE " << strDbName.toStdString().c_str() << " WITH NAME autogen\n";
os << "# DML\n" << "# CONTEXT-DATABASE:iscs6000\n" os << "# DML\n" << "# CONTEXT-DATABASE:" << strDbName.toStdString().c_str() <<"\n"
<< "# CONTEXT-RETENTION-POLICY:autogen\n" << "# CONTEXT-RETENTION-POLICY:autogen\n"
<< "# writing tsm data\n"; << "# writing tsm data\n";
} }

View File

@ -73,7 +73,7 @@ struct CChunkedJsonHandler : public rapidjson::BaseReaderHandler<rapidjson::UTF8
const size_t m_nBufSize; const size_t m_nBufSize;
size_t m_nInLen; //当前缓冲区需要压缩的数据长度 size_t m_nInLen; //当前缓冲区需要压缩的数据长度
}; };
CChunkedJsonHandler(QString strFilePath); CChunkedJsonHandler(const QString &strDbName, const QString &strFilePath);
bool StartObject(); bool StartObject();
bool EndObject(SizeType memberCount); bool EndObject(SizeType memberCount);
@ -120,7 +120,7 @@ struct CChunkedJsonHandler : public rapidjson::BaseReaderHandler<rapidjson::UTF8
kExpectResultObjectValueBool, kExpectResultObjectValueBool,
}state_; }state_;
static void genDMLHeader(CGZipOStream& os); static void genDMLHeader(const QString &strDbName,CGZipOStream& os);
std::string m_strCurMeasurementName; std::string m_strCurMeasurementName;

View File

@ -97,6 +97,22 @@ void iot_dbms::CHisMngApi::delHis(QSqlDatabase *conn, const QString &ip, const Q
emit delHisFinished(false); emit delHisFinished(false);
} }
void iot_dbms::CHisMngApi::delHisAllV2(QSqlDatabase *conn, const QString &ip, const QString &databaseName)
{
if(m_pImp->delHisAllV2(*conn,ip,databaseName))
emit delHisAllFinished(true);
else
emit delHisAllFinished(false);
}
void iot_dbms::CHisMngApi::delHisV2(QSqlDatabase *conn, const QString &ip, const QString &databaseName, qint64 endTimeStamp)
{
if(m_pImp->delHisV2(*conn,ip,databaseName,endTimeStamp))
emit delHisFinished(true);
else
emit delHisFinished(false);
}
void iot_dbms::CHisMngApi::needTerminate() void iot_dbms::CHisMngApi::needTerminate()
{ {
m_pImp->needTerminate(); m_pImp->needTerminate();

View File

@ -111,7 +111,8 @@ bool iot_dbms::CHisMngApiImp::getColumnMySQL(QSqlDatabase &conn, const QString &
bool iot_dbms::CHisMngApiImp::getColumnPostgres(QSqlDatabase &conn, const QString &sTableName, QList<iot_dbms::CHisMngApiImp::SColumn> &listColumn) bool iot_dbms::CHisMngApiImp::getColumnPostgres(QSqlDatabase &conn, const QString &sTableName, QList<iot_dbms::CHisMngApiImp::SColumn> &listColumn)
{ {
QString sSql = "SELECT * from " /* 为以后搜索方便,保留此注释 EMS_DEFAULT_DATABASE */
QString sSql = QString("SELECT * from "
"(SELECT " "(SELECT "
" DISTINCT ON (pg_attribute.attname) pg_attribute.attname, " " DISTINCT ON (pg_attribute.attname) pg_attribute.attname, "
"format_type(pg_attribute.atttypid, pg_attribute.atttypmod), " "format_type(pg_attribute.atttypid, pg_attribute.atttypmod), "
@ -119,11 +120,11 @@ bool iot_dbms::CHisMngApiImp::getColumnPostgres(QSqlDatabase &conn, const QStrin
"attnotnull,attnum " "attnotnull,attnum "
"FROM pg_index, pg_class, pg_attribute, pg_namespace " "FROM pg_index, pg_class, pg_attribute, pg_namespace "
"WHERE pg_attribute.attnum > 0 AND " "WHERE pg_attribute.attnum > 0 AND "
"pg_class.oid = '" + sTableName + "'::regclass " "pg_class.oid = '%1'::regclass "
"AND nspname = 'iscs6000' " "AND nspname = '%2' "
"AND pg_class.relnamespace = pg_namespace.oid " "AND pg_class.relnamespace = pg_namespace.oid "
"AND pg_attribute.attrelid = pg_class.oid " "AND pg_attribute.attrelid = pg_class.oid "
"AND pg_attribute.attisdropped = false) as ts order by attnum;"; "AND pg_attribute.attisdropped = false) as ts order by attnum;").arg(sTableName).arg(conn.databaseName());
QSqlQuery query( conn ); QSqlQuery query( conn );
if ( query.exec( sSql ) == false ){ if ( query.exec( sSql ) == false ){
logError(query.lastError().text()); logError(query.lastError().text());
@ -280,8 +281,20 @@ bool iot_dbms::CHisMngApiImp::exportTables(QSqlDatabase &conn, qint64 startTimeS
bool iot_dbms::CHisMngApiImp::exportTsdbBin(const QString &ip, const QString &dbName, const QString &dirPath, qint64 startTime, qint64 endTime) bool iot_dbms::CHisMngApiImp::exportTsdbBin(const QString &ip, const QString &dbName, const QString &dirPath, qint64 startTime, qint64 endTime)
{ {
QString program = "influxd";//备份工具
QStringList arguments; QStringList arguments;
QString program;//备份工具
#ifdef OS_WINDOWS
program = "influxd";
#endif
#ifdef OS_LINUX
program = "pkexec";
arguments << "influxd";
#endif
arguments << "backup" << "-host" << ip+":8088" << "-portable" << "-database" << dbName; arguments << "backup" << "-host" << ip+":8088" << "-portable" << "-database" << dbName;
if(startTime != 0){ if(startTime != 0){
arguments << "-start" << QDateTime::fromMSecsSinceEpoch(startTime).toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate); arguments << "-start" << QDateTime::fromMSecsSinceEpoch(startTime).toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate);
@ -290,38 +303,47 @@ bool iot_dbms::CHisMngApiImp::exportTsdbBin(const QString &ip, const QString &db
arguments << "-end" << QDateTime::fromMSecsSinceEpoch(endTime).toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate); arguments << "-end" << QDateTime::fromMSecsSinceEpoch(endTime).toTimeSpec(Qt::OffsetFromUTC).toString(Qt::ISODate);
} }
arguments << dirPath; arguments << QDir::toNativeSeparators(dirPath);
LOGINFO("arguments is [%s]",arguments.join(" ").toStdString().c_str());
m_pExportProc->start(program,arguments); m_pExportProc->start(program,arguments);
if(!m_pExportProc->waitForFinished(-1)) if(!m_pExportProc->waitForFinished(-1))
{ {
//< todo 导出错误 //< todo 导出错误
logStatus("log here #1023"); QString errorLog = m_pExportProc->errorString();
QString stdOut = m_pExportProc->readAllStandardOutput();
QString stdErr = m_pExportProc->readAllStandardError();
logError("Export failed: " + errorLog + "\nOutput: " + stdOut + "\nError: " + stdErr);
return false; return false;
} }
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::exportTsdbByInspect(const QString &dbName, const QString &dstFilePath, qint64 startTime, qint64 endTime) bool iot_dbms::CHisMngApiImp::exportTsdbByInspect(const STsdbConnParam &connParam, const QString &dstFilePath, qint64 startTime, qint64 endTime)
{ {
if(!isTsdbDbExist(connParam))
if(!isTsdbDbExist(dbName,"127.0.0.1"))
return false; return false;
m_pExportProc->terminate(); m_pExportProc->terminate();
m_pExportProc->kill(); m_pExportProc->kill();
QString program = "influx_inspect"; QString program;
QStringList arguments; QStringList arguments;
arguments << "export" << "-compress" << "-database" << dbName ;
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
program = "influx_inspect";
QString influxdb_home = qgetenv("INFLUXDB_HOME"); QString influxdb_home = qgetenv("INFLUXDB_HOME");
arguments << "export" << "-compress" << "-database" << connParam.strDbName.c_str() ;
arguments << QString() + "-datadir=" + influxdb_home + "influxdb_data\\data"; arguments << QString() + "-datadir=" + influxdb_home + "influxdb_data\\data";
arguments << QString() + "-waldir=" + influxdb_home + "influxdb_data\\wal"; arguments << QString() + "-waldir=" + influxdb_home + "influxdb_data\\wal";
#endif #endif
#ifdef OS_LINUX #ifdef OS_LINUX
program = "pkexec";
arguments << "influx_inspect";
arguments << "export" << "-compress" << "-database" << connParam.strDbName.c_str() ;
arguments << "-datadir=/var/lib/influxdb/data"; arguments << "-datadir=/var/lib/influxdb/data";
arguments << "-waldir=/var/lib/influxdb/wal"; arguments << "-waldir=/var/lib/influxdb/wal";
#endif #endif
@ -334,11 +356,13 @@ bool iot_dbms::CHisMngApiImp::exportTsdbByInspect(const QString &dbName, const Q
while(!m_pExportProc->waitForFinished(1)) while(!m_pExportProc->waitForFinished(1))
{ {
QProcess::ProcessError error = m_pExportProc->error();
QCoreApplication::processEvents(QEventLoop::AllEvents,100); QCoreApplication::processEvents(QEventLoop::AllEvents,100);
if(is_stop) if(is_stop || (error != QProcess::UnknownError && error != QProcess::Timedout))
{ {
is_stop = false; is_stop = false;
logStatus(tr("停止转储")); logStatus(tr("停止转储"));
logError("Export failed: " + m_pExportProc->errorString());
m_pExportProc->terminate(); m_pExportProc->terminate();
m_pExportProc->kill(); m_pExportProc->kill();
return false; return false;
@ -362,7 +386,7 @@ void iot_dbms::CHisMngApiImp::slotBackupProgressHandler()
} }
else if(result.contains("backup failed: EOF")) else if(result.contains("backup failed: EOF"))
{ {
logError(tr("备份历史数据失败,检查iscs6000是否正确配置")); logError(tr("备份历史数据失败,检查数据库是否正确配置"));
m_pExportProc->kill(); m_pExportProc->kill();
} }
else if(result.contains("Download shard 0 failed")) else if(result.contains("Download shard 0 failed"))
@ -393,9 +417,9 @@ void iot_dbms::CHisMngApiImp::slotBackupFinishedHandler(int exitCode, QProcess::
// logStatus(tr("导出完成")); // logStatus(tr("导出完成"));
} }
bool iot_dbms::CHisMngApiImp::isTsdbDbExist(const QString &database, const QString &ip) bool iot_dbms::CHisMngApiImp::isTsdbDbExist(const STsdbConnParam &connParam)
{ {
iot_dbms::CTsdbConn db_conn(ip.toStdString().c_str()); iot_dbms::CTsdbConn db_conn(connParam);
if(!db_conn.pingServer()) if(!db_conn.pingServer())
{ {
logError(tr("数据库测试连接失败")); logError(tr("数据库测试连接失败"));
@ -407,7 +431,7 @@ bool iot_dbms::CHisMngApiImp::isTsdbDbExist(const QString &database, const QStri
if(db_conn.doQuery(sql, &result, 1000)) if(db_conn.doQuery(sql, &result, 1000))
{ {
if (result.find(database.toStdString()) != std::string::npos) { if (result.find(connParam.strDbName) != std::string::npos) {
return true; return true;
} }
logError(tr("时序库不存在")); logError(tr("时序库不存在"));
@ -431,6 +455,83 @@ bool iot_dbms::CHisMngApiImp::isLocalhost(const QString &addr)
return false; return false;
} }
bool iot_dbms::CHisMngApiImp::hasDataByPeriod(const STsdbConnParam& connParam,const QString& measurement, qint64 startTime, qint64 endTime,QString& queryErr)
{
QProcess process;
QString delProgram = "influx";
QString sql=QString("SELECT COUNT(*) FROM %1 WHERE time >= %2ms AND time <= %3ms LIMIT 1").arg(measurement).arg(startTime).arg(endTime);
QStringList arguments;
arguments << "-username" << QString::fromStdString(connParam.strUserName)
<< "-password" << QString::fromStdString(connParam.strUserPassword)
<< "-host"
<< QString::fromStdString(connParam.strIP)
<< "-execute"
<< sql
<< QString("-database=")+ QString::fromStdString(connParam.strDbName);
process.start(delProgram, arguments);
if (!process.waitForFinished(-1)) {
QByteArray errorOutput = process.readAllStandardError();
queryErr=QString::fromUtf8(errorOutput);
LOGERROR("exec-influxdb-cleanData-ERR: %s %s err(%s)",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str(),queryErr.toStdString().c_str());
return false;
}
QByteArray standardOutput = process.readAllStandardOutput();
QByteArray errorOutput = process.readAllStandardError();
if(!errorOutput.isEmpty())
{
queryErr=QString::fromUtf8(errorOutput);
LOGERROR("exec-influxdb-cleanData-ERR: %s %s err(%s)",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str(),queryErr.toStdString().c_str());
return false;
}
LOGTRACE("exec-influxdb-cleanData-ifHasData-ok: %s %s",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str());
if(!standardOutput.isEmpty())
{
return true;
}
else
{
return false;
}
}
void iot_dbms::CHisMngApiImp::deleteDataByPeriod(const STsdbConnParam& connParam,const QString& measurement, qint64 startTime, qint64 endTime,QString& queryErr)
{
QProcess process;
QString delProgram = "influx";
QString sql=QString("delete from %1 WHERE time >= %2ms AND time <= %3ms ").arg(measurement).arg(startTime).arg(endTime);
QStringList arguments;
arguments << "-username" << QString::fromStdString(connParam.strUserName)
<< "-password" << QString::fromStdString(connParam.strUserPassword)
<< "-host"
<< QString::fromStdString(connParam.strIP)
<< "-execute"
<< sql
<< QString("-database=")+ QString::fromStdString(connParam.strDbName);
process.start(delProgram, arguments);
if (!process.waitForFinished(-1)) {
QByteArray errorOutput = process.readAllStandardError();
queryErr=QString::fromUtf8(errorOutput);
LOGERROR("exec-influxdb-cleanData-ERR: %s %s err(%s)",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str(),queryErr.toStdString().c_str());
return ;
}
QByteArray standardOutput = process.readAllStandardOutput();
QByteArray errorOutput = process.readAllStandardError();
if(!errorOutput.isEmpty())
{
queryErr=QString::fromUtf8(errorOutput);
LOGERROR("exec-influxdb-deleteData-ERR: %s %s err(%s)",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str(),queryErr.toStdString().c_str());
return ;
}
LOGTRACE("exec-influxdb-deleteData-ok: %s %s",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str());
if(!standardOutput.isEmpty())
{
//正常不应该有标准输出
queryErr=QString::fromUtf8(standardOutput);
LOGERROR("exec-influxdb-deleteData-out: %s %s out(%s)",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str(),queryErr.toStdString().c_str());
return ;
}
}
std::string iot_dbms::CHisMngApiImp::genUrlHisEvent(const QString &ip, const QString &databaseName, qint64 startTime, qint64 endTime) std::string iot_dbms::CHisMngApiImp::genUrlHisEvent(const QString &ip, const QString &databaseName, qint64 startTime, qint64 endTime)
{ {
QString strStartTime = QString::number(startTime); QString strStartTime = QString::number(startTime);
@ -548,6 +649,10 @@ std::string iot_dbms::CHisMngApiImp::genUrlHis(const QString &ip, const QString
bool iot_dbms::CHisMngApiImp::optimizeTable(QSqlDatabase &conn, const QString &tableName) bool iot_dbms::CHisMngApiImp::optimizeTable(QSqlDatabase &conn, const QString &tableName)
{ {
if(!isMySqL(conn))
{
return true;
}
QString sql = "optimize table "+ tableName; QString sql = "optimize table "+ tableName;
return executeSql(conn,sql); return executeSql(conn,sql);
} }
@ -819,7 +924,7 @@ bool iot_dbms::CHisMngApiImp::exportHisEventTsdb(const QString &ip,
rapidjson::Reader reader; rapidjson::Reader reader;
{ {
CChunkedJsonHandler handler(dstFilePath); CChunkedJsonHandler handler(databaseName,dstFilePath);
while(1) while(1)
{ {
if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler)) if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler))
@ -864,7 +969,7 @@ bool iot_dbms::CHisMngApiImp::exportTsdbByQuery(const QString &ip, const QString
rapidjson::Reader reader; rapidjson::Reader reader;
{ {
CChunkedJsonHandler handler(dstFilePath); CChunkedJsonHandler handler(dbName,dstFilePath);
while(1) while(1)
{ {
if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler)) if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler))
@ -896,7 +1001,7 @@ bool iot_dbms::CHisMngApiImp::exportHisData(const QString &ip, const QString &da
rapidjson::Reader reader; rapidjson::Reader reader;
{ {
CChunkedJsonHandler handler(dstFilePath); CChunkedJsonHandler handler(databaseName,dstFilePath);
while(1) while(1)
{ {
if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler)) if(reader.Parse<rapidjson::kParseNumbersAsStringsFlag>(stream,handler))
@ -956,8 +1061,13 @@ bool iot_dbms::CHisMngApiImp::exportHisDump(QSqlDatabase &conn, const QString &d
logStatus("正在导出时序库内容"); logStatus("正在导出时序库内容");
STsdbConnParam connParam; //ip和port不指定则默认本机默认端口8086
connParam.strUserName = tsdbName.toStdString();
connParam.strUserPassword = conn.password().toStdString(); //todo:此处有风险如果QSqlDatabase直接调用的open(user,password)接口,则此函数获取不到密码
connParam.strDbName = tsdbName.toStdString();
//< 历史事件时序库 //< 历史事件时序库
if(!exportTsdbByInspect(tsdbName,tsdbFilePath,1,endTimeStamp)) if(!exportTsdbByInspect(connParam,tsdbFilePath,1,endTimeStamp))
{ {
logError(tr("无法导出时序库内容")); logError(tr("无法导出时序库内容"));
return false; return false;
@ -1033,12 +1143,16 @@ bool iot_dbms::CHisMngApiImp::exportHisPartV2(QSqlDatabase conn, const QString &
} }
logStatus(tr("关系库历史事件导出完成")); logStatus(tr("关系库历史事件导出完成"));
logStatus(tr("开始导出时序库历史")); logStatus(tr("开始导出时序库历史"));
if( isLocalhost(ip) ) if( isLocalhost(ip) )
{ {
// 本地接口导出 // 本地接口导出
if(!exportTsdbByInspect(tsdbDbName,tsdbFilePath,starttime,endtime)) STsdbConnParam connParam; //ip和port不指定则默认本机默认端口8086
connParam.strUserName = conn.databaseName().toStdString();
connParam.strUserPassword = conn.password().toStdString(); //todo:此处有风险如果QSqlDatabase直接调用的open(user,password)接口,则此函数获取不到密码
connParam.strDbName = conn.databaseName().toStdString();
if(!exportTsdbByInspect(connParam,tsdbFilePath,starttime,endtime))
{ {
logError(tr("导出时序库历史错误")); logError(tr("导出时序库历史错误"));
return false; return false;
@ -1081,7 +1195,7 @@ bool iot_dbms::CHisMngApiImp::importHisPart(QSqlDatabase &conn,
//< 导入时序库历史事件 //< 导入时序库历史事件
logStatus(tr("开始导入时序库历史事件")); logStatus(tr("开始导入时序库历史事件"));
if(!importTsdbSQL(ip,tsdbDbName,tsdbEventFilePath,true)) if(!importTsdbSQL(ip,tsdbDbName,conn.password(),tsdbDbName,tsdbEventFilePath,true))
{ {
logError(tr("导出时序库历史事件错误")); logError(tr("导出时序库历史事件错误"));
return false; return false;
@ -1094,7 +1208,7 @@ bool iot_dbms::CHisMngApiImp::importHisPart(QSqlDatabase &conn,
{ {
//< 导入时序库采样数据 //< 导入时序库采样数据
logStatus(tr("开始导入时序库采样数据")); logStatus(tr("开始导入时序库采样数据"));
if(!importTsdbSQL(ip,tsdbDbName,tsdbDataFilePath,true)) if(!importTsdbSQL(ip,tsdbDbName,conn.password(),tsdbDbName,tsdbDataFilePath,true))
{ {
logError(tr("导入时序库采样数据错误")); logError(tr("导入时序库采样数据错误"));
return false; return false;
@ -1117,7 +1231,7 @@ bool iot_dbms::CHisMngApiImp::importHisPartV2(QSqlDatabase conn, const QString &
//< 导入时序库采样数据 //< 导入时序库采样数据
logStatus(tr("开始导入时序库采样数据")); logStatus(tr("开始导入时序库采样数据"));
if(!importTsdbSQL(ip,tsdbDbName,tsdbFilePath,false)) if(!importTsdbSQL(ip,tsdbDbName,conn.password(),tsdbDbName,tsdbFilePath,false))
{ {
logError(tr("导入时序库数据错误")); logError(tr("导入时序库数据错误"));
return false; return false;
@ -1126,19 +1240,44 @@ bool iot_dbms::CHisMngApiImp::importHisPartV2(QSqlDatabase conn, const QString &
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::delHisTsdb(const QString &ip, const QString &databaseName, qint64 endTimeStamp) bool iot_dbms::CHisMngApiImp::delHisTsdb(const QString &ip,const QString &userName, const QString &password, const QString &databaseName, qint64 endTimeStamp)
{ {
QString delProgram("influx"); STsdbConnParam connParam;
connParam.strIP = ip.toStdString();
connParam.strUserName = userName.toStdString();
connParam.strUserPassword = password.toStdString();
connParam.strDbName = databaseName.toStdString();
int result = 0;
if(isTsdbDbExist(connParam))
{
QString delProgram("influx");
// example influx -execute "DELETE WHERE time < '2016-01-01'" -database="xxx"
QStringList arguments;
QString sql = "DELETE WHERE time < " + QString::number(endTimeStamp) +"ms";
/* 为以后搜索方便,保留此注释
* arguments << "-username" << EMS_DEFAULT_DATABASE
* << "-password" << EMS_DEFAULT_PASSWD
* << "-host"
* << ip
* << "-execute"
* << sql
* << QString("-database=")+ databaseName;
*/
arguments << "-username" << userName
<< "-password" << password
<< "-host"
<< ip
<< "-execute"
<< sql
<< QString("-database=")+ databaseName;
result = QProcess::execute(delProgram,arguments);
LOGINFO("执行清理时序数据: %s %s",delProgram.toStdString().c_str(),arguments.join(" ").toStdString().c_str());
}
// example influx -execute "DELETE WHERE time < '2016-01-01'" -database="iscs6000"
QStringList arguments;
QString sql = "DELETE WHERE time < " + QString::number(endTimeStamp) +"ms";
arguments << "-host"
<< ip
<< "-execute"
<< sql
<< QString("-database=")+ databaseName;
int result = QProcess::execute(delProgram,arguments);
if( 0 == result) if( 0 == result)
{ {
//< to-do //< to-do
@ -1163,6 +1302,110 @@ bool iot_dbms::CHisMngApiImp::delHisTsdb(const QString &ip, const QString &datab
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::delHisTsdbV2(const QString &ip, const QString &userName, const QString &password, const QString &databaseName, qint64 endTimeStamp)
{
STsdbConnParam connParam;
connParam.strIP = ip.toStdString();
connParam.strUserName = userName.toStdString();
connParam.strUserPassword = password.toStdString();
connParam.strDbName = databaseName.toStdString();
QDateTime endDateTime = QDateTime::fromMSecsSinceEpoch(endTimeStamp);
bool handlResult=true;
QString queryErr="";
QStringList tableNames;
tableNames<<"acc_sample_result";
tableNames<<"ai_sample_result";
tableNames<<"di_sample_result";
tableNames<<"his_event_point";
for(int i = 0; i < tableNames.size(); ++i)
{
QString currentTable=tableNames[i];
QDateTime startDeleteTime;
bool hasDeleteStartTime=false;
//按月跨度找到第一个月有数据的时间即使找到1970也才655次循环
for(int i=0;i<700;++i)
{
QDateTime endTime=endDateTime.addMonths(-i);
QDateTime startTime=endDateTime.addMonths(-i-1);
if(!hasDataByPeriod(connParam,currentTable,startTime.toMSecsSinceEpoch(),endTime.toMSecsSinceEpoch(),queryErr)&&(queryErr.isEmpty()))
{
startDeleteTime=endTime;
hasDeleteStartTime=true;
LOGINFO("delHisTsdbV2 %s get startDeleteTime: %s ",currentTable.toStdString().c_str(),startDeleteTime.toString(Qt::ISODate).toStdString().c_str());
break;
}
if(!queryErr.isEmpty())
{
LOGERROR("deleteDataByPeriod-queryStart-err %s start(%s) end(%s) ",currentTable.toStdString().c_str(),startTime.toString(Qt::ISODate).toStdString().c_str(),endTime.toString(Qt::ISODate).toStdString().c_str());
return false;
}
}
//按天跨度删除数据
if(hasDeleteStartTime)
{
int daysDifference = qAbs(endDateTime.daysTo(startDeleteTime));
for(int i=0;i<daysDifference;++i)
{
QDateTime endTime=endDateTime.addDays(-i);
QDateTime startTime=endDateTime.addDays(-i-1);
deleteDataByPeriod(connParam,currentTable,startTime.toMSecsSinceEpoch(),endTime.toMSecsSinceEpoch(),queryErr);
if(!queryErr.isEmpty())
{
LOGERROR("deleteDataByPeriod-err %s start(%s) end(%s) ",currentTable.toStdString().c_str(),startTime.toString(Qt::ISODate).toStdString().c_str(),endTime.toString(Qt::ISODate).toStdString().c_str());
queryErr="";
handlResult=false;
}
}
//当天的删除
if(0==daysDifference)
{
QDateTime endTime=endDateTime;
QDateTime startTime=endDateTime.addDays(-1);
deleteDataByPeriod(connParam,currentTable,startTime.toMSecsSinceEpoch(),endTime.toMSecsSinceEpoch(),queryErr);
if(!queryErr.isEmpty())
{
LOGERROR("deleteDataByPeriod-err %s start(%s) end(%s) ",currentTable.toStdString().c_str(),startTime.toString(Qt::ISODate).toStdString().c_str(),endTime.toString(Qt::ISODate).toStdString().c_str());
queryErr="";
handlResult=false;
}
}
}
else
{
LOGINFO("delHisTsdbV2 %s not find startDeleteTime before %s ",currentTable.toStdString().c_str(),endDateTime.toString(Qt::ISODate).toStdString().c_str());
}
}
if( handlResult)
{
//< to-do
// 清除统计缓存
std::string curDir = iot_public::CFileUtil::getCurModuleDir();
QDir dir(curDir.c_str());
dir.cdUp();
dir.cdUp();
if(dir.cd("data"))
{
if(dir.cd("stat_server"))
{
dir.removeRecursively();
}
}
}
if(handlResult)
{
LOGINFO("Tsdb-clean-ok: %s %s",databaseName.toStdString().c_str(),tableNames.join(" ").toStdString().c_str());
}
return handlResult;
}
bool iot_dbms::CHisMngApiImp::delHisEventDb(QSqlDatabase &conn, qint64 endTimeStamp) bool iot_dbms::CHisMngApiImp::delHisEventDb(QSqlDatabase &conn, qint64 endTimeStamp)
{ {
std::vector<std::string> tables = getHisEventTables(); std::vector<std::string> tables = getHisEventTables();
@ -1171,14 +1414,21 @@ bool iot_dbms::CHisMngApiImp::delHisEventDb(QSqlDatabase &conn, qint64 endTimeSt
{ {
if(!trashMysqlTableByPartition(conn,tables[i].c_str(),endTimeStamp)) if(!trashMysqlTableByPartition(conn,tables[i].c_str(),endTimeStamp))
{ {
return false; logError(tr("通过分区删除") + tables[i].c_str() + tr("旧数据失败") );
} }
if(!trashTableByTimestamp(conn,tables[i].c_str(),endTimeStamp)) if(!trashTableByTimestamp(conn,tables[i].c_str(),endTimeStamp))
{ {
logError(tr("通过时间删除") + tables[i].c_str() + tr("旧数据失败") );
}
if(!optimizeTable(conn,tables[i].c_str())) //极端情况下优化表空间
{
logError(tr("优化") + tables[i].c_str() + tr("表空间失败") );
logError(tr("删除") + tables[i].c_str() + tr("旧数据失败") ); logError(tr("删除") + tables[i].c_str() + tr("旧数据失败") );
return false; return false;
} }
logStatus(tr("删除") + tables[i].c_str() + tr("旧数据成功")); logStatus(tr("删除") + tables[i].c_str() + tr("旧数据成功"));
} }
return true; return true;
@ -1192,7 +1442,8 @@ bool iot_dbms::CHisMngApiImp::delHis(QSqlDatabase &conn, const QString &ip, cons
return false; return false;
} }
if(!delHisTsdb(ip,databaseName,endTimeStamp)) //时序库暂用了数据库同样的用户名密码
if(!delHisTsdb(ip,conn.databaseName(),conn.password(),databaseName,endTimeStamp))
{ {
logError(tr("清空时序库失败")); logError(tr("清空时序库失败"));
return false; return false;
@ -1201,6 +1452,23 @@ bool iot_dbms::CHisMngApiImp::delHis(QSqlDatabase &conn, const QString &ip, cons
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::delHisV2(QSqlDatabase &conn, const QString &ip, const QString &databaseName, qint64 endTimeStamp)
{
if(!delHisEventDb(conn,endTimeStamp))
{
logError(tr("清空关系库历史事件失败"));
return false;
}
//时序库暂用了数据库同样的用户名密码
if(!delHisTsdbV2(ip,conn.databaseName(),conn.password(),databaseName,endTimeStamp))
{
logError(tr("清空时序库失败"));
return false;
}
logStatus(tr("清空时序库成功"));
return true;
}
bool iot_dbms::CHisMngApiImp::delHisAll(QSqlDatabase &conn, const QString &ip, const QString &databaseName) bool iot_dbms::CHisMngApiImp::delHisAll(QSqlDatabase &conn, const QString &ip, const QString &databaseName)
{ {
@ -1210,7 +1478,26 @@ bool iot_dbms::CHisMngApiImp::delHisAll(QSqlDatabase &conn, const QString &ip, c
return false; return false;
} }
if(!delHisTsdb(ip,databaseName,QDateTime::currentMSecsSinceEpoch())) //时序库暂用了数据库同样的用户名密码
if(!delHisTsdb(ip,conn.databaseName(),conn.password(),databaseName,QDateTime::currentMSecsSinceEpoch()))
{
logError(tr("清空时序库失败"));
return false;
}
logStatus(tr("清空时序库成功"));
return true;
}
bool iot_dbms::CHisMngApiImp::delHisAllV2(QSqlDatabase &conn, const QString &ip, const QString &databaseName)
{
if(!delHisDbAll(conn))
{
logError(tr("清空关系库历史事件失败"));
return false;
}
//时序库暂用了数据库同样的用户名密码
if(!delHisTsdbV2(ip,conn.databaseName(),conn.password(),databaseName,QDateTime::currentMSecsSinceEpoch()))
{ {
logError(tr("清空时序库失败")); logError(tr("清空时序库失败"));
return false; return false;
@ -1235,18 +1522,18 @@ bool iot_dbms::CHisMngApiImp::delHisDbAll(QSqlDatabase &conn)
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::importTsdbBin(const QString &ip, const QString &databaseName, const QString &srcDirPath) bool iot_dbms::CHisMngApiImp::importTsdbBin(const STsdbConnParam &connParam, const QString &srcDirPath)
{ {
if( ip.isEmpty() || databaseName.isEmpty() || srcDirPath.isEmpty()) if(connParam.strIP.empty() || connParam.strDbName.empty() || srcDirPath.isEmpty())
return false; return false;
// 检查路径权限 读权限 // 检查路径权限 读权限
QFileInfo fi(srcDirPath); // QFileInfo fi(srcDirPath);
if (fi.permission(QFile::ReadUser) == false) // if (fi.permission(QFile::ReadUser) == false)
{ // {
logError(tr("无法对目录") + srcDirPath + tr("进行读操作,请检查操作用户权限,备份失败")); // logError(tr("无法对目录") + srcDirPath + tr("进行读操作,请检查操作用户权限,备份失败"));
return false; // return false;
} // }
if(iot_dbms::initTsdbApi() == false) if(iot_dbms::initTsdbApi() == false)
{ {
@ -1256,7 +1543,7 @@ bool iot_dbms::CHisMngApiImp::importTsdbBin(const QString &ip, const QString &da
// 连接influxdb,delete and create database // 连接influxdb,delete and create database
{ {
iot_dbms::CTsdbConn db_conn(ip.toStdString().c_str()); iot_dbms::CTsdbConn db_conn(connParam);
if(db_conn.pingServer() == false) if(db_conn.pingServer() == false)
{ {
logError(tr("数据库连接失败")); logError(tr("数据库连接失败"));
@ -1264,9 +1551,9 @@ bool iot_dbms::CHisMngApiImp::importTsdbBin(const QString &ip, const QString &da
} }
// 1. 删除数据库 // 1. 删除数据库
if(db_conn.deleteDatabase(databaseName.toStdString().c_str()) == false) if(db_conn.deleteDatabase(connParam.strDbName.c_str()) == false)
{ {
logError(tr("无法删除influxDB数据库:")+ databaseName); logError(tr("无法删除influxDB数据库:")+ QString(connParam.strDbName.c_str()));
return false; return false;
} }
} }
@ -1281,48 +1568,75 @@ bool iot_dbms::CHisMngApiImp::importTsdbBin(const QString &ip, const QString &da
// 2.导入备份 // 2.导入备份
QString program = "influxd"; QString program = "influxd";
QStringList arguments; QStringList arguments;
arguments << "restore" << "-host" << ip+":8088" << "-portable" << "-db" << databaseName << srcDirPath;
#ifdef OS_LINUX
program = "pkexec"; //提升权限
arguments << "influxd";
#endif
arguments << "restore" << "-host" << (connParam.strIP + ":8088").c_str() << "-portable" << "-db" << connParam.strDbName.c_str() << srcDirPath;
LOGINFO("arguments is [%s]",arguments.join(" ").toStdString().c_str());
//开始导入备份进程 //开始导入备份进程
m_pImportProc->start(program,arguments); m_pImportProc->start(program,arguments);
if(!m_pImportProc->waitForFinished(-1)) if(!m_pImportProc->waitForFinished(-1))
{ {
//todo 解决错误 QString errorLog = m_pImportProc->errorString();
logError("import failed! errorlog: " + errorLog );
return false; return false;
} }
return true; return true;
} }
bool iot_dbms::CHisMngApiImp::importTsdbSQL(const QString &ip, const QString &databaseName, const QString &srcFilePath, bool isPrecisionMs) bool iot_dbms::CHisMngApiImp::importTsdbSQL(const QString &ip,const QString &userName, const QString &password, const QString &databaseName, const QString &srcFilePath, bool isPrecisionMs)
{ {
if( ip.isEmpty() || databaseName.isEmpty() || srcFilePath.isEmpty()) if( ip.isEmpty() || userName.isEmpty() || password.isEmpty() || databaseName.isEmpty() || srcFilePath.isEmpty())
return false; return false;
// 检查路径权限 读权限 // 检查路径权限 读权限
QFileInfo fi(srcFilePath); // QFileInfo fi(srcFilePath);
if (fi.permission(QFile::ReadUser) == false) // if (fi.permission(QFile::ReadUser) == false)
{ // {
logError(tr("无法对目录") + srcFilePath + tr("进行读操作,请检查操作用户权限,备份失败")); // logError(tr("无法对目录") + srcFilePath + tr("进行读操作,请检查操作用户权限,备份失败"));
return false; // return false;
} // }
QString program = "influx";
QString program;
QStringList arguments; QStringList arguments;
#ifdef OS_WINDOWS
program = "influx";
#endif
#ifdef OS_LINUX
program = "pkexec"; //提升权限
arguments << "influx";
#endif
//< 导出实例influx -import -host 192.168.77.200 -compressed -path=export.txt.gz -precision=ms //< 导出实例influx -import -host 192.168.77.200 -compressed -path=export.txt.gz -precision=ms
QString tmpPath = QString("-path=") + srcFilePath; QString tmpPath = QString("-path=") + srcFilePath;
arguments << "-import" << "-host" << ip << "-compressed";
/* 为以后搜索方便,保留此注释
* arguments << "-username" << EMS_DEFAULT_DATABASE
* << "-password" << EMS_DEFAULT_PASSWD
* << "-import" << "-host" << ip << "-compressed";
*/
arguments << "-username" << userName
<< "-password" << password
<< "-import" << "-host" << ip << "-compressed";
if(isPrecisionMs) if(isPrecisionMs)
arguments << "-precision=ms"; arguments << "-precision=ms";
arguments << tmpPath; arguments << tmpPath;
LOGINFO("arguments is [%s]",arguments.join(" ").toStdString().c_str());
//开始导入备份进程 //开始导入备份进程
m_pImportProc->start(program,arguments); m_pImportProc->start(program,arguments);
if(!m_pImportProc->waitForFinished(-1)) if(!m_pImportProc->waitForFinished(-1))
{ {
//todo 解决错误 QString errorLog = m_pImportProc->errorString();
logError("import failed! errorlog: " + errorLog );
return false; return false;
} }
return true; return true;
@ -1420,7 +1734,13 @@ bool iot_dbms::CHisMngApiImp::importHis(QSqlDatabase &conn, const QString &srcFi
} }
logStatus(tr("导入历史记录备份成功")); logStatus(tr("导入历史记录备份成功"));
if(!importTsdbBin(ip,databaseName,srcDirPath)) STsdbConnParam connParam; //ip和port不指定则默认本机默认端口8086
connParam.strIP = ip.toStdString();
connParam.strUserName = databaseName.toStdString();
connParam.strUserPassword = conn.password().toStdString(); //todo:此处有风险如果QSqlDatabase直接调用的open(user,password)接口,则此函数获取不到密码
connParam.strDbName = databaseName.toStdString();
if(!importTsdbBin(connParam,srcDirPath))
{ {
logError(tr("导入采样数据备份失败")); logError(tr("导入采样数据备份失败"));
return false; return false;
@ -1444,7 +1764,7 @@ bool iot_dbms::CHisMngApiImp::importHisDump(QSqlDatabase &conn,
logStatus(tr("导入历史事件备份成功")); logStatus(tr("导入历史事件备份成功"));
logStatus(tr("开始导入采样数据备份")); logStatus(tr("开始导入采样数据备份"));
if(!importTsdbSQL(ip,databaseName,tsdbFilePath,false)) if(!importTsdbSQL(ip,databaseName,conn.password(),databaseName,tsdbFilePath,false))
{ {
logError(tr("导入采样数据备份失败")); logError(tr("导入采样数据备份失败"));
return false; return false;

View File

@ -5,6 +5,7 @@
#include <QSqlDatabase> #include <QSqlDatabase>
#include <QTextStream> #include <QTextStream>
#include <QProcess> #include <QProcess>
#include "tsdb_api/CTsdbConn.h"
namespace iot_dbms { namespace iot_dbms {
@ -125,8 +126,10 @@ public:
* @param endTimeStamp * @param endTimeStamp
* @return * @return
*/ */
bool delHisTsdb(const QString &ip,const QString &databaseName,qint64 endTimeStamp); bool delHisTsdb(const QString &ip,const QString &userName, const QString &password,const QString &databaseName,qint64 endTimeStamp);
bool delHisTsdbV2(const QString &ip,const QString &userName, const QString &password,const QString &databaseName,qint64 endTimeStamp);
/** /**
* @brief delHisEventDb * @brief delHisEventDb
* @param conn * @param conn
@ -144,7 +147,15 @@ public:
* @return * @return
*/ */
bool delHis(QSqlDatabase& conn,const QString &ip,const QString &databaseName,qint64 endTimeStamp); bool delHis(QSqlDatabase& conn,const QString &ip,const QString &databaseName,qint64 endTimeStamp);
/**
* @brief delHis ()
* @param conn
* @param ip
* @param databaseName
* @param endTimeStamp
* @return
*/
bool delHisV2(QSqlDatabase& conn,const QString &ip,const QString &databaseName,qint64 endTimeStamp);
/** /**
* @brief delHisAll * @brief delHisAll
* @param conn * @param conn
@ -154,6 +165,15 @@ public:
*/ */
bool delHisAll(QSqlDatabase& conn,const QString &ip,const QString &databaseName); bool delHisAll(QSqlDatabase& conn,const QString &ip,const QString &databaseName);
/**
* @brief delHisAll ()
* @param conn
* @param ip
* @param databaseName
* @return
*/
bool delHisAllV2(QSqlDatabase& conn,const QString &ip,const QString &databaseName);
/** /**
* @brief delHisDbAll * @brief delHisDbAll
* @param conn * @param conn
@ -164,10 +184,10 @@ public:
//< import 部分 //< import 部分
//< import tsdb bin influxd restore //< import tsdb bin influxd restore
bool importTsdbBin(const QString &ip, const QString &databaseName,const QString & srcDirPath); bool importTsdbBin(const STsdbConnParam &connParam,const QString & srcDirPath);
//< import tsdb sql influx -import -compressed //< import tsdb sql influx -import -compressed
bool importTsdbSQL(const QString &ip, const QString &databaseName,const QString & srcFilePath,bool isPrecisionMs); bool importTsdbSQL(const QString &ip,const QString &userName, const QString &password, const QString &databaseName,const QString & srcFilePath,bool isPrecisionMs);
//< import db sql 执行sql文件 //< import db sql 执行sql文件
bool importDbSQL(QSqlDatabase &conn, const QString &srcFilePath); bool importDbSQL(QSqlDatabase &conn, const QString &srcFilePath);
@ -228,7 +248,7 @@ private:
bool exportTables(QSqlDatabase &conn, qint64 startTimeStamp, qint64 endTimeStamp, const std::string &tableName, QTextStream &textStream); bool exportTables(QSqlDatabase &conn, qint64 startTimeStamp, qint64 endTimeStamp, const std::string &tableName, QTextStream &textStream);
bool exportTsdbBin(const QString &ip, const QString & dbName,const QString &dirPath,qint64 startTime = 0,qint64 endTime = 0); bool exportTsdbBin(const QString &ip, const QString & dbName,const QString &dirPath,qint64 startTime = 0,qint64 endTime = 0);
bool exportTsdbByInspect(const QString & dbName, const QString & dstFilePath, qint64 startTime,qint64 endTime); bool exportTsdbByInspect(const STsdbConnParam &connParam, const QString & dstFilePath, qint64 startTime,qint64 endTime);
std::string genUrlHisEvent(const QString &ip, const QString &databaseName,qint64 startTime,qint64 endTime); std::string genUrlHisEvent(const QString &ip, const QString &databaseName,qint64 startTime,qint64 endTime);
std::string genUrlHisData(const QString &ip,const QString &databaseName,qint64 startTime,qint64 endTime,const std::vector<std::string> &vecTables); std::string genUrlHisData(const QString &ip,const QString &databaseName,qint64 startTime,qint64 endTime,const std::vector<std::string> &vecTables);
std::string genUrlHis(const QString &ip,const QString &databaseName,qint64 startTime,qint64 endTime); std::string genUrlHis(const QString &ip,const QString &databaseName,qint64 startTime,qint64 endTime);
@ -251,12 +271,13 @@ private slots:
void slotBackupFinishedHandler(int exitCode, QProcess::ExitStatus exitStatus); void slotBackupFinishedHandler(int exitCode, QProcess::ExitStatus exitStatus);
private: private:
bool isTsdbDbExist(const QString & database, const QString &ip); bool isTsdbDbExist(const STsdbConnParam &connParam);
bool isLocalhost(const QString& addr); bool isLocalhost(const QString& addr);
bool is_stop = false; bool is_stop = false;
bool hasDataByPeriod(const STsdbConnParam& connParam,const QString& measurement,qint64 startTime,const qint64 endTime,QString& queryErr);
void deleteDataByPeriod(const STsdbConnParam& connParam,const QString& measurement,qint64 startTime,qint64 endTime,QString& queryErr);
}; };
} //< namespace iot_dbms; } //< namespace iot_dbms;

View File

@ -4,37 +4,39 @@
<context> <context>
<name>QObject</name> <name>QObject</name>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="122"/> <location filename="CHisMngApiImp.cpp" line="165"/>
<source></source> <source></source>
<translation>Database connection not open</translation> <translation>Database connection not open</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="131"/> <location filename="CHisMngApiImp.cpp" line="176"/>
<location filename="CHisMngApiImp.cpp" line="184"/>
<source></source> <source></source>
<translation>Get the table</translation> <translation>Get the table</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="131"/> <location filename="CHisMngApiImp.cpp" line="176"/>
<location filename="CHisMngApiImp.cpp" line="184"/>
<source></source> <source></source>
<translation>Column information failed</translation> <translation>Column information failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="151"/> <location filename="CHisMngApiImp.cpp" line="205"/>
<source></source> <source></source>
<translation>The table could not be querien</translation> <translation>The table could not be queried</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="575"/> <location filename="CHisMngApiImp.cpp" line="759"/>
<source></source> <source></source>
<translation>Start backing up the table:</translation> <translation>Start backing up the table:</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="578"/> <location filename="CHisMngApiImp.cpp" line="762"/>
<source>:</source> <source>:</source>
<translation>The table could not be backed up:</translation> <translation>The table could not be backed up:</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="581"/> <location filename="CHisMngApiImp.cpp" line="765"/>
<source></source> <source></source>
<translation>Complete the backup table:</translation> <translation>Complete the backup table:</translation>
</message> </message>
@ -42,7 +44,7 @@
<context> <context>
<name>iot_dbms::CHisMngApi</name> <name>iot_dbms::CHisMngApi</name>
<message> <message>
<location filename="CHisMngApi.cpp" line="190"/> <location filename="CHisMngApi.cpp" line="133"/>
<source></source> <source></source>
<translation>Start dump</translation> <translation>Start dump</translation>
</message> </message>
@ -50,347 +52,430 @@
<context> <context>
<name>iot_dbms::CHisMngApiImp</name> <name>iot_dbms::CHisMngApiImp</name>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="151"/>
<source></source> <source></source>
<translation>Number of columns</translation> <translation type="vanished">Number of columns</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="196"/> <location filename="CHisMngApiImp.cpp" line="253"/>
<source></source> <source></source>
<translation>Error, unprocessed data type:</translation> <translation>Error, unprocessed data type:</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="271"/> <location filename="CHisMngApiImp.cpp" line="360"/>
<source>,</source> <source>,</source>
<oldsource></oldsource>
<translation>The server backup service is not turned on, please configure</translation> <translation>The server backup service is not turned on, please configure</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="276"/> <location filename="CHisMngApiImp.cpp" line="365"/>
<source>,iscs6000是否正确配置</source> <source>,</source>
<translation>Failed to back up historical data to check that iscs6000 is configured correctly</translation> <oldsource>,iscs6000是否正确配置</oldsource>
<translation type="unfinished">Failed to back up historical data, please check if rqeh6000 is configured correctly</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="281"/> <location filename="CHisMngApiImp.cpp" line="370"/>
<source>,8088</source> <source>,8088</source>
<translation>Backup history data failed to check if the network is properly connected and if port 8088 of the backup service is on</translation> <oldsource>8088</oldsource>
<translation>Backup history data failed, please check if the network is properly connected and if port 8088 of the backup service is on</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="416"/> <location filename="CHisMngApiImp.cpp" line="589"/>
<location filename="CHisMngApiImp.cpp" line="473"/> <location filename="CHisMngApiImp.cpp" line="646"/>
<source></source> <source></source>
<translation>The database cannot be connected</translation> <translation>The database cannot be connected</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="459"/> <location filename="CHisMngApiImp.cpp" line="632"/>
<location filename="CHisMngApiImp.cpp" line="461"/> <location filename="CHisMngApiImp.cpp" line="634"/>
<source></source> <source></source>
<translation>Table</translation> <translation>Table</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="459"/> <location filename="CHisMngApiImp.cpp" line="632"/>
<location filename="CHisMngApiImp.cpp" line="461"/> <location filename="CHisMngApiImp.cpp" line="634"/>
<source></source> <source></source>
<translation>Delete a partition</translation> <translation>Delete a partition</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="459"/> <location filename="CHisMngApiImp.cpp" line="632"/>
<location filename="CHisMngApiImp.cpp" line="1003"/> <location filename="CHisMngApiImp.cpp" line="1278"/>
<location filename="CHisMngApiImp.cpp" line="1244"/> <location filename="CHisMngApiImp.cpp" line="1527"/>
<source></source> <source></source>
<translation>Failed</translation> <translation>Failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="461"/> <location filename="CHisMngApiImp.cpp" line="634"/>
<source></source> <source></source>
<translation>Success</translation> <translation>Success</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="585"/> <location filename="CHisMngApiImp.cpp" line="769"/>
<source></source> <source></source>
<translation>Path is not writeable</translation> <translation>Path is not writeable</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="600"/> <location filename="CHisMngApiImp.cpp" line="781"/>
<location filename="CHisMngApiImp.cpp" line="617"/>
<location filename="CHisMngApiImp.cpp" line="652"/>
<source></source> <source></source>
<translation>Backup history event error</translation> <translation>Backup history event error</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="671"/> <location filename="CHisMngApiImp.cpp" line="818"/>
<location filename="CHisMngApiImp.cpp" line="728"/> <location filename="CHisMngApiImp.cpp" line="863"/>
<location filename="CHisMngApiImp.cpp" line="895"/>
<source>influxDB</source> <source>influxDB</source>
<translation>Unable to connect to influxDB</translation> <translation>Unable to connect to influxDB</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="778"/> <location filename="CHisMngApiImp.cpp" line="957"/>
<source></source> <source></source>
<translation>The Historical Event Relationship Library cannot be exported</translation> <translation>The Historical Event Relationship Library cannot be exported</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="786"/> <location filename="CHisMngApiImp.cpp" line="971"/>
<source></source> <source></source>
<translation>Time Database was unable to be exported</translation> <translation>Time Database was unable to be exported</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="825"/> <location filename="CHisMngApiImp.cpp" line="1000"/>
<location filename="CHisMngApiImp.cpp" line="1037"/>
<source></source> <source></source>
<translation>Start exporting history events of relation database</translation> <translation>Start exporting history events of relation database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="828"/> <location filename="CHisMngApiImp.cpp" line="1003"/>
<location filename="CHisMngApiImp.cpp" line="1040"/>
<source></source> <source></source>
<translation>cannot export history events of relation database</translation> <translation>cannot export history events of relation database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="831"/> <location filename="CHisMngApiImp.cpp" line="1006"/>
<location filename="CHisMngApiImp.cpp" line="1043"/>
<source></source> <source></source>
<translation>history events of relation history export completed</translation> <translation>history events of relation history export completed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="834"/> <location filename="CHisMngApiImp.cpp" line="1009"/>
<source></source> <source></source>
<translation>Start exporting time-series library history events</translation> <translation>Start exporting time-series library history events</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="837"/> <location filename="CHisMngApiImp.cpp" line="1012"/>
<location filename="CHisMngApiImp.cpp" line="883"/> <location filename="CHisMngApiImp.cpp" line="1099"/>
<source></source> <source></source>
<translation>Export history events of Time-series database failed</translation> <translation>Export history events of Time-series database failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="840"/> <location filename="CHisMngApiImp.cpp" line="1015"/>
<source></source> <source></source>
<translation>Export history events of Time-series database completed</translation> <translation>Export history events of Time-series database completed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="847"/> <location filename="CHisMngApiImp.cpp" line="1022"/>
<source></source> <source></source>
<translation>start export sample points of time-series database</translation> <translation>start export sample points of time-series database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="850"/> <location filename="CHisMngApiImp.cpp" line="1025"/>
<source></source> <source></source>
<translation>Export sample points of time-series database failed</translation> <translation>Export sample points of time-series database failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="853"/> <location filename="CHisMngApiImp.cpp" line="1028"/>
<source></source> <source></source>
<translation>Export sample points of time-series database done</translation> <translation>Export sample points of time-series database done</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="871"/> <location filename="CHisMngApiImp.cpp" line="1087"/>
<location filename="CHisMngApiImp.cpp" line="1123"/>
<source></source> <source></source>
<translation>Start import history events of relation database</translation> <translation>Start import history events of relation database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="874"/> <location filename="CHisMngApiImp.cpp" line="1090"/>
<location filename="CHisMngApiImp.cpp" line="1126"/>
<source></source> <source></source>
<translation>Import history events of relation database failed</translation> <translation>Import history events of relation database failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="877"/> <location filename="CHisMngApiImp.cpp" line="1093"/>
<location filename="CHisMngApiImp.cpp" line="1129"/>
<source></source> <source></source>
<translation>Import history events of relation database done</translation> <translation>Import history events of relation database done</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="880"/> <location filename="CHisMngApiImp.cpp" line="1096"/>
<source></source> <source></source>
<translation>Start import history events of time-series database</translation> <translation>Start import history events of time-series database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="886"/> <location filename="CHisMngApiImp.cpp" line="1102"/>
<source></source> <source></source>
<translation>Import history events of time-series done</translation> <translation>Import history events of time-series done</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="893"/> <location filename="CHisMngApiImp.cpp" line="1109"/>
<location filename="CHisMngApiImp.cpp" line="1132"/>
<source></source> <source></source>
<translation>Import sample points of time-series database</translation> <translation>Import sample points of time-series database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="896"/> <location filename="CHisMngApiImp.cpp" line="1112"/>
<source></source> <source></source>
<translation>Import sample poins of time-series database failed</translation> <translation>Import sample poins of time-series database failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="899"/> <location filename="CHisMngApiImp.cpp" line="1115"/>
<source></source> <source></source>
<translation>Import sample points of time-series database done</translation> <translation>Import sample points of time-series database done</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="947"/> <location filename="CHisMngApiImp.cpp" line="1223"/>
<location filename="CHisMngApiImp.cpp" line="950"/> <location filename="CHisMngApiImp.cpp" line="1227"/>
<source></source> <source></source>
<translation>delete </translation> <translation>delete </translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="947"/> <location filename="CHisMngApiImp.cpp" line="1212"/>
<location filename="CHisMngApiImp.cpp" line="1217"/>
<location filename="CHisMngApiImp.cpp" line="1223"/>
<source></source> <source></source>
<translation>old data failed</translation> <translation>old data failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="950"/> <location filename="CHisMngApiImp.cpp" line="205"/>
<source></source>
<translation>Number of rows</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="274"/>
<location filename="CHisMngApiImp.cpp" line="341"/>
<source></source>
<translation>Stop dump</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="401"/>
<source></source>
<translation>Database test connection failed</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="413"/>
<source></source>
<translation>Time-series database does not exist</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="416"/>
<source></source>
<translation>query db error</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1045"/>
<source></source>
<translation>Start exporting time-series database history</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1056"/>
<location filename="CHisMngApiImp.cpp" line="1066"/>
<source></source>
<translation>Error exporting time-series database history</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1059"/>
<location filename="CHisMngApiImp.cpp" line="1069"/>
<source></source>
<translation>Time-series database history export completed</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1135"/>
<source></source>
<translation>Error importing time-series database data</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1138"/>
<source></source>
<translation>Time-series database data import completed</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1212"/>
<source></source>
<translation>Delete by partition</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1217"/>
<source></source>
<translation>Delete by time</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1222"/>
<source></source>
<translation>Optimize</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1222"/>
<source></source>
<translation>Tablespace failed</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1227"/>
<source></source> <source></source>
<translation>old data successfully</translation> <translation>Old data successfully</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="959"/> <location filename="CHisMngApiImp.cpp" line="1236"/>
<location filename="CHisMngApiImp.cpp" line="977"/> <location filename="CHisMngApiImp.cpp" line="1255"/>
<source></source> <source></source>
<translation>clear history events of relation database failed</translation> <translation>Failed to clear history events of relational database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="965"/> <location filename="CHisMngApiImp.cpp" line="1243"/>
<location filename="CHisMngApiImp.cpp" line="983"/> <location filename="CHisMngApiImp.cpp" line="1262"/>
<source></source> <source></source>
<translation>clear time-series database failed</translation> <translation>Failed to clear time-series database</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="968"/>
<location filename="CHisMngApiImp.cpp" line="986"/>
<source></source>
<translation>clear time-series database done</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1000"/>
<source>truncate</source>
<translation>start truncate table</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1003"/>
<location filename="CHisMngApiImp.cpp" line="1005"/>
<source></source>
<translation>truncate table</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1005"/>
<location filename="CHisMngApiImp.cpp" line="1246"/> <location filename="CHisMngApiImp.cpp" line="1246"/>
<location filename="CHisMngApiImp.cpp" line="1265"/>
<source></source>
<translation>Successfully cleared time-series database</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1275"/>
<source>truncate</source>
<translation>Start truncating table</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1278"/>
<location filename="CHisMngApiImp.cpp" line="1280"/>
<source></source>
<translation>Truncate table</translation>
</message>
<message>
<location filename="CHisMngApiImp.cpp" line="1280"/>
<location filename="CHisMngApiImp.cpp" line="1529"/>
<source></source> <source></source>
<translation>done</translation> <translation>Completed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1019"/> <location filename="CHisMngApiImp.cpp" line="1294"/>
<location filename="CHisMngApiImp.cpp" line="1078"/> <location filename="CHisMngApiImp.cpp" line="1353"/>
<source></source> <source></source>
<translation>Cannot cope with table</translation> <translation>Cannot operate on the directory</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1019"/> <location filename="CHisMngApiImp.cpp" line="1294"/>
<location filename="CHisMngApiImp.cpp" line="1078"/> <location filename="CHisMngApiImp.cpp" line="1353"/>
<source>,,</source> <source>,,</source>
<translation>To read, please check the operation user permissions, the backup failed</translation> <translation>Please check the operation user permissions to perform read operations, backup failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1025"/> <location filename="CHisMngApiImp.cpp" line="1300"/>
<source>influx数据库连接条件,</source> <source>influx数据库连接条件,</source>
<translation>Unable to initialize the influx database connection condition, check that the software dependency is installed correctly</translation> <translation>Unable to initialize the influx database connection condition, check that the software dependency is installed correctly</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1034"/> <location filename="CHisMngApiImp.cpp" line="1309"/>
<source></source> <source></source>
<translation>Database connection failed</translation> <translation>Database connection failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1041"/> <location filename="CHisMngApiImp.cpp" line="1316"/>
<source>influxDB数据库:</source> <source>influxDB数据库:</source>
<translation>The influxDB database could not be deleted:</translation> <translation>The influxDB database could not be deleted:</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1049"/> <location filename="CHisMngApiImp.cpp" line="1324"/>
<source>influx数据库连接资源</source> <source>influx数据库连接资源</source>
<translation>Could not destroy the influx database connection resource</translation> <translation>Could not destroy the influx database connection resource</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1113"/> <location filename="CHisMngApiImp.cpp" line="1394"/>
<source></source> <source></source>
<translation>Start importing data files</translation> <translation>Start importing data files</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1118"/> <location filename="CHisMngApiImp.cpp" line="1399"/>
<source></source> <source></source>
<translation>Failed to open import file</translation> <translation>Failed to open import file</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1160"/> <location filename="CHisMngApiImp.cpp" line="1441"/>
<source></source> <source></source>
<translation>Failed to import history events</translation> <translation>Failed to import history events</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1174"/> <location filename="CHisMngApiImp.cpp" line="1455"/>
<source></source> <source></source>
<translation>Importing done:</translation> <translation>Importing done:</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1187"/> <location filename="CHisMngApiImp.cpp" line="1468"/>
<source></source> <source></source>
<translation>Failed to delete old history</translation> <translation>Failed to delete old history</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1190"/> <location filename="CHisMngApiImp.cpp" line="1471"/>
<source></source> <source></source>
<translation>Removing old history successfully</translation> <translation>Removing old history successfully</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1193"/> <location filename="CHisMngApiImp.cpp" line="1474"/>
<source></source> <source></source>
<translation>Import history backup failed</translation> <translation>Import history backup failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1196"/> <location filename="CHisMngApiImp.cpp" line="1477"/>
<source></source> <source></source>
<translation>Import history backup successful</translation> <translation>Import history backup successful</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1200"/> <location filename="CHisMngApiImp.cpp" line="1487"/>
<location filename="CHisMngApiImp.cpp" line="1224"/> <location filename="CHisMngApiImp.cpp" line="1511"/>
<source></source> <source></source>
<translation>Importing sampledata backup failed</translation> <translation>Importing sampledata backup failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1203"/> <location filename="CHisMngApiImp.cpp" line="1490"/>
<location filename="CHisMngApiImp.cpp" line="1227"/> <location filename="CHisMngApiImp.cpp" line="1514"/>
<source></source> <source></source>
<translation>Import edited data backup successfully</translation> <translation>Import edited data backup successfully</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1213"/> <location filename="CHisMngApiImp.cpp" line="1500"/>
<source></source> <source></source>
<translation>Start importing history events</translation> <translation>Start importing history events</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1216"/> <location filename="CHisMngApiImp.cpp" line="1503"/>
<source></source> <source></source>
<translation>failed to import history events backup</translation> <translation>failed to import history events backup</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1219"/> <location filename="CHisMngApiImp.cpp" line="1506"/>
<source></source> <source></source>
<translation>Import history events backup successfully</translation> <translation>Import history events backup successfully</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1221"/> <location filename="CHisMngApiImp.cpp" line="1508"/>
<source></source> <source></source>
<translation>Start importing sample data backups</translation> <translation>Start importing sample data backups</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1241"/> <location filename="CHisMngApiImp.cpp" line="1524"/>
<source></source> <source></source>
<translation>Start cleaning up the table</translation> <translation>Start cleaning up the table</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1244"/> <location filename="CHisMngApiImp.cpp" line="1527"/>
<location filename="CHisMngApiImp.cpp" line="1246"/> <location filename="CHisMngApiImp.cpp" line="1529"/>
<source></source> <source></source>
<translation>Clean up the table</translation> <translation>Clean up the table</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1255"/> <location filename="CHisMngApiImp.cpp" line="1539"/>
<source></source> <source></source>
<translation>Export history failed</translation> <translation>Export history failed</translation>
</message> </message>
<message> <message>
<location filename="CHisMngApiImp.cpp" line="1261"/> <location filename="CHisMngApiImp.cpp" line="1545"/>
<source></source> <source></source>
<translation>Failed to delete history</translation> <translation>Failed to delete history</translation>
</message> </message>

View File

@ -512,16 +512,6 @@ static void testEventQuery()
static int doTest() static int doTest()
{ {
if (!iot_dbms::initTsdbApi())
{
LOGERROR("initTsdbApi() failed !");
return 1;
}
g_pTsdbConn = new iot_dbms::CTsdbConn("127.0.0.1", 8086, g_pszDbName, "", "");
g_pvecTagName = new std::vector<std::string>;
if (!g_pTsdbConn->pingServer(1000)) if (!g_pTsdbConn->pingServer(1000))
{ {
LOGERROR("pingServer() return false !"); LOGERROR("pingServer() return false !");
@ -563,20 +553,35 @@ int main(/*int argc, char *argv[]*/)
LOGINFO("sizeof(iot_dbms::VarMeasPiontVal) == %lu", sizeof(iot_dbms::VarMeasPiontVal)); LOGINFO("sizeof(iot_dbms::VarMeasPiontVal) == %lu", sizeof(iot_dbms::VarMeasPiontVal));
LOGINFO("sizeof(iot_dbms::SHisSamplePointVar) == %lu", sizeof(iot_dbms::SVarHisSamplePoint)); LOGINFO("sizeof(iot_dbms::SHisSamplePointVar) == %lu", sizeof(iot_dbms::SVarHisSamplePoint));
if (!iot_dbms::initTsdbApi())
nRc = doTest();
delete g_pTsdbConn;
g_pTsdbConn = NULL;
delete g_pvecTagName;
g_pvecTagName = NULL;
if (!iot_dbms::releaseTsdbApi())
{ {
LOGERROR("releaseTsdbApi() failed !"); LOGERROR("initTsdbApi() failed !");
nRc = 1; nRc = 1;
} }
else
{
g_pvecTagName = new std::vector<std::string>;
// g_pTsdbConn = new iot_dbms::CTsdbConn( "127.0.0.1", 8086, g_pszDbName,
// EMS_DEFAULT_DATABASE, EMS_DEFAULT_PASSWD );
auto spTsdbConn = iot_dbms::getOneUseableConn( true );
g_pTsdbConn = spTsdbConn.get();
nRc = doTest();
// delete g_pTsdbConn;
g_pTsdbConn = NULL;
delete g_pvecTagName;
g_pvecTagName = NULL;
if (!iot_dbms::releaseTsdbApi())
{
LOGERROR("releaseTsdbApi() failed !");
nRc = 1;
}
}
//< 停止日志系统 //< 停止日志系统
iot_public::StopLogSystem(); iot_public::StopLogSystem();

View File

@ -69,6 +69,6 @@ bool CHisUtil::isDataExported(const QDomElement &elem)
QString CHisUtil::getBackupType(const QDomElement &eleDbSet) QString CHisUtil::getBackupType(const QDomElement &eleDbSet)
{ {
if(isDump(eleDbSet)) if(isDump(eleDbSet))
return "转储"; return QObject::tr("转储");
return eleDbSet.attribute( "isAll" ) == "1"?QObject::tr("全量备份"):QObject::tr("增量备份"); return eleDbSet.attribute( "isAll" ) == "1"?QObject::tr("全量备份"):QObject::tr("增量备份");
} }

View File

@ -4,7 +4,7 @@
#include <QCheckBox> #include <QCheckBox>
#include <QDir> #include <QDir>
#include <QFileInfo> #include <QFileInfo>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include <QFileDialog> #include <QFileDialog>
#include <public/pub_sysinfo_api/SysInfoApi.h> #include <public/pub_sysinfo_api/SysInfoApi.h>
#include <CExportZipWorker.h> #include <CExportZipWorker.h>
@ -131,7 +131,7 @@ void CLogMngWidget::exportLog()
{ {
if(ui->app->layout()->count() == 0 ) if(ui->app->layout()->count() == 0 )
{ {
QMessageBox::warning(this,tr("提醒"),tr("请先选择导出类型")); N_MessageBox::warning(this,tr("提醒"),tr("请先选择导出类型"));
return; return;
} }

View File

@ -1,6 +1,6 @@
#include "CStationReuseForm.h" #include "CStationReuseForm.h"
#include "ui_CStationReuseForm.h" #include "ui_CStationReuseForm.h"
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include "db_manager_api/db_manager_api.h" #include "db_manager_api/db_manager_api.h"
#include "conndig.h" #include "conndig.h"
#include "common/Common.h" #include "common/Common.h"
@ -75,7 +75,7 @@ void CStationReuseForm::onSetIpPort(QString ip, QString db, db_opt* pDbOpt)
m_pSrcDbOpt = pDbOpt ; m_pSrcDbOpt = pDbOpt ;
ui->comboBoxdataServiceSrv->clear(); ui->comboBoxdataServiceSrv->clear();
ui->comboBoxdataServiceSrv->addItem(m_pSrcDbOpt->getHostName()); ui->comboBoxdataServiceSrv->addItem(m_pSrcDbOpt->getHostName());
ui->comboBoxdataServiceSrv->addItem(("选择厂站复用源数据源 ")); ui->comboBoxdataServiceSrv->addItem((tr("选择厂站复用源数据源 ")));
ui->comboBoxdataBaseSrv->addItems(listDatabase); ui->comboBoxdataBaseSrv->addItems(listDatabase);
ui->comboBoxdataBaseSrv->setCurrentText(strCurDatabase); ui->comboBoxdataBaseSrv->setCurrentText(strCurDatabase);
} }
@ -84,7 +84,7 @@ void CStationReuseForm::onSetIpPort(QString ip, QString db, db_opt* pDbOpt)
m_pDstDbOpt = pDbOpt ; m_pDstDbOpt = pDbOpt ;
ui->comboBoxdataServiceDst->clear(); ui->comboBoxdataServiceDst->clear();
ui->comboBoxdataServiceDst->addItem(m_pDstDbOpt->getHostName()); ui->comboBoxdataServiceDst->addItem(m_pDstDbOpt->getHostName());
ui->comboBoxdataServiceDst->addItem(("选择厂站复用目标数据源 ")); ui->comboBoxdataServiceDst->addItem((tr("选择厂站复用目标数据源 ")));
ui->comboBoxdataBaseDst->addItems(listDatabase); ui->comboBoxdataBaseDst->addItems(listDatabase);
ui->comboBoxdataBaseDst->setCurrentText(strCurDatabase); ui->comboBoxdataBaseDst->setCurrentText(strCurDatabase);
@ -167,11 +167,11 @@ void CStationReuseForm::slotComboBoxDataBaseDstChanged(const QString &sText)
void CStationReuseForm::soltPushButtonReuseClicked() void CStationReuseForm::soltPushButtonReuseClicked()
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, int resultButton = N_MessageBox::information(this,
tr("提示"), tr("请确保源数据库和目标数据库的所有表结构一致,否则会出错!"), tr("提示"), tr("请确保源数据库和目标数据库的所有表结构一致,否则会出错!"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); N_MessageBox::Yes | N_MessageBox::No, N_MessageBox::Yes);
if(resultButton == QMessageBox::No){ return; } if(resultButton == N_MessageBox::No){ return; }
QString sDataServiceSrc = ui->comboBoxdataServiceSrv->currentText(); QString sDataServiceSrc = ui->comboBoxdataServiceSrv->currentText();
QString sDataBaseSrc = ui->comboBoxdataBaseSrv->currentText(); QString sDataBaseSrc = ui->comboBoxdataBaseSrv->currentText();
@ -180,50 +180,50 @@ void CStationReuseForm::soltPushButtonReuseClicked()
if ( sDataServiceSrc == "" ) if ( sDataServiceSrc == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源数据服务 ") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源数据服务 ") );
return; return;
} }
if ( sDataBaseSrc == "" ) if ( sDataBaseSrc == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源数据库 ") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源数据库 ") );
return; return;
} }
if ( sDataServiceDst == "" ) if ( sDataServiceDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标数据服务 ") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标数据服务 ") );
return; return;
} }
if ( sDataBaseDst == "" ) if ( sDataBaseDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标数据库 ") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标数据库 ") );
return; return;
} }
if ( m_pSrcDbOpt == NULL ) if ( m_pSrcDbOpt == NULL )
{ {
QMessageBox::warning( this, tr("警告"), tr("源数据服务未连接 ") ); N_MessageBox::warning( this, tr("警告"), tr("源数据服务未连接 ") );
return; return;
} }
if ( m_pDstDbOpt == NULL ) if ( m_pDstDbOpt == NULL )
{ {
QMessageBox::warning( this, tr("警告"), tr("目标数据服务未连接 ") ); N_MessageBox::warning( this, tr("警告"), tr("目标数据服务未连接 ") );
return; return;
} }
if ( sDataServiceSrc == sDataServiceDst && sDataBaseSrc == sDataBaseDst ) if ( sDataServiceSrc == sDataServiceDst && sDataBaseSrc == sDataBaseDst )
{ {
QMessageBox::warning( this, tr("警告"), tr("源和目标不能相同") ); N_MessageBox::warning( this, tr("警告"), tr("源和目标不能相同") );
return; return;
} }
QString sSubStationSrc = ui->comboBoxStationSrv->currentText(); QString sSubStationSrc = ui->comboBoxStationSrv->currentText();
if ( sSubStationSrc == "" ) if ( sSubStationSrc == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源车站 ") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源车站 ") );
return; return;
} }
QString sSubStationDst = ui->comboBoxStationDst->currentText(); QString sSubStationDst = ui->comboBoxStationDst->currentText();
if ( sSubStationDst == "" ) if ( sSubStationDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标车站") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标车站") );
return; return;
} }

View File

@ -19,7 +19,7 @@ enum dbType
}; };
ConnDig::ConnDig(QWidget *parent) : ConnDig::ConnDig(QWidget *parent) :
QDialog(parent), CustomUiDialog(parent),
ui(new Ui::ConnDig) ui(new Ui::ConnDig)
{ {
ui->setupUi(this); ui->setupUi(this);
@ -29,6 +29,7 @@ ConnDig::ConnDig(QWidget *parent) :
connect(ui->pushButton_cancel, SIGNAL(clicked(bool)), this, SLOT(onCancel())); connect(ui->pushButton_cancel, SIGNAL(clicked(bool)), this, SLOT(onCancel()));
connect(ui->comboBox_type, SIGNAL(currentTextChanged(QString)), this, SLOT(onDbTypeChanged(QString))); connect(ui->comboBox_type, SIGNAL(currentTextChanged(QString)), this, SLOT(onDbTypeChanged(QString)));
setAutoLayout(true);
} }
ConnDig::~ConnDig() ConnDig::~ConnDig()
@ -62,12 +63,12 @@ void ConnDig::initUi()
ui->lineEdit_user->setText(settings.value("login/user","root").toString()); ui->lineEdit_user->setText(settings.value("login/user","root").toString());
ui->lineEdit_pwd->setText(settings.value("login/psw",CN_PASSWD).toString()); ui->lineEdit_pwd->setText(settings.value("login/psw",EMS_DEFAULT_PASSWD).toString());
ui->lineEdit_ip->setText(settings.value("login/ip","127.0.0.1").toString()); ui->lineEdit_ip->setText(settings.value("login/ip","127.0.0.1").toString());
ui->lineEdit_port->setText(settings.value("login/port","3306").toString()); ui->lineEdit_port->setText(settings.value("login/port","3306").toString());
ui->comboBox_type->setCurrentIndex(settings.value("login/type","0").toInt()); ui->comboBox_type->setCurrentIndex(settings.value("login/type","0").toInt());
ui->lineEdit_name->setText(settings.value("login/dbname","iscs6000").toString()); ui->lineEdit_name->setText(settings.value("login/dbname",EMS_DEFAULT_DATABASE).toString());
QRegExp regExp("^[1-9]*[1-9][0-9]*$"); QRegExp regExp("^[1-9]*[1-9][0-9]*$");
@ -87,12 +88,12 @@ void ConnDig::onAccept()
{ {
if(!connectDb()) if(!connectDb())
return; return;
QDialog::accept(); CustomUiDialog::accept();
} }
void ConnDig::onCancel() void ConnDig::onCancel()
{ {
QDialog::reject(); CustomUiDialog::reject();
} }
void ConnDig::onDbTypeChanged(const QString &dbType) void ConnDig::onDbTypeChanged(const QString &dbType)

View File

@ -1,14 +1,14 @@
#ifndef CONNDIG_H #ifndef CONNDIG_H
#define CONNDIG_H #define CONNDIG_H
#include <QDialog> #include "pub_widget/CustomDialog.h"
namespace Ui { namespace Ui {
class ConnDig; class ConnDig;
} }
class db_opt; class db_opt;
class ConnDig : public QDialog class ConnDig : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT

View File

@ -6,206 +6,195 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>350</width> <width>235</width>
<height>338</height> <height>262</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
<string>Dialog</string> <string>Dialog</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0"> <item row="0" column="0">
<layout class="QVBoxLayout" name="verticalLayout"> <layout class="QGridLayout" name="gridLayout">
<item> <item row="0" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_2"> <widget class="QLabel" name="label">
<item> <property name="minimumSize">
<widget class="QLabel" name="label"> <size>
<property name="minimumSize"> <width>80</width>
<size> <height>0</height>
<width>80</width> </size>
<height>0</height> </property>
</size> <property name="maximumSize">
</property> <size>
<property name="maximumSize"> <width>80</width>
<size> <height>16777215</height>
<width>80</width> </size>
<height>16777215</height> </property>
</size> <property name="text">
</property> <string>用户 </string>
<property name="text"> </property>
<string>用户 </string> </widget>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_user">
<property name="text">
<string/>
</property>
<property name="maxLength">
<number>50</number>
</property>
<property name="placeholderText">
<string/>
</property>
</widget>
</item>
</layout>
</item> </item>
<item> <item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_3"> <widget class="QLineEdit" name="lineEdit_user">
<item> <property name="text">
<widget class="QLabel" name="label_2"> <string/>
<property name="minimumSize"> </property>
<size> <property name="maxLength">
<width>80</width> <number>50</number>
<height>0</height> </property>
</size> <property name="placeholderText">
</property> <string/>
<property name="maximumSize"> </property>
<size> </widget>
<width>80</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>密码 </string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_pwd">
<property name="maxLength">
<number>50</number>
</property>
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
</layout>
</item> </item>
<item> <item row="1" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_4"> <widget class="QLabel" name="label_2">
<item> <property name="minimumSize">
<widget class="QLabel" name="label_3"> <size>
<property name="minimumSize"> <width>80</width>
<size> <height>0</height>
<width>80</width> </size>
<height>0</height> </property>
</size> <property name="maximumSize">
</property> <size>
<property name="maximumSize"> <width>80</width>
<size> <height>16777215</height>
<width>80</width> </size>
<height>16777215</height> </property>
</size> <property name="text">
</property> <string>密码 </string>
<property name="text"> </property>
<string>IP地址</string> </widget>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_ip"/>
</item>
</layout>
</item> </item>
<item> <item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_5"> <widget class="QLineEdit" name="lineEdit_pwd">
<item> <property name="maxLength">
<widget class="QLabel" name="label_4"> <number>50</number>
<property name="minimumSize"> </property>
<size> <property name="echoMode">
<width>80</width> <enum>QLineEdit::Password</enum>
<height>0</height> </property>
</size> </widget>
</property>
<property name="maximumSize">
<size>
<width>80</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>端口 </string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_port"/>
</item>
</layout>
</item> </item>
<item> <item row="2" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_6"> <widget class="QLabel" name="label_3">
<item> <property name="minimumSize">
<widget class="QLabel" name="label_5"> <size>
<property name="minimumSize"> <width>80</width>
<size> <height>0</height>
<width>80</width> </size>
<height>0</height> </property>
</size> <property name="maximumSize">
</property> <size>
<property name="maximumSize"> <width>80</width>
<size> <height>16777215</height>
<width>80</width> </size>
<height>16777215</height> </property>
</size> <property name="text">
</property> <string>IP地址</string>
<property name="text"> </property>
<string>数据库类型</string> </widget>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="comboBox_type">
<property name="minimumSize">
<size>
<width>240</width>
<height>40</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>240</width>
<height>40</height>
</size>
</property>
</widget>
</item>
</layout>
</item> </item>
<item> <item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_7"> <widget class="QLineEdit" name="lineEdit_ip"/>
<item> </item>
<widget class="QLabel" name="label_6"> <item row="3" column="0">
<property name="minimumSize"> <widget class="QLabel" name="label_4">
<size> <property name="minimumSize">
<width>80</width> <size>
<height>0</height> <width>80</width>
</size> <height>0</height>
</property> </size>
<property name="maximumSize"> </property>
<size> <property name="maximumSize">
<width>80</width> <size>
<height>16777215</height> <width>80</width>
</size> <height>16777215</height>
</property> </size>
<property name="text"> </property>
<string>数据库名称</string> <property name="text">
</property> <string>端口 </string>
</widget> </property>
</item> </widget>
<item> </item>
<widget class="QLineEdit" name="lineEdit_name"/> <item row="3" column="1">
</item> <widget class="QLineEdit" name="lineEdit_port"/>
</layout> </item>
<item row="4" column="0">
<widget class="QLabel" name="label_5">
<property name="minimumSize">
<size>
<width>80</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>80</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>数据库类型</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QComboBox" name="comboBox_type"/>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_6">
<property name="minimumSize">
<size>
<width>80</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>80</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>数据库名称</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLineEdit" name="lineEdit_name"/>
</item> </item>
</layout> </layout>
</item> </item>
<item row="1" column="0"> <item row="1" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="0">
<layout class="QHBoxLayout" name="horizontalLayout"> <layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item> <item>
<widget class="QPushButton" name="pushButton_conn"> <widget class="QPushButton" name="pushButton_conn">
<property name="minimumSize"> <property name="minimumSize">
@ -244,6 +233,19 @@
</property> </property>
</widget> </widget>
</item> </item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout> </layout>
</item> </item>
</layout> </layout>

View File

@ -2,10 +2,9 @@
#include "db_manager_api/db_opt.h" #include "db_manager_api/db_opt.h"
#include <QApplication> #include <QApplication>
#include <QSqlRecord> #include <QSqlRecord>
#include <QMessageBox>
#include "db_manager_api/kbdwaitprgdlg.h" #include "db_manager_api/kbdwaitprgdlg.h"
#include <QPushButton> #include <QPushButton>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include "db_manager_common.h" #include "db_manager_common.h"
#include "db_sysinfo_api/CDbSysInfo.h" #include "db_sysinfo_api/CDbSysInfo.h"
@ -111,7 +110,7 @@ void db_compare::dataReuse(db_opt* pSrcDbOpt, QString sDataBaseOrg, db_opt* pDst
if( m_sDstStaTagName.isEmpty() || m_sDstStaDesc.isEmpty() ) if( m_sDstStaTagName.isEmpty() || m_sDstStaDesc.isEmpty() )
{ {
emit mergeRes("目标车站信息为空,请检查数据库", 1); emit mergeRes(tr("目标车站信息为空,请检查数据库"), 1);
emit signalEnable(); emit signalEnable();
return; return;
} }
@ -171,7 +170,7 @@ void db_compare::reuseFunc()
// 目标中找不到的表直接忽略 // 目标中找不到的表直接忽略
else if(false == CDbSysInfo::getTableModeByTableName(curTableName.toStdString(),stTableModelInfo) ) else if(false == CDbSysInfo::getTableModeByTableName(curTableName.toStdString(),stTableModelInfo) )
{ {
emit mergeRes("数据库表[" + curTableName + "]复用忽略.", 0); emit mergeRes(tr("数据库表[%1]复用忽略.").arg(curTableName), 0);
continue; continue;
} else if( tableMergeMap[curTableName] == "skip" ) } else if( tableMergeMap[curTableName] == "skip" )
{ {
@ -208,8 +207,8 @@ void db_compare::reuseFunc()
QString sSelectError = ""; QString sSelectError = "";
if ( m_pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false ) if ( m_pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false )
{ {
emit mergeRes("从源数据库查询记录查询失败:" + sSelectError, 1); emit mergeRes(tr("从源数据库查询记录查询失败:%1").arg(sSelectError), 1);
emit mergeRes("表 :" + curTableName + ", 复用失败!", 1); emit mergeRes(tr("表 :%1, 复用失败!").arg(curTableName), 1);
continue; continue;
} }
if(objSqlQuery.size() <=0 ){ if(objSqlQuery.size() <=0 ){
@ -235,11 +234,11 @@ void db_compare::reuseFunc()
objSqlQuery.clear(); objSqlQuery.clear();
if(bReuseRet) if(bReuseRet)
{ {
emit mergeRes("表:" + curTableName + ", 复用成功!", 0); emit mergeRes(tr("表:%1, 复用成功!").arg(curTableName), 0);
} }
else else
{ {
emit mergeRes("表:" + curTableName + ", 复用失败!", 1); emit mergeRes(tr("表:%1, 复用失败!").arg(curTableName), 1);
continue; continue;
} }
} }
@ -258,7 +257,7 @@ bool db_compare::checkTable( QString& sTableName )
//判断表是否存在 //判断表是否存在
if(!ifExistTable(m_pDstDbOpt, m_sDatabaseDst, sTableName ) ) if(!ifExistTable(m_pDstDbOpt, m_sDatabaseDst, sTableName ) )
{ {
emit mergeRes("目标数据库中不存在表:" + sTableName, 1); emit mergeRes(tr("目标数据库中不存在表:%1").arg(sTableName), 1);
return false; return false;
} }
//判断源表与目标表字段是否一致 //判断源表与目标表字段是否一致
@ -266,7 +265,7 @@ bool db_compare::checkTable( QString& sTableName )
int columnNum_dst = getColumnNum(m_pDstDbOpt, m_sDatabaseDst, sTableName); int columnNum_dst = getColumnNum(m_pDstDbOpt, m_sDatabaseDst, sTableName);
if(columnNum_org != columnNum_dst) if(columnNum_org != columnNum_dst)
{ {
emit mergeRes("源数据库与目标数据库的表:" + sTableName + "字段结构不一致!", 1); emit mergeRes(tr("源数据库与目标数据库的表:%1字段结构不一致").arg(sTableName), 1);
return false; return false;
} }
//判断源表与目标表主键是否一致 //判断源表与目标表主键是否一致
@ -276,7 +275,7 @@ bool db_compare::checkTable( QString& sTableName )
int key_num_dst = keys_dst.size(); int key_num_dst = keys_dst.size();
if(key_num_org != key_num_dst) if(key_num_org != key_num_dst)
{ {
emit mergeRes("源数据库与目标数据库的表:" + sTableName + "主键数量不一致!", 1); emit mergeRes(tr("源数据库与目标数据库的表:%1主键数量不一致").arg(sTableName), 1);
return false; return false;
} }
else else
@ -292,7 +291,7 @@ bool db_compare::checkTable( QString& sTableName )
} }
if(keysColums) if(keysColums)
{ {
emit mergeRes("源数据库与目标数据库的表:" + sTableName + "主键字段不一致!", 1); emit mergeRes(tr("源数据库与目标数据库的表:%1主键字段不一致").arg(sTableName), 1);
return false; return false;
} }
} }
@ -306,7 +305,7 @@ bool db_compare::hasColumn(db_opt *pDb_opt, QString &sDatabaseName, QString &sTa
QString error; QString error;
if ( pDb_opt->executeSql( sql, result, error ) == false ) if ( pDb_opt->executeSql( sql, result, error ) == false )
{ {
emit mergeRes("判断表是否存在字段失败" + error, 1); emit mergeRes(tr("判断表是否存在字段失败 %1").arg(error), 1);
qDebug() << "判断表是否存在字段失败: sql == " << sql; qDebug() << "判断表是否存在字段失败: sql == " << sql;
return false; return false;
} }
@ -356,7 +355,7 @@ int db_compare::mergeTable(db_opt* pSrcDbOpt, QString dataBaseOrg, db_opt* pDstD
QString sSelectError = ""; QString sSelectError = "";
if ( pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false ) if ( pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false )
{ {
emit mergeRes("判断表是否没有主键查询失败:" + sSelectError, 1); emit mergeRes(tr("判断表是否没有主键查询失败:%1").arg(sSelectError), 1);
return -1; return -1;
} }
int size_Org = objSqlQuery.size(); int size_Org = objSqlQuery.size();
@ -382,7 +381,7 @@ int db_compare::mergeTable(db_opt* pSrcDbOpt, QString dataBaseOrg, db_opt* pDstD
if ( pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false ) if ( pSrcDbOpt->executeSql( sSqlSelect, objSqlQuery, sSelectError ) == false )
{ {
qDebug() << "src db select error ============================ sql == " << sSqlSelect; qDebug() << "src db select error ============================ sql == " << sSqlSelect;
emit mergeRes("查找源数据库失败" + sSelectError, 1); emit mergeRes(tr("查找源数据库失败%1").arg(sSelectError), 1);
return -1; return -1;
} }
m_max61850Id = 0; m_max61850Id = 0;
@ -439,7 +438,7 @@ void db_compare::clearAllDataByTableName(db_opt *pDstDbOpt, QString dataBaseDst,
if( pDstDbOpt->executeSql(sqlDel, error ) == false ) if( pDstDbOpt->executeSql(sqlDel, error ) == false )
{ {
emit mergeRes(tr("删除表:%1数据失败").arg(tableName) + error, 1); emit mergeRes(tr("删除表:%1数据失败").arg(tableName) + error, 1);
emit mergeRes("SQL语句为" + sqlDel, 1); emit mergeRes(tr("SQL语句为%1").arg(sqlDel), 1);
qDebug() << sqlDel; qDebug() << sqlDel;
// emit mergeRes(sSql_Insert, 0); // emit mergeRes(sSql_Insert, 0);
} }
@ -538,7 +537,7 @@ bool db_compare::insertRecord(db_opt* pDb_option, QString dataBase, QString tabl
if( pDb_option->executeSql(sSql_allColumnName, query_allColumnName, sError_allColumnName) == false ) if( pDb_option->executeSql(sSql_allColumnName, query_allColumnName, sError_allColumnName) == false )
{ {
emit mergeRes( "获取表的所有字段名失败:" + sError_allColumnName, 1 ); emit mergeRes( tr("获取表的所有字段名失败:%1").arg(sError_allColumnName), 1 );
return false; return false;
} }
while(query_allColumnName.next()) while(query_allColumnName.next())
@ -593,8 +592,8 @@ bool db_compare::insertRecord(db_opt* pDb_option, QString dataBase, QString tabl
QString sError_Insert = ""; QString sError_Insert = "";
if( pDb_option->executeSql(sSql_Insert, query_Insert, sError_Insert ) == false ) if( pDb_option->executeSql(sSql_Insert, query_Insert, sError_Insert ) == false )
{ {
emit mergeRes("插入记录语句执行失败:" + sError_Insert, 1); emit mergeRes(tr("插入记录语句执行失败:%1").arg(sError_Insert), 1);
emit mergeRes("SQL语句为" + sSql_Insert, 1); emit mergeRes(tr("SQL语句为%1").arg(sSql_Insert), 1);
qDebug() << sSql_Insert; qDebug() << sSql_Insert;
// emit mergeRes(sSql_Insert, 0); // emit mergeRes(sSql_Insert, 0);
return false; return false;
@ -771,7 +770,7 @@ bool db_compare::ifExistColumn(db_opt* pDb_opt, QString sDataBase, QString table
QString sError; QString sError;
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("判断" + columnName + "字段是否存在:" + sError, 1); emit mergeRes(tr("判断%1字段是否存在:%2").arg(columnName).arg(sError), 1);
return ret; return ret;
} }
while(query.next()) while(query.next())
@ -864,7 +863,7 @@ bool db_compare::ifKeysConflict(db_opt* pDb_opt, QString sDataBase, QString sTab
QString sError_u = ""; QString sError_u = "";
if( pDb_opt->executeSql(sSql_u, query_u, sError_u) == false ) if( pDb_opt->executeSql(sSql_u, query_u, sError_u) == false )
{ {
emit mergeRes("判断UNIQUE记录冲突查询失败" + sError_u, 1); emit mergeRes(tr("判断UNIQUE记录冲突查询失败%1").arg(sError_u), 1);
return false; return false;
} }
if(query_u.size() > 0) if(query_u.size() > 0)
@ -896,7 +895,7 @@ bool db_compare::ifKeysConflict(db_opt* pDb_opt, QString sDataBase, QString sTab
QString sError_k = ""; QString sError_k = "";
if( pDb_opt->executeSql(sSql_k, query_k, sError_k) == false ) if( pDb_opt->executeSql(sSql_k, query_k, sError_k) == false )
{ {
emit mergeRes("判断主键冲突查询失败:" + sError_k, 1); emit mergeRes(tr("判断主键冲突查询失败:%1").arg(sError_k), 1);
} }
if(query_k.size() > 0) if(query_k.size() > 0)
{ {
@ -932,7 +931,7 @@ void db_compare::deleteConflictRecord(db_opt* pDb_opt, QString sDataBase, QStrin
QString sError_u = ""; QString sError_u = "";
if( pDb_opt->executeSql(sSql_u, query_u, sError_u) == false ) if( pDb_opt->executeSql(sSql_u, query_u, sError_u) == false )
{ {
emit mergeRes("删除UNIQUE冲突记录失败" + sError_u, 1); emit mergeRes(tr("删除UNIQUE冲突记录失败%1").arg(sError_u), 1);
} }
query_u.clear(); query_u.clear();
} }
@ -955,7 +954,7 @@ void db_compare::deleteConflictRecord(db_opt* pDb_opt, QString sDataBase, QStrin
QString sError_k = ""; QString sError_k = "";
if( pDb_opt->executeSql(sSql_k, query_k, sError_k) == false ) if( pDb_opt->executeSql(sSql_k, query_k, sError_k) == false )
{ {
emit mergeRes("删除主键冲突记录失败:" + sError_k, 1); emit mergeRes(tr("删除主键冲突记录失败:%1").arg(sError_k), 1);
} }
query_k.clear(); query_k.clear();
} }
@ -968,7 +967,7 @@ int db_compare::getColumnNum(db_opt* pDb_opt, QString sDataBase, QString sTableN
QString sError; QString sError;
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询字段数量失败:" + sError, 1); emit mergeRes(tr("查询字段数量失败:%1").arg(sError), 1);
} }
while(query.next()) while(query.next())
{ {
@ -988,7 +987,7 @@ QStringList db_compare::getMainKeys(db_opt* pDb_opt, QString sDataBase, QString
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("获取主键查询失败:" + sError, 1); emit mergeRes(tr("获取主键查询失败:%1").arg(sError), 1);
} }
while(query.next()) while(query.next())
@ -1012,7 +1011,7 @@ QStringList db_compare::getUniques(db_opt* pDb_opt, QString sDataBaseName, QStri
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询UNIQUE字段失败" + sError, 1); emit mergeRes(tr("查询UNIQUE字段失败%1").arg(sError), 1);
} }
while(query.next()) while(query.next())
@ -1033,7 +1032,7 @@ bool db_compare::ifExistTable(db_opt* pDb_opt, QString sDataBase, QString sTable
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("获取主键查询失败:" + sError, 1); emit mergeRes(tr("获取主键查询失败:%1").arg(sError), 1);
} }
while(query.next()) while(query.next())
{ {
@ -1053,7 +1052,7 @@ bool db_compare::ifSubSystemSame( db_opt* pDb_opt, QString& sDatabaseName, QStri
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询专业是否匹配出错," + sError, 1); emit mergeRes(tr("查询专业是否匹配出错,%1").arg(sError), 1);
return false; return false;
} }
while(query.next()) while(query.next())
@ -1071,7 +1070,7 @@ bool db_compare::ifSubSystemSame( db_opt* pDb_opt, QString& sDatabaseName, QStri
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询专业是否匹配出错," + sError, 1); emit mergeRes(tr("查询专业是否匹配出错,%1").arg(sError), 1);
return false; return false;
} }
while(query.next()) while(query.next())
@ -1089,7 +1088,7 @@ bool db_compare::ifDistinguishStation( db_opt* pDb_opt, QString& sDatabaseName,
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询专业是否匹配出错," + sError, 1); emit mergeRes(tr("查询专业是否匹配出错,%1").arg(sError), 1);
return false; return false;
} }
while(query.next()) while(query.next())
@ -1107,7 +1106,7 @@ bool db_compare::ifDistinguishSubSystem( db_opt* pDb_opt, QString& sDatabaseName
QString sError = ""; QString sError = "";
if( pDb_opt->executeSql(sSql, query, sError) == false ) if( pDb_opt->executeSql(sSql, query, sError) == false )
{ {
emit mergeRes("查询专业是否匹配出错," + sError, 1); emit mergeRes(tr("查询专业是否匹配出错,%1").arg(sError), 1);
return false; return false;
} }
while(query.next()) while(query.next())

View File

@ -1,107 +1,111 @@
#------------------------------------------------- #-------------------------------------------------
# #
# Project created by QtCreator 2018-06-28T13:47:06 # Project created by QtCreator 2018-06-28T13:47:06
# #
#------------------------------------------------- #-------------------------------------------------
QT += core gui sql xml network QT += core gui sql xml network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = db_manager TARGET = db_manager
TEMPLATE = app TEMPLATE = app
#CONFIG += c++11 #CONFIG += c++11
# The following define makes your compiler emit warnings if you use # The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings # any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the # depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it. # deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \ SOURCES += \
main.cpp \ main.cpp \
db_set.cpp \ db_set.cpp \
db_compare.cpp \ db_compare.cpp \
mytreewidget.cpp \ mytreewidget.cpp \
pj_manager.cpp \ pj_manager.cpp \
conndig.cpp \ conndig.cpp \
his_widgets/new_his_backup_dialog.cpp \ his_widgets/new_his_backup_dialog.cpp \
his_widgets/import_his_backup_dialog.cpp \ his_widgets/import_his_backup_dialog.cpp \
his_widgets/new_his_dump_dialog.cpp \ his_widgets/new_his_dump_dialog.cpp \
pj_manager_his/pj_manager_his.cpp \ pj_manager_his/pj_manager_his.cpp \
pj_manager_his/pj_manager_his_data_srv.cpp \ pj_manager_his/pj_manager_his_data_srv.cpp \
CHisUtil.cpp \ CHisUtil.cpp \
CLogMngWidget.cpp \ CLogMngWidget.cpp \
CExportZipWorker.cpp\ CExportZipWorker.cpp\
SingleApplication.cpp \ SingleApplication.cpp \
SingleApplication_p.cpp \ SingleApplication_p.cpp \
CStationReuseForm.cpp CStationReuseForm.cpp \
CCreateInfluxDBUserDlg.cpp
HEADERS += \
db_manager_common.h \ HEADERS += \
db_set.h \ db_manager_common.h \
db_compare.h \ db_set.h \
mytreewidget.h \ db_compare.h \
pj_manager.h \ mytreewidget.h \
conndig.h \ pj_manager.h \
his_widgets/new_his_backup_dialog.h \ conndig.h \
his_widgets/import_his_backup_dialog.h \ his_widgets/new_his_backup_dialog.h \
his_widgets/new_his_dump_dialog.h \ his_widgets/import_his_backup_dialog.h \
CHisUtil.h \ his_widgets/new_his_dump_dialog.h \
CLogMngWidget.h \ CHisUtil.h \
CExportZipWorker.h \ CLogMngWidget.h \
SingleApplication.h \ CExportZipWorker.h \
SingleApplication_p.h \ SingleApplication.h \
CStationReuseForm.h SingleApplication_p.h \
CStationReuseForm.h \
FORMS += \ CCreateInfluxDBUserDlg.h
db_set.ui \
pj_manager.ui \ FORMS += \
conndig.ui \ db_set.ui \
his_widgets/new_his_backup_dialog.ui \ pj_manager.ui \
his_widgets/import_his_backup_dialog.ui \ conndig.ui \
his_widgets/new_his_dump_dialog.ui \ his_widgets/new_his_backup_dialog.ui \
logMngWidget.ui \ his_widgets/import_his_backup_dialog.ui \
CStationReuseForm.ui his_widgets/new_his_dump_dialog.ui \
logMngWidget.ui \
CStationReuseForm.ui \
LIBS += -lboost_thread \ CCreateInfluxDBUserDlg.ui
-lboost_chrono \
-lboost_system
LIBS += -lboost_thread \
-lboost_chrono \
LIBS += -lpub_logger_api -llog4cplus -lz -lcurl -lpub_sysinfo_api -ltsdb_api -ldb_base_api -ldb_manager_api -ldb_his_mng_api -lpub_utility_api -ldb_sysinfo_api -lboost_system
DEFINES += QAPPLICATION_CLASS=QApplication
LIBS += -lpub_logger_api -llog4cplus -lz -lcurl -lpub_sysinfo_api -ltsdb_api -ldb_base_api -ldb_manager_api -ldb_his_mng_api -lpub_utility_api -ldb_sysinfo_api
win32{ LIBS += -lpub_widget
LIBS += -ladvapi32
QMAKE_CXXFLAGS += /wd"4003" DEFINES += QAPPLICATION_CLASS=QApplication
QMAKE_CXXFLAGS_WARN_ON -= -w34189
RC_ICONS = res/db_manager.ico win32{
LIBS += -ladvapi32
CONFIG(debug, debug|release) { QMAKE_CXXFLAGS += /wd"4003"
LIBS += -lquazipd QMAKE_CXXFLAGS_WARN_ON -= -w34189
} RC_ICONS = res/db_manager.ico
CONFIG(release, debug|release) {
LIBS += -lquazip CONFIG(debug, debug|release) {
} LIBS += -lquazipd
}
} CONFIG(release, debug|release) {
else{ LIBS += -lquazip
LIBS += -lquazip }
}
}
TRANSLATIONS = $$PWD/en.ts else{
RESOURCES += res.qrc LIBS += -lquazip
}
#-0-----------------------------------------------------------------
COMMON_PRI=$$PWD/../../common.pri TRANSLATIONS = $$PWD/en.ts
exists($$COMMON_PRI) { RESOURCES += res.qrc
include($$COMMON_PRI)
}else { #-0-----------------------------------------------------------------
error("FATAL error: can not find common.pri") COMMON_PRI=$$PWD/../../common.pri
} exists($$COMMON_PRI) {
include($$COMMON_PRI)
}else {
error("FATAL error: can not find common.pri")
}

View File

@ -16,14 +16,10 @@
#define TSDB_DB_NAME "iscs6000"
#define DB_FILE_NAME "db_export.sql" #define DB_FILE_NAME "db_export.sql"
#define TSDB_FILE_NAME "tsdb_export.sql.gz" #define TSDB_FILE_NAME "tsdb_export.sql.gz"
#define TSDB_FILE_EVENT_NAME "tsdb_export_event.sql.gz" #define TSDB_FILE_EVENT_NAME "tsdb_export_event.sql.gz"
#define TSDB_FILE_DATA_NAME "tsdb_export_data.sql.gz" #define TSDB_FILE_DATA_NAME "tsdb_export_data.sql.gz"
#define TSDB_BIN_DIR "tsdb_bin_export" #define TSDB_BIN_DIR "tsdb_bin_export"
#define CN_PASSWD "kbdct@0755"
#endif // DB_MANAGER_COMMON_H #endif // DB_MANAGER_COMMON_H

View File

@ -1,6 +1,6 @@
#include "db_set.h" #include "db_set.h"
#include "ui_db_set.h" #include "ui_db_set.h"
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include <QSqlDatabase> #include <QSqlDatabase>
#include <QSqlError> #include <QSqlError>
#include <db_manager_common.h> #include <db_manager_common.h>
@ -9,11 +9,13 @@
using namespace iot_dbms; using namespace iot_dbms;
db_set::db_set( QWidget* parent ) db_set::db_set( QWidget* parent )
: QDialog( parent ) : CustomUiDialog( parent )
, ui( new Ui::db_set ) , ui( new Ui::db_set )
{ {
ui->setupUi( this ); ui->setupUi( this );
ui->le_passwd->setText(CN_PASSWD); ui->le_passwd->setText(EMS_DEFAULT_PASSWD);
setAutoLayout(true);
} }
db_set::~db_set() db_set::~db_set()
@ -135,14 +137,11 @@ void db_set::accept()
{ {
if( ui->le_name->text() == "" || ui->le_ip->text() == "" || ui->le_port->text() == "") if( ui->le_name->text() == "" || ui->le_ip->text() == "" || ui->le_port->text() == "")
{ {
QMessageBox msg(this); N_MessageBox::information(this,tr("提示"),tr("不准选择空路径"));
msg.setText(tr("不准选择空路径"));
msg.setWindowTitle(tr("提示"));
msg.exec();
return; return;
} }
else else
return QDialog::accept(); return CustomUiDialog::accept();
} }
@ -174,7 +173,7 @@ void db_set::on_rb_kingbase_clicked()
void db_set::on_pushButton_clicked() void db_set::on_pushButton_clicked()
{ {
if( ui->le_user->text() == "" || ui->le_ip->text() == "" || ui->le_port->text() == "" || ui->le_passwd->text() == ""){ if( ui->le_user->text() == "" || ui->le_ip->text() == "" || ui->le_port->text() == "" || ui->le_passwd->text() == ""){
QMessageBox::warning(this,tr("警告"),tr("请把信息填写完整")); N_MessageBox::warning(this,tr("警告"),tr("请把信息填写完整"));
return; return;
} }
@ -208,11 +207,11 @@ void db_set::on_pushButton_clicked()
if(ok) if(ok)
{ {
QMessageBox::information(this,tr("测试结果"),tr("连接成功")); N_MessageBox::information(this,tr("测试结果"),tr("连接成功"));
} }
else else
{ {
QMessageBox::warning(this,tr("测试结果"),QString(tr("连接失败:")) + objDb.getLastErrorString()); N_MessageBox::warning(this,tr("测试结果"),QString(tr("连接失败:")) + objDb.getLastErrorString());
} }
} }
} }

View File

@ -1,16 +1,15 @@
#ifndef DBSET_H #ifndef DBSET_H
#define DBSET_H #define DBSET_H
#include <QDialog>
#include "db_base_api/CDbPara.h" #include "db_base_api/CDbPara.h"
#include "pub_widget/CustomDialog.h"
namespace Ui namespace Ui
{ {
class db_set; class db_set;
} }
class db_set : public QDialog class db_set : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT

View File

@ -6,73 +6,15 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>359</width> <width>283</width>
<height>290</height> <height>354</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
<string>Dialog</string> <string>Dialog</string>
</property> </property>
<layout class="QVBoxLayout" name="verticalLayout"> <layout class="QGridLayout" name="gridLayout_2">
<item> <item row="1" column="0">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>数据库类型:</string>
</property>
</widget>
</item>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QRadioButton" name="rb_mysql">
<property name="text">
<string>MySQL</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="0" column="1">
<widget class="QRadioButton" name="rb_opengauss">
<property name="text">
<string>openGauss</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="0">
<widget class="QRadioButton" name="rb_oracle">
<property name="text">
<string>Oracle</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="1">
<widget class="QRadioButton" name="rb_kingbase">
<property name="text">
<string>KingBase</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QFormLayout" name="formLayout"> <layout class="QFormLayout" name="formLayout">
<item row="0" column="0"> <item row="0" column="0">
<widget class="QLabel" name="label_2"> <widget class="QLabel" name="label_2">
@ -140,7 +82,7 @@
<item row="4" column="1"> <item row="4" column="1">
<widget class="QLineEdit" name="le_passwd"> <widget class="QLineEdit" name="le_passwd">
<property name="text"> <property name="text">
<string>kbdct@0755</string> <string>ems@byd23</string>
</property> </property>
<property name="echoMode"> <property name="echoMode">
<enum>QLineEdit::Password</enum> <enum>QLineEdit::Password</enum>
@ -149,36 +91,110 @@
</item> </item>
</layout> </layout>
</item> </item>
<item> <item row="0" column="0">
<widget class="QPushButton" name="pushButton"> <layout class="QHBoxLayout" name="horizontalLayout">
<property name="sizePolicy"> <item>
<sizepolicy hsizetype="Preferred" vsizetype="Preferred"> <widget class="QLabel" name="label">
<horstretch>0</horstretch> <property name="text">
<verstretch>0</verstretch> <string>数据库类型:</string>
</sizepolicy> </property>
</property> </widget>
<property name="font"> </item>
<font> <item>
<family>微软雅黑</family> <layout class="QGridLayout" name="gridLayout">
<pointsize>10</pointsize> <item row="0" column="0">
<weight>50</weight> <widget class="QRadioButton" name="rb_mysql">
<bold>false</bold> <property name="text">
</font> <string>MySQL</string>
</property> </property>
<property name="text"> <property name="checked">
<string>测试连接是否正常</string> <bool>true</bool>
</property> </property>
</widget> <attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="0" column="1">
<widget class="QRadioButton" name="rb_opengauss">
<property name="text">
<string>openGauss</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="0">
<widget class="QRadioButton" name="rb_oracle">
<property name="text">
<string>Oracle</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
<item row="1" column="1">
<widget class="QRadioButton" name="rb_kingbase">
<property name="text">
<string>KingBase</string>
</property>
<attribute name="buttonGroup">
<string notr="true">buttonGroup</string>
</attribute>
</widget>
</item>
</layout>
</item>
</layout>
</item> </item>
<item> <item row="2" column="0">
<widget class="QDialogButtonBox" name="buttonBox"> <spacer name="verticalSpacer">
<property name="orientation"> <property name="orientation">
<enum>Qt::Horizontal</enum> <enum>Qt::Vertical</enum>
</property> </property>
<property name="standardButtons"> <property name="sizeHint" stdset="0">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set> <size>
<width>20</width>
<height>40</height>
</size>
</property> </property>
</widget> </spacer>
</item>
<item row="3" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>测试连接</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</item> </item>
</layout> </layout>
</widget> </widget>

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
#include "import_his_backup_dialog.h" #include "import_his_backup_dialog.h"
#include "ui_import_his_backup_dialog.h" #include "ui_import_his_backup_dialog.h"
#include "public/pub_utility_api/FileUtil.h" #include "public/pub_utility_api/FileUtil.h"
#include "public/pub_utility_api/TimeUtil.h"
#include "db_manager_common.h" #include "db_manager_common.h"
#include "CHisUtil.h" #include "CHisUtil.h"
@ -9,18 +10,21 @@
#include <QDomDocument> #include <QDomDocument>
#include <QDomElement> #include <QDomElement>
#include <QDateTime> #include <QDateTime>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
import_his_backup_dialog::import_his_backup_dialog(QWidget *parent) : import_his_backup_dialog::import_his_backup_dialog(QWidget *parent) :
QDialog(parent), CustomUiDialog(parent),
ui(new Ui::import_his_backup_dialog) ui(new Ui::import_his_backup_dialog)
{ {
ui->setupUi(this); ui->setupUi(this);
initUi(); initUi();
initHisMng(); initHisMng();
setCloseBtnVisible(false);
m_lLastImportTsdbPrintInfo = 0L;
setAutoLayout(true);
} }
import_his_backup_dialog::~import_his_backup_dialog() import_his_backup_dialog::~import_his_backup_dialog()
@ -61,6 +65,20 @@ void import_his_backup_dialog::addMsg(const QString &msg)
isDbErr = true; isDbErr = true;
return; return;
} }
qint64 lCurTime = iot_public::getMonotonicMsec();
if(msg.contains("(PPS)")) //针对influxdb特例化处理否则消息框消息太多临时解决为1分钟输出1条过程信息
{
if(lCurTime - m_lLastImportTsdbPrintInfo < 60 * 1000)
{
return;
}
else
{
m_lLastImportTsdbPrintInfo = lCurTime;
}
}
ui->listWidget->addItem(msg); ui->listWidget->addItem(msg);
} }
@ -72,8 +90,6 @@ void import_his_backup_dialog::initUi()
this->setWindowTitle(tr("导入备份")); this->setWindowTitle(tr("导入备份"));
// ui->tabWidget->setCurrentIndex(0); // ui->tabWidget->setCurrentIndex(0);
ui->listWidget->setStyleSheet("QListWidget::item{height:20px;color:#0a0a0a}");
this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); //< 取消关闭按钮
ui->label_dumpdate_tag->setHidden(true); ui->label_dumpdate_tag->setHidden(true);
ui->label_dumpdate->setHidden(true); ui->label_dumpdate->setHidden(true);
@ -221,25 +237,29 @@ QString import_his_backup_dialog::getTsdbDataFilePath()
void import_his_backup_dialog::startImport() void import_his_backup_dialog::startImport()
{ {
m_lLastImportTsdbPrintInfo = 0L;
/* 为以后搜索方便,保留此注释
* EMS_DEFAULT_DATABASE
*/
if(isDump) if(isDump)
{ {
emit importHisDump(m_pConn,getDbFilePath(),m_pConn->hostName(),TSDB_DB_NAME,getTsdbFilePath()); emit importHisDump(m_pConn,getDbFilePath(),m_pConn->hostName(),m_pConn->databaseName(),getTsdbFilePath());
return; return;
} }
if(isAll) if(isAll)
{ {
emit importHis(m_pConn,getDbFilePath(),m_pConn->hostName(),TSDB_DB_NAME,getTsdbBinDir()); emit importHis(m_pConn,getDbFilePath(),m_pConn->hostName(),m_pConn->databaseName(),getTsdbBinDir());
return; return;
} }
if(isPart) if(isPart)
{ {
if(partVersion == 1) { if(partVersion == 1) {
emit importPart(m_pConn,m_pConn->hostName(),TSDB_DB_NAME,isEventExported,isDataExported,getDbFilePath(),getTsdbEventFilePath(),getTsdbDataFilePath()); emit importPart(m_pConn,m_pConn->hostName(),m_pConn->databaseName(),isEventExported,isDataExported,getDbFilePath(),getTsdbEventFilePath(),getTsdbDataFilePath());
} }
else{ else{
emit importPartV2(m_pConn,m_pConn->hostName(),TSDB_DB_NAME,getDbFilePath(),getTsdbFilePath()); emit importPartV2(m_pConn,m_pConn->hostName(),m_pConn->databaseName(),getDbFilePath(),getTsdbFilePath());
} }
} }
@ -256,7 +276,8 @@ void import_his_backup_dialog::on_buttonBox_clicked(QAbstractButton *button)
{ {
if(button->text() == tr("开始")) if(button->text() == tr("开始"))
{ {
if(QMessageBox::question(this,tr("提醒"),tr("是否恢复备份?(如果是恢复全量备份则会覆盖原始数据!)")) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("提醒"),tr("是否恢复备份?(如果是恢复全量备份则会覆盖原始数据!)"))
!= N_MessageBox::Ok)
{ {
return; return;
} }

View File

@ -3,18 +3,18 @@
#include <dbms/db_his_mng_api/CHisMngApi.h> #include <dbms/db_his_mng_api/CHisMngApi.h>
#include <QDialog>
#include <QSqlDatabase> #include <QSqlDatabase>
#include <QThread> #include <QThread>
#include <QTimer> #include <QTimer>
#include <QAbstractButton> #include <QAbstractButton>
#include <QDomElement> #include <QDomElement>
#include "pub_widget/CustomDialog.h"
namespace Ui { namespace Ui {
class import_his_backup_dialog; class import_his_backup_dialog;
} }
class import_his_backup_dialog : public QDialog class import_his_backup_dialog : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT
@ -70,7 +70,7 @@ private:
int partVersion; int partVersion;
bool isEventExported = false; bool isEventExported = false;
bool isDataExported = false; bool isDataExported = false;
qint64 m_lLastImportTsdbPrintInfo; //最后一次打印tsdb导入信息的日志时间1分钟打印一次防止qlistwidget行数太多
void initUi(); void initUi();
void initHisMng(); void initHisMng();

View File

@ -14,19 +14,6 @@
<string>Dialog</string> <string>Dialog</string>
</property> </property>
<layout class="QGridLayout" name="gridLayout"> <layout class="QGridLayout" name="gridLayout">
<item row="1" column="0">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="styleSheet">
<string notr="true"> button-layout: 2</string>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Apply|QDialogButtonBox::Cancel</set>
</property>
</widget>
</item>
<item row="0" column="0"> <item row="0" column="0">
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
<property name="currentIndex"> <property name="currentIndex">
@ -280,6 +267,19 @@
</widget> </widget>
</widget> </widget>
</item> </item>
<item row="1" column="0">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="styleSheet">
<string notr="true"> button-layout: 2</string>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Apply|QDialogButtonBox::Cancel</set>
</property>
</widget>
</item>
</layout> </layout>
</widget> </widget>
<resources/> <resources/>

View File

@ -3,7 +3,7 @@
#include <QDateTime> #include <QDateTime>
#include <QPushButton> #include <QPushButton>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include <public/pub_utility_api/FileUtil.h> #include <public/pub_utility_api/FileUtil.h>
#include <QDir> #include <QDir>
#include <QHostInfo> #include <QHostInfo>
@ -15,7 +15,7 @@
Q_DECLARE_METATYPE(std::vector<std::string>) Q_DECLARE_METATYPE(std::vector<std::string>)
new_his_backup_dialog::new_his_backup_dialog(QWidget *parent) : new_his_backup_dialog::new_his_backup_dialog(QWidget *parent) :
QDialog(parent), CustomUiDialog(parent),
ui(new Ui::new_his_backup_dialog) ui(new Ui::new_his_backup_dialog)
{ {
ui->setupUi(this); ui->setupUi(this);
@ -28,6 +28,9 @@ new_his_backup_dialog::new_his_backup_dialog(QWidget *parent) :
qRegisterMetaType< std::vector<int> >(); qRegisterMetaType< std::vector<int> >();
qRegisterMetaType< std::vector<std::string> >(); qRegisterMetaType< std::vector<std::string> >();
setCloseBtnVisible(false);
setAutoLayout(true);
} }
new_his_backup_dialog::~new_his_backup_dialog() new_his_backup_dialog::~new_his_backup_dialog()
@ -73,8 +76,6 @@ void new_his_backup_dialog::init()
ui->tabWidget->setCurrentIndex(0); ui->tabWidget->setCurrentIndex(0);
this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); //< 取消关闭按钮
ui->dateTimeEdit_start->setDateTime(QDateTime::currentDateTime().addYears(-1)); ui->dateTimeEdit_start->setDateTime(QDateTime::currentDateTime().addYears(-1));
ui->dateTimeEdit_end->setDateTime(QDateTime::currentDateTime()); ui->dateTimeEdit_end->setDateTime(QDateTime::currentDateTime());
@ -116,7 +117,6 @@ void new_his_backup_dialog::initConnect()
void new_his_backup_dialog::initStyleSheet() void new_his_backup_dialog::initStyleSheet()
{ {
ui->listWidget->setStyleSheet("QListWidget::item{height:20px;color:#0a0a0a}");
} }
void new_his_backup_dialog::initHisMng() void new_his_backup_dialog::initHisMng()
@ -262,13 +262,13 @@ void new_his_backup_dialog::checkTimeValid()
if(ui->dateTimeEdit_end->dateTime() > QDateTime::currentDateTime()) if(ui->dateTimeEdit_end->dateTime() > QDateTime::currentDateTime())
{ {
ui->dateTimeEdit_end->setDateTime(QDateTime::currentDateTime()); ui->dateTimeEdit_end->setDateTime(QDateTime::currentDateTime());
QMessageBox::information(this,tr("提醒"),tr("结束时间请先设置小于当前时间")); N_MessageBox::information(this,tr("提醒"),tr("结束时间请先设置小于当前时间"));
return; return;
} }
if(ui->dateTimeEdit_start->dateTime() > ui->dateTimeEdit_end->dateTime()) if(ui->dateTimeEdit_start->dateTime() > ui->dateTimeEdit_end->dateTime())
{ {
ui->dateTimeEdit_start->setDateTime(ui->dateTimeEdit_end->dateTime().addDays(-1)); ui->dateTimeEdit_start->setDateTime(ui->dateTimeEdit_end->dateTime().addDays(-1));
QMessageBox::information(this,tr("提醒"),tr("开始时间请先设置小于结束时间")); N_MessageBox::information(this,tr("提醒"),tr("开始时间请先设置小于结束时间"));
} }
} }
@ -296,7 +296,10 @@ void new_his_backup_dialog::startBackupAll()
endtime = ui->dateTimeEdit_end->dateTime().toMSecsSinceEpoch(); endtime = ui->dateTimeEdit_end->dateTime().toMSecsSinceEpoch();
} }
emit exportHis(m_pConn,m_dbFilePath,TSDB_DB_NAME,m_tsdbBinDir,starttime,endtime ); /* 为以后搜索方便,保留此注释
* emit exportHis(m_pConn,m_dbFilePath,EMS_DEFAULT_DATABASE,m_tsdbBinDir,starttime,endtime );
*/
emit exportHis(m_pConn,m_dbFilePath,m_pConn->databaseName(),m_tsdbBinDir,starttime,endtime );
} }
void new_his_backup_dialog::startBackupPart() void new_his_backup_dialog::startBackupPart()
@ -310,11 +313,12 @@ void new_his_backup_dialog::startBackupPart()
endtime = ui->dateTimeEdit_end->dateTime().toMSecsSinceEpoch(); endtime = ui->dateTimeEdit_end->dateTime().toMSecsSinceEpoch();
} }
emit exportPart(m_pConn,m_pConn->hostName(),TSDB_DB_NAME, /* 为以后搜索方便,保留此注释
* emit exportPart(m_pConn,m_pConn->hostName(),EMS_DEFAULT_DATABASE,
*/
emit exportPart(m_pConn,m_pConn->hostName(),m_pConn->databaseName(),
starttime, starttime,
endtime, endtime,
m_dbFilePath, m_dbFilePath,
m_tsdbFilePath m_tsdbFilePath
); );

View File

@ -3,18 +3,17 @@
#include <dbms/db_his_mng_api/CHisMngApi.h> #include <dbms/db_his_mng_api/CHisMngApi.h>
#include <QDialog>
#include <QThread> #include <QThread>
#include <QSqlDatabase> #include <QSqlDatabase>
#include <QAbstractButton> #include <QAbstractButton>
#include <QTimer> #include <QTimer>
#include "pub_widget/CustomDialog.h"
namespace Ui { namespace Ui {
class new_his_backup_dialog; class new_his_backup_dialog;
} }
class new_his_backup_dialog : public QDialog class new_his_backup_dialog : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT

View File

@ -13,11 +13,8 @@
#include <public/pub_utility_api/FileUtil.h> #include <public/pub_utility_api/FileUtil.h>
#include "CHisUtil.h" #include "CHisUtil.h"
new_his_dump_dialog::new_his_dump_dialog(QWidget *parent) : new_his_dump_dialog::new_his_dump_dialog(QWidget *parent) :
QDialog(parent), CustomUiDialog(parent),
ui(new Ui::new_his_dump_dialog) ui(new Ui::new_his_dump_dialog)
{ {
ui->setupUi(this); ui->setupUi(this);
@ -25,6 +22,10 @@ new_his_dump_dialog::new_his_dump_dialog(QWidget *parent) :
initUi(); initUi();
initHisMng(); initHisMng();
init(); init();
setCloseBtnVisible(false);
setAutoLayout(true);
} }
new_his_dump_dialog::~new_his_dump_dialog() new_his_dump_dialog::~new_his_dump_dialog()
@ -60,12 +61,12 @@ void new_his_dump_dialog::handleDumpHisFinished(bool result)
{ {
if(result) if(result)
{ {
addMsg("转储完成"); addMsg(tr("转储完成"));
genConfig(); genConfig();
} }
else else
{ {
addMsg("转储失败"); addMsg(tr("转储失败"));
} }
finish(); finish();
} }
@ -80,10 +81,6 @@ void new_his_dump_dialog::setDumpDateTime(qint64 timestamp)
void new_his_dump_dialog::initUi() void new_his_dump_dialog::initUi()
{ {
ui->listWidget->setUniformItemSizes(true); ui->listWidget->setUniformItemSizes(true);
this->setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint); //< 取消关闭按钮
ui->listWidget->setStyleSheet("QListWidget::item{height:20px;color:#0a0a0a}");
this->setWindowTitle(tr("手动转储")); this->setWindowTitle(tr("手动转储"));
ui->buttonBox->button(QDialogButtonBox::Apply)->setText(tr("开始")); ui->buttonBox->button(QDialogButtonBox::Apply)->setText(tr("开始"));
@ -130,9 +127,10 @@ void new_his_dump_dialog::updateTime()
void new_his_dump_dialog::startDump() void new_his_dump_dialog::startDump()
{ {
emit dumpHis(m_pConn,m_dbFilePath, /* 为以后搜索方便,保留此注释
TSDB_DB_NAME,m_tsdbFilePath, * emit dumpHis(m_pConn,m_dbFilePath,EMS_DEFAULT_DATABASE,m_tsdbFilePath,m_dumpTimestamp);
m_dumpTimestamp); */
emit dumpHis(m_pConn,m_dbFilePath,m_pConn->databaseName(),m_tsdbFilePath,m_dumpTimestamp);
} }
void new_his_dump_dialog::finish() void new_his_dump_dialog::finish()
@ -218,7 +216,7 @@ void new_his_dump_dialog::on_buttonBox_clicked(QAbstractButton *button)
connect(&timer,&QTimer::timeout,this,&new_his_dump_dialog::updateTime); connect(&timer,&QTimer::timeout,this,&new_his_dump_dialog::updateTime);
timer.setInterval(100); timer.setInterval(100);
timer.start(); timer.start();
button->setText("取消"); button->setText(tr("取消"));
ui->buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); ui->buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false);
ui->buttonBox->button(QDialogButtonBox::Cancel)->setDown(true); ui->buttonBox->button(QDialogButtonBox::Cancel)->setDown(true);

View File

@ -1,17 +1,17 @@
#ifndef NEW_HIS_DUMP_DIALOG_H #ifndef NEW_HIS_DUMP_DIALOG_H
#define NEW_HIS_DUMP_DIALOG_H #define NEW_HIS_DUMP_DIALOG_H
#include <QDialog>
#include <dbms/db_his_mng_api/CHisMngApi.h> #include <dbms/db_his_mng_api/CHisMngApi.h>
#include <QAbstractButton> #include <QAbstractButton>
#include <QThread> #include <QThread>
#include <QTimer> #include <QTimer>
#include "pub_widget/CustomDialog.h"
namespace Ui { namespace Ui {
class new_his_dump_dialog; class new_his_dump_dialog;
} }
class new_his_dump_dialog : public QDialog class new_his_dump_dialog : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT

View File

@ -10,6 +10,7 @@
#include "pub_utility_api/I18N.h" #include "pub_utility_api/I18N.h"
#include "pub_utility_api/FileUtil.h" #include "pub_utility_api/FileUtil.h"
#include "pub_utility_api/SingleProcInstance.h" #include "pub_utility_api/SingleProcInstance.h"
#include "pub_widget/PubWidgetInit.h"
using namespace iot_public; using namespace iot_public;
class SingleApplication; class SingleApplication;
@ -42,6 +43,8 @@ void initI8n()
pTrans->load( strQmFile.c_str()); pTrans->load( strQmFile.c_str());
QApplication::installTranslator( pTrans ); QApplication::installTranslator( pTrans );
} }
iot_public::installTranslator(strLanguage);
} }
@ -53,8 +56,8 @@ int main( int argc, char *argv[] )
SingleApplication a( argc, argv ); SingleApplication a( argc, argv );
QCoreApplication::setOrganizationName( "KbdSoft.ZHJK" ); QCoreApplication::setOrganizationName( "IOT" );
QCoreApplication::setOrganizationDomain( "KbdTech.com" ); QCoreApplication::setOrganizationDomain( "iot.com" );
QCoreApplication::setApplicationName( "db_manager" ); QCoreApplication::setApplicationName( "db_manager" );
iot_public::StartLogSystem( "PUBLIC", "db_manager" ); iot_public::StartLogSystem( "PUBLIC", "db_manager" );
@ -66,7 +69,7 @@ int main( int argc, char *argv[] )
QObject::connect( &a, &SingleApplication::instanceStarted, [&w]() QObject::connect( &a, &SingleApplication::instanceStarted, [&w]()
{ {
LOGINFO( "重新打开应用程序,开始工作!" ); LOGINFO( QObject::tr("重新打开应用程序,开始工作!").toStdString().c_str() );
w.show(); w.show();
w.showNormal(); w.showNormal();
w.activateWindow(); w.activateWindow();

View File

@ -1,11 +1,11 @@
#include <QDateTime> #include <QDateTime>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include <QFileDialog> #include <QFileDialog>
#include <QThread> #include <QThread>
#include <QInputDialog> #include <QInputDialog>
#include <QDockWidget> #include <QDockWidget>
#include <QPlainTextEdit> #include <QPlainTextEdit>
#include <QMenu>
#include "pub_utility_api/I18N.h" #include "pub_utility_api/I18N.h"
#include "public/pub_utility_api/FileUtil.h" #include "public/pub_utility_api/FileUtil.h"
@ -23,12 +23,17 @@
#include "db_set.h" #include "db_set.h"
#include"db_manager_common.h" #include"db_manager_common.h"
#include "../db_manager_api/db_manager_api_common.h" #include "../db_manager_api/db_manager_api_common.h"
#include "pub_utility_api/FileStyle.h"
#include "CCreateInfluxDBUserDlg.h"
using namespace iot_public; using namespace iot_public;
#define INDEX_NONDB_LOG 0 #define INDEX_NONDB_LOG 0
#define INDEX_LOG_STACK_PROJECT 3 #define INDEX_LOG_STACK_PROJECT 3
const int CN_MainTabIndex_Project = 0;
const int CN_MainTabIndex_DB = 1;
const int CN_MainTabIndex_Log = 2;
quint32 getDefaultImportExportType() quint32 getDefaultImportExportType()
{ {
@ -55,7 +60,7 @@ enum EN_ITEM_DATA_INDEX_TYPE
}; };
pj_manager::pj_manager(QWidget *parent) : pj_manager::pj_manager(QWidget *parent) :
QMainWindow(parent), CustomUiMainWindow(parent),
ui(new Ui::pj_manager), ui(new Ui::pj_manager),
m_his_backup_dockWidiget(NULL) m_his_backup_dockWidiget(NULL)
{ {
@ -80,6 +85,8 @@ pj_manager::pj_manager(QWidget *parent) :
appendTableInfoFromXml(sPlatFilePath, m_tableInfoMap ); appendTableInfoFromXml(sPlatFilePath, m_tableInfoMap );
appendTableInfoFromXml(sProdFilePath, m_tableInfoMap ); appendTableInfoFromXml(sProdFilePath, m_tableInfoMap );
setTitleWidget(ui->mainmenu);
} }
pj_manager::~pj_manager() pj_manager::~pj_manager()
@ -102,30 +109,49 @@ void pj_manager::initPath()
void pj_manager::loadQss() void pj_manager::loadQss()
{ {
QString qss; QString qss = QString();
QFile qssFile(":/res/pj_manager.qss"); std::string strFullPath = iot_public::CFileStyle::getPathOfStyleFile("public.qss","zh","light");
qssFile.open(QFile::ReadOnly);
if (qssFile.isOpen()) QFile qssfile1(QString::fromStdString(strFullPath));
qssfile1.open(QFile::ReadOnly);
if (qssfile1.isOpen())
{ {
qss = QLatin1String(qssFile.readAll()); qss += QLatin1String(qssfile1.readAll());
qApp->setStyleSheet(qss); qssfile1.close();
qssFile.close(); }
else
{
qDebug() << "public.qss 无法打开!";
}
strFullPath = iot_public::CFileStyle::getPathOfStyleFile("db_manager.qss","zh","light");
QFile qssfile2(QString::fromStdString(strFullPath));
qssfile2.open(QFile::ReadOnly);
if (qssfile2.isOpen())
{
qss += QLatin1String(qssfile2.readAll());
qssfile2.close();
} }
else else
{ {
qDebug() << "pj_manager.qss 无法打开!"; qDebug() << "db_manager.qss 无法打开!";
}
if (!qss.isEmpty())
{
qApp->setStyleSheet(qss);
} }
} }
void pj_manager::initUi() void pj_manager::initUi()
{ {
setWindowTitle(tr("工程管理工具")); setWindowTitle(tr("工程管理"));
#ifdef OS_LINUX #ifdef OS_LINUX
setWindowIcon( QIcon( ":res/db_manager.png" ) ); setWindowIcon( QIcon( ":res/db_manager.png" ) );
#endif #endif
ui->statusbar->hide(); // ui->statusbar->hide();
ui->menubar->hide();
setDisabled(); setDisabled();
ui->listWidget_error->setUniformItemSizes(true); ui->listWidget_error->setUniformItemSizes(true);
@ -147,7 +173,7 @@ void pj_manager::initUi()
initBackupTableWidget(); initBackupTableWidget();
initLabels(); initLabels();
ui->tabWidget_main->setCurrentIndex(0); ui->stackedWidget_main->setCurrentIndex(CN_MainTabIndex_Project);
ui->stackedWidget_project->setCurrentIndex(0); ui->stackedWidget_project->setCurrentIndex(0);
ui->stackedWidget_database->setCurrentIndex(0); ui->stackedWidget_database->setCurrentIndex(0);
ui->tab_his->setCurrentIndex(0); ui->tab_his->setCurrentIndex(0);
@ -159,10 +185,11 @@ void pj_manager::initUi()
ui->tabWidget_info->setTabIcon( 0, QIcon( ":res/msg_info.png" ) ); ui->tabWidget_info->setTabIcon( 0, QIcon( ":res/msg_info.png" ) );
ui->tabWidget_info->setTabIcon( 1, QIcon( ":res/msg_error.png" ) ); ui->tabWidget_info->setTabIcon( 1, QIcon( ":res/msg_error.png" ) );
QListWidgetItem *itemSelected1 = ui->listWidget->item(0);
QListWidgetItem *itemSelected2 = ui->listWidget_db->item(0); ui->listWidget->setCurrentRow(0);
itemSelected1->setSelected(true); ui->listWidget_db->setCurrentRow(0);
itemSelected2->setSelected(true); ui->listWidget_db->item(1)->setHidden(true); //厂站复用
ui->listWidget_db->item(2)->setHidden(true); //厂站合并
loadQss(); loadQss();
@ -174,10 +201,29 @@ void pj_manager::initUi()
//< 更改英文ui适配 //< 更改英文ui适配
if(isEn()) if(isEn())
{
initEnUi(); initEnUi();
}
initLogMngWidget(); initLogMngWidget();
QPushButton* btn;
btn = new QPushButton();
btn->setObjectName("btn_project");
btn->setText(tr("工程管理"));
ui->memuForm->addToolBtn(btn);
btn = new QPushButton();
btn->setObjectName("btn_dbManager");
btn->setText(tr("数据库管理"));
ui->memuForm->addToolBtn(btn);
btn = new QPushButton();
btn->setObjectName("btn_logManager");
btn->setText(tr("日志管理"));
ui->memuForm->addToolBtn(btn);
connect(ui->memuForm, SIGNAL(buttonClicked(int)),ui->stackedWidget_main, SLOT(setCurrentIndex(int)));
} }
@ -298,6 +344,8 @@ void pj_manager::onCreateTriggerDone()
void pj_manager::initConnect() void pj_manager::initConnect()
{ {
connect(ui->stackedWidget_main,SIGNAL(currentChanged(int)),this,SLOT(slotMainTableWidgetCurrentChanged(int)));
connect(m_pDma, SIGNAL(sig_showMsg(QString, int)), this, SLOT(onShowMsg(QString,int))); connect(m_pDma, SIGNAL(sig_showMsg(QString, int)), this, SLOT(onShowMsg(QString,int)));
connect(m_pDma, SIGNAL(signalPercent(int)), this, SLOT(onSetPercent(int))); connect(m_pDma, SIGNAL(signalPercent(int)), this, SLOT(onSetPercent(int)));
@ -340,6 +388,7 @@ void pj_manager::initConnect()
connect(this, SIGNAL(sigCreateTriggerDone()), this, SLOT(onCreateTriggerDone() ) ); connect(this, SIGNAL(sigCreateTriggerDone()), this, SLOT(onCreateTriggerDone() ) );
connect(this, SIGNAL(sigDeploy()), this, SLOT(slotDeploy() ) ); connect(this, SIGNAL(sigDeploy()), this, SLOT(slotDeploy() ) );
connect(ui->listWidget_db,SIGNAL(clicked(QModelIndex)),this,SLOT(onListWidgetDbChanged(QModelIndex))); connect(ui->listWidget_db,SIGNAL(clicked(QModelIndex)),this,SLOT(onListWidgetDbChanged(QModelIndex)));
connect(ui->listWidget_logMng,SIGNAL(clicked(QModelIndex)),this,SLOT(onListWidgetLogMngChanged(QModelIndex)));
connect(ui->treeWidget, SIGNAL( customContextMenuRequested(const QPoint&)), this, SLOT( slotTreeWidgetContextMenuRequest(const QPoint&) ) ); connect(ui->treeWidget, SIGNAL( customContextMenuRequested(const QPoint&)), this, SLOT( slotTreeWidgetContextMenuRequest(const QPoint&) ) );
connect(ui->treeWidget, SIGNAL( itemClicked(QTreeWidgetItem*, int)), this, SLOT( slotItemClicked(QTreeWidgetItem*, int)) ); connect(ui->treeWidget, SIGNAL( itemClicked(QTreeWidgetItem*, int)), this, SLOT( slotItemClicked(QTreeWidgetItem*, int)) );
connect(this, SIGNAL( sigSetDbProgressBar(int) ), ui->progressBar_db, SLOT( setValue(int) ) ); connect(this, SIGNAL( sigSetDbProgressBar(int) ), ui->progressBar_db, SLOT( setValue(int) ) );
@ -406,6 +455,11 @@ void pj_manager::onListWidgetDbChanged(QModelIndex index)
} }
} }
void pj_manager::onListWidgetLogMngChanged(QModelIndex)
{
}
void pj_manager::onShowBackup() void pj_manager::onShowBackup()
{ {
ui->stackedWidget_project->setCurrentIndex(0); ui->stackedWidget_project->setCurrentIndex(0);
@ -482,7 +536,6 @@ void pj_manager::setDisabled(bool value)
ui->page_backup->setDisabled(value); ui->page_backup->setDisabled(value);
ui->page_update->setDisabled(value); ui->page_update->setDisabled(value);
ui->page_hisdata->setDisabled(value); ui->page_hisdata->setDisabled(value);
ui->menubar->setDisabled(value);
ui->listWidget->setDisabled(value); ui->listWidget->setDisabled(value);
if(value) if(value)
pjUi = false; pjUi = false;
@ -492,14 +545,14 @@ void pj_manager::setDisabled(bool value)
void pj_manager::onConnDb() void pj_manager::onConnDb()
{ {
if(ui->tabWidget_main->currentIndex() == 0) if(ui->stackedWidget_main->currentIndex() == CN_MainTabIndex_Project)
{ {
if(ui->stackedWidget_project->currentIndex() == 0) if(ui->stackedWidget_project->currentIndex() == 0)
{ {
int value = ui->progressBar_backup->text().split("%")[0].toInt(); int value = ui->progressBar_backup->text().split("%")[0].toInt();
if( value > 0 && value < 100 ) if( value > 0 && value < 100 )
{ {
QMessageBox::warning(this, tr("警告"), tr("正在执行操作,请勿重新连接!") ); N_MessageBox::warning(this, tr("警告"), tr("正在执行操作,请勿重新连接!") );
return; return;
} }
} }
@ -508,7 +561,7 @@ void pj_manager::onConnDb()
int value = ui->progressBar_update->text().split("%")[0].toInt(); int value = ui->progressBar_update->text().split("%")[0].toInt();
if( value > 0 && value < 100 ) if( value > 0 && value < 100 )
{ {
QMessageBox::warning(this, tr("警告"), tr("正在执行操作,请勿重新连接!") ); N_MessageBox::warning(this, tr("警告"), tr("正在执行操作,请勿重新连接!") );
return; return;
} }
} }
@ -606,7 +659,7 @@ void pj_manager::onBackup()
Qt::WindowMaximizeButtonHint ); Qt::WindowMaximizeButtonHint );
if(!ok) if(!ok)
return; return;
if(ui->tabWidget_main->currentIndex() == 0 && ui->stackedWidget_project->currentIndex() == 0) if(ui->stackedWidget_main->currentIndex() == CN_MainTabIndex_Project && ui->stackedWidget_project->currentIndex() == 0)
{ {
if(ui->radioButton_db->isChecked()) if(ui->radioButton_db->isChecked())
{ {
@ -625,10 +678,11 @@ void pj_manager::onBackup()
void pj_manager::onRestore() void pj_manager::onRestore()
{ {
if(QMessageBox::question(this,tr("恢复提醒"),tr("请确认连接的数据库所配置的所有系统已经离线,本工具只支持离线恢复,是否继续")) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("恢复提醒"),tr("请确认连接的数据库所配置的所有系统已经离线,本工具只支持离线恢复,是否继续"))
!= N_MessageBox::Ok)
return; return;
if(ui->tabWidget_main->currentIndex() == 0 && ui->stackedWidget_project->currentIndex() == 0) if(ui->stackedWidget_main->currentIndex() == CN_MainTabIndex_Project && ui->stackedWidget_project->currentIndex() == 0)
{ {
if(ui->radioButton_db->isChecked()) if(ui->radioButton_db->isChecked())
{ {
@ -640,8 +694,9 @@ void pj_manager::onRestore()
} }
else if(ui->radioButton_comp->isChecked()) else if(ui->radioButton_comp->isChecked())
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, "提示", "请先关闭所有系统运行程序,\n包含net_keep_alived和db_his_data_srv.\n拷贝完成后,会关闭当前软件!\n是否继续", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("请先关闭所有系统运行程序,\n包含net_keep_alived和db_his_data_srv.\n拷贝完成后,会关闭当前软件!\n是否继续"),
if(resultButton == QMessageBox::No) N_MessageBox::Yes | N_MessageBox::No, N_MessageBox::Yes);
if(resultButton == N_MessageBox::No)
{ {
return; return;
} }
@ -656,8 +711,8 @@ void pj_manager::backupDb()
quint32 nExportType = getDefaultImportExportType(); quint32 nExportType = getDefaultImportExportType();
if(!m_pDma->backupDb(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName)) if(!m_pDma->backupDb(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName))
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -667,8 +722,8 @@ void pj_manager::backupDb()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份完成!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份完成!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
genBakCfg(); genBakCfg();
@ -679,7 +734,7 @@ void pj_manager::backupDb()
void pj_manager::onSetPercent(int nPercent) void pj_manager::onSetPercent(int nPercent)
{ {
int index1 = ui->tabWidget_main->currentIndex(); int index1 = ui->stackedWidget_main->currentIndex();
if(index1 == 0) if(index1 == 0)
{ {
int index2 = ui->stackedWidget_project->currentIndex(); int index2 = ui->stackedWidget_project->currentIndex();
@ -788,11 +843,7 @@ void pj_manager::initUpdateTableWidget()
void pj_manager::initLogMngWidget() void pj_manager::initLogMngWidget()
{ {
QGridLayout* layout = new QGridLayout; connect(ui->logMngWidget,&CLogMngWidget::showMsg,this,&pj_manager::onShowMsg);
m_logMngWidget = new CLogMngWidget;
ui->page_logmng->setLayout(layout);
ui->page_logmng->layout()->addWidget(m_logMngWidget);
connect(m_logMngWidget,&CLogMngWidget::showMsg,this,&pj_manager::onShowMsg);
} }
void pj_manager::onRadioButtonChanged() void pj_manager::onRadioButtonChanged()
@ -806,8 +857,8 @@ void pj_manager::backupSimp()
if(!m_pDma->backupSimp(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName ) ) if(!m_pDma->backupSimp(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName ) )
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -817,8 +868,8 @@ void pj_manager::backupSimp()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份完成!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份完成!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
genBakCfg(); genBakCfg();
@ -832,8 +883,8 @@ void pj_manager::backupComp()
quint32 nExportType = getDefaultImportExportType(); quint32 nExportType = getDefaultImportExportType();
if(!m_pDma->backupComp(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName) ) if(!m_pDma->backupComp(m_pDbOpt, m_sDatabaseName, nExportType,m_currentBackupName) )
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -843,8 +894,8 @@ void pj_manager::backupComp()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("备份完成!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("备份完成!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
genBakCfg(); genBakCfg();
@ -859,7 +910,7 @@ void pj_manager::restoreDb()
QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems(); QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems();
if( ptableItem.count() <= 0 ) if( ptableItem.count() <= 0 )
{ {
QMessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") ); N_MessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") );
return; return;
} }
@ -872,8 +923,8 @@ void pj_manager::restoreDb()
} }
if( !m_pDma->restoreDb( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) ) if( !m_pDma->restoreDb( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) )
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -883,8 +934,8 @@ void pj_manager::restoreDb()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复成功!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复成功!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -898,7 +949,7 @@ void pj_manager::restoreSimp()
QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems(); QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems();
if( ptableItem.count() <= 0 ) if( ptableItem.count() <= 0 )
{ {
QMessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") ); N_MessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") );
return; return;
} }
@ -911,8 +962,8 @@ void pj_manager::restoreSimp()
} }
if( !m_pDma->restoreSimp( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) ) if( !m_pDma->restoreSimp( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) )
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -922,8 +973,8 @@ void pj_manager::restoreSimp()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复成功!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复成功!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -937,7 +988,7 @@ void pj_manager::restoreComp()
QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems(); QList<QTableWidgetItem*> ptableItem = ui->tableWidget_backup->selectedItems();
if( ptableItem.count() <= 0 ) if( ptableItem.count() <= 0 )
{ {
QMessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") ); N_MessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") );
return; return;
} }
@ -950,8 +1001,8 @@ void pj_manager::restoreComp()
} }
if( !m_pDma->restoreComp( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) ) if( !m_pDma->restoreComp( m_pDbOpt ,m_sDatabaseName, sBackupContent, nImportType ) )
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -961,8 +1012,8 @@ void pj_manager::restoreComp()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("恢复成功!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("恢复成功!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetBackupProgressBar(0); emit sigSetBackupProgressBar(0);
@ -976,7 +1027,7 @@ void pj_manager::onUpdateExe()
int index = ui->tabWidget_update->currentIndex(); int index = ui->tabWidget_update->currentIndex();
if( index == 0 ) if( index == 0 )
{ {
if(QMessageBox::question(this,tr("升级提醒"),tr("升级操作将会对当前工程数据和数据库进行覆盖,请确认是否继续?")) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("升级提醒"),tr("升级操作将会对当前工程数据和数据库进行覆盖,请确认是否继续?"), N_MessageBox::Yes) != N_MessageBox::Yes)
return; return;
updateProject(); updateProject();
} }
@ -990,7 +1041,7 @@ void pj_manager::updateProject()
QList<QTableWidgetItem*> ptableItem = ui->tableWidget_update->selectedItems(); QList<QTableWidgetItem*> ptableItem = ui->tableWidget_update->selectedItems();
if( ptableItem.count() <= 0 ) if( ptableItem.count() <= 0 )
{ {
QMessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") ); N_MessageBox::warning( this, tr("警告"), tr("请在备份记录中选择一项备份的工程!") );
return; return;
} }
@ -998,8 +1049,8 @@ void pj_manager::updateProject()
QString sBackupContent = "/" + ptItem->text(); QString sBackupContent = "/" + ptItem->text();
if(!m_pDma->updateProject(m_pDbOpt, m_sDatabaseName, sBackupContent)) if(!m_pDma->updateProject(m_pDbOpt, m_sDatabaseName, sBackupContent))
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("升级失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("升级失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetUpdateProgressBar(0); emit sigSetUpdateProgressBar(0);
initLabels(); initLabels();
@ -1009,8 +1060,8 @@ void pj_manager::updateProject()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("升级成功!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("升级成功!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetUpdateProgressBar(0); emit sigSetUpdateProgressBar(0);
initLabels(); initLabels();
@ -1023,8 +1074,8 @@ void pj_manager::updateDatabase()
{ {
if(!m_pDma->updateDatabase(m_pDbOpt, m_sDatabaseName)) if(!m_pDma->updateDatabase(m_pDbOpt, m_sDatabaseName))
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("升级失败!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("升级失败!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetUpdateProgressBar(0); emit sigSetUpdateProgressBar(0);
initLabels(); initLabels();
@ -1033,8 +1084,8 @@ void pj_manager::updateDatabase()
} }
else else
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("升级成功!"), QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("升级成功!"), N_MessageBox::Yes);
if(resultButton == QMessageBox::Yes) if(resultButton == N_MessageBox::Yes)
{ {
emit sigSetUpdateProgressBar(0); emit sigSetUpdateProgressBar(0);
initLabels(); initLabels();
@ -1151,6 +1202,7 @@ void pj_manager::slotTreeWidgetContextMenuRequest( const QPoint& )
menu.addAction( tr("删除数据服务配置"), this, SLOT( slotDeleteDatabaseServiceSet() ) ); menu.addAction( tr("删除数据服务配置"), this, SLOT( slotDeleteDatabaseServiceSet() ) );
menu.addSeparator(); menu.addSeparator();
menu.addAction( tr("新建数据库"), this, SLOT(onCreateDatabase() ) ); menu.addAction( tr("新建数据库"), this, SLOT(onCreateDatabase() ) );
menu.addAction( tr("新建influxDB用户") ,this , SLOT( slotCreateInflucDBUser()));
} }
else if ( nItemType == EN_ITEM_DATABASE ) else if ( nItemType == EN_ITEM_DATABASE )
{ {
@ -1294,8 +1346,8 @@ void pj_manager::slotDisConnectDatabaseService()
void pj_manager::slotAddDatabaseServiceSet() void pj_manager::slotAddDatabaseServiceSet()
{ {
db_set* pDbSet = new db_set( this ); db_set* pDbSet = new db_set( this );
pDbSet->setTitle( tr("增加数据配置") ); pDbSet->setTitle( tr("增加数据配置") );
if ( pDbSet && pDbSet->exec() == QDialog::Accepted ) if ( pDbSet && pDbSet->exec() == CustomUiDialog::Accepted )
{ {
QTreeWidgetItem* pItem = new QTreeWidgetItem; QTreeWidgetItem* pItem = new QTreeWidgetItem;
pItem->setText( 0, pDbSet->getName() ); pItem->setText( 0, pDbSet->getName() );
@ -1323,8 +1375,8 @@ void pj_manager::slotModifyDatabaseServiceSet()
if ( pItem->childCount() > 0 ) if ( pItem->childCount() > 0 )
{ {
QMessageBox::StandardButton button = QMessageBox::information( this, tr("提示"), tr("修改配置需要断开数据库连接,是否断开?"), QMessageBox::Yes, QMessageBox::No ); int button = N_MessageBox::information( this, tr("提示"), tr("修改配置需要断开数据库连接,是否断开?"), N_MessageBox::Yes, N_MessageBox::No );
if ( button == QMessageBox::StandardButton::Yes ) if ( button == N_MessageBox::Yes )
slotDisConnectDatabaseService(); slotDisConnectDatabaseService();
else else
return; return;
@ -1339,7 +1391,7 @@ void pj_manager::slotModifyDatabaseServiceSet()
pDbSet->setUser( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_USER ).toString() ); pDbSet->setUser( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_USER ).toString() );
pDbSet->setPasswd( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_PASSWD ).toString() ); pDbSet->setPasswd( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_PASSWD ).toString() );
if ( pDbSet->exec() == QDialog::Accepted ) if ( pDbSet->exec() == CustomUiDialog::Accepted )
{ {
pItem->setText( 0, pDbSet->getName() ); pItem->setText( 0, pDbSet->getName() );
pItem->setData( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_DBTYPE, pDbSet->getDbType() ); pItem->setData( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_DBTYPE, pDbSet->getDbType() );
@ -1359,7 +1411,7 @@ void pj_manager::slotDeleteDatabaseServiceSet()
db_opt* pDbOpt = getDbOpt( ui->treeWidget->currentItem() ); db_opt* pDbOpt = getDbOpt( ui->treeWidget->currentItem() );
if ( pDbOpt != NULL ) if ( pDbOpt != NULL )
{ {
QMessageBox::information( this, tr("提示"), tr("请先断开数据服务") ); N_MessageBox::information( this, tr("提示"), tr("请先断开数据服务") );
return; return;
} }
@ -1389,8 +1441,8 @@ void pj_manager::slotImportBaseData()
if(strLanguage.empty()) if(strLanguage.empty())
return; return;
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("导入基础数据将会清空原来表中的数据,是否导入?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("导入基础数据将会清空原来表中的数据,是否导入?"), N_MessageBox::Yes | N_MessageBox::No, N_MessageBox::Yes);
if(resultButton == QMessageBox::No) if(resultButton == N_MessageBox::No)
{ {
return; return;
} }
@ -1408,7 +1460,7 @@ void pj_manager::slotImportBaseData()
} }
else else
{ {
QMessageBox::warning( this, tr("警告"), tr("无法打开基础数据路径!") ); N_MessageBox::warning( this, tr("警告"), tr("无法打开基础数据路径!") );
} }
if( sListFile.count() == 0 ) if( sListFile.count() == 0 )
@ -1432,8 +1484,8 @@ void pj_manager::slotImportBaseData()
void pj_manager::slotUpdateDatabase() void pj_manager::slotUpdateDatabase()
{ {
QMessageBox::StandardButton button = QMessageBox::information( this, tr("提示"), tr("升级数据库将会修改表结构,确认升级?"), QMessageBox::Yes, QMessageBox::No ); int button = N_MessageBox::information( this, tr("提示"), tr("升级数据库将会修改表结构,确认升级?"), N_MessageBox::Yes, N_MessageBox::No );
if ( button != QMessageBox::StandardButton::Yes ) if ( button != N_MessageBox::Yes )
return; return;
QTreeWidgetItem* pItem = ui->treeWidget->currentItem(); QTreeWidgetItem* pItem = ui->treeWidget->currentItem();
@ -1441,7 +1493,7 @@ void pj_manager::slotUpdateDatabase()
return; return;
if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE ) if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库选择错误") ); N_MessageBox::warning( this, tr("警告"), tr("数据库选择错误") );
return; return;
} }
QString sDatabaseName = pItem->text( 0 ); QString sDatabaseName = pItem->text( 0 );
@ -1484,7 +1536,7 @@ bool pj_manager::slotCreateTrigger()
return false; return false;
if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE ) if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库选择错误") ); N_MessageBox::warning( this, tr("警告"), tr("数据库选择错误") );
return false; return false;
} }
QString sDatabaseName = pItem->text( 0 ); QString sDatabaseName = pItem->text( 0 );
@ -1507,7 +1559,7 @@ bool pj_manager::slotDeleteTrigger()
if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE ) if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库选择错误") ); N_MessageBox::warning( this, tr("警告"), tr("数据库选择错误") );
return false; return false;
} }
@ -1527,12 +1579,12 @@ bool pj_manager::slotDeleteTrigger()
void pj_manager::slotDeleteDatabase() void pj_manager::slotDeleteDatabase()
{ {
QMessageBox::StandardButton button = QMessageBox::information( this, tr("提示"), tr("确认删除数据库?"), QMessageBox::Yes, QMessageBox::No ); int button = N_MessageBox::information( this, tr("提示"), tr("确认删除数据库?"), N_MessageBox::Yes, N_MessageBox::No );
if ( button != QMessageBox::StandardButton::Yes ) if ( button != N_MessageBox::Yes )
return; return;
button = QMessageBox::information( this, tr("提示"), tr("请再次确认删除数据库?"), QMessageBox::Yes, QMessageBox::No ); button = N_MessageBox::information( this, tr("提示"), tr("请再次确认删除数据库?"), N_MessageBox::Yes, N_MessageBox::No );
if ( button != QMessageBox::StandardButton::Yes ) if ( button != N_MessageBox::Yes )
return; return;
QTreeWidgetItem* pItemService = ui->treeWidget->currentItem()->parent(); QTreeWidgetItem* pItemService = ui->treeWidget->currentItem()->parent();
@ -1591,7 +1643,7 @@ void pj_manager::slotExecuteSqlScript()
if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE ) if ( pItem->data( 0, Qt::UserRole + EN_ITEM_DATA_INDEX_ITEMTYPE ).toInt() != EN_ITEM_DATABASE )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库选择错误") ); N_MessageBox::warning( this, tr("警告"), tr("数据库选择错误") );
return; return;
} }
@ -1628,7 +1680,7 @@ void pj_manager::slotDeploy()
case iot_dbms::EDbType::DB_MYSQL: case iot_dbms::EDbType::DB_MYSQL:
info.db_type = "mysql"; break; info.db_type = "mysql"; break;
case iot_dbms::EDbType::DB_OPENGAUSS: case iot_dbms::EDbType::DB_OPENGAUSS:
info.db_type = "openguass"; info.db_type = "opengauss";
m_pDbOpt->closeDatabase(); m_pDbOpt->closeDatabase();
break; break;
case iot_dbms::EDbType::DB_KINGBASE: case iot_dbms::EDbType::DB_KINGBASE:
@ -1636,8 +1688,8 @@ void pj_manager::slotDeploy()
m_pDbOpt->closeDatabase(); m_pDbOpt->closeDatabase();
break; break;
default: default:
LOGERROR("不支持的数据库类型!"); LOGERROR(tr("不支持的数据库类型!").toStdString().c_str());
onShowMsg("初始化完整工程失败:不支持的数据库类型!",1); onShowMsg(tr("初始化完整工程失败:不支持的数据库类型!"), 1);
return; return;
} }
@ -1646,7 +1698,7 @@ void pj_manager::slotDeploy()
onShowMsg(tr("开始初始化完整工程")); onShowMsg(tr("开始初始化完整工程"));
if(!m_pDma->initCompleteProject()) if(!m_pDma->initCompleteProject())
{ {
onShowMsg("初始化完整工程失败!",1); onShowMsg(tr("初始化完整工程失败!"),1);
} }
switch (m_pDbOpt->getDbType()) switch (m_pDbOpt->getDbType())
{ {
@ -1660,8 +1712,8 @@ void pj_manager::slotDeploy()
m_pDbOpt->openDatabase(info.address,info.port,info.username,info.password,info.db_name); m_pDbOpt->openDatabase(info.address,info.port,info.username,info.password,info.db_name);
break; break;
default: default:
LOGERROR("不支持的数据库类型!"); LOGERROR(tr("不支持的数据库类型!").toStdString().c_str());
onShowMsg("初始化完整工程失败:不支持的数据库类型!",1); onShowMsg(tr("初始化完整工程失败:不支持的数据库类型!"),1);
return; return;
} }
} }
@ -1878,6 +1930,13 @@ void pj_manager::appendTableInfoFromXml( const QString& sFilePath,QMap<QString,
{ {
if("Table" == eleTable.tagName()) if("Table" == eleTable.tagName())
{ {
QString sUseType = eleTable.attribute("use_type");
if(sUseType.isEmpty())
{
eleTable = eleTable.nextSiblingElement();
continue; //< 为空表示禁用
}
QString sTableName = eleTable.attribute("name"); QString sTableName = eleTable.attribute("name");
QDomElement table_db = eleTable.firstChildElement(); QDomElement table_db = eleTable.firstChildElement();
sTableInfos tableInfo; sTableInfos tableInfo;
@ -1973,7 +2032,7 @@ bool pj_manager::getImportExportType(const QString &sBackupContent,quint32 &nImp
{ {
if ( isDbTypeDiff ) if ( isDbTypeDiff )
{ {
if(QMessageBox::question(this,tr("提醒"),tr("检测到正在进行跨数据库恢复备份,\n将只升级数据库和导入数据,\n是否继续?")) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("提醒"),tr("检测到正在进行跨数据库恢复备份,\n将只升级数据库和导入数据,\n是否继续?")) != N_MessageBox::Ok)
return false; return false;
nImportType = 0; nImportType = 0;
nImportType = EN_IMPORT_DATA | EN_IMPORT_UPDATE; nImportType = EN_IMPORT_DATA | EN_IMPORT_UPDATE;
@ -2161,8 +2220,8 @@ void pj_manager::slotComboBoxDataBaseDstCurrentIndexChanged(const QString &sText
void pj_manager::slotPushButtonMergeClicked() void pj_manager::slotPushButtonMergeClicked()
{ {
QMessageBox::StandardButton resultButton = QMessageBox::information(this, tr("提示"), tr("请确保源数据库和目标数据库的所有表结构一致,否则会出错!"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); int resultButton = N_MessageBox::information(this, tr("提示"), tr("请确保源数据库和目标数据库的所有表结构一致,否则会出错!"), N_MessageBox::Yes | N_MessageBox::No, N_MessageBox::Yes);
if(resultButton == QMessageBox::No) if(resultButton == N_MessageBox::No)
{ {
return; return;
} }
@ -2172,65 +2231,65 @@ void pj_manager::slotPushButtonMergeClicked()
QString sDataBaseDst = ui->comboBox_db_dst->currentText(); QString sDataBaseDst = ui->comboBox_db_dst->currentText();
if ( sDataServiceOrg == "" ) if ( sDataServiceOrg == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源数据服务") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源数据服务") );
return; return;
} }
if ( sDataBaseOrg == "" ) if ( sDataBaseOrg == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源数据库") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源数据库") );
return; return;
} }
if ( sDataServiceDst == "" ) if ( sDataServiceDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标数据服务") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标数据服务") );
return; return;
} }
if ( sDataBaseDst == "" ) if ( sDataBaseDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标数据库") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标数据库") );
return; return;
} }
db_opt* pDbOpt_org = (db_opt*)ui->comboBox_sv_src->currentData( Qt::UserRole ).toULongLong(); db_opt* pDbOpt_org = (db_opt*)ui->comboBox_sv_src->currentData( Qt::UserRole ).toULongLong();
if ( pDbOpt_org == NULL ) if ( pDbOpt_org == NULL )
{ {
QMessageBox::warning( this, tr("警告"), tr("源数据服务未连接") ); N_MessageBox::warning( this, tr("警告"), tr("源数据服务未连接") );
return; return;
} }
db_opt* pDbOpt_dst = (db_opt*)ui->comboBox_sv_dst->currentData( Qt::UserRole ).toULongLong(); db_opt* pDbOpt_dst = (db_opt*)ui->comboBox_sv_dst->currentData( Qt::UserRole ).toULongLong();
if ( pDbOpt_dst == NULL ) if ( pDbOpt_dst == NULL )
{ {
QMessageBox::warning( this, tr("警告"), tr("目标数据服务未连接") ); N_MessageBox::warning( this, tr("警告"), tr("目标数据服务未连接") );
return; return;
} }
if ( sDataServiceOrg == sDataServiceDst && sDataBaseOrg == sDataBaseDst ) if ( sDataServiceOrg == sDataServiceDst && sDataBaseOrg == sDataBaseDst )
{ {
QMessageBox::warning( this, tr("警告"), tr("源和目标不能相同") ); N_MessageBox::warning( this, tr("警告"), tr("源和目标不能相同") );
return; return;
} }
QString sSubStationSrc = ui->comboBox_station->currentText(); QString sSubStationSrc = ui->comboBox_station->currentText();
if ( sSubStationSrc == "" ) if ( sSubStationSrc == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源车站") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源车站") );
return; return;
} }
int nSubStationIdSrc = ui->comboBox_station->currentData().toInt(); int nSubStationIdSrc = ui->comboBox_station->currentData().toInt();
QString sSubSystemSrc = ui->comboBox_subsystem->currentText(); QString sSubSystemSrc = ui->comboBox_subsystem->currentText();
if ( sSubSystemSrc == "" ) if ( sSubSystemSrc == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择源专业") ); N_MessageBox::warning( this, tr("警告"), tr("未选择源专业") );
return; return;
} }
int nSubSystemIdSrc = ui->comboBox_subsystem->currentData().toInt(); int nSubSystemIdSrc = ui->comboBox_subsystem->currentData().toInt();
if ( nSubSystemIdSrc <= 0 ) if ( nSubSystemIdSrc <= 0 )
{ {
QMessageBox::warning( this, tr("警告"), tr("专业ID不正确ID值") + QString::number( nSubSystemIdSrc ) ); N_MessageBox::warning( this, tr("警告"), tr("专业ID不正确ID值") + QString::number( nSubSystemIdSrc ) );
return; return;
} }
QString sSubStationDst = ui->comboBox_station_2->currentText(); QString sSubStationDst = ui->comboBox_station_2->currentText();
if ( sSubStationDst == "" ) if ( sSubStationDst == "" )
{ {
QMessageBox::warning( this, tr("警告"), tr("未选择目标车站") ); N_MessageBox::warning( this, tr("警告"), tr("未选择目标车站") );
return; return;
} }
int nSubStationIdDst = ui->comboBox_station_2->currentData().toInt(); int nSubStationIdDst = ui->comboBox_station_2->currentData().toInt();
@ -2244,12 +2303,79 @@ void pj_manager::slotShowBackupFolder(int row, int /*column*/)
showInFolder(getBackupDir() + QDir::separator() + ui->tableWidget_backup->item(row,2)->text()); showInFolder(getBackupDir() + QDir::separator() + ui->tableWidget_backup->item(row,2)->text());
} }
void pj_manager::slotMainTableWidgetCurrentChanged(int index)
{
if(index == CN_MainTabIndex_Log)
{
ui->stackedWidget_logMng->setCurrentIndex(0);
ui->listWidget_logMng->setFocus();
ui->listWidget_logMng->setCurrentRow(0);
}
}
void pj_manager::slotCreateInflucDBUser()
{
// 用户名及密码
CCreateInfluxDBUserDlg dlg(this);
dlg.setIP(QString("127.0.0.1"));
dlg.setAdminUser(QString(EMS_DEFAULT_DATABASE));
dlg.setUserInfo(QString("rqeh6001"));
dlg.setPassWord(QString(EMS_DEFAULT_PASSWD));
if( dlg.exec() == QDialog::Accepted)
{
QString localhost = dlg.getIP();
QString adminUser = dlg.getAdminUser();
QString password = dlg.getPassWordInfo();
QString userinfo = dlg.getUserInfo();
if (!createInfluxDBUser(adminUser,password,localhost ,userinfo))
{
N_MessageBox::warning( this, tr("警告"), tr("用户创建失败") );
}else
{
N_MessageBox::information(this , tr("提示") , tr("用户创建成功"));
}
}
}
bool pj_manager::createInfluxDBUser(const QString &adminUser, const QString &password, const QString &host, const QString &username)
{
bool ret = false;
QString program = "influx";
// 构造命令参数
QStringList arguments;
arguments << "-username" << adminUser
<< "-password" << password
<< "-host" << host
<< "-execute"
<< QString("create user %1 with password '%2' with all privileges").arg(username, EMS_DEFAULT_PASSWD);
QProcess process;
process.start(program, arguments);
if (!process.waitForFinished(-1)) {
LOGERROR( "Failed to execute command: %s" , process.errorString().toStdString().c_str() );
return ret;
}
// 检查命令输出
QString output = process.readAllStandardOutput();
QString errorOutput = process.readAllStandardError();
if (!errorOutput.isEmpty()) {
LOGERROR( "Error occurred while creating user: %s", errorOutput.toStdString().c_str());
} else {
LOGERROR("User created successfully: %s", output.toStdString().c_str());
ret = true;
}
return ret;
}
bool pj_manager::databaseCheck() bool pj_manager::databaseCheck()
{ {
db_opt* pDbOpt = getDbOpt( ui->treeWidget->currentItem() ); db_opt* pDbOpt = getDbOpt( ui->treeWidget->currentItem() );
if ( pDbOpt == NULL ) if ( pDbOpt == NULL )
{ {
QMessageBox::information( this, tr("提示"), tr("请先连接数据服务") ); N_MessageBox::information( this, tr("提示"), tr("请先连接数据服务") );
return false; return false;
} }
@ -2264,7 +2390,7 @@ bool pj_manager::databaseCheck()
bool ok; bool ok;
sDatabaseName = QInputDialog::getText( this, tr( "新建数据库" ), sDatabaseName = QInputDialog::getText( this, tr( "新建数据库" ),
tr( "数据库名:" ), QLineEdit::Normal, tr( "数据库名:" ), QLineEdit::Normal,
"iscs6000", &ok, Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint ); EMS_DEFAULT_DATABASE, &ok, Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint );
if ( !ok || sDatabaseName.isEmpty() ) if ( !ok || sDatabaseName.isEmpty() )
return false; return false;
@ -2275,7 +2401,7 @@ bool pj_manager::databaseCheck()
{ {
if ( listDatabase.at( i ).toLower() == sDatabaseName.toLower() ) if ( listDatabase.at( i ).toLower() == sDatabaseName.toLower() )
{ {
QMessageBox::critical( this, tr("错误"), tr("已有同名数据库,创建失败") ); N_MessageBox::critical( this, tr("错误"), tr("已有同名数据库,创建失败") );
return false; return false;
} }
} }
@ -2286,7 +2412,7 @@ bool pj_manager::databaseCheck()
ushort uni = cha.unicode(); ushort uni = cha.unicode();
if( uni >= 0x4E00 && uni <= 0x9FA5 ) if( uni >= 0x4E00 && uni <= 0x9FA5 )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库名不能为汉字") ); N_MessageBox::warning( this, tr("警告"), tr("数据库名不能为汉字") );
return false; return false;
} }
} }
@ -2295,13 +2421,13 @@ bool pj_manager::databaseCheck()
sDatabaseName.startsWith("5") || sDatabaseName.startsWith("6") || sDatabaseName.startsWith("7") || sDatabaseName.startsWith("8") || \ sDatabaseName.startsWith("5") || sDatabaseName.startsWith("6") || sDatabaseName.startsWith("7") || sDatabaseName.startsWith("8") || \
sDatabaseName.startsWith("9") || sDatabaseName.startsWith("0") ) sDatabaseName.startsWith("9") || sDatabaseName.startsWith("0") )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库名不能以数字开头") ); N_MessageBox::warning( this, tr("警告"), tr("数据库名不能以数字开头") );
return false; return false;
} }
if( sDatabaseName.contains("-") ) if( sDatabaseName.contains("-") )
{ {
QMessageBox::warning( this, tr("警告"), tr("数据库名不能包含中划线") ); N_MessageBox::warning( this, tr("警告"), tr("数据库名不能包含中划线") );
return false; return false;
} }
return true; return true;
@ -2328,23 +2454,26 @@ bool pj_manager::createDatabase()
else else
{ {
onShowMsg( sError, 1 ); onShowMsg( sError, 1 );
QMessageBox::critical( this, tr("错误"), tr("数据库创建失败") ); N_MessageBox::critical( this, tr("错误"), tr("数据库创建失败") );
return false; return false;
} }
if(pDbOpt->getDbType() == iot_dbms::DB_KINGBASE ) if(pDbOpt->getDbType() == iot_dbms::DB_KINGBASE )
{ {
sSql = "CREATE SCHEMA iscs6000;" ; /* 为以后搜索方便保留此注释。mysql的database实际应该对应schema
* sSql = QString("CREATE SCHEMA %1;").arg(EMS_DEFAULT_DATABASE) ;
*/
sSql = QString("CREATE SCHEMA %1;").arg(sDatabaseName) ;
if(!pDbOpt->switchDatabase(sDatabaseName)) if(!pDbOpt->switchDatabase(sDatabaseName))
{ {
QMessageBox::critical( this, tr("错误"), tr("无法切换到数据库") ); N_MessageBox::critical( this, tr("错误"), tr("无法切换到数据库") );
return false; return false;
} }
if( !pDbOpt->executeSql( sSql, sError ) ) if( !pDbOpt->executeSql( sSql, sError ) )
{ {
onShowMsg( sError, 1 ); onShowMsg( sError, 1 );
QMessageBox::critical( this, tr("错误"), tr("模式创建失败") ); N_MessageBox::critical( this, tr("错误"), tr("模式创建失败") );
return false; return false;
} }
} }
@ -2361,9 +2490,9 @@ void pj_manager::initHisMng()
connect(m_pHisMng,& iot_dbms::CHisMngApi::error,this,&pj_manager::addErrMsg); connect(m_pHisMng,& iot_dbms::CHisMngApi::error,this,&pj_manager::addErrMsg);
connect(this,&pj_manager::optimizeDbSpace,m_pHisMng,& iot_dbms::CHisMngApi::optimizeDbSpace); connect(this,&pj_manager::optimizeDbSpace,m_pHisMng,& iot_dbms::CHisMngApi::optimizeDbSpace);
connect(m_pHisMng,& iot_dbms::CHisMngApi::optimizeDbSpaceFinished,this,&pj_manager::handleOptimizeDbSpaceFinished); connect(m_pHisMng,& iot_dbms::CHisMngApi::optimizeDbSpaceFinished,this,&pj_manager::handleOptimizeDbSpaceFinished);
connect(this,&pj_manager::delHisAll,m_pHisMng,& iot_dbms::CHisMngApi::delHisAll); connect(this,&pj_manager::delHisAll,m_pHisMng,& iot_dbms::CHisMngApi::delHisAllV2);
connect(m_pHisMng,& iot_dbms::CHisMngApi::delHisAllFinished,this,&pj_manager::handleDelHisAllFinished); connect(m_pHisMng,& iot_dbms::CHisMngApi::delHisAllFinished,this,&pj_manager::handleDelHisAllFinished);
connect(this,&pj_manager::delHis,m_pHisMng,& iot_dbms::CHisMngApi::delHis); connect(this,&pj_manager::delHis,m_pHisMng,& iot_dbms::CHisMngApi::delHisV2);
connect(m_pHisMng,& iot_dbms::CHisMngApi::delHisFinished,this,&pj_manager::handleDelHisFinished); connect(m_pHisMng,& iot_dbms::CHisMngApi::delHisFinished,this,&pj_manager::handleDelHisFinished);
hisWorkThread.start(); hisWorkThread.start();
@ -2493,7 +2622,7 @@ void pj_manager::onCreateDatabase()
void pj_manager::onMsgDlg(const QString &msg) void pj_manager::onMsgDlg(const QString &msg)
{ {
QMessageBox::information( this, tr("提醒"), msg ); N_MessageBox::information( this, tr("提醒"), msg );
} }
void pj_manager::on_listWidget_nondb_clicked(const QModelIndex &index) void pj_manager::on_listWidget_nondb_clicked(const QModelIndex &index)
@ -2517,7 +2646,10 @@ void pj_manager::on_comboBox_product_currentTextChanged(const QString &arg1)
void pj_manager::on_btn_deploy_clicked() void pj_manager::on_btn_deploy_clicked()
{ {
if(QMessageBox::question(this,tr("部署提醒"),tr("请确认连接的数据库所配置的所有系统已经离线,\n所部署的数据库将无法恢复,请注意备份,\n是否继续?")) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("部署提醒"),tr("请确认连接的数据库所配\n"
"置的所有系统已经离线,所\n"
"部署的数据库将无法恢复,\n"
"请注意备份,是否继续?")) != N_MessageBox::Ok)
return; return;
emit sigDeploy(); emit sigDeploy();
} }

View File

@ -14,6 +14,8 @@
#include <tchar.h> #include <tchar.h>
#include "db_manager_common.h" #include "db_manager_common.h"
#endif #endif
#include "pub_widget/CustomMainWindow.h"
namespace Ui { namespace Ui {
class pj_manager; class pj_manager;
@ -29,7 +31,7 @@ struct sTableInfos
using namespace iot_dbms; using namespace iot_dbms;
class CLogMngWidget; class CLogMngWidget;
class pj_manager : public QMainWindow class pj_manager : public CustomUiMainWindow
{ {
Q_OBJECT Q_OBJECT
@ -65,6 +67,7 @@ signals:
private slots: private slots:
void onListWidgetChanged(QModelIndex); void onListWidgetChanged(QModelIndex);
void onListWidgetDbChanged(QModelIndex); void onListWidgetDbChanged(QModelIndex);
void onListWidgetLogMngChanged(QModelIndex);
void onShowBackup(); void onShowBackup();
void onShowUpdate(); void onShowUpdate();
void onShowDeploy(); void onShowDeploy();
@ -119,7 +122,10 @@ private slots:
void slotPushButtonMergeClicked(); void slotPushButtonMergeClicked();
void slotShowBackupFolder(int row,int column); void slotShowBackupFolder(int row,int column);
void slotMainTableWidgetCurrentChanged(int index);
void slotCreateInflucDBUser(); //创建influxdb 数据库用户
bool createInfluxDBUser(const QString &adminUser, const QString &password, const QString &host, const QString &username); //创建influxdb 数据库用户
//< 历史数据相关====================================================================================================================================================== //< 历史数据相关======================================================================================================================================================
void on_tab_his_currentChanged(int index); //历史stackwidget标签页切换 void on_tab_his_currentChanged(int index); //历史stackwidget标签页切换
@ -145,6 +151,7 @@ private slots:
//< 转储相关 //< 转储相关
void isLocalHostPageChange();// 判断是否本地地址来决定加载转储页面 void isLocalHostPageChange();// 判断是否本地地址来决定加载转储页面
bool isCfgExist();
void on_btn_export_cfg_clicked(); // 导出转储配置按钮 void on_btn_export_cfg_clicked(); // 导出转储配置按钮
void on_btn_start_srv_clicked(); // 开始转储服务 void on_btn_start_srv_clicked(); // 开始转储服务
void on_btn_close_srv_clicked(); // 关闭转储服务 void on_btn_close_srv_clicked(); // 关闭转储服务
@ -277,12 +284,9 @@ private:
QSet<QString> m_setHisTabls; QSet<QString> m_setHisTabls;
QDockWidget* m_his_backup_dockWidiget; // 历史对象信息查看ui QDockWidget* m_his_backup_dockWidiget; // 历史对象信息查看ui
CLogMngWidget* m_logMngWidget; // 日志管理ui
bool pjUi = false; //工程管理界面是否可用 bool pjUi = false; //工程管理界面是否可用
bool dbUi = true; //数据管理界面是否可用 bool dbUi = true; //数据管理界面是否可用
}; };
#endif // PJ_MANAGER_H #endif // PJ_MANAGER_H

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
**/ **/
#include <QDateTime> #include <QDateTime>
#include <QMessageBox> #include "pub_widget/MessageBox.h"
#include <QFileDialog> #include <QFileDialog>
#include <QThread> #include <QThread>
#include <QInputDialog> #include <QInputDialog>
@ -15,6 +15,7 @@
#include <QDesktopServices> #include <QDesktopServices>
#include <QHostAddress> #include <QHostAddress>
#include <QNetworkInterface> #include <QNetworkInterface>
#include <QMenu>
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
#include <windows.h> #include <windows.h>
@ -39,7 +40,7 @@ void pj_manager::on_btn_his_new_bakup_clicked()
{ {
if(m_pDbOpt == NULL) if(m_pDbOpt == NULL)
{ {
QMessageBox::information(this,tr("提醒"),tr("请先连接数据库")); N_MessageBox::information(this,tr("提醒"),tr("请先连接数据库"));
return; return;
} }
new_his_backup_dialog new_bk_dialog(this); new_his_backup_dialog new_bk_dialog(this);
@ -110,10 +111,10 @@ void pj_manager::on_btn_his_del_backup_clicked()
{ {
if(ui->treeWidget_hst_data->selectedItems().size() == 0) if(ui->treeWidget_hst_data->selectedItems().size() == 0)
{ {
QMessageBox::information(this,tr("提醒"),tr("请选择备份")); N_MessageBox::information(this,tr("提醒"),tr("请选择备份"));
return; return;
} }
if(QMessageBox::question(this,tr("提醒"),tr("请确认是否删除备份") + ui->treeWidget_hst_data->selectedItems()[0]->text(0)) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("提醒"),tr("请确认是否删除备份") + ui->treeWidget_hst_data->selectedItems()[0]->text(0)) != N_MessageBox::Ok)
{ {
return; return;
} }
@ -244,7 +245,7 @@ void pj_manager::delHisBackup()
if(ui->treeWidget_hst_data->selectedItems().size() > 0) if(ui->treeWidget_hst_data->selectedItems().size() > 0)
{ {
//< 确认 //< 确认
if(QMessageBox::question(this,tr("删除备份"),tr("是否删除备份")+ui->treeWidget_hst_data->selectedItems()[0]->text(0)) != QMessageBox::Yes) if(N_MessageBox::question(this,tr("删除备份"),tr("是否删除备份")+ui->treeWidget_hst_data->selectedItems()[0]->text(0)) != N_MessageBox::Ok)
{ {
return; return;
} }
@ -269,12 +270,12 @@ void pj_manager::importHisBackup()
{ {
if(ui->treeWidget_hst_data->selectedItems().size() == 0) if(ui->treeWidget_hst_data->selectedItems().size() == 0)
{ {
QMessageBox::information(this,tr("提醒"),tr("请先选择备份对象")); N_MessageBox::information(this,tr("提醒"),tr("请先选择备份对象"));
return; return;
} }
if(m_pDbOpt == NULL) if(m_pDbOpt == NULL)
{ {
QMessageBox::information(this,tr("提醒"),tr("请先连接数据库")); N_MessageBox::information(this,tr("提醒"),tr("请先连接数据库"));
return; return;
} }
@ -345,13 +346,13 @@ bool pj_manager::isLocalhost(const QString& addr)
QString pj_manager::getHisDumpSrvWeekday(const QString& weekday) QString pj_manager::getHisDumpSrvWeekday(const QString& weekday)
{ {
if(weekday == "") return "7"; if(weekday == tr("")) return "7";
if(weekday == "") return "1"; if(weekday == tr("")) return "1";
if(weekday == "") return "2"; if(weekday == tr("")) return "2";
if(weekday == "") return "3"; if(weekday == tr("")) return "3";
if(weekday == "") return "4"; if(weekday == tr("")) return "4";
if(weekday == "") return "5"; if(weekday == tr("")) return "5";
if(weekday == "") return "6"; if(weekday == tr("")) return "6";
return "0"; return "0";
} }
@ -366,8 +367,8 @@ QString pj_manager::getHisDumpSrvType(bool ischecked)
QString pj_manager::getHisDumpSrvAction(const QString& type) QString pj_manager::getHisDumpSrvAction(const QString& type)
{ {
if(type == "备份和清理") return "1"; if(type == tr("备份和清理")) return "1";
if(type == "仅清理") return "2"; if(type == tr("仅清理")) return "2";
return "0"; return "0";
} }
@ -375,25 +376,25 @@ QString pj_manager::getHisDumpSrvWeekday(int weekday)
{ {
switch (weekday) { switch (weekday) {
case 1: case 1:
return ""; return tr("");
break; break;
case 2: case 2:
return ""; return tr("");
break; break;
case 3: case 3:
return ""; return tr("");
break; break;
case 4: case 4:
return ""; return tr("");
break; break;
case 5: case 5:
return ""; return tr("");
break; break;
case 6: case 6:
return ""; return tr("");
break; break;
case 7: case 7:
return ""; return tr("");
break; break;
default: default:
return "0"; return "0";
@ -407,10 +408,10 @@ QString pj_manager::getHisDumpSrvAction(int action)
{ {
switch (action) { switch (action) {
case 1: case 1:
return "备份和清理"; return tr("备份和清理");
break; break;
case 2: case 2:
return "仅清理"; return tr("仅清理");
break; break;
default: default:
return "0"; return "0";
@ -532,7 +533,7 @@ void pj_manager::on_btn_export_cfg_clicked()
QFile file( sName ); QFile file( sName );
if ( file.open( QIODevice::WriteOnly ) == false ) if ( file.open( QIODevice::WriteOnly ) == false )
{ {
onShowMsg( "打开配置文件" + sName + "失败", 1 ); onShowMsg( tr("打开配置文件%1失败").arg(sName), 1 );
return; return;
} }
QDomDocument dom; QDomDocument dom;
@ -552,13 +553,14 @@ void pj_manager::on_btn_export_cfg_clicked()
eleDbSet.setAttribute( "username", sCurrentUser ); eleDbSet.setAttribute( "username", sCurrentUser );
eleDbSet.setAttribute( "passwd", sCurrentPasswd ); eleDbSet.setAttribute( "passwd", sCurrentPasswd );
eleDbSet.setAttribute( "dbType", m_pDbOpt->getDbType() == EDbType::DB_MYSQL?"QMYSQL":"QPSQL" ); eleDbSet.setAttribute( "dbType", m_pDbOpt->getDbType() == EDbType::DB_MYSQL?"QMYSQL":"QPSQL" );
eleDbSet.setAttribute( "dbName", m_pDbOpt->getDatabaseName() );
eleDbManagerCfg.appendChild( eleDbSet ); eleDbManagerCfg.appendChild( eleDbSet );
file.write( dom.toByteArray() ); file.write( dom.toByteArray() );
file.close(); file.close();
QMessageBox::information(this,"提醒","配置已导出,请手动重启服务,使新配置生效"); N_MessageBox::information(this, tr("提醒"),tr("配置已导出,请手动重启服务,使新配置生效"));
} }
@ -588,22 +590,22 @@ void pj_manager::addErrMsg(const QString &msg)
void pj_manager::handleOptimizeDbSpaceFinished(bool result) void pj_manager::handleOptimizeDbSpaceFinished(bool result)
{ {
ui->btn_optimize_his_table->setDisabled(false); ui->btn_optimize_his_table->setDisabled(false);
if(result) QMessageBox::information(this,tr("提醒"),tr("表空间优化已完成")); if(result) N_MessageBox::information(this,tr("提醒"),tr("表空间优化已完成"));
else QMessageBox::information(this,tr("提醒"),tr("表空间优化失败")); else N_MessageBox::information(this,tr("提醒"),tr("表空间优化失败"));
} }
void pj_manager::handleDelHisAllFinished(bool result) void pj_manager::handleDelHisAllFinished(bool result)
{ {
ui->btn_start_trash->setDisabled(false); ui->btn_start_trash->setDisabled(false);
if(result) QMessageBox::information(this,tr("提醒"),tr("清理全部历史数据已完成")); if(result) N_MessageBox::information(this,tr("提醒"),tr("清理全部历史数据已完成"));
else QMessageBox::information(this,tr("提醒"),tr("清理全部历史数据失败")); else N_MessageBox::information(this,tr("提醒"),tr("清理全部历史数据失败"));
} }
void pj_manager::handleDelHisFinished(bool result) void pj_manager::handleDelHisFinished(bool result)
{ {
ui->btn_start_trash->setDisabled(false); ui->btn_start_trash->setDisabled(false);
if(result) QMessageBox::information(this,tr("提醒"),tr("清理历史数据已完成")); if(result) N_MessageBox::information(this,tr("提醒"),tr("清理历史数据已完成"));
else QMessageBox::information(this,tr("提醒"),tr("清理历史数据失败")); else N_MessageBox::information(this,tr("提醒"),tr("清理历史数据失败"));
} }
void pj_manager::on_btn_look_table_space_size_clicked() void pj_manager::on_btn_look_table_space_size_clicked()
@ -624,7 +626,10 @@ void pj_manager::on_groupBox_exportPart_toggled(bool arg1)
void pj_manager::on_btn_start_trash_clicked() void pj_manager::on_btn_start_trash_clicked()
{ {
if(QMessageBox::question(this,tr("提醒"),tr("请确认是否删除?")) != QMessageBox::Yes) /* 为以后搜索方便,保留此注释
* EMS_DEFAULT_DATABASE
*/
if(N_MessageBox::question(this,tr("提醒"),tr("请确认是否删除?")) != N_MessageBox::Ok)
{ {
return; return;
} }
@ -634,10 +639,10 @@ void pj_manager::on_btn_start_trash_clicked()
{ {
return; return;
} }
emit delHisAll(m_pDbOpt->getDatabaseConn(),m_pDbOpt->getHostName(),TSDB_DB_NAME); emit delHisAll(m_pDbOpt->getDatabaseConn(),m_pDbOpt->getHostName(),m_pDbOpt->getDatabaseName());
} }
else else
emit delHis(m_pDbOpt->getDatabaseConn(),m_pDbOpt->getHostName(),TSDB_DB_NAME,ui->dateTimeEdit_trash_end->dateTime().toMSecsSinceEpoch()); emit delHis(m_pDbOpt->getDatabaseConn(),m_pDbOpt->getHostName(),m_pDbOpt->getDatabaseName(),ui->dateTimeEdit_trash_end->dateTime().toMSecsSinceEpoch());
ui->btn_start_trash->setDisabled(true); ui->btn_start_trash->setDisabled(true);
} }
@ -653,7 +658,7 @@ bool pj_manager::truncateHisTbls()
{ {
QApplication::processEvents(); QApplication::processEvents();
onShowMsg( sError, 1 ); onShowMsg( sError, 1 );
QMessageBox::critical( this, tr("错误"), tr("") + sTableName + tr("删除失败:") + sError); N_MessageBox::critical( this, tr("错误"), tr("") + sTableName + tr("删除失败:") + sError);
return false; return false;
} }
onShowMsg( tr("清空表: ") + sTableName ); onShowMsg( tr("清空表: ") + sTableName );

View File

@ -15,27 +15,40 @@
#include <tchar.h> #include <tchar.h>
#endif #endif
#include "pub_widget/MessageBox.h"
#include "pj_manager.h" #include "pj_manager.h"
#include "ui_pj_manager.h" #include "ui_pj_manager.h"
#include"db_manager_common.h" #include"db_manager_common.h"
#include "public/pub_utility_api/FileUtil.h" #include "public/pub_utility_api/FileUtil.h"
#include "setup/CommonDef.h"
bool pj_manager::isCfgExist()
{
if( QFile::exists( getHisDumpSrvConfigPath() ) )
{
return true;
}
return false;
}
void pj_manager::on_btn_start_srv_clicked() void pj_manager::on_btn_start_srv_clicked()
{ {
if(! isCfgExist() )
{
N_MessageBox::warning(this,tr("提醒"),tr("配置文件不存在,请导出"));
return;
}
#ifdef OS_LINUX #ifdef OS_LINUX
if(QProcess::execute("pkexec systemctl start iscs6000_db_his_data_srv.service")== QProcess::NormalExit) if(QProcess::execute(QString("pkexec systemctl start %1.service").arg(g_pszDBHisDataServiceName))== QProcess::NormalExit)
QMessageBox::information(this,tr("提醒"),tr("服务已开启")); N_MessageBox::information(this,tr("提醒"),tr("服务已开启"));
else else
QMessageBox::warning(this,tr("提醒"),tr("服务开启失败")); N_MessageBox::warning(this,tr("提醒"),tr("服务开启失败"));
refreshHisSrvState(); refreshHisSrvState();
#endif #endif
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
const TCHAR *pszServiceName = _T("db_his_data_srv");
//< 打开服务控制管理器 //< 打开服务控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL) if (hSCM == NULL)
@ -44,7 +57,7 @@ if (hSCM == NULL)
} }
else else
{ {
SC_HANDLE hService = ::OpenService(hSCM, pszServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE); SC_HANDLE hService = ::OpenService(hSCM, g_pTCharDBHisDataServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);
if (NULL == hService) if (NULL == hService)
{ {
@ -53,8 +66,8 @@ else
} }
else else
{ {
QProcess::execute("net start db_his_data_srv"); QProcess::execute(QString("net start %1").arg(g_pszDBHisDataServiceName) );
QMessageBox::information(this,tr("提醒"),tr("服务已启动")); N_MessageBox::information(this,tr("提醒"),tr("服务已启动"));
} }
::CloseServiceHandle(hService); ::CloseServiceHandle(hService);
@ -67,21 +80,26 @@ refreshHisSrvState();
void pj_manager::on_btn_close_srv_clicked() void pj_manager::on_btn_close_srv_clicked()
{ {
if(! isCfgExist() )
{
N_MessageBox::warning(this,tr("提醒"),tr("配置文件不存在,请导出"));
return;
}
#ifdef OS_LINUX #ifdef OS_LINUX
if(QProcess::execute("pkexec systemctl stop iscs6000_db_his_data_srv.service") == QProcess::NormalExit) if(QProcess::execute(QString("pkexec systemctl stop %1.service").arg(g_pszDBHisDataServiceName)) == QProcess::NormalExit)
{ {
QMessageBox::information(this,tr("提醒"),tr("服务已关闭")); N_MessageBox::information(this,tr("提醒"),tr("服务已关闭"));
} }
else else
{ {
QMessageBox::warning(this,tr("提醒"),tr("服务关闭失败")); N_MessageBox::warning(this,tr("提醒"),tr("服务关闭失败"));
} }
refreshHisSrvState(); refreshHisSrvState();
#endif #endif
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
const TCHAR *pszServiceName = _T("db_his_data_srv");
//< 打开服务控制管理器 //< 打开服务控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL) if (hSCM == NULL)
@ -90,8 +108,8 @@ if (hSCM == NULL)
} }
else else
{ {
SC_HANDLE hService = ::OpenService(hSCM, pszServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE); SC_HANDLE hService = ::OpenService(hSCM, g_pTCharDBHisDataServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);
//SC_HANDLE hService = ::OpenService(hSCM, _T("iscs6000_launcher_17b5ab7"), SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE); //SC_HANDLE hService = ::OpenService(hSCM, _T("xxxx_launcher_17b5ab7"), SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);
if (NULL == hService) if (NULL == hService)
{ {
@ -106,9 +124,9 @@ else
{ {
//< todo 当使用SERVICE_USER_XXX_PROCESS类型的服务注册时停止服务存在困难 //< todo 当使用SERVICE_USER_XXX_PROCESS类型的服务注册时停止服务存在困难
//< 此情况下服务的真实名称是注册名加上用户会话的ID而ID是变化的且微软没有开发获取的方法 //< 此情况下服务的真实名称是注册名加上用户会话的ID而ID是变化的且微软没有开发获取的方法
//< 比如真实的服务名是“iscs6000_launcher_17b5ab7”且正在运行如果查询“iscs6000_launcher”的状态是停止的 //< 比如真实的服务名是“xxxx_launcher_17b5ab7”且正在运行如果查询“xxxx_launcher”的状态是停止的
//< 也无法通过停止“iscs6000_launcher”服务来停止“iscs6000_launcher_17b5ab7” //< 也无法通过停止“xxxx_launcher”服务来停止“xxxx_launcher_17b5ab7”
//< 删除“iscs6000_launcher”服务后“iscs6000_launcher_17b5ab7”还可见必须注销重新登录才会消失 //< 删除“xxxx_launcher”服务后“xxxx_launcher_17b5ab7”还可见必须注销重新登录才会消失
if(SERVICE_STOPPED != objStatus.dwCurrentState if(SERVICE_STOPPED != objStatus.dwCurrentState
&& TRUE == ControlService(hService, SERVICE_CONTROL_STOP, &objStatus)) && TRUE == ControlService(hService, SERVICE_CONTROL_STOP, &objStatus))
@ -131,7 +149,7 @@ else
if (SERVICE_STOPPED == objStatus.dwCurrentState) if (SERVICE_STOPPED == objStatus.dwCurrentState)
{ {
QMessageBox::information(this,tr("提醒"),tr("关闭服务成功")); N_MessageBox::information(this,tr("提醒"),tr("关闭服务成功"));
} }
else else
{ {
@ -156,6 +174,13 @@ refreshHisSrvState();
void pj_manager::on_btn_enable_srv_clicked() void pj_manager::on_btn_enable_srv_clicked()
{ {
if(! isCfgExist() )
{
N_MessageBox::warning(this,tr("提醒"),tr("配置文件不存在,请导出"));
return;
}
#ifdef OS_LINUX #ifdef OS_LINUX
const QString strExec = QCoreApplication::applicationDirPath() + "/db_his_data_srv"; const QString strExec = QCoreApplication::applicationDirPath() + "/db_his_data_srv";
@ -180,16 +205,15 @@ else
return; return;
} }
const char *pszSystemdCfgFile = "/tmp/iscs6000_db_his_data_srv.service";
//< 生成或修改systemd服务配置文件 //< 生成或修改systemd服务配置文件
{ {
QSettings objIniSetting(pszSystemdCfgFile, QSettings::IniFormat); QSettings objIniSetting(g_pszDBHisDataServiceTempFile, QSettings::IniFormat);
objIniSetting.setIniCodec( QTextCodec::codecForLocale() ); objIniSetting.setIniCodec( QTextCodec::codecForLocale() );
if (!objIniSetting.isWritable()) if (!objIniSetting.isWritable())
{ {
onShowMsg(tr("服务配置文件不可写请确认是否具有权限请以root用户打开db_manager程序, ") onShowMsg(tr("服务配置文件不可写请确认是否具有权限请以root用户打开db_manager程序, ")
+ pszSystemdCfgFile,1); + g_pszDBHisDataServiceTempFile,1);
return; return;
} }
@ -198,7 +222,7 @@ const char *pszSystemdCfgFile = "/tmp/iscs6000_db_his_data_srv.service";
objIniSetting.clear(); objIniSetting.clear();
objIniSetting.beginGroup("Unit"); objIniSetting.beginGroup("Unit");
objIniSetting.setValue("Description", "iscs6000_db_his_data_srv"); objIniSetting.setValue("Description", g_pszDBHisDataServiceName);
objIniSetting.setValue("After", "network.target"); objIniSetting.setValue("After", "network.target");
objIniSetting.endGroup(); objIniSetting.endGroup();
@ -219,15 +243,14 @@ const char *pszSystemdCfgFile = "/tmp/iscs6000_db_his_data_srv.service";
if (QSettings::NoError != objIniSetting.status()) if (QSettings::NoError != objIniSetting.status())
{ {
onShowMsg(tr("写入服务配置文件失败!") onShowMsg(tr("写入服务配置文件失败!")
+ pszSystemdCfgFile,1); + g_pszDBHisDataServiceTempFile,1);
return ; return ;
} }
} }
//const char *pszSystemdCfgFile = "/usr/lib/systemd/system/iscs6000_db_his_data_srv.service";
//< 设置服务开机自启动 //< 设置服务开机自启动
if (0 != system("pkexec bash -c 'cp -f /tmp/iscs6000_db_his_data_srv.service /usr/lib/systemd/system/ && systemctl daemon-reload && systemctl enable iscs6000_db_his_data_srv'")) QString strRegAutoStartShell = QString("pkexec bash -c 'cp -f %1 %2 && systemctl daemon-reload && systemctl enable %3'").arg(g_pszDBHisDataServiceTempFile).arg(g_pszDBHisDataServiceFile).arg(g_pszDBHisDataServiceName);
if (0 != system(strRegAutoStartShell.toStdString().c_str()))
{ {
onShowMsg(tr("设置服务开机自启动失败!"),1); onShowMsg(tr("设置服务开机自启动失败!"),1);
return; return;
@ -236,11 +259,10 @@ if (0 != system("pkexec bash -c 'cp -f /tmp/iscs6000_db_his_data_srv.service /u
//< 刷新服务状态 //< 刷新服务状态
refreshHisSrvState(); refreshHisSrvState();
QMessageBox::information(this,tr("提醒"),tr("服务已注册并设置自启动")); N_MessageBox::information(this,tr("提醒"),tr("服务已注册并设置自启动"));
#endif #endif
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
const TCHAR *pszServiceName = _T("db_his_data_srv");
bool bRet = false; bool bRet = false;
const QString strExec = QDir::toNativeSeparators const QString strExec = QDir::toNativeSeparators
(QCoreApplication::applicationDirPath() + "/db_his_data_srv.exe"); (QCoreApplication::applicationDirPath() + "/db_his_data_srv.exe");
@ -260,7 +282,7 @@ if (NULL == hSCM)
else else
{ {
//< 判断服务是否已存在 //< 判断服务是否已存在
SC_HANDLE hService = ::OpenService(hSCM, pszServiceName, SERVICE_QUERY_CONFIG); SC_HANDLE hService = ::OpenService(hSCM, g_pTCharDBHisDataServiceName, SERVICE_QUERY_CONFIG);
if (NULL == hService) if (NULL == hService)
{ {
//< 创建服务 //< 创建服务
@ -273,7 +295,7 @@ else
//< 2、多用户登录时会启动多个实例而实际上由于端口占用等原因是起不来的 //< 2、多用户登录时会启动多个实例而实际上由于端口占用等原因是起不来的
//< 3、本程序停止服务时存在困难见下面unregSysService()中的注释。 //< 3、本程序停止服务时存在困难见下面unregSysService()中的注释。
hService = ::CreateService( hService = ::CreateService(
hSCM, pszServiceName, pszServiceName, hSCM, g_pTCharDBHisDataServiceName, g_pTCharDBHisDataServiceName,
SERVICE_ALL_ACCESS, 0x00000010/*SERVICE_WIN32_OWN_PROCESS*/, SERVICE_ALL_ACCESS, 0x00000010/*SERVICE_WIN32_OWN_PROCESS*/,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
strExec.toStdWString().c_str(), NULL, NULL, NULL, NULL, NULL); strExec.toStdWString().c_str(), NULL, NULL, NULL, NULL, NULL);
@ -285,7 +307,7 @@ else
else else
{ {
SERVICE_DESCRIPTION stSrvDesc; SERVICE_DESCRIPTION stSrvDesc;
TCHAR szDesc[] = _T("宏茂技术监控系统自动清除过期数据服务"); TCHAR szDesc[] = _T("自动清除过期数据服务");
stSrvDesc.lpDescription = szDesc; stSrvDesc.lpDescription = szDesc;
if (::ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &stSrvDesc)) if (::ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &stSrvDesc))
{ {
@ -312,18 +334,24 @@ refreshHisSrvState();
void pj_manager::on_btn_disable_srv_clicked() void pj_manager::on_btn_disable_srv_clicked()
{ {
if(! isCfgExist() )
{
N_MessageBox::warning(this,tr("提醒"),tr("配置文件不存在,请导出"));
return;
}
#ifdef OS_LINUX #ifdef OS_LINUX
if(QProcess::execute("pkexec systemctl disable iscs6000_db_his_data_srv.service") == QProcess::NormalExit) if(QProcess::execute(QString("pkexec systemctl disable %1.service").arg(g_pszDBHisDataServiceName)) == QProcess::NormalExit)
QMessageBox::information(this,tr("提醒"),tr("服务已关闭自启动")); N_MessageBox::information(this,tr("提醒"),tr("服务已关闭自启动"));
else else
QMessageBox::warning(this,tr("提醒"),tr("服务关闭自启动失败")); N_MessageBox::warning(this,tr("提醒"),tr("服务关闭自启动失败"));
refreshHisSrvState(); refreshHisSrvState();
#endif #endif
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
const TCHAR *pszServiceName = _T("db_his_data_srv");
//< 打开服务控制管理器 //< 打开服务控制管理器
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSCM == NULL) if (hSCM == NULL)
@ -332,8 +360,8 @@ if (hSCM == NULL)
} }
else else
{ {
SC_HANDLE hService = ::OpenService(hSCM, pszServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE); SC_HANDLE hService = ::OpenService(hSCM, g_pTCharDBHisDataServiceName, SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);
//SC_HANDLE hService = ::OpenService(hSCM, _T("iscs6000_launcher_17b5ab7"), SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE); //SC_HANDLE hService = ::OpenService(hSCM, _T("xxxx_launcher_17b5ab7"), SERVICE_QUERY_STATUS | SERVICE_STOP | DELETE);
if (NULL == hService) if (NULL == hService)
{ {
@ -348,9 +376,9 @@ else
{ {
//< todo 当使用SERVICE_USER_XXX_PROCESS类型的服务注册时停止服务存在困难 //< todo 当使用SERVICE_USER_XXX_PROCESS类型的服务注册时停止服务存在困难
//< 此情况下服务的真实名称是注册名加上用户会话的ID而ID是变化的且微软没有开发获取的方法 //< 此情况下服务的真实名称是注册名加上用户会话的ID而ID是变化的且微软没有开发获取的方法
//< 比如真实的服务名是“iscs6000_launcher_17b5ab7”且正在运行如果查询“iscs6000_launcher”的状态是停止的 //< 比如真实的服务名是“xxxx_launcher_17b5ab7”且正在运行如果查询“xxxx_launcher”的状态是停止的
//< 也无法通过停止“iscs6000_launcher”服务来停止“iscs6000_launcher_17b5ab7” //< 也无法通过停止“xxxx_launcher”服务来停止“xxxx_launcher_17b5ab7”
//< 删除“iscs6000_launcher”服务后“iscs6000_launcher_17b5ab7”还可见必须注销重新登录才会消失 //< 删除“xxxx_launcher”服务后“xxxx_launcher_17b5ab7”还可见必须注销重新登录才会消失
if(SERVICE_STOPPED != objStatus.dwCurrentState if(SERVICE_STOPPED != objStatus.dwCurrentState
&& TRUE == ControlService(hService, SERVICE_CONTROL_STOP, &objStatus)) && TRUE == ControlService(hService, SERVICE_CONTROL_STOP, &objStatus))
@ -407,7 +435,7 @@ void pj_manager::refreshHisSrvState()
{ {
#ifdef OS_LINUX #ifdef OS_LINUX
if (0 == QProcess::execute("systemctl is-enabled iscs6000_db_his_data_srv.service")) if (0 == QProcess::execute(QString("systemctl is-enabled %1.service").arg(g_pszDBHisDataServiceName)))
{ {
ui->label_srv_is_enabled->setText(tr("")); ui->label_srv_is_enabled->setText(tr(""));
ui->label_srv_is_enabled->setStyleSheet("color: #037550"); ui->label_srv_is_enabled->setStyleSheet("color: #037550");
@ -420,7 +448,7 @@ void pj_manager::refreshHisSrvState()
} }
if (0 == QProcess::execute("systemctl is-active iscs6000_db_his_data_srv.service")) if (0 == QProcess::execute(QString("systemctl is-active %1.service").arg(g_pszDBHisDataServiceName)))
{ {
ui->label_srv_is_active->setText(tr("开启")); ui->label_srv_is_active->setText(tr("开启"));
ui->label_srv_is_active->setStyleSheet("color: #037550"); ui->label_srv_is_active->setStyleSheet("color: #037550");
@ -436,19 +464,18 @@ void pj_manager::refreshHisSrvState()
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
const TCHAR *pszServiceName = _T("db_his_data_srv");
SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (NULL == hSCM) if (NULL == hSCM)
{ {
onShowMsg(QObject::tr("打开服务管理器失败,请确认是否具有权限!建议以管理员权限打开"),1); onShowMsg(QObject::tr("打开服务管理器失败,请确认是否具有权限!建议以管理员权限打开"),1);
} }
if (4 == GetServiceStatus(pszServiceName)) if (4 == GetServiceStatus(g_pTCharDBHisDataServiceName))
{ {
ui->label_srv_is_active->setText(tr("开启")); ui->label_srv_is_active->setText(tr("开启"));
ui->label_srv_is_active->setStyleSheet("color: #037550"); ui->label_srv_is_active->setStyleSheet("color: #037550");
} }
else if(1 == GetServiceStatus(pszServiceName)) else if(1 == GetServiceStatus(g_pTCharDBHisDataServiceName))
{ {
ui->label_srv_is_active->setText(tr("关闭")); ui->label_srv_is_active->setText(tr("关闭"));
ui->label_srv_is_active->setStyleSheet("color: #D74C41"); ui->label_srv_is_active->setStyleSheet("color: #D74C41");
@ -456,7 +483,7 @@ void pj_manager::refreshHisSrvState()
} }
SC_HANDLE hService = ::OpenService(hSCM, pszServiceName, SERVICE_QUERY_CONFIG); SC_HANDLE hService = ::OpenService(hSCM, g_pTCharDBHisDataServiceName, SERVICE_QUERY_CONFIG);
if(NULL == hService) if(NULL == hService)
{ {
ui->label_srv_is_enabled->setText(tr("")); ui->label_srv_is_enabled->setText(tr(""));

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -12,11 +12,11 @@
#define LANG_CONFIG_NAME "language.xml" #define LANG_CONFIG_NAME "language.xml"
#define TEST_DB_NAME "iscs6000testdbganyuhang" #define TEST_DB_NAME "iscs6000testdb"
#define TEST_DB_IP "127.0.0.1" #define TEST_DB_IP "127.0.0.1"
#define TEST_DB_PORT 3306 #define TEST_DB_PORT 3306
#define TEST_DB_USERNAME "root" #define TEST_DB_USERNAME "root"
#define TEST_DB_PASSWORD "kbdct@0755" #define TEST_DB_PASSWORD EMS_DEFAULT_PASSWD
class project_data_veri : public QObject class project_data_veri : public QObject

View File

@ -142,7 +142,7 @@ bool db_manager_api::createDatabase(SDbConnInfo db_conn, EInitProjectErr &err, Q
db_conn.username, db_conn.password ) == false ) db_conn.username, db_conn.password ) == false )
{ {
err = DATABASE_ERR; err = DATABASE_ERR;
errTxt = tr("打开数据库:") + db_conn.address + tr("失败!"); errTxt = tr("打开数据库:") + QString("%1:%2 %3@%4").arg(db_conn.address).arg(db_conn.port).arg(db_conn.username).arg(db_conn.password) + tr("失败!");
return false; return false;
} }
sig_showMsg( tr("打开数据库成功...") ); sig_showMsg( tr("打开数据库成功...") );
@ -450,6 +450,7 @@ void db_manager_api::backupSimpExe()
QSet<QString> setIgnorePattern; QSet<QString> setIgnorePattern;
setIgnorePattern.insert("syncthing_home"); setIgnorePattern.insert("syncthing_home");
setIgnorePattern.insert("cache");
if( !m_pFileOpt->copyFiles(m_sAllSrc, m_sAllDst,setIgnorePattern) ) if( !m_pFileOpt->copyFiles(m_sAllSrc, m_sAllDst,setIgnorePattern) )
{ {
sig_showMsg(tr("拷贝文件失败!"), 1); sig_showMsg(tr("拷贝文件失败!"), 1);
@ -509,6 +510,7 @@ void db_manager_api::backupCompExe()
QSet<QString> setIgnorePattern; QSet<QString> setIgnorePattern;
setIgnorePattern.insert("syncthing_home"); setIgnorePattern.insert("syncthing_home");
setIgnorePattern.insert("cache");
if( !m_pFileOpt->copyFiles(m_sAllSrc, m_sAllDst,setIgnorePattern) ) if( !m_pFileOpt->copyFiles(m_sAllSrc, m_sAllDst,setIgnorePattern) )
{ {
sig_showMsg(tr("拷贝文件失败!"), 1); sig_showMsg(tr("拷贝文件失败!"), 1);
@ -881,16 +883,24 @@ bool db_manager_api::createTrigger(db_opt* pDbOpt, QString& sDatabaseName)
return m_ret; return m_ret;
} }
bool db_manager_api::updateDatabase(db_opt* pDbOpt, QString& sDatabaseName) bool db_manager_api::updateDatabase(db_opt* pDbOpt, QString& sDatabaseName,bool isNoWaitDlg)
{ {
m_pDbOpt = pDbOpt; m_pDbOpt = pDbOpt;
m_sDatabaseName = sDatabaseName; m_sDatabaseName = sDatabaseName;
m_ret = true; m_ret = true;
ThreadFun fun = boost::bind(&db_manager_api::updateDatabaseExe, this); if(!isNoWaitDlg)
KbdWaitPrgDlg m_WaitPrgDialog(fun);
if (m_WaitPrgDialog.exec())
{ {
ThreadFun fun = boost::bind(&db_manager_api::updateDatabaseExe, this);
KbdWaitPrgDlg m_WaitPrgDialog(fun);
if (m_WaitPrgDialog.exec())
{
}
} }
else
{
updateDatabaseExe();
}
return m_ret; return m_ret;
} }
@ -965,6 +975,54 @@ bool db_manager_api::initCompleteProjectExe()
//**************获取国际化路径,同时初始化基础数据路径************************ //**************获取国际化路径,同时初始化基础数据路径************************
initProjectI18NPath(); initProjectI18NPath();
//************************拷贝common和data目录************************************
QString strDataDstPath = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../data" ).c_str();
QString strDataSrcPath = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../products/").c_str();
strDataSrcPath += QDir::separator()+m_productName + QDir::separator() + m_projectName + QDir::separator()+ "data";
QStringList srcList;
QStringList dstList;
QDir dbDir;
if (dbDir.exists(strDataSrcPath))
{
dstList.append(strDataDstPath);
srcList.append(strDataSrcPath);
}
QString strComDstPath = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../platform/common" ).c_str();
QString strCommSrcPath2 = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../products/").c_str();
strCommSrcPath2 += QDir::separator() + m_productName + QDir::separator() + m_projectName + QDir::separator() + "common";
QString strCommSrcPath1 = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../products/").c_str();
strCommSrcPath1 += QDir::separator() + m_productName + QDir::separator() + "common";
if (dbDir.exists(strCommSrcPath1))
{
dstList.append(strComDstPath);
srcList.append(strCommSrcPath1);
}
if (dbDir.exists(strCommSrcPath2))
{
dstList.append(strComDstPath);
srcList.append(strCommSrcPath2);
}
QString strProductDstPath = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../product" ).c_str();
QString strProductSrcPath = CFileUtil::getSimplePath(CFileUtil::getCurModuleDir() + "../../products/").c_str();
strProductSrcPath += QDir::separator()+m_productName + QDir::separator() + m_projectName + QDir::separator()+ "product";
if (dbDir.exists(strProductSrcPath))
{
dstList.append(strProductDstPath);
srcList.append(strProductSrcPath);
}
m_pFileOpt->deleteDir(strDataDstPath);
if (!m_pFileOpt->copyFiles(srcList, dstList))
{
sig_showMsg(tr("拷贝文件失败!"), 1);
return false;
}
sig_showMsg(tr("复制文件成功..."));
//***************************创建数据库,存在删除*************************** //***************************创建数据库,存在删除***************************
sig_showMsg( tr("开始创建数据库...") ); sig_showMsg( tr("开始创建数据库...") );
if(!createDatabase(m_dbConnInfo, err, errTxt)) //创建数据库 if(!createDatabase(m_dbConnInfo, err, errTxt)) //创建数据库
@ -985,16 +1043,6 @@ bool db_manager_api::initCompleteProjectExe()
sig_showMsg( tr("数据库表结构升级成功...") ); sig_showMsg( tr("数据库表结构升级成功...") );
//**************************恢复旧的数据库数据,不恢复脚本和触发器********************
sig_showMsg( tr("开始创建数据库表结构...") );
QString strProjectPath = QStringLiteral("products") + QDir::separator() + m_productName + QDir::separator() + m_projectName+"/database" ; //增加数据库路径
if(!restoreDatabase(strProjectPath,err, errTxt))
{
sig_showMsg( errTxt,1); //显示错误信息
return false;
}
sig_showMsg( tr("开始创建数据库表结构...") );
//**********************导入Excel格式基础数据****************************** //**********************导入Excel格式基础数据******************************
sig_showMsg( tr("开始导入基础数据...") ); sig_showMsg( tr("开始导入基础数据...") );
m_ret = true; m_ret = true;
@ -1006,6 +1054,16 @@ bool db_manager_api::initCompleteProjectExe()
} }
sig_showMsg(tr( "导入基础数据完成...") ); sig_showMsg(tr( "导入基础数据完成...") );
//**************************恢复旧的数据库数据,不恢复脚本和触发器********************
sig_showMsg( tr("开始创建数据库表结构...") );
QString strProjectPath = QStringLiteral("products") + QDir::separator() + m_productName + QDir::separator() + m_projectName+"/database" ; //增加数据库路径
if(!restoreDatabase(strProjectPath,err, errTxt))
{
sig_showMsg( errTxt,1); //显示错误信息
return false;
}
sig_showMsg( tr("开始创建数据库表结构...") );
//************************部署+导入触发器等******************************** //************************部署+导入触发器等********************************
sig_showMsg( tr("开始部署...") ); sig_showMsg( tr("开始部署...") );
if(!deployToLocal(err, errTxt,0)) if(!deployToLocal(err, errTxt,0))
@ -1027,6 +1085,8 @@ bool db_manager_api::initCompleteProjectExe()
sig_showMsg( tr("初始化完整工程完成...") ); sig_showMsg( tr("初始化完整工程完成...") );
m_pDbOpt->closeDatabase();
sig_showMsg( tr("断开数据库链接...") );
return true; return true;
} }

View File

@ -1,4 +1,4 @@
#ifndef DB_MANAGER_API_COMMON_H #ifndef DB_MANAGER_API_COMMON_H
#define DB_MANAGER_API_COMMON_H #define DB_MANAGER_API_COMMON_H
#include "pub_utility_api/UtilityCommon.h" #include "pub_utility_api/UtilityCommon.h"
@ -25,13 +25,9 @@
#define FUNC_DEFINE_FILE_KINGBASE "iscs6000_func_Kingbase.sql" #define FUNC_DEFINE_FILE_KINGBASE "iscs6000_func_Kingbase.sql"
#define KINGBASE_DEFAULT_SCHEMA "iscs6000"
#define DB_MANAGER_CFG_NAME "db_manager_cfg.xml" #define DB_MANAGER_CFG_NAME "db_manager_cfg.xml"
#define CFG_MD_BACKUP "backup" #define CFG_MD_BACKUP "backup"
#define CFG_MD_BACKUP_KEY_REPORTFILE "reportFilePath" #define CFG_MD_BACKUP_KEY_REPORTFILE "reportFilePath"
#define CN_PASSWD "kbdct@0755"
#endif // DB_MANAGER_API_COMMON_H #endif // DB_MANAGER_API_COMMON_H

View File

@ -364,44 +364,44 @@ bool db_opt::createDbNode( QString sDatabaseName )
qDebug() << "查询数据库节点出错"; qDebug() << "查询数据库节点出错";
return false; return false;
} }
QString username; QString username = m_sUser;
QString port; QString port = QString("%1").arg(m_nPort);
QString dbType; QString dbType;
switch (getDbType()) switch (getDbType())
{ {
case EDbType::DB_MYSQL: case EDbType::DB_MYSQL:
username = "root"; // username = "root";
port = "3306"; // port = "3306";
dbType = "2"; dbType = "2";
break; break;
case EDbType::DB_OPENGAUSS: case EDbType::DB_OPENGAUSS:
username = "iscs"; // username = "iscs";
port = "5432"; // port = "5432";
dbType = "3"; dbType = "3";
break; break;
case EDbType::DB_KINGBASE: case EDbType::DB_KINGBASE:
username = "system"; // username = "system";
port = "54321"; // port = "54321";
dbType = "4"; dbType = "4";
break; break;
default: default:
LOGERROR("不支持的数据库类型!"); LOGERROR("不支持的数据库类型!");
break; return false;
} }
/* 为以后搜索方便,保留此注释 EMS_DEFAULT_PASSWD*/
QString sSql; QString sSql;
if( querySel.next() ) if( querySel.next() )
{ {
sSql = "update sys_model_dbconfig_node set DB_TYPE = '" + dbType + "', DB_SERVICE_NAME = '" + sDatabaseName + "'," \ sSql = "update sys_model_dbconfig_node set DB_TYPE = '" + dbType + "', DB_SERVICE_NAME = '" + sDatabaseName + "'," \
"USER_NAME = '" + username + "', USER_PASSWORD = '"+ CN_PASSWD + "', NIC_CUR_ID = '1', DB_NAME = '0', DB_HOST_PRIOR = '1', IS_DB_SWITCH = '1', IS_DIRECT_ACCESS = '1', DB_PORT = '"+ port +"'" \ "USER_NAME = '" + username + "', USER_PASSWORD = '"+ m_objDb.getDbPara().getPassword() + "', NIC_CUR_ID = '1', DB_NAME = '0', DB_HOST_PRIOR = '1', IS_DB_SWITCH = '1', IS_DIRECT_ACCESS = '1', DB_PORT = '"+ port +"'" \
"where NODE_NAME = '" + QHostInfo::localHostName() + "';"; "where NODE_NAME = '" + QHostInfo::localHostName() + "';";
} }
else else
{ {
sSql = "insert into sys_model_dbconfig_node (NODE_NAME,DB_TYPE,DB_SERVICE_NAME,USER_NAME,USER_PASSWORD,NIC_CUR_ID,DB_NAME,DB_HOST_PRIOR,IS_DB_SWITCH,IS_DIRECT_ACCESS,DB_PORT)" \ sSql = "insert into sys_model_dbconfig_node (NODE_NAME,DB_TYPE,DB_SERVICE_NAME,USER_NAME,USER_PASSWORD,NIC_CUR_ID,DB_NAME,DB_HOST_PRIOR,IS_DB_SWITCH,IS_DIRECT_ACCESS,DB_PORT)" \
"values ('" + QHostInfo::localHostName() + "','" + dbType + "','" + sDatabaseName + "','" + username + "','"+ CN_PASSWD + "','1','0','1','1','1','" + port + "');"; "values ('" + QHostInfo::localHostName() + "','" + dbType + "','" + sDatabaseName + "','" + username + "','"+ m_objDb.getDbPara().getPassword() + "','1','0','1','1','1','" + port + "');";
} }
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
@ -790,7 +790,7 @@ bool db_opt::importDatabase( QString sDatabaseName, QString sFileName, quint32 n
//************************导入Excel数据****************************************** //************************导入Excel数据******************************************
signalSendMsg( "开始导入Excel数据文件...!" ); signalSendMsg( tr("开始导入Excel数据文件...!") );
if( nImportType & EN_IMPORT_DATA ) if( nImportType & EN_IMPORT_DATA )
{ {
QString sExcelPath = sFileName; QString sExcelPath = sFileName;
@ -1085,7 +1085,7 @@ bool db_opt::executeXmlFileUpdate( QString sDatabaseName)
return false; return false;
} }
signalSendMsg( "数据库表结构更新完成!"); signalSendMsg(tr("数据库表结构更新完成!"));
return true; return true;
} }
@ -1236,7 +1236,7 @@ void db_opt::filterTable( QStringList& listTable )
if ( !QFile::exists( dir.filePath( sFilePath ) ) ) if ( !QFile::exists( dir.filePath( sFilePath ) ) )
{ {
sFilePath = ""; sFilePath = "";
signalSendMsg("数据库定义配置文件不存在", 1); signalSendMsg(tr("数据库定义配置文件不存在"), 1);
return; return;
} }
} }
@ -1274,6 +1274,13 @@ void db_opt::filterTable( QStringList& listTable )
if("Table" == eleTable.tagName()) if("Table" == eleTable.tagName())
{ {
QString sTableName = eleTable.attribute("name"); QString sTableName = eleTable.attribute("name");
QString sUseType = eleTable.attribute("use_type");
if(sUseType.isEmpty())
{
eleTable = eleTable.nextSiblingElement();
continue; //< 为空表示禁用
}
QDomElement table_db = eleTable.firstChildElement(); QDomElement table_db = eleTable.firstChildElement();
while (!table_db.isNull()) { while (!table_db.isNull()) {
@ -1350,6 +1357,13 @@ void db_opt::filterTable(QMap<QString, QString> &tableOptMap)
if("Table" == eleTable.tagName()) if("Table" == eleTable.tagName())
{ {
QString sTableName = eleTable.attribute("name"); QString sTableName = eleTable.attribute("name");
QString sUseType = eleTable.attribute("use_type");
if(sUseType.isEmpty())
{
eleTable = eleTable.nextSiblingElement();
continue; //< 为空表示禁用
}
QDomElement table_db = eleTable.firstChildElement(); QDomElement table_db = eleTable.firstChildElement();
while (!table_db.isNull()) { while (!table_db.isNull()) {
@ -1406,6 +1420,13 @@ bool db_opt::appendTableNeedBak(const QString& cfgFilePath, QStringList & listTa
if("Table" == eleTable.tagName()) if("Table" == eleTable.tagName())
{ {
QString sTableName = eleTable.attribute("name"); QString sTableName = eleTable.attribute("name");
QString sUseType = eleTable.attribute("use_type");
if(sUseType.isEmpty())
{
eleTable = eleTable.nextSiblingElement();
continue; //< 为空表示禁用
}
QDomElement table_db = eleTable.firstChildElement(); QDomElement table_db = eleTable.firstChildElement();
while (!table_db.isNull()) { while (!table_db.isNull()) {
@ -1534,7 +1555,7 @@ bool db_opt::deleteIndex( QString& sTableName, QSqlQuery& query )
{ {
if( !getTableIndex( sTableName, query) ) if( !getTableIndex( sTableName, query) )
{ {
signalSendMsg( "deleteIndex函数获取表索引失败", 1 ); signalSendMsg(tr("deleteIndex函数获取表索引失败"), 1 );
return false; return false;
} }
if( query.size() <= 0 ) if( query.size() <= 0 )
@ -1610,7 +1631,10 @@ bool db_opt::createDb(QString &dbName,QString &sError)
if(getDbType() == EDbType::DB_KINGBASE) if(getDbType() == EDbType::DB_KINGBASE)
{ {
sSql = "CREATE SCHEMA iscs6000;"; /* 为以后搜索方便保留此注释。mysql的database实际应该对应schema
* sSql = QString("CREATE SCHEMA %1;").arg(EMS_DEFAULT_DATABASE);
*/
sSql = QString("CREATE SCHEMA %1;").arg(dbName);
if(!switchDatabase(dbName)) if(!switchDatabase(dbName))
{ {
sError = tr("无法切换到数据库") ; sError = tr("无法切换到数据库") ;
@ -1622,7 +1646,22 @@ bool db_opt::createDb(QString &dbName,QString &sError)
} }
} }
if(getDbType() == EDbType::DB_OPENGAUSS)
{
/* 为以后搜索方便保留此注释。mysql的database实际应该对应schema
* sSql = QString("CREATE SCHEMA %1;").arg(EMS_DEFAULT_DATABASE);
*/
sSql = QString("CREATE SCHEMA %1;").arg(dbName);
if(!switchDatabase(dbName))
{
sError = tr("无法切换到数据库") ;
return false;
}
if ( !executeSql( sSql, sError ) )
{
return false;
}
}
return true; return true;
} }
@ -1651,7 +1690,7 @@ void db_opt::slotDeleteTrigger( QString sDatabaseName, QString sFileName )
//先删除所有触发器,防止造成重复触发器错误 //先删除所有触发器,防止造成重复触发器错误
//deleteAllTrigger_impl( sDatabaseName ); //deleteAllTrigger_impl( sDatabaseName );
signalSendMsg( "开始执行SQL文件..." ); signalSendMsg( tr("开始执行SQL文件...") );
QFile file( sFileName ); QFile file( sFileName );
if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{ {
@ -1808,7 +1847,7 @@ void db_opt::slotRecoverAllFunction( QString sDatabaseName )
bool db_opt::deleteAllTrigger_impl( QString sDatabaseName, bool getCreateTrigger ) bool db_opt::deleteAllTrigger_impl( QString sDatabaseName, bool getCreateTrigger )
{ {
signalSendMsg( "开始删除触发器..." ); signalSendMsg( tr("开始删除触发器...") );
m_listOldTriggerName.clear(); m_listOldTriggerName.clear();
m_listCreateTriggerString.clear(); m_listCreateTriggerString.clear();
@ -1908,7 +1947,7 @@ bool db_opt::deleteAllProcedure_impl( QString sDatabaseName )
bool db_opt::deleteAllFunction_impl( QString sDatabaseName ) bool db_opt::deleteAllFunction_impl( QString sDatabaseName )
{ {
signalSendMsg( "开始删除函数..." ); signalSendMsg( tr("开始删除函数...") );
m_listOldFunctionName.clear(); m_listOldFunctionName.clear();
m_listCreateFunctionString.clear(); m_listCreateFunctionString.clear();
@ -1991,7 +2030,7 @@ bool db_opt::recoverAllTrigger_impl( QString sDatabaseName )
bool db_opt::recoverAllProcedure_impl( QString sDatabaseName ) bool db_opt::recoverAllProcedure_impl( QString sDatabaseName )
{ {
signalSendMsg( "开始恢复存储过程..." ); signalSendMsg( tr("开始恢复存储过程...") );
// 将缺少的存储过程重新导入 // 将缺少的存储过程重新导入
QString sError = ""; QString sError = "";
@ -2136,7 +2175,7 @@ bool db_opt::deleteVoidedTable(const QStringList &tableNameDb)
return false; return false;
} }
sDeleteTableString = ""; sDeleteTableString = "";
signalSendMsg("表:" + tableNameDb[i] + "删除成功!", 0); signalSendMsg(tr("表:%1删除成功!").arg(tableNameDb[i]), 0);
} }
return true; return true;
} }
@ -2186,14 +2225,14 @@ bool db_opt::handleEleTable(const QDomElement &eleTable, const QString &sDatabas
signalSendMsg(tr("重新获取表")+ sTableName +tr("的所有字段失败!"), 1); return false; signalSendMsg(tr("重新获取表")+ sTableName +tr("的所有字段失败!"), 1); return false;
} }
if( !updatePriKey( sDatabaseName, sTableName, xmlTableKeys ) ){ if( !updatePriKey( sDatabaseName, sTableName, xmlTableKeys ) ){
signalSendMsg( "更新表的主键失败", 1 ); return false; signalSendMsg( tr("更新表的主键失败"), 1 ); return false;
} }
idxColumn += nColAdded; //调整idxColumn idxColumn += nColAdded; //调整idxColumn
if( !deleteVoidedColumn( idxColumn,listXmlColumns, listColumn, sTableName) ){ if( !deleteVoidedColumn( idxColumn,listXmlColumns, listColumn, sTableName) ){
signalSendMsg( "删除多余的字段失败", 1 ); return false; signalSendMsg( tr("删除多余的字段失败"), 1 ); return false;
} }
if( !updateTableIndex( sTableName, normalIndex, uniqueIndex, fulltextIndex ) ){ if( !updateTableIndex( sTableName, normalIndex, uniqueIndex, fulltextIndex ) ){
signalSendMsg( "更新表的索引失败", 1 ); return false; signalSendMsg( tr("更新表的索引失败"), 1 ); return false;
} }
return true; return true;
} }
@ -2357,7 +2396,8 @@ bool db_opt::handleDbStruct(const QDomElement &databaseStruct,const QString& sDa
while ( !eleTable.isNull() ) while ( !eleTable.isNull() )
{ {
QString sTableName = eleTable.attribute("name").toLower(); QString sTableName = eleTable.attribute("name").toLower();
if ( eleTable.attribute("use_type","") == "rdb" ) {// 筛选掉纯内存库表 QString sUseType = eleTable.attribute("use_type","");
if ( sUseType == "rdb" || sUseType.isEmpty() ) {// 筛选掉纯内存库表或者禁用的表
eleTable = eleTable.nextSiblingElement(); eleTable = eleTable.nextSiblingElement();
continue; continue;
} }

View File

@ -2,9 +2,14 @@
#include "pub_logger_api/logger.h" #include "pub_logger_api/logger.h"
#include "db_manager_api_common.h" #include "db_manager_api_common.h"
/* 为以后搜索方便,保留此注释
* KINGBASE_DEFAULT_SCHEMA和EMS_DEFAULT_DATABASE pgsql数据库中数据库和模式同名
*/
//#define KINGBASE_DEFAULT_SCHEMA EMS_DEFAULT_DATABASE
using namespace iot_dbms; using namespace iot_dbms;
const QString g_sDefaultSchema= QStringLiteral(KINGBASE_DEFAULT_SCHEMA); //const QString g_sDefaultSchema= QStringLiteral(KINGBASE_DEFAULT_SCHEMA);
db_opt_kingbase::db_opt_kingbase() db_opt_kingbase::db_opt_kingbase()
{ {
@ -68,7 +73,7 @@ bool db_opt_kingbase::getTableName( QString sDatabaseName, QList<STable>& listTa
} }
QString sSql = "SELECT t.table_name, pg_catalog.obj_description(pgc.oid, 'pg_class') FROM information_schema.tables t INNER JOIN pg_catalog.pg_class pgc ON t.table_name = pgc.relname WHERE t.table_type='BASE TABLE' AND t.table_schema='" + g_sDefaultSchema + "';"; QString sSql = "SELECT t.table_name, pg_catalog.obj_description(pgc.oid, 'pg_class') FROM information_schema.tables t INNER JOIN pg_catalog.pg_class pgc ON t.table_name = pgc.relname WHERE t.table_type='BASE TABLE' AND t.table_schema='" + m_objDb.getDbPara().getDatabaseName() + "';";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -97,7 +102,7 @@ bool db_opt_kingbase::getTableName( QString sDatabaseName, QStringList& listTabl
return false; return false;
} }
QString sSql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '"+ g_sDefaultSchema + "' AND table_type = 'BASE TABLE'"; QString sSql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '"+ m_objDb.getDbPara().getDatabaseName() + "' AND table_type = 'BASE TABLE'";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -253,7 +258,7 @@ bool db_opt_kingbase::getCreateTableString( QString sDatabaseName, QString sTabl
return false; return false;
} }
{ {
sSql = "SELECT * FROM show_create_table('" + g_sDefaultSchema + "', '" + sTableName + "');"; sSql = "SELECT * FROM show_create_table('" + m_objDb.getDbPara().getDatabaseName() + "', '" + sTableName + "');";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -387,7 +392,7 @@ bool db_opt_kingbase::getColumn( QString sDatabaseName, QString sTableName, QLis
"FROM pg_index, pg_class, pg_attribute, pg_namespace " "FROM pg_index, pg_class, pg_attribute, pg_namespace "
"WHERE pg_attribute.attnum > 0 AND " "WHERE pg_attribute.attnum > 0 AND "
"pg_class.oid = '" + sTableName + "'::regclass " "pg_class.oid = '" + sTableName + "'::regclass "
"AND nspname = '" + g_sDefaultSchema + "' " "AND nspname = '" + m_objDb.getDbPara().getDatabaseName() + "' "
"AND pg_class.relnamespace = pg_namespace.oid " "AND pg_class.relnamespace = pg_namespace.oid "
"AND pg_attribute.attrelid = pg_class.oid " "AND pg_attribute.attrelid = pg_class.oid "
"AND pg_attribute.attisdropped = false) as ts order by attnum;"; "AND pg_attribute.attisdropped = false) as ts order by attnum;";
@ -591,7 +596,7 @@ QStringList db_opt_kingbase::getMainKeys(QString sDataBase, QString sTableName)
" WHERE pg_attribute.attnum > 0 AND " " WHERE pg_attribute.attnum > 0 AND "
" pg_class.oid = '" + sTableName + "'::regclass AND " " pg_class.oid = '" + sTableName + "'::regclass AND "
" indrelid = pg_class.oid " " indrelid = pg_class.oid "
" AND nspname = '" + g_sDefaultSchema + "' " " AND nspname = '" + m_objDb.getDbPara().getDatabaseName() + "' "
" AND pg_class.relnamespace = pg_namespace.oid " " AND pg_class.relnamespace = pg_namespace.oid "
" AND pg_attribute.attrelid = pg_class.oid " " AND pg_attribute.attrelid = pg_class.oid "
" AND pg_attribute.attnum = any(pg_index.indkey)" " AND pg_attribute.attnum = any(pg_index.indkey)"
@ -633,7 +638,7 @@ bool db_opt_kingbase::getTriggerName(QString sDatabaseName, QString sTableName,
listTriggerName.clear(); listTriggerName.clear();
QString sSql = "select TRIGGER_NAME,EVENT_OBJECT_TABLE from information_schema.TRIGGERS \ QString sSql = "select TRIGGER_NAME,EVENT_OBJECT_TABLE from information_schema.TRIGGERS \
where event_object_catalog='" + g_sDefaultSchema + "' "; where event_object_catalog='" + m_objDb.getDbPara().getDatabaseName() + "' ";
if ( sTableName != "" ) if ( sTableName != "" )
sSql += "and EVENT_OBJECT_TABLE='" + sTableName + "' "; sSql += "and EVENT_OBJECT_TABLE='" + sTableName + "' ";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
@ -666,7 +671,7 @@ bool db_opt_kingbase::getCreateTriggerString( QString sDatabaseName, QString sTa
} }
QString sSql = "select TRIGGER_NAME,ACTION_TIMING,EVENT_MANIPULATION,EVENT_OBJECT_TABLE,ACTION_ORIENTATION,ACTION_STATEMENT from information_schema.TRIGGERS \ QString sSql = "select TRIGGER_NAME,ACTION_TIMING,EVENT_MANIPULATION,EVENT_OBJECT_TABLE,ACTION_ORIENTATION,ACTION_STATEMENT from information_schema.TRIGGERS \
where event_object_catalog='" + g_sDefaultSchema + "' and TRIGGER_NAME = '" + sTriggerName + "' "; where event_object_catalog='" + m_objDb.getDbPara().getDatabaseName() + "' and TRIGGER_NAME = '" + sTriggerName + "' ";
if ( sTableName != "" ) if ( sTableName != "" )
sSql += " and EVENT_OBJECT_TABLE='" + sTableName + "' "; sSql += " and EVENT_OBJECT_TABLE='" + sTableName + "' ";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
@ -731,7 +736,7 @@ bool db_opt_kingbase::getFunctionName( QString sDatabaseName, QStringList& listF
} }
listFunctionName.clear(); listFunctionName.clear();
QString sSql = "SELECT p.oid::regprocedure FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_proc p ON pronamespace = n.oid WHERE nspname = '" + g_sDefaultSchema +"';"; QString sSql = "SELECT p.oid::regprocedure FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_proc p ON pronamespace = n.oid WHERE nspname = '" + m_objDb.getDbPara().getDatabaseName() +"';";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -855,7 +860,8 @@ bool db_opt_kingbase::checkTrigger(const QString &sDatabaseName)
while ( !eleTable.isNull() ) while ( !eleTable.isNull() )
{ {
QString sTableName = eleTable.attribute("name").toLower(); QString sTableName = eleTable.attribute("name").toLower();
if ( eleTable.attribute("use_type","") == "rdb" ) {// 筛选掉纯内存库表 QString sUseType = eleTable.attribute("use_type","");
if ( sUseType == "rdb" || sUseType.isEmpty()) {// 筛选掉纯内存库表
eleTable = eleTable.nextSiblingElement(); eleTable = eleTable.nextSiblingElement();
continue; continue;
} }
@ -958,7 +964,7 @@ bool db_opt_kingbase::dropPrimaryKey(const QString &sDatabaseName, const QString
QString sSql = "select concat('alter table " + sTableName + QString sSql = "select concat('alter table " + sTableName +
"drop constraint ', constraint_name) as my_query " + "drop constraint ', constraint_name) as my_query " +
"from information_schema.table_constraints " + "from information_schema.table_constraints " +
"where table_schema = '" + g_sDefaultSchema + "' and table_name = '" + sTableName + "where table_schema = '" + m_objDb.getDbPara().getDatabaseName() + "' and table_name = '" + sTableName +
"' and constraint_type = 'PRIMARY KEY';"; "' and constraint_type = 'PRIMARY KEY';";
{ {
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
@ -989,7 +995,7 @@ bool db_opt_kingbase::getTableIndex(QString &sTableName, QSqlQuery &query)
QString sError; QString sError;
query.clear(); query.clear();
QString sSql = "select indexname from pg_indexes where tablename not like 'pg%' and schemaname = '" + g_sDefaultSchema + "' and indexname not like '%_pkey' and tablename = '" + sTableName + "' ;"; QString sSql = "select indexname from pg_indexes where tablename not like 'pg%' and schemaname = '" + m_objDb.getDbPara().getDatabaseName() + "' and indexname not like '%_pkey' and tablename = '" + sTableName + "' ;";
if ( executeSql( sSql, query, sError ) == false ) if ( executeSql( sSql, query, sError ) == false )
{ {
qDebug() << "获取表索引出错"; qDebug() << "获取表索引出错";

View File

@ -984,7 +984,7 @@ bool db_opt_mysql::importSqlFileHelper(QString sFileName, quint32 nImportType, i
} }
restoreDatabaseParameter(); restoreDatabaseParameter();
file.close(); file.close();
signalSendMsg( "导入SQL文件完成...!" ); signalSendMsg( tr("导入SQL文件完成...!") );
return true; return true;
} }

View File

@ -66,7 +66,7 @@ bool db_opt_opengauss::getTableName( QString sDatabaseName, QList<STable>& listT
} }
QString sSql = "SELECT t.table_name, pg_catalog.obj_description(pgc.oid, 'pg_class') FROM information_schema.tables t INNER JOIN pg_catalog.pg_class pgc ON t.table_name = pgc.relname WHERE t.table_type='BASE TABLE' AND t.table_schema='public';"; QString sSql = "SELECT t.table_name, pg_catalog.obj_description(pgc.oid, 'pg_class') FROM information_schema.tables t INNER JOIN pg_catalog.pg_class pgc ON t.table_name = pgc.relname WHERE t.table_type='BASE TABLE' AND t.table_schema='" + m_objDb.getDbPara().getDatabaseName() + "';";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -95,7 +95,7 @@ bool db_opt_opengauss::getTableName( QString sDatabaseName, QStringList& listTab
return false; return false;
} }
QString sSql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"; QString sSql = "SELECT t.table_name, pg_catalog.obj_description(pgc.oid, 'pg_class') FROM information_schema.tables t INNER JOIN pg_catalog.pg_class pgc ON t.table_name = pgc.relname WHERE t.table_type='BASE TABLE' AND t.table_schema='" + m_objDb.getDbPara().getDatabaseName() + "';";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -122,7 +122,7 @@ bool db_opt_opengauss::getCreateTableString( QString sDatabaseName, QString sTab
} }
QString sSql = QString sSql =
"CREATE OR REPLACE FUNCTION public.show_create_table(\n" "CREATE OR REPLACE FUNCTION show_create_table(\n"
" in_schema_name varchar,\n" " in_schema_name varchar,\n"
" in_table_name varchar\n" " in_table_name varchar\n"
")\n" ")\n"
@ -243,8 +243,8 @@ bool db_opt_opengauss::getCreateTableString( QString sDatabaseName, QString sTab
" -- return the ddl\n" " -- return the ddl\n"
" RETURN v_table_ddl;\n" " RETURN v_table_ddl;\n"
" END;\n" " END;\n"
"$$;\n" "$$;\n";
"SELECT * FROM public.show_create_table('public', '" + sTableName + "');"; //"SELECT * FROM public.show_create_table('public', '" + sTableName + "');";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
@ -376,7 +376,7 @@ bool db_opt_opengauss::getColumn( QString sDatabaseName, QString sTableName, QLi
"FROM pg_index, pg_class, pg_attribute, pg_namespace " "FROM pg_index, pg_class, pg_attribute, pg_namespace "
"WHERE pg_attribute.attnum > 0 AND " "WHERE pg_attribute.attnum > 0 AND "
"pg_class.oid = '" + sTableName + "'::regclass " "pg_class.oid = '" + sTableName + "'::regclass "
"AND nspname = 'public' " "AND nspname = '" + m_objDb.getDbPara().getDatabaseName() + "' "
"AND pg_class.relnamespace = pg_namespace.oid " "AND pg_class.relnamespace = pg_namespace.oid "
"AND pg_attribute.attrelid = pg_class.oid " "AND pg_attribute.attrelid = pg_class.oid "
"AND pg_attribute.attisdropped = false) order by attnum;"; "AND pg_attribute.attisdropped = false) order by attnum;";
@ -569,7 +569,7 @@ QStringList db_opt_opengauss::getMainKeys(QString sDataBase, QString sTableName)
" WHERE pg_attribute.attnum > 0 AND " " WHERE pg_attribute.attnum > 0 AND "
" pg_class.oid = '" + sTableName + "'::regclass AND " " pg_class.oid = '" + sTableName + "'::regclass AND "
" indrelid = pg_class.oid " " indrelid = pg_class.oid "
" AND nspname = 'public' " " AND nspname = '" + m_objDb.getDbPara().getDatabaseName() + "' "
" AND pg_class.relnamespace = pg_namespace.oid " " AND pg_class.relnamespace = pg_namespace.oid "
" AND pg_attribute.attrelid = pg_class.oid " " AND pg_attribute.attrelid = pg_class.oid "
" AND pg_attribute.attnum = any(pg_index.indkey)" " AND pg_attribute.attnum = any(pg_index.indkey)"
@ -706,7 +706,7 @@ bool db_opt_opengauss::getFunctionName( QString sDatabaseName, QStringList& list
} }
listFunctionName.clear(); listFunctionName.clear();
QString sSql = "SELECT proname FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_proc p ON pronamespace = n.oid WHERE nspname = 'public';"; QString sSql = "SELECT p.oid::regprocedure FROM pg_catalog.pg_namespace n JOIN pg_catalog.pg_proc p ON pronamespace = n.oid WHERE nspname = '" + m_objDb.getDbPara().getDatabaseName() +"';";
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
if ( query.exec( sSql ) == false ) if ( query.exec( sSql ) == false )
return false; return false;
@ -863,10 +863,10 @@ bool db_opt_opengauss::dropPrimaryKey(const QString &sDatabaseName, const QStrin
} }
QString sSql = "select concat('alter table public." + sTableName + QString sSql = "select concat('alter table " + sTableName +
"drop constraint ', constraint_name) as my_query " + "drop constraint ', constraint_name) as my_query " +
"from information_schema.table_constraints " + "from information_schema.table_constraints " +
"where table_schema = 'public' and table_name = '" + sTableName + "where table_schema = '" + m_objDb.getDbPara().getDatabaseName() + "' and table_name = '" + sTableName +
"' and constraint_type = 'PRIMARY KEY';"; "' and constraint_type = 'PRIMARY KEY';";
{ {
QSqlQuery query( *m_objDb.getDatabase() ); QSqlQuery query( *m_objDb.getDatabase() );
@ -897,7 +897,7 @@ bool db_opt_opengauss::getTableIndex(QString &sTableName, QSqlQuery &query)
QString sError; QString sError;
query.clear(); query.clear();
QString sSql = "select indexname from pg_indexes where tablename not like 'pg%' and schemaname = 'public' and indexname not like '%_pkey' and tablename = '" + sTableName + "' ;"; QString sSql = "select indexname from pg_indexes where tablename not like 'pg%' and schemaname = '" + m_objDb.getDbPara().getDatabaseName() + "' and indexname not like '%_pkey' and tablename = '" + sTableName + "' ;";
if ( executeSql( sSql, query, sError ) == false ) if ( executeSql( sSql, query, sError ) == false )
{ {
qDebug() << "获取表索引出错"; qDebug() << "获取表索引出错";
@ -913,7 +913,7 @@ bool db_opt_opengauss::deleteTableIndex(QString &sTableName, QSqlQuery &query)
QString sError; QString sError;
Q_UNUSED(sTableName) Q_UNUSED(sTableName)
QString sSql = "drop index " + query.value("indexname").toString(); QString sSql = "drop index " +m_objDb.getDbPara().getDatabaseName()+"."+ query.value("indexname").toString();
if ( executeSql( sSql, sError ) == false ) if ( executeSql( sSql, sError ) == false )
{ {
qDebug() << "删除表索引出错"; qDebug() << "删除表索引出错";
@ -950,7 +950,7 @@ bool db_opt_opengauss::createUniqueIndex(QString &sTableName, QList<QStringList>
{ {
QString sError; QString sError;
QString sSql = "CREATE UNIQUE INDEX IN_" + sTableName.toUpper() + " ON " + sTableName + " ("; QString sSql = "CREATE UNIQUE INDEX Un_" + sTableName.toUpper() + " ON " + sTableName + " (";
for(int i = 0; i < uniqueIndex.count(); i++) for(int i = 0; i < uniqueIndex.count(); i++)
{ {
sSql += uniqueIndex[i][0] + " "+ uniqueIndex[i][1] + ","; sSql += uniqueIndex[i][0] + " "+ uniqueIndex[i][1] + ",";

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,7 @@
#define TEST_DB_IP "127.0.0.1" #define TEST_DB_IP "127.0.0.1"
#define TEST_DB_PORT 3306 #define TEST_DB_PORT 3306
#define TEST_DB_USERNAME "root" #define TEST_DB_USERNAME "root"
#define TEST_DB_PASSWORD "kbdct@0755" #define TEST_DB_PASSWORD EMS_DEFAULT_PASSWD
MainWindow::MainWindow(QWidget *parent) : MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), QMainWindow(parent),

View File

@ -101,8 +101,8 @@ void COStreamFile::writeMsg( const std::string &strData )
} }
uint64 ullSize = cn_check_mask | strData.size(); uint64 ullSize = cn_check_mask | strData.size();
m_pStream->WriteLittleEndian64( ullSize ); m_pStream->WriteLittleEndian64( ullSize );
LOGDEBUG( "write little endian64 %llu", ( unsigned long long ) strData.size()); LOGDEBUG( "write little endian64 %d", strData.size());
m_pStream->WriteRaw(( const void * ) strData.data(), strData.size()); m_pStream->WriteRaw(( const void * ) strData.data(), static_cast<int>(strData.size()));
} }
} //< namespace iot_dbms } //< namespace iot_dbms

View File

@ -21,7 +21,7 @@ QWidget* CColumnModeDelegate::createEditor( QWidget *parent, const QStyleOptionV
pComboBox->addItem("rdb"); pComboBox->addItem("rdb");
return pComboBox; return pComboBox;
} }
else if ( nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol ==19 || nCol == 20 || nCol == 21 ) else if ( nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol ==19 || nCol == 20 )
{ {
QComboBox *pComboBox = new QComboBox(parent); QComboBox *pComboBox = new QComboBox(parent);
pComboBox->addItem("yes"); pComboBox->addItem("yes");
@ -95,7 +95,7 @@ void CColumnModeDelegate::setEditorData( QWidget *editor, const QModelIndex &ind
pSpinBox->setValue( nValue ); pSpinBox->setValue( nValue );
} }
else if ( nCol == 4 || nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol == 19 || else if ( nCol == 4 || nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol == 19 ||
nCol == 20 || nCol == 21 || nCol == 6 || nCol == 11 || nCol == 12 || nCol == 15 || nCol == 16 ) nCol == 20 || nCol == 6 || nCol == 11 || nCol == 12 || nCol == 15 || nCol == 16 )
{ {
QString text = index.model()->data(index).toString(); QString text = index.model()->data(index).toString();
QComboBox* pComboBox = static_cast<QComboBox*>(editor); QComboBox* pComboBox = static_cast<QComboBox*>(editor);
@ -113,7 +113,7 @@ void CColumnModeDelegate::setModelData( QWidget *editor, QAbstractItemModel *mod
model->setData(index, pSpinBox->value()); model->setData(index, pSpinBox->value());
} }
else if ( nCol == 4 || nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol == 19 || else if ( nCol == 4 || nCol == 5 || nCol == 9 || nCol == 10 || nCol == 13 || nCol == 19 ||
nCol == 20 || nCol == 21 || nCol == 6 || nCol == 11 || nCol == 12 || nCol == 15 || nCol == 16 ) nCol == 20 || nCol == 6 || nCol == 11 || nCol == 12 || nCol == 15 || nCol == 16 )
{ {
QComboBox* pComboBox = static_cast<QComboBox*>(editor); QComboBox* pComboBox = static_cast<QComboBox*>(editor);
QString data = pComboBox->currentText(); QString data = pComboBox->currentText();

View File

@ -27,8 +27,7 @@ CColumnModeModel::CColumnModeModel()
<< "数据长度(rdb)" << "数据长度(rdb)"
<< "默认值(rdb)" << "默认值(rdb)"
<< "是否同步到备内存库" << "是否同步到备内存库"
<< "是否更新到内存库" << "是否更新到内存库";
<< "内存库持久化";
} }
CColumnModeModel::~CColumnModeModel() CColumnModeModel::~CColumnModeModel()
@ -143,9 +142,6 @@ QVariant CColumnModeModel::data( const QModelIndex &index, int role ) const
case 20: case 20:
oVal = m_pListColumn->at(index.row())->sIsUpdateToRdb; oVal = m_pListColumn->at(index.row())->sIsUpdateToRdb;
break; break;
case 21:
oVal = m_pListColumn->at(index.row())->sCache;
break;
} }
return oVal; return oVal;
} }
@ -314,13 +310,6 @@ bool CColumnModeModel::setData( const QModelIndex& index, const QVariant &value,
emit signalDataChanged(); emit signalDataChanged();
} }
break; break;
case 21:
if ( m_pListColumn->at(index.row())->sCache != value.toString() )
{
m_pListColumn->at(index.row())->sCache = value.toString();
emit signalDataChanged();
}
break;
} }
return true; return true;
} }

View File

@ -4,18 +4,21 @@
#include "pub_sysinfo_api/SysInfoApi.h" #include "pub_sysinfo_api/SysInfoApi.h"
#include "CFileSelect.h" #include "CFileSelect.h"
#include <QCloseEvent> #include <QCloseEvent>
#include "pub_widget/MessageBox.h"
CDbStudio::CDbStudio(QWidget *parent) : CDbStudio::CDbStudio(QWidget *parent) :
QMainWindow(parent), CustomUiMainWindow(parent),
ui(new Ui::CDbStudio) ui(new Ui::CDbStudio)
{ {
ui->setupUi(this); ui->setupUi(this);
setAutoLayout(true);
ui->menuBar->hide();
ui->mainToolBar->hide();
ui->statusBar->hide();
if ( false == loadConfig() )
{
exit(0);
return;
}
initUi(); initUi();
initMainMenu();
} }
CDbStudio::~CDbStudio() CDbStudio::~CDbStudio()
@ -23,30 +26,74 @@ CDbStudio::~CDbStudio()
delete ui; delete ui;
} }
bool CDbStudio::loadConfig() void CDbStudio::slotMainMenuClicked(int nIndex)
{
if ( false == loadConfig(nIndex) )
{
N_MessageBox::warning(this,tr("警告"),tr("加载配置文件失败"));
return;
}
refreshTableModeTableView();
refreshColumnModeListWidget();
}
void CDbStudio::initMainMenu()
{
QPushButton* platBtn = new QPushButton();
platBtn->setObjectName("btn_platform");
platBtn->setText(tr("平台配置"));
ui->mainMenu->addToolBtn(platBtn);
QPushButton* prodBtn = new QPushButton();
prodBtn->setObjectName("btn_product");
prodBtn->setText(tr("产品配置"));
ui->mainMenu->addToolBtn(prodBtn);
connect(ui->mainMenu, &MenuFrame::buttonClicked,this, &CDbStudio::slotMainMenuClicked);
slotMainMenuClicked(CN_MainMenu_Platform);
platBtn->setChecked(true);
}
void CDbStudio::clearTableInfo()
{
foreach (STable* pTable, m_listTable) {
delete pTable;
}
m_listTable.clear();
m_listTable_db.clear(); //< m_listTable_db都在m_listTable
m_listTable_rdb.clear(); //< m_listTable_rdb都在m_listTable
m_listSubsystem.clear();
}
bool CDbStudio::loadConfig(int nMenuIndex)
{ {
m_bSaved = true; m_bSaved = true;
m_sComment = ""; m_sComment = "";
clearTableInfo();
// 先选择编辑的文件 // 先选择编辑的文件
CFileSelect objFileSelect; CFileSelect objFileSelect(nMenuIndex,this);
objFileSelect.exec(); // objFileSelect.exec();
m_sFilePath = objFileSelect.getFilePath(); m_sFilePath = objFileSelect.getFilePath();
if ( m_sFilePath == "" ) if ( m_sFilePath == "" )
return false; return false;
// 设置窗口名称 // 设置窗口名称
setWindowTitle( "表结构修改工具" + objFileSelect.getDesc() ); m_strCurTitle = tr("表结构管理工具") + objFileSelect.getDesc();
setWindowTitle( m_strCurTitle );
QFile oFile( m_sFilePath ); QFile oFile( m_sFilePath );
if ( !oFile.exists() ) if ( !oFile.exists() )
{ {
QMessageBox::critical( 0, "错误", QString("配置文件【%1】不存在").arg(m_sFilePath) ); N_MessageBox::critical( 0, "错误", QString("配置文件【%1】不存在").arg(m_sFilePath) );
return false; return false;
} }
if ( !oFile.open(QIODevice::ReadOnly) ) if ( !oFile.open(QIODevice::ReadOnly) )
{ {
QMessageBox::critical( 0, "错误", QString("配置文件【%1】打开失败").arg(m_sFilePath) ); N_MessageBox::critical( 0, "错误", QString("配置文件【%1】打开失败").arg(m_sFilePath) );
return false; return false;
} }
@ -54,7 +101,7 @@ bool CDbStudio::loadConfig()
if ( !oDoc.setContent(&oFile) ) if ( !oDoc.setContent(&oFile) )
{ {
oFile.close(); oFile.close();
QMessageBox::critical( 0, "错误", QString("配置文件【%1】解析内容错误").arg(m_sFilePath) ); N_MessageBox::critical( 0, "错误", QString("配置文件【%1】解析内容错误").arg(m_sFilePath) );
return false; return false;
} }
@ -93,7 +140,6 @@ bool CDbStudio::loadConfig()
pTable->nSubsystemFlag = eleTableRdb.attribute( "subsystem_flag", "0" ).toULongLong(); pTable->nSubsystemFlag = eleTableRdb.attribute( "subsystem_flag", "0" ).toULongLong();
pTable->sSelectByLocation = eleTableRdb.attribute( "select_by_location", "" ); pTable->sSelectByLocation = eleTableRdb.attribute( "select_by_location", "" );
pTable->sSelectBySubsystem = eleTableRdb.attribute( "select_by_subsystem", "" ); pTable->sSelectBySubsystem = eleTableRdb.attribute( "select_by_subsystem", "" );
pTable->sCache = eleTableRdb.attribute( "cache", "" );
} }
QDomElement eleColumn = eleTable.firstChildElement("Column"); QDomElement eleColumn = eleTable.firstChildElement("Column");
@ -132,7 +178,6 @@ bool CDbStudio::loadConfig()
pColumn->sDefaultValue_rdb = eleColumnRdb.attribute( "default_value", "" ); pColumn->sDefaultValue_rdb = eleColumnRdb.attribute( "default_value", "" );
pColumn->sIsSynToSlave = eleColumnRdb.attribute( "is_syn_to_slave", "" ); pColumn->sIsSynToSlave = eleColumnRdb.attribute( "is_syn_to_slave", "" );
pColumn->sIsUpdateToRdb = eleColumnRdb.attribute( "is_update_to_rdb", "" ); pColumn->sIsUpdateToRdb = eleColumnRdb.attribute( "is_update_to_rdb", "" );
pColumn->sCache = eleColumnRdb.attribute( "cache", "" );
} }
pTable->listColumn.append( pColumn ); pTable->listColumn.append( pColumn );
@ -148,13 +193,13 @@ bool CDbStudio::loadConfig()
std::vector<iot_public::SSubsystemInfo> vecSubsystemInfo; std::vector<iot_public::SSubsystemInfo> vecSubsystemInfo;
if ( iot_public::createSysInfoInstance( pSysInfo ) == false ) if ( iot_public::createSysInfoInstance( pSysInfo ) == false )
{ {
QMessageBox::warning( 0, "警告", tr("createSysInfoInstance失败导致无法修改表所属的专业其他功能可用") ); N_MessageBox::warning( 0, "警告", tr("createSysInfoInstance失败导致无法修改表所属的专业其他功能可用") );
} }
else else
{ {
if ( 0 != pSysInfo->getAllSubsystemInfo( vecSubsystemInfo )) if ( 0 != pSysInfo->getAllSubsystemInfo( vecSubsystemInfo ))
{ {
QMessageBox::critical( 0, "错误", tr("获取专业信息失败") ); N_MessageBox::critical( 0, "错误", tr("获取专业信息失败") );
return false; return false;
} }
} }
@ -194,10 +239,6 @@ bool CDbStudio::loadConfig()
void CDbStudio::initUi() void CDbStudio::initUi()
{ {
ui->menuBar->hide();
ui->mainToolBar->hide();
ui->statusBar->hide();
initTableModeUi(); initTableModeUi();
initColumnModeUi(); initColumnModeUi();
} }
@ -224,7 +265,7 @@ void CDbStudio::initTableModeUi()
ui->tableView_tableMode->setItemDelegateForColumn( 8, new CTableModeDelegate(&m_listSubsystem) ); ui->tableView_tableMode->setItemDelegateForColumn( 8, new CTableModeDelegate(&m_listSubsystem) );
ui->tableView_tableMode->setItemDelegateForColumn( 9, new CTableModeDelegate(&m_listSubsystem) ); ui->tableView_tableMode->setItemDelegateForColumn( 9, new CTableModeDelegate(&m_listSubsystem) );
ui->tableView_tableMode->setItemDelegateForColumn( 10, new CTableModeDelegate(&m_listSubsystem) ); ui->tableView_tableMode->setItemDelegateForColumn( 10, new CTableModeDelegate(&m_listSubsystem) );
ui->tableView_tableMode->setItemDelegateForColumn( 11, new CTableModeDelegate(&m_listSubsystem) );
connect( m_pTableModeModel, SIGNAL(signalTableNameChanged()), this, SLOT(slotTableNameChanged()) ); connect( m_pTableModeModel, SIGNAL(signalTableNameChanged()), this, SLOT(slotTableNameChanged()) );
connect( m_pTableModeModel, SIGNAL(signalDataChanged()), this, SLOT(slotDataChanged()) ); connect( m_pTableModeModel, SIGNAL(signalDataChanged()), this, SLOT(slotDataChanged()) );
@ -234,7 +275,7 @@ void CDbStudio::initTableModeUi()
connect( ui->pushButton_delTable, SIGNAL(clicked(bool)), this, SLOT(slotDelTable(bool)) ); connect( ui->pushButton_delTable, SIGNAL(clicked(bool)), this, SLOT(slotDelTable(bool)) );
connect( ui->pushButton_saveTable, SIGNAL(clicked(bool)), this, SLOT(slotSave(bool)) ); connect( ui->pushButton_saveTable, SIGNAL(clicked(bool)), this, SLOT(slotSave(bool)) );
refreshTableModeTableView(); // refreshTableModeTableView();
} }
void CDbStudio::initColumnModeUi() void CDbStudio::initColumnModeUi()
@ -268,7 +309,6 @@ void CDbStudio::initColumnModeUi()
ui->tableView_columnMode->setItemDelegateForColumn( 17, new CColumnModeDelegate ); ui->tableView_columnMode->setItemDelegateForColumn( 17, new CColumnModeDelegate );
ui->tableView_columnMode->setItemDelegateForColumn( 19, new CColumnModeDelegate ); ui->tableView_columnMode->setItemDelegateForColumn( 19, new CColumnModeDelegate );
ui->tableView_columnMode->setItemDelegateForColumn( 20, new CColumnModeDelegate ); ui->tableView_columnMode->setItemDelegateForColumn( 20, new CColumnModeDelegate );
ui->tableView_columnMode->setItemDelegateForColumn( 21, new CColumnModeDelegate );
connect( m_pColumnModeModel, SIGNAL(signalDataChanged()), this, SLOT(slotDataChanged()) ); connect( m_pColumnModeModel, SIGNAL(signalDataChanged()), this, SLOT(slotDataChanged()) );
connect( ui->listWidget_columnMode, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotColumnModeListWidgetItemClicked(QListWidgetItem*)) ); connect( ui->listWidget_columnMode, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(slotColumnModeListWidgetItemClicked(QListWidgetItem*)) );
@ -280,15 +320,15 @@ void CDbStudio::initColumnModeUi()
connect( ui->pushButton_moveUp, SIGNAL(clicked(bool)), this, SLOT(slotColumnMoveUp(bool)) ); connect( ui->pushButton_moveUp, SIGNAL(clicked(bool)), this, SLOT(slotColumnMoveUp(bool)) );
connect( ui->pushButton_moveDown, SIGNAL(clicked(bool)), this, SLOT(slotColumnMoveDown(bool)) ); connect( ui->pushButton_moveDown, SIGNAL(clicked(bool)), this, SLOT(slotColumnMoveDown(bool)) );
refreshColumnModeListWidget(); // refreshColumnModeListWidget();
} }
void CDbStudio::closeEvent(QCloseEvent *pEvent) void CDbStudio::closeEvent(QCloseEvent *pEvent)
{ {
if ( m_bSaved == false ) if ( m_bSaved == false )
{ {
int nRet = QMessageBox::information( 0, "提示", "当前修改未保存,是否保存?", QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel ); int nRet = N_MessageBox::information( 0, "提示", "当前修改未保存,是否保存?", N_MessageBox::Yes, N_MessageBox::No, N_MessageBox::Cancel );
if ( nRet == QMessageBox::Yes ) if ( nRet == N_MessageBox::Yes )
{ {
bool bRet = slotSave( true ); bool bRet = slotSave( true );
if ( bRet == false ) if ( bRet == false )
@ -297,7 +337,7 @@ void CDbStudio::closeEvent(QCloseEvent *pEvent)
return; return;
} }
} }
else if ( nRet == QMessageBox::Cancel ) else if ( nRet == N_MessageBox::Cancel )
{ {
pEvent->ignore(); pEvent->ignore();
return; return;
@ -349,7 +389,6 @@ void CDbStudio::refreshTableModeTableView()
ui->tableView_tableMode->setColumnHidden( 8, false ); ui->tableView_tableMode->setColumnHidden( 8, false );
ui->tableView_tableMode->setColumnHidden( 9, false ); ui->tableView_tableMode->setColumnHidden( 9, false );
ui->tableView_tableMode->setColumnHidden( 10, false ); ui->tableView_tableMode->setColumnHidden( 10, false );
ui->tableView_tableMode->setColumnHidden( 11, false );
m_pTableModeModel->setTablePtr( &m_listTable ); m_pTableModeModel->setTablePtr( &m_listTable );
} }
@ -361,7 +400,6 @@ void CDbStudio::refreshTableModeTableView()
ui->tableView_tableMode->setColumnHidden( 8, true ); ui->tableView_tableMode->setColumnHidden( 8, true );
ui->tableView_tableMode->setColumnHidden( 9, true ); ui->tableView_tableMode->setColumnHidden( 9, true );
ui->tableView_tableMode->setColumnHidden( 10, true ); ui->tableView_tableMode->setColumnHidden( 10, true );
ui->tableView_tableMode->setColumnHidden( 11, false );
m_pTableModeModel->setTablePtr( &m_listTable_db ); m_pTableModeModel->setTablePtr( &m_listTable_db );
@ -374,7 +412,6 @@ void CDbStudio::refreshTableModeTableView()
ui->tableView_tableMode->setColumnHidden( 8, false ); ui->tableView_tableMode->setColumnHidden( 8, false );
ui->tableView_tableMode->setColumnHidden( 9, false ); ui->tableView_tableMode->setColumnHidden( 9, false );
ui->tableView_tableMode->setColumnHidden( 10, false ); ui->tableView_tableMode->setColumnHidden( 10, false );
ui->tableView_tableMode->setColumnHidden( 11, true );
m_pTableModeModel->setTablePtr( &m_listTable_rdb ); m_pTableModeModel->setTablePtr( &m_listTable_rdb );
@ -497,18 +534,27 @@ void CDbStudio::refreshColumnModeListWidget()
void CDbStudio::configChanged() void CDbStudio::configChanged()
{ {
setWindowTitle( "表结构修改工具(未保存)" ); setWindowTitle( m_strCurTitle + "(未保存)" );
ui->tableView_tableMode->setStyleSheet( "background-color: wheat;" ); // ui->tableView_tableMode->setStyleSheet( "background-color: wheat;" );
ui->tableView_columnMode->setStyleSheet( "background-color: wheat;" ); // ui->tableView_columnMode->setStyleSheet( "background-color: wheat;" );
m_bSaved = false; m_bSaved = false;
ui->tableView_tableMode->setProperty("changed",true);
ui->tableView_columnMode->setProperty("changed",true);
this->style()->polish(ui->tableView_tableMode);
this->style()->polish(ui->tableView_columnMode);
} }
void CDbStudio::configSaved() void CDbStudio::configSaved()
{ {
setWindowTitle( "表结构修改工具" ); setWindowTitle( m_strCurTitle );
ui->tableView_tableMode->setStyleSheet( "" ); ui->tableView_tableMode->setStyleSheet( "" );
ui->tableView_columnMode->setStyleSheet( "" ); ui->tableView_columnMode->setStyleSheet( "" );
m_bSaved = true; m_bSaved = true;
ui->tableView_tableMode->setProperty("changed",false);
ui->tableView_columnMode->setProperty("changed",false);
this->style()->polish(ui->tableView_tableMode);
this->style()->polish(ui->tableView_columnMode);
} }
void CDbStudio::slotShowTableStateChanged( int ) void CDbStudio::slotShowTableStateChanged( int )
@ -537,13 +583,13 @@ void CDbStudio::slotDelTable( bool )
int nRow = ui->tableView_tableMode->currentIndex().row(); int nRow = ui->tableView_tableMode->currentIndex().row();
if ( nRow < 0 || nRow >= m_listTable.count() ) if ( nRow < 0 || nRow >= m_listTable.count() )
{ {
QMessageBox::critical( 0, "错误", "请先选择要删除的表" ); N_MessageBox::critical( 0, "错误", "请先选择要删除的表" );
return; return;
} }
STable* pTable = m_listTable.at( nRow ); STable* pTable = m_listTable.at( nRow );
QMessageBox::StandardButton ret = QMessageBox::question( 0, "警告", "确定删除表 【"+pTable->sName+"】?"); int ret = N_MessageBox::question( 0, "警告", "确定删除表 【"+pTable->sName+"】?");
if ( ret == QMessageBox::StandardButton::Yes ) if ( ret == N_MessageBox::Ok )
{ {
m_pTableModeModel->clearTablePtr(); m_pTableModeModel->clearTablePtr();
m_listTable.removeAt( nRow ); m_listTable.removeAt( nRow );
@ -551,7 +597,7 @@ void CDbStudio::slotDelTable( bool )
pTable = NULL; pTable = NULL;
refreshTableModeTableView(); refreshTableModeTableView();
QMessageBox::information(0,"提示","删除成功"); N_MessageBox::information(0,"提示","删除成功");
} }
refreshColumnModeListWidget(); refreshColumnModeListWidget();
@ -590,7 +636,7 @@ void CDbStudio::slotAddColumn( bool )
QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem(); QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem();
if ( pItem == NULL ) if ( pItem == NULL )
{ {
QMessageBox::warning( 0, "警告", "请先选择一张表" ); N_MessageBox::warning( 0, "警告", "请先选择一张表" );
return; return;
} }
@ -617,7 +663,7 @@ void CDbStudio::slotDelColumn( bool )
QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem(); QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem();
if ( pItem == NULL ) if ( pItem == NULL )
{ {
QMessageBox::warning( 0, "警告", "请先选择一张表" ); N_MessageBox::warning( 0, "警告", "请先选择一张表" );
return; return;
} }
@ -628,13 +674,13 @@ void CDbStudio::slotDelColumn( bool )
int nRow = ui->tableView_columnMode->currentIndex().row(); int nRow = ui->tableView_columnMode->currentIndex().row();
if ( nRow < 0 || nRow >= m_listTable.at(nIndex)->listColumn.count() ) if ( nRow < 0 || nRow >= m_listTable.at(nIndex)->listColumn.count() )
{ {
QMessageBox::critical( 0, "错误", "请先选择要删除的列" ); N_MessageBox::critical( 0, "错误", "请先选择要删除的列" );
return; return;
} }
SColumn* pColumn = m_listTable.at(nIndex)->listColumn.at( nRow ); SColumn* pColumn = m_listTable.at(nIndex)->listColumn.at( nRow );
QMessageBox::StandardButton ret = QMessageBox::question( 0, "警告", "确定删除列 【"+pColumn->sName+"】?"); int ret = N_MessageBox::question( 0, "警告", "确定删除列 【"+pColumn->sName+"】?");
if ( ret == QMessageBox::StandardButton::Yes ) if ( ret == N_MessageBox::Ok )
{ {
m_pColumnModeModel->clearTablePtr(); m_pColumnModeModel->clearTablePtr();
m_listTable.at(nIndex)->listColumn.removeAt( nRow ); m_listTable.at(nIndex)->listColumn.removeAt( nRow );
@ -642,7 +688,7 @@ void CDbStudio::slotDelColumn( bool )
pColumn = NULL; pColumn = NULL;
m_pColumnModeModel->setTablePtr( &m_listTable.at(nIndex)->listColumn ); m_pColumnModeModel->setTablePtr( &m_listTable.at(nIndex)->listColumn );
QMessageBox::information(0,"提示","删除成功"); N_MessageBox::information(0,"提示","删除成功");
} }
configChanged(); configChanged();
} }
@ -652,7 +698,7 @@ void CDbStudio::slotColumnMoveUp( bool )
QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem(); QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem();
if ( pItem == NULL ) if ( pItem == NULL )
{ {
QMessageBox::warning( 0, "警告", "请先选择一张表" ); N_MessageBox::warning( 0, "警告", "请先选择一张表" );
return; return;
} }
int nIndex = pItem->data( Qt::UserRole ).toInt(); int nIndex = pItem->data( Qt::UserRole ).toInt();
@ -662,7 +708,7 @@ void CDbStudio::slotColumnMoveUp( bool )
int nCurrentRow = ui->tableView_columnMode->currentIndex().row(); int nCurrentRow = ui->tableView_columnMode->currentIndex().row();
if ( nCurrentRow < 0 ) if ( nCurrentRow < 0 )
{ {
QMessageBox::warning( 0, "警告", "请先选择要上移的列" ); N_MessageBox::warning( 0, "警告", "请先选择要上移的列" );
return; return;
} }
else if ( nCurrentRow == 0 ) else if ( nCurrentRow == 0 )
@ -683,7 +729,7 @@ void CDbStudio::slotColumnMoveDown( bool )
QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem(); QListWidgetItem* pItem = ui->listWidget_columnMode->currentItem();
if ( pItem == NULL ) if ( pItem == NULL )
{ {
QMessageBox::warning( 0, "警告", "请先选择一张表" ); N_MessageBox::warning( 0, "警告", "请先选择一张表" );
return; return;
} }
int nIndex = pItem->data( Qt::UserRole ).toInt(); int nIndex = pItem->data( Qt::UserRole ).toInt();
@ -693,7 +739,7 @@ void CDbStudio::slotColumnMoveDown( bool )
int nCurrentRow = ui->tableView_columnMode->currentIndex().row(); int nCurrentRow = ui->tableView_columnMode->currentIndex().row();
if ( nCurrentRow < 0 ) if ( nCurrentRow < 0 )
{ {
QMessageBox::warning( 0, "警告", "请先选择要上移的列" ); N_MessageBox::warning( 0, "警告", "请先选择要上移的列" );
return; return;
} }
else if ( nCurrentRow >= m_pColumnModeModel->rowCount()-1 ) else if ( nCurrentRow >= m_pColumnModeModel->rowCount()-1 )
@ -722,12 +768,12 @@ bool CDbStudio::slotSave( bool )
STable* pTable = m_listTable.at(nTableIndex); STable* pTable = m_listTable.at(nTableIndex);
if ( pTable->sName == "" ) if ( pTable->sName == "" )
{ {
QMessageBox::critical( 0, "错误", QString("存在空名字的表") ); N_MessageBox::critical( 0, "错误", QString("存在空名字的表") );
return false; return false;
} }
else if ( listTableName.contains(pTable->sName.toLower()) ) else if ( listTableName.contains(pTable->sName.toLower()) )
{ {
QMessageBox::critical( 0, "错误", QString("存在同名字的表【%1】").arg(pTable->sName) ); N_MessageBox::critical( 0, "错误", QString("存在同名字的表【%1】").arg(pTable->sName) );
return false; return false;
} }
listTableName.append( pTable->sName.toLower() ); listTableName.append( pTable->sName.toLower() );
@ -738,12 +784,12 @@ bool CDbStudio::slotSave( bool )
SColumn* pColumn = pTable->listColumn.at(nColumnIndex); SColumn* pColumn = pTable->listColumn.at(nColumnIndex);
if ( pColumn->sName == "" ) if ( pColumn->sName == "" )
{ {
QMessageBox::critical( 0, "错误", QString("表【%1】存在空名字的列").arg(pTable->sName) ); N_MessageBox::critical( 0, "错误", QString("表【%1】存在空名字的列").arg(pTable->sName) );
return false; return false;
} }
else if ( listColumnName.contains(pColumn->sName.toLower()) ) else if ( listColumnName.contains(pColumn->sName.toLower()) )
{ {
QMessageBox::critical( 0, "错误", QString("表【%1】存在同名字的列【%2】").arg(pTable->sName).arg(pColumn->sName) ); N_MessageBox::critical( 0, "错误", QString("表【%1】存在同名字的列【%2】").arg(pTable->sName).arg(pColumn->sName) );
return false; return false;
} }
listColumnName.append( pColumn->sName.toLower() ); listColumnName.append( pColumn->sName.toLower() );
@ -771,12 +817,12 @@ bool CDbStudio::slotSave( bool )
QFile oFile( m_sFilePath ); QFile oFile( m_sFilePath );
if ( !oFile.exists() ) if ( !oFile.exists() )
{ {
QMessageBox::critical( 0, "错误", QString("配置文件【%1】不存在保存失败").arg(m_sFilePath) ); N_MessageBox::critical( 0, "错误", QString("配置文件【%1】不存在保存失败").arg(m_sFilePath) );
return false; return false;
} }
if ( !oFile.open(QIODevice::WriteOnly | QIODevice::Text) ) if ( !oFile.open(QIODevice::WriteOnly | QIODevice::Text) )
{ {
QMessageBox::critical( 0, "错误", QString("配置文件【%1】打开失败保存失败").arg(m_sFilePath) ); N_MessageBox::critical( 0, "错误", QString("配置文件【%1】打开失败保存失败").arg(m_sFilePath) );
return false; return false;
} }
QXmlStreamWriter writer(&oFile); QXmlStreamWriter writer(&oFile);
@ -812,7 +858,6 @@ bool CDbStudio::slotSave( bool )
writer.writeAttribute( "subsystem_flag" , QString::number(pTable->nSubsystemFlag) ); writer.writeAttribute( "subsystem_flag" , QString::number(pTable->nSubsystemFlag) );
writer.writeAttribute( "select_by_location" , pTable->sSelectByLocation ); writer.writeAttribute( "select_by_location" , pTable->sSelectByLocation );
writer.writeAttribute( "select_by_subsystem" , pTable->sSelectBySubsystem ); writer.writeAttribute( "select_by_subsystem" , pTable->sSelectBySubsystem );
writer.writeAttribute( "cache" , pTable->sCache );
writer.writeEndElement(); writer.writeEndElement();
} }
@ -905,7 +950,6 @@ bool CDbStudio::slotSave( bool )
writer.writeAttribute( "default_value" , pColumn->sDefaultValue_rdb ); writer.writeAttribute( "default_value" , pColumn->sDefaultValue_rdb );
writer.writeAttribute( "is_syn_to_slave" , pColumn->sIsSynToSlave ); writer.writeAttribute( "is_syn_to_slave" , pColumn->sIsSynToSlave );
writer.writeAttribute( "is_update_to_rdb" , pColumn->sIsUpdateToRdb ); writer.writeAttribute( "is_update_to_rdb" , pColumn->sIsUpdateToRdb );
writer.writeAttribute( "cache" , pColumn->sCache );
writer.writeEndElement(); writer.writeEndElement();
} }
@ -916,7 +960,7 @@ bool CDbStudio::slotSave( bool )
writer.writeEndElement(); writer.writeEndElement();
writer.writeEndDocument(); writer.writeEndDocument();
oFile.close(); oFile.close();
QMessageBox::information(0,"提示",QString("保存配置文件【%1】成功").arg(m_sFilePath)); N_MessageBox::information(0,"提示",QString("保存配置文件【%1】成功").arg(m_sFilePath));
configSaved(); configSaved();
return true; return true;
@ -931,32 +975,3 @@ void CDbStudio::slotDataChanged()
{ {
configChanged(); configChanged();
} }

View File

@ -22,12 +22,13 @@
#include "CColumnModeModel.h" #include "CColumnModeModel.h"
#include "CColumnModeDelegate.h" #include "CColumnModeDelegate.h"
#include "StructDefine.h" #include "StructDefine.h"
#include "pub_widget/CustomMainWindow.h"
namespace Ui { namespace Ui {
class CDbStudio; class CDbStudio;
} }
class CDbStudio : public QMainWindow class CDbStudio : public CustomUiMainWindow
{ {
Q_OBJECT Q_OBJECT
@ -37,7 +38,7 @@ public:
public: public:
void initUi(); void initUi();
bool loadConfig(); bool loadConfig(int nMenuIndex);
void initTableModeUi(); void initTableModeUi();
void initColumnModeUi(); void initColumnModeUi();
@ -65,6 +66,11 @@ public slots:
void slotTableNameChanged(); void slotTableNameChanged();
void slotDataChanged(); void slotDataChanged();
void slotMainMenuClicked(int nIndex);
private:
void initMainMenu();
void clearTableInfo();
private: private:
Ui::CDbStudio *ui; Ui::CDbStudio *ui;
QString m_sComment; // 配置文件的注释 QString m_sComment; // 配置文件的注释
@ -76,6 +82,7 @@ private:
QList<SSubsystem*> m_listSubsystem; // 专业信息 QList<SSubsystem*> m_listSubsystem; // 专业信息
bool m_bSaved; // 是否保存过 bool m_bSaved; // 是否保存过
QString m_sFilePath; // 当前编辑的文件,带路径 QString m_sFilePath; // 当前编辑的文件,带路径
QString m_strCurTitle; //< 当前标题
}; };
#endif // CDBSTUDIO_H #endif // CDBSTUDIO_H

View File

@ -14,7 +14,13 @@
<string>CDbStudio</string> <string>CDbStudio</string>
</property> </property>
<widget class="QWidget" name="centralWidget"> <widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout"> <layout class="QHBoxLayout" name="horizontalLayout_3">
<property name="leftMargin">
<number>0</number>
</property>
<item>
<widget class="MenuFrame" name="mainMenu" native="true"/>
</item>
<item> <item>
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
<property name="currentIndex"> <property name="currentIndex">
@ -174,7 +180,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>1030</width> <width>1030</width>
<height>25</height> <height>23</height>
</rect> </rect>
</property> </property>
</widget> </widget>
@ -189,6 +195,14 @@
<widget class="QStatusBar" name="statusBar"/> <widget class="QStatusBar" name="statusBar"/>
</widget> </widget>
<layoutdefault spacing="6" margin="11"/> <layoutdefault spacing="6" margin="11"/>
<customwidgets>
<customwidget>
<class>MenuFrame</class>
<extends>QWidget</extends>
<header>pub_widget/MenuFrame.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<tabstops> <tabstops>
<tabstop>tabWidget</tabstop> <tabstop>tabWidget</tabstop>
<tabstop>tableView_tableMode</tabstop> <tabstop>tableView_tableMode</tabstop>

View File

@ -3,13 +3,23 @@
#include "ui_CFileSelect.h" #include "ui_CFileSelect.h"
#include "StructDefine.h" #include "StructDefine.h"
CFileSelect::CFileSelect(QWidget *parent) : CFileSelect::CFileSelect(int nMenuIndex,QWidget *parent) :
QDialog(parent), CustomUiDialog(parent),
ui(new Ui::CFileSelect) ui(new Ui::CFileSelect)
{ {
ui->setupUi(this); ui->setupUi(this);
init(); init();
switch (nMenuIndex) {
case CN_MainMenu_Platform:
slotPlatformClicked();
break;
case CN_MainMenu_Product:
slotProductClicked();
break;
default:
break;
}
} }
CFileSelect::~CFileSelect() CFileSelect::~CFileSelect()
@ -19,6 +29,7 @@ CFileSelect::~CFileSelect()
void CFileSelect::init() void CFileSelect::init()
{ {
CustomUiDialog::setAutoLayout(true);
this->setWindowTitle( tr("文件选择") ); this->setWindowTitle( tr("文件选择") );
m_sFilePath = ""; m_sFilePath = "";
m_sDesc = ""; m_sDesc = "";

View File

@ -1,18 +1,21 @@
#ifndef CFILESELECT_H #ifndef CFILESELECT_H
#define CFILESELECT_H #define CFILESELECT_H
#include <QDialog> #include "pub_widget/CustomDialog.h"
const int CN_MainMenu_Platform = 0;
const int CN_MainMenu_Product = 1;
namespace Ui { namespace Ui {
class CFileSelect; class CFileSelect;
} }
class CFileSelect : public QDialog class CFileSelect : public CustomUiDialog
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit CFileSelect(QWidget *parent = 0); explicit CFileSelect(int nMenuIndex,QWidget *parent = 0);
~CFileSelect(); ~CFileSelect();
public: public:

View File

@ -2,10 +2,12 @@
#include <QPushButton> #include <QPushButton>
CSubsystem::CSubsystem( QWidget* pParent, QList<SSubsystem*>* pListSubsystem ) CSubsystem::CSubsystem( QWidget* pParent, QList<SSubsystem*>* pListSubsystem )
:QDialog(pParent) :CustomDialog(pParent)
{ {
this->setParent( pParent ); this->setParent( pParent );
this->setWindowTitle( "专业选择" ); this->setWindowTitle( tr("专业选择") );
this->setMinimumWidth(200);
m_bAccepted = false; m_bAccepted = false;
m_pListSubsystem = pListSubsystem; m_pListSubsystem = pListSubsystem;
@ -64,13 +66,13 @@ bool CSubsystem::isAccepted()
void CSubsystem::slotOk() void CSubsystem::slotOk()
{ {
m_bAccepted = true; m_bAccepted = true;
QDialog::accept(); CustomDialog::accept();
} }
void CSubsystem::slotCancel() void CSubsystem::slotCancel()
{ {
m_bAccepted = false; m_bAccepted = false;
QDialog::reject(); CustomDialog::reject();
} }

View File

@ -1,14 +1,14 @@
#ifndef CSUBSYSTEM_H #ifndef CSUBSYSTEM_H
#define CSUBSYSTEM_H #define CSUBSYSTEM_H
#include <QDialog>
#include <QCheckBox> #include <QCheckBox>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QDialogButtonBox> #include <QDialogButtonBox>
#include <QDebug> #include <QDebug>
#include "StructDefine.h" #include "StructDefine.h"
#include "pub_widget/CustomDialog.h"
class CSubsystem : public QDialog class CSubsystem : public CustomDialog
{ {
Q_OBJECT Q_OBJECT

View File

@ -16,6 +16,7 @@ QWidget* CTableModeDelegate::createEditor( QWidget *parent, const QStyleOptionVi
if ( nCol == 4 ) if ( nCol == 4 )
{ {
QComboBox *pComboBox = new QComboBox(parent); QComboBox *pComboBox = new QComboBox(parent);
pComboBox->addItem("");
pComboBox->addItem("db+rdb"); pComboBox->addItem("db+rdb");
pComboBox->addItem("db"); pComboBox->addItem("db");
pComboBox->addItem("rdb"); pComboBox->addItem("rdb");
@ -24,6 +25,7 @@ QWidget* CTableModeDelegate::createEditor( QWidget *parent, const QStyleOptionVi
else if ( nCol == 5) else if ( nCol == 5)
{ {
QComboBox *pComboBox = new QComboBox(parent); QComboBox *pComboBox = new QComboBox(parent);
pComboBox->addItem("");
pComboBox->addItem("param"); pComboBox->addItem("param");
pComboBox->addItem("his"); pComboBox->addItem("his");
pComboBox->addItem("temp"); pComboBox->addItem("temp");
@ -40,9 +42,10 @@ QWidget* CTableModeDelegate::createEditor( QWidget *parent, const QStyleOptionVi
CSubsystem* pSubsystem = new CSubsystem( parent, m_pListSubsystem ); CSubsystem* pSubsystem = new CSubsystem( parent, m_pListSubsystem );
return pSubsystem; return pSubsystem;
} }
else if ( nCol == 6 || nCol == 9 || nCol == 10 || nCol == 11 ) else if ( nCol == 6 || nCol == 9 || nCol == 10 )
{ {
QComboBox *pComboBox = new QComboBox(parent); QComboBox *pComboBox = new QComboBox(parent);
pComboBox->addItem("");
pComboBox->addItem("yes"); pComboBox->addItem("yes");
pComboBox->addItem("no"); pComboBox->addItem("no");
return pComboBox; return pComboBox;
@ -65,7 +68,7 @@ void CTableModeDelegate::setEditorData( QWidget *editor, const QModelIndex &inde
CSubsystem* pSubsystem = static_cast<CSubsystem*>(editor); CSubsystem* pSubsystem = static_cast<CSubsystem*>(editor);
pSubsystem->setSubsystemId( nValue ); pSubsystem->setSubsystemId( nValue );
} }
else if ( nCol == 4 || nCol == 5 || nCol == 6 || nCol == 9 || nCol == 10 || nCol == 11 ) else if ( nCol == 4 || nCol == 5 || nCol == 6 || nCol == 9 || nCol == 10 )
{ {
QString text = index.model()->data(index).toString(); QString text = index.model()->data(index).toString();
QComboBox* pComboBox = static_cast<QComboBox*>(editor); QComboBox* pComboBox = static_cast<QComboBox*>(editor);
@ -88,7 +91,7 @@ void CTableModeDelegate::setModelData( QWidget *editor, QAbstractItemModel *mode
if ( pSubsystem->isAccepted() ) if ( pSubsystem->isAccepted() )
model->setData(index, pSubsystem->getSubsystemId()); model->setData(index, pSubsystem->getSubsystemId());
} }
else if ( nCol == 4 || nCol == 5 || nCol == 6 || nCol == 9 || nCol == 10 || nCol == 11 ) else if ( nCol == 4 || nCol == 5 || nCol == 6 || nCol == 9 || nCol == 10 )
{ {
QComboBox* pComboBox = static_cast<QComboBox*>(editor); QComboBox* pComboBox = static_cast<QComboBox*>(editor);
QString text = pComboBox->currentText(); QString text = pComboBox->currentText();

View File

@ -16,9 +16,8 @@ CTableModeModel::CTableModeModel()
<< "最大行数" << "最大行数"
<< "专业标志" << "专业标志"
<< "是否区分车站" << "是否区分位置"
<< "是否区分专业" << "是否区分专业";
<< "内存库持久化";
} }
CTableModeModel::~CTableModeModel() CTableModeModel::~CTableModeModel()
@ -103,9 +102,6 @@ QVariant CTableModeModel::data( const QModelIndex &index, int role ) const
case 10: case 10:
oVal = m_pListTable->at(index.row())->sSelectBySubsystem; oVal = m_pListTable->at(index.row())->sSelectBySubsystem;
break; break;
case 11:
oVal = m_pListTable->at(index.row())->sCache;
break;
} }
return oVal; return oVal;
} }
@ -203,13 +199,6 @@ bool CTableModeModel::setData( const QModelIndex &index, const QVariant &value,
emit signalDataChanged(); emit signalDataChanged();
} }
break; break;
case 11:
if ( m_pListTable->at(index.row())->sCache != value.toString() )
{
m_pListTable->at(index.row())->sCache = value.toString();
emit signalDataChanged();
}
break;
} }
return true; return true;
} }

View File

@ -35,7 +35,6 @@ struct SColumn
QString sDefaultValue_rdb; // 默认值 QString sDefaultValue_rdb; // 默认值
QString sIsSynToSlave; // 是否需要同步到备内存库 yes\no(是,否) QString sIsSynToSlave; // 是否需要同步到备内存库 yes\no(是,否)
QString sIsUpdateToRdb; // 关系库的变化是否更新到内存库 yes\no(是,否) QString sIsUpdateToRdb; // 关系库的变化是否更新到内存库 yes\no(是,否)
QString sCache; // 是否持久化 yes\no
SColumn() SColumn()
{ {
@ -65,7 +64,6 @@ struct SColumn
sDefaultValue_rdb = ""; sDefaultValue_rdb = "";
sIsSynToSlave = ""; sIsSynToSlave = "";
sIsUpdateToRdb = ""; sIsUpdateToRdb = "";
sCache = "";
} }
}; };
@ -88,7 +86,6 @@ struct STable
quint64 nSubsystemFlag; // 专业标志 quint64 nSubsystemFlag; // 专业标志
QString sSelectByLocation; // 是否区分车站 yes\no QString sSelectByLocation; // 是否区分车站 yes\no
QString sSelectBySubsystem; // 是否区分专业 yes\no QString sSelectBySubsystem; // 是否区分专业 yes\no
QString sCache; // 是否持久化 yes\no
// 列 // 列
QList<SColumn*> listColumn; // 所有列集合 QList<SColumn*> listColumn; // 所有列集合
@ -110,7 +107,17 @@ struct STable
nSubsystemFlag = 0; nSubsystemFlag = 0;
sSelectByLocation = ""; sSelectByLocation = "";
sSelectBySubsystem = ""; sSelectBySubsystem = "";
sCache = ""; }
~STable()
{
foreach (SColumn *pCol, listColumn) {
delete pCol;
}
listColumn.clear();
listColumn_db.clear(); //< listColumn_db都在listColumn中
listColumn_rdb.clear(); //< listColumn_rdb都在listColumn中
} }
}; };

View File

@ -21,7 +21,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
# In order to do so, uncomment the following line. # In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt. # You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
RC_ICONS = icons/db_studio.ico
SOURCES += \ SOURCES += \
main.cpp \ main.cpp \
@ -47,8 +47,7 @@ FORMS += \
CDbStudio.ui \ CDbStudio.ui \
CFileSelect.ui CFileSelect.ui
LIBS += \ LIBS += -lpub_sysinfo_api -lpub_widget -lpub_utility_api
-lpub_sysinfo_api \
!include( ../../common.pri ){ !include( ../../common.pri ){
error(the file common.pri is not exist!!) error(the file common.pri is not exist!!)

View File

@ -2,12 +2,43 @@
#include <QApplication> #include <QApplication>
#include "common/QtAppGlobalSet.h" #include "common/QtAppGlobalSet.h"
#include "CDbStudio.h" #include "CDbStudio.h"
#include "pub_utility_api/FileStyle.h"
#include "pub_widget/PubWidgetInit.h"
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
iot_common::doQtAppGlobalSet(); iot_common::doQtAppGlobalSet();
QApplication a(argc, argv); QApplication a(argc, argv);
QString qss = QString();
std::string strFullPath = iot_public::CFileStyle::getPathOfStyleFile("public.qss","zh","light");
QFile qssfile1(QString::fromStdString(strFullPath));
qssfile1.open(QFile::ReadOnly);
if (qssfile1.isOpen())
{
qss += QLatin1String(qssfile1.readAll());
qssfile1.close();
}
strFullPath = iot_public::CFileStyle::getPathOfStyleFile("db_studio.qss","zh","light");
QFile qssfile2(QString::fromStdString(strFullPath));
qssfile2.open(QFile::ReadOnly);
if (qssfile2.isOpen())
{
qss += QLatin1String(qssfile2.readAll());
qssfile2.close();
}
if (!qss.isEmpty())
{
qApp->setStyleSheet(qss);
}
iot_public::installTranslator("zh");
// qApp->setFont(QFont("Microsoft YaHei",10));
CDbStudio w; CDbStudio w;
w.show(); w.show();

View File

@ -10,7 +10,20 @@
#include "boost/lexical_cast.hpp" #include "boost/lexical_cast.hpp"
#include "boost/format.hpp" #include "boost/format.hpp"
#include "boost/asio/ip/host_name.hpp" #include "boost/asio/ip/host_name.hpp"
#include "boost/algorithm/string/predicate.hpp"
//< 屏蔽xml_parser编译告警
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#endif
#include "boost/property_tree/xml_parser.hpp" #include "boost/property_tree/xml_parser.hpp"
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include "pub_utility_api/FileUtil.h" #include "pub_utility_api/FileUtil.h"
#include <algorithm> #include <algorithm>
#include <bitset> #include <bitset>
@ -114,7 +127,7 @@ int CDbSysInfo::getAppIdByTableName( const std::string& strAppName, const std::s
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type"); std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
if ("Table" != itTable->first || sUseType == "db") if ("Table" != itTable->first || !boost::contains(sUseType,"rdb"))
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("Rdb")); BOOST_AUTO(rdb, itTable->second.get_child("Rdb"));
if ( rdb.size() <= 0 ) if ( rdb.size() <= 0 )
@ -150,7 +163,7 @@ int CDbSysInfo::getAppIdByTableName( const std::string& strAppName, const std::s
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type"); std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
if ("Table" != itTable->first || sUseType == "db") if ("Table" != itTable->first || !boost::contains(sUseType,"rdb") )
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("Rdb")); BOOST_AUTO(rdb, itTable->second.get_child("Rdb"));
if ( rdb.size() <= 0 ) if ( rdb.size() <= 0 )
@ -278,9 +291,8 @@ bool CDbSysInfo::getAllRdbTableNameBySubsystemId( const int nSubsystemId, std::v
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("")); BOOST_AUTO(rdb, itTable->second.get_child(""));
for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++) for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++)
@ -306,9 +318,8 @@ bool CDbSysInfo::getAllRdbTableNameBySubsystemId( const int nSubsystemId, std::v
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("")); BOOST_AUTO(rdb, itTable->second.get_child(""));
for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++) for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++)
@ -352,9 +363,8 @@ bool CDbSysInfo::getAllRdbColumnNameByTableName( const std::string sTableName, s
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
std::vector<SColumnModeInfo> tmpVecColumn; std::vector<SColumnModeInfo> tmpVecColumn;
BOOST_AUTO(column, itTable->second.get_child("")); BOOST_AUTO(column, itTable->second.get_child(""));
@ -389,9 +399,8 @@ bool CDbSysInfo::getAllRdbColumnNameByTableName( const std::string sTableName, s
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
std::vector<SColumnModeInfo> tmpVecColumn; std::vector<SColumnModeInfo> tmpVecColumn;
BOOST_AUTO(column, itTable->second.get_child("")); BOOST_AUTO(column, itTable->second.get_child(""));
@ -451,7 +460,7 @@ bool CDbSysInfo::getTableModeByTableName( const std::string& strTableName ,STab
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type"); std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
if ("Table" != itTable->first || sUseType == "rdb") continue; //过滤非关系库表 if ("Table" != itTable->first || sUseType == "rdb" || sUseType.empty()) continue; //过滤非关系库表
STableModeInfo stTableInfo; STableModeInfo stTableInfo;
stTableInfo.strName = itTable->second.get<std::string>("<xmlattr>.name"); stTableInfo.strName = itTable->second.get<std::string>("<xmlattr>.name");
@ -501,7 +510,7 @@ bool CDbSysInfo::getTableModeByTableName( const std::string& strTableName ,STab
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type"); std::string sUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
if ("Table" != itTable->first || sUseType == "rdb") continue; //过滤非关系库表 if ("Table" != itTable->first || sUseType == "rdb" || sUseType.empty()) continue; //过滤非关系库表
STableModeInfo stTableInfo; STableModeInfo stTableInfo;
stTableInfo.strName = itTable->second.get<std::string>("<xmlattr>.name"); stTableInfo.strName = itTable->second.get<std::string>("<xmlattr>.name");
@ -571,9 +580,8 @@ bool CDbSysInfo::getSubsystemFlagByTableName( const std::string sTableName, uint
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("")); BOOST_AUTO(rdb, itTable->second.get_child(""));
for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++) for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++)
@ -599,9 +607,8 @@ bool CDbSysInfo::getSubsystemFlagByTableName( const std::string sTableName, uint
BOOST_AUTO(table, pt.get_child("DatabaseStruct")); BOOST_AUTO(table, pt.get_child("DatabaseStruct"));
for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++) for (BOOST_AUTO(itTable, table.begin()); itTable!=table.end(); itTable++)
{ {
if ("Table" != itTable->first ) std::string strUseType = itTable->second.get<std::string>("<xmlattr>.use_type");
continue; if ("Table" != itTable->first || !boost::contains(strUseType,"rdb") )
if ( itTable->second.get<std::string>("<xmlattr>.use_type") == "db" )
continue; continue;
BOOST_AUTO(rdb, itTable->second.get_child("")); BOOST_AUTO(rdb, itTable->second.get_child(""));
for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++) for (BOOST_AUTO(itRdb, rdb.begin()); itRdb!=rdb.end(); itRdb++)

View File

@ -15,6 +15,8 @@ SUBDIRS += \
tsdb_save_api \ tsdb_save_api \
tsdb_api\ tsdb_api\
tsdb_save \ tsdb_save \
tsdb_local_save \
tsdb_etl \
db_his_query_api\ db_his_query_api\
db_his_mng_api \ db_his_mng_api \
db_manager_api \ db_manager_api \

View File

@ -1,6 +1,7 @@
#include "CBptree.h" #include "CBptree.h"
#include "RdbFunc.h" #include "RdbFunc.h"
#include "pub_logger_api/logger.h" #include "pub_logger_api/logger.h"
#include "boost/concept_check.hpp"
using namespace iot_dbms; using namespace iot_dbms;
@ -39,7 +40,9 @@ int CBptree::find( const char* const pKey )
int CBptree::remove( const char* const pKey ) int CBptree::remove( const char* const pKey )
{ {
char* p = (char*)pKey; boost::ignore_unused_variable_warning(pKey);
//char* p = (char*)pKey;
return -1; return -1;
} }

View File

@ -1,373 +0,0 @@
#include "CRdbCache.h"
#include "pub_utility_api/FileUtil.h"
#include "pub_logger_api/logger.h"
#include "pub_sysinfo_api/SysInfoApi.h"
#include "CRdbDictionary.h"
#include "CRdbLocalTable.h"
#include "RdbServerMessage.pb.h"
#include "rdb_api/FuncForNet.h"
#include "rdb_api/CRdbAccessEx.h"
#include "db_sysinfo_api/CDbSysInfo.h"
#define CN_RDBCACHE "RdbCache" // 缓存文件内容中预留的字符串
#define CN_MAXROWOFONEFILE 100000 // 单个缓存文件容纳的最多行数
#define CN_VERSIONFILE "rdb_cache_version.md5" // 内存库缓存版本
using namespace iot_public;
using namespace iot_dbms;
using namespace iot_idl;
CRdbCache::CRdbCache( QString sAppName )
{
m_sAppName = sAppName;
}
CRdbCache::~CRdbCache()
{
}
bool CRdbCache::save()
{
// 创建/清空缓存目录
QString sPath = QString("%1/../../data/cache/rdb_server/%2").arg(CFileUtil::getCurModuleDir().c_str()).arg(m_sAppName);
QDir objDir(sPath);
sPath = objDir.absolutePath();
if ( !objDir.exists() )// 不存在就创建
{
LOGINFO("缓存目录不存在,现在创建【%s】",sPath.toStdString().c_str());
if ( !objDir.mkpath(sPath) )
{
LOGERROR("创建缓存目录失败【%s】",sPath.toStdString().c_str());
return false;
}
}
else// 存在就清空
{
// 清空会导致后续打开文件失败,暂时屏蔽
//objDir.removeRecursively();
// 遍历删除文件
QFileInfoList listFile = objDir.entryInfoList();
for ( int i=0; i<listFile.size(); i++ )
{
if ( listFile.at(i).isDir() )
continue;
QFile objFile(listFile.at(i).absoluteFilePath());
objFile.remove();
}
LOGINFO("清空缓存目录【%s】",sPath.toStdString().c_str());
}
// 获取应用id
int nAppId = CDbSysInfo::getAppIdByAppName( m_sAppName.toStdString() );
if ( nAppId < 0 )
{
LOGERROR("获取应用Id失败");
return false;
}
// 写缓存文件
CRdbDictionary objDict(nAppId);
for ( int nTableIndex=0; nTableIndex<objDict.GetTableNums(); nTableIndex++ )
{
SRdbTableAttribute* pRdbTable = objDict.GetTableStruct(nTableIndex);
SRdbColumnAttribute* pRdbColumn = objDict.GetColumnStruct(pRdbTable->nStartColumnNo);
// 获取指针异常
if ( pRdbTable == NULL || pRdbColumn == NULL )
{
LOGERROR("获取指针异常");
continue;
}
// 未设置表持久化
if ( pRdbTable->nCache != 1 )
continue;
// 表没有主键
if ( pRdbTable->nKeyFlag != 1 )
{
LOGERROR("表没有主键,不执行持久化【%s】",pRdbTable->strName);
continue;
}
// 查询当前表所有非主键且配置了持久化的列
std::vector<SRdbColumnAttribute*> vecColumn;
for ( int i=0; i<pRdbTable->nColumnCount; i++ )
{
if ( !pRdbColumn[i].bIsKey && pRdbColumn[i].bCache )
{
vecColumn.push_back( &pRdbColumn[i] );
}
}
// 没有配置持久化的列
if ( vecColumn.size() <= 0 )
continue;
// 打开内存表
CRdbLocalTable objTable(nAppId);
int nRet = objTable.OpenTable(pRdbTable->strName);
if ( nRet != 0 )
{
LOGERROR("打开内存表失败【%s】",pRdbTable->strName);
continue;
}
// 读取内存表数据
int nFileIndex = 0; // 缓存文件序号
RdbReplace objReplace;
objReplace.set_strsessionid(CN_RDBCACHE);
objReplace.set_strtablename(pRdbTable->strName);
objTable.LockTable();
for ( int nRowIndex=0; nRowIndex<objTable.getRecordCount(); nRowIndex++ )
{
// 获取行地址
char* data = 0;
if ( !objTable.getDataAddr(nRowIndex,(const void**)&data) )
{
LOGERROR("获取行地址失败【%s】",pRdbTable->strName);
break;
}
// 拷贝主键
RdbSynUpdate* pUpdate = objReplace.add_msgupdate();
pUpdate->set_strkeys( data, pRdbTable->nKeyRecLen );
// 拷贝列值
size_t i = 0;
CVarType objValue;
while ( i < vecColumn.size() )
{
RdbUpdateValue* pUpdVal = pUpdate->add_msgupdatevalue();
pUpdVal->set_strcolumnname( vecColumn[i]->strName );
SVariable* pVal = pUpdVal->mutable_msgvalue();
objTable.GetColumnValue( nRowIndex, objTable.GetColumnNo(vecColumn[i]->strName), objValue );
Vartype2SVarivale( objValue, *pVal );
i++;
}
// 适时写入文件,防止文件过大
if ( (nRowIndex==objTable.getRecordCount()-1) || (nRowIndex!=0&&nRowIndex%CN_MAXROWOFONEFILE==0) )
{
// 打开缓存文件
QString sFilePath = sPath+"/"+pRdbTable->strName+"."+QString::number(nFileIndex);
QFile objFile(sFilePath);
if ( !objFile.open(QIODevice::WriteOnly) )
{
LOGERROR("打开缓存文件失败【%s】", sFilePath.toStdString().c_str());
break;
}
// 写入文件
QDataStream objStream(&objFile);
std::string sData = objReplace.SerializeAsString();
objStream.writeRawData( sData.c_str(), sData.size() );
objFile.close();
// 清理RdbReplace中的数据
objReplace.clear_msgupdate();
// 文件序号加1
nFileIndex++;
}
}
objTable.UnlockTable();
}
// 写版本文件
QString sCacheVersion = getCacheVersion();
if ( sCacheVersion == "" )
{
LOGERROR("获取配置版本失败");
return false;
}
QFile objFile(sPath+"/"+CN_VERSIONFILE);
if ( !objFile.open(QIODevice::WriteOnly|QIODevice::Text) )
{
LOGERROR("打开文件失败【%s】",CN_VERSIONFILE);
return false;
}
objFile.write(sCacheVersion.toUtf8());
objFile.close();
// 返回成功
return true;
}
bool CRdbCache::load()
{
// 检查缓存文件夹
QString sPath = QString("%1/../../data/cache/rdb_server/%2").arg(CFileUtil::getCurModuleDir().c_str()).arg(m_sAppName);
QDir objDir(sPath);
sPath = objDir.absolutePath();
if ( !objDir.exists() )
{
LOGDEBUG("缓存目录不存在,不加载缓存【%s】",sPath.toStdString().c_str());
return false;
}
// 检查缓存版本
QFile objFile(sPath+"/"+CN_VERSIONFILE);
if ( !objFile.open(QIODevice::ReadOnly|QIODevice::Text) )
{
LOGDEBUG("打开文件失败【%s】",CN_VERSIONFILE);
return false;
}
QString sCacheVersion_file(objFile.readAll());
objFile.close();
QString sCacheVersion_current = getCacheVersion();
if ( sCacheVersion_current != sCacheVersion_file )
{
LOGERROR("缓存版本不正确,不加载缓存");
return false;
}
// 获取应用id
int nAppId = CDbSysInfo::getAppIdByAppName( m_sAppName.toStdString() );
if ( nAppId < 0 )
{
LOGERROR("获取应用Id失败");
return false;
}
// 读缓存文件
CRdbDictionary objDict( nAppId );
for ( int nTableIndex=0; nTableIndex<objDict.GetTableNums(); nTableIndex++ )
{
SRdbTableAttribute* pRdbTable = objDict.GetTableStruct(nTableIndex);
if ( pRdbTable->nCache != 1 )// 不持久化
continue;
if ( pRdbTable->nKeyFlag == 0 )// 没有主键
continue;
int nFileIndex = 0; // 缓存文件序号
while (true)
{
// 打开缓存文件
QString sFilePath = sPath+"/"+pRdbTable->strName+"."+QString::number(nFileIndex);
nFileIndex++;
QFile objFile(sFilePath);
if ( !objFile.exists() || !objFile.open(QIODevice::ReadOnly) )
break;
// 读取文件内容、反序列化
QByteArray bytData = objFile.readAll();
RdbReplace objReplace;
objFile.close();
if ( !objReplace.ParseFromArray(bytData.data(),bytData.size()) )
{
LOGERROR("反序列化失败【%s】",sFilePath.toStdString().c_str());
continue;
}
// 判断预留字符串
if ( objReplace.strsessionid() != CN_RDBCACHE )
{
LOGERROR("文件内容错误【%s】",sFilePath.toStdString().c_str());
continue;
}
// 打开内存表
CRdbAccessEx objAccessEx;
if ( !objAccessEx.open(nAppId,objReplace.strtablename().c_str()) )
{
LOGERROR( "打开内存库表失败【%s】", objReplace.strtablename().c_str() );
continue;
}
// 更新数据
objAccessEx.lock();
int nRecord = objReplace.msgupdate_size();
for ( int nIndex=0; nIndex<nRecord; nIndex++ )
{
const RdbSynUpdate& objSynUpdate = objReplace.msgupdate(nIndex);
if ( objSynUpdate.has_strkeys() )// 有主键,则以主键更新,不判断条件,没有主键的不处理
{
std::vector<RSQL_UPD_COLUMN> vecUpdColumn;
int nUpdValue = objSynUpdate.msgupdatevalue_size();
for ( int i=0; i<nUpdValue; i++ )
{
RSQL_UPD_COLUMN stUpdColumn;
const RdbUpdateValue& refUpdVal = objSynUpdate.msgupdatevalue(i);
strncpy( stUpdColumn.updcolname, refUpdVal.strcolumnname().c_str(), sizeof(stUpdColumn.updcolname) );
SVariable2Vartype( refUpdVal.msgvalue(), stUpdColumn.updvalue );
vecUpdColumn.push_back( stUpdColumn );
}
if ( !objAccessEx.updateRecordByKey(objSynUpdate.strkeys().c_str(),vecUpdColumn) )
{
LOGERROR( "更新内存库表失败【%s】", objReplace.strtablename().c_str() );
continue;
}
}
else
{
LOGERROR("不应该执行到这里,请检查程序逻辑");
}
}
objAccessEx.unLock();
objAccessEx.close();
}
}
// 返回成功
return true;
}
QString CRdbCache::getCacheVersion()
{
// 判断文件是否存在
std::string strPath = iot_public::CFileUtil::getCurModuleDir();
QString sDbConfigFile_platform = QString("%1/../../platform/common/database/initscript/iscs6000_table_struct.xml").arg(strPath.c_str());
QString sDbConfigFile_product = QString("%1/../../product/common/database/initscript/iscs6000_table_struct.xml").arg(strPath.c_str());
QFileInfo objFileInfo_platform( sDbConfigFile_platform );
QFileInfo objFileInfo_product( sDbConfigFile_product );
if ( !objFileInfo_platform.exists() || !objFileInfo_product.exists() )
{
LOGERROR("文件不存在【iscs6000_table_struct.xml】");
return "";
}
sDbConfigFile_platform = objFileInfo_platform.absoluteFilePath();// 获取去掉../的路径
sDbConfigFile_product = objFileInfo_product.absoluteFilePath();// 获取去掉../的路径
// 读取平台配置文件
QFile objFile0(sDbConfigFile_platform);
if ( !objFile0.open(QFile::ReadOnly|QFile::Text) )
{
LOGERROR("打开平台文件失败【iscs6000_table_struct.xml】");
return "";
}
QCryptographicHash objHash(QCryptographicHash::Md5);
objHash.addData(objFile0.readAll());
objFile0.close();
// 读取产品配置文件
QFile objFile1(sDbConfigFile_product);
if ( !objFile1.open(QFile::ReadOnly|QFile::Text) )
{
LOGERROR("打开产品文件失败【iscs6000_table_struct.xml】");
return "";
}
objHash.addData(objFile1.readAll());
objFile1.close();
// 返回结果
return objHash.result().toHex();
}

View File

@ -1,35 +0,0 @@
#ifndef CRDBCACHE_H
#define CRDBCACHE_H
#include <QDebug>
#include <QString>
#include <QDir>
#include <QFile>
#include <QDataStream>
#include <QFileInfo>
#include <QFileInfoList>
#include <QCryptographicHash>
// 内存库缓存类,用于持久化
class CRdbCache
{
public:
CRdbCache( QString sAppName );
~CRdbCache();
public:
// 保存缓存由sys_ctl调用
bool save();
// 加载缓存由rdb_server调用
bool load();
private:
// 获取缓存版本
QString getCacheVersion();// 将平台和产品的表结构配置文件加起来算md5作为缓存的版本
private:
QString m_sAppName;// 应用名称
};
#endif // CRDBCACHE_H

View File

@ -148,7 +148,6 @@ int CRdbLoadTableAttribute::CreateTableByConfig( QString sFile )
strncpy( stTableMode.strParaTable, stTableMode.strName, sizeof( stTableMode.strParaTable ) ); strncpy( stTableMode.strParaTable, stTableMode.strName, sizeof( stTableMode.strParaTable ) );
stTableMode.nSelectByLocation = eleTableRdb.attribute("select_by_location","no")=="yes"?1:0; stTableMode.nSelectByLocation = eleTableRdb.attribute("select_by_location","no")=="yes"?1:0;
stTableMode.nSelectBySubsystem = eleTableRdb.attribute("select_by_subsystem","no")=="yes"?1:0; stTableMode.nSelectBySubsystem = eleTableRdb.attribute("select_by_subsystem","no")=="yes"?1:0;
stTableMode.nCache = eleTableRdb.attribute("cache","no")=="yes"?1:0;
stTableMode.nLastLoadTime = 0; stTableMode.nLastLoadTime = 0;
// 表需要申请的行数大于设置的最大行数时最大行数修改为实际行数的120% // 表需要申请的行数大于设置的最大行数时最大行数修改为实际行数的120%
@ -259,7 +258,6 @@ int CRdbLoadTableAttribute::CreateTableByConfig( QString sFile )
pColumn->bIsKey = eleColumn.attribute("is_key","no")=="yes"?true:false; pColumn->bIsKey = eleColumn.attribute("is_key","no")=="yes"?true:false;
pColumn->bNeedSyn = eleColumnRdb.attribute("is_syn_to_slave","no")=="yes"?true:false; pColumn->bNeedSyn = eleColumnRdb.attribute("is_syn_to_slave","no")=="yes"?true:false;
pColumn->bNotUpdateRtdb = eleColumnRdb.attribute("is_update_to_rdb","no")=="yes"?false:true; pColumn->bNotUpdateRtdb = eleColumnRdb.attribute("is_update_to_rdb","no")=="yes"?false:true;
pColumn->bCache = eleColumnRdb.attribute("cache","no")=="yes"?true:false;
if ( pColumn->bIsKey && nTableKeyNum < RDB_KEYCOLUMN_NUMS ) if ( pColumn->bIsKey && nTableKeyNum < RDB_KEYCOLUMN_NUMS )
{ {
strncpy( stTableMode.strArrayKeyColumnName[nTableKeyNum], pColumn->strName, RDB_COLUMN_NAME_LEN ); strncpy( stTableMode.strArrayKeyColumnName[nTableKeyNum], pColumn->strName, RDB_COLUMN_NAME_LEN );
@ -290,13 +288,6 @@ int CRdbLoadTableAttribute::CreateTableByConfig( QString sFile )
LOGERROR( "创建表 [%s] 失败,失败原因:%d", stTableMode.strName, nRet ); LOGERROR( "创建表 [%s] 失败,失败原因:%d", stTableMode.strName, nRet );
return -1; return -1;
} }
// QString sXml = "";
// QTextStream objStr(&sXml);
// eleTable.save(objStr,4);
// LOGERROR("%s",sXml.toStdString().c_str());
} }
oFile.close(); oFile.close();
@ -320,6 +311,8 @@ int CRdbLoadTableAttribute::CreateTableByConfig( QString sFile )

View File

@ -53,7 +53,6 @@ int CRdbLocalManager::AddTable( SRdbTableAttribute* pRdbTableAttr, int columnnum
pDestRtdbColumnAttr[i].bNeedSyn = pSrcRtdbColumnAttr[i].bNeedSyn; pDestRtdbColumnAttr[i].bNeedSyn = pSrcRtdbColumnAttr[i].bNeedSyn;
pDestRtdbColumnAttr[i].bIsKey = pSrcRtdbColumnAttr[i].bIsKey; pDestRtdbColumnAttr[i].bIsKey = pSrcRtdbColumnAttr[i].bIsKey;
pDestRtdbColumnAttr[i].bNotUpdateRtdb = pSrcRtdbColumnAttr[i].bNotUpdateRtdb; pDestRtdbColumnAttr[i].bNotUpdateRtdb = pSrcRtdbColumnAttr[i].bNotUpdateRtdb;
pDestRtdbColumnAttr[i].bCache = pSrcRtdbColumnAttr[i].bCache;
// pDestRtdbColumnAttr[i].eventflag=pSrcRtdbColumnAttr[i].eventflag; // pDestRtdbColumnAttr[i].eventflag=pSrcRtdbColumnAttr[i].eventflag;
rcol.addColumn( pDestRtdbColumnAttr[i].nDataType, pDestRtdbColumnAttr[i].nDataLen, rcol.addColumn( pDestRtdbColumnAttr[i].nDataType, pDestRtdbColumnAttr[i].nDataLen,
pDestRtdbColumnAttr[i].nBitNums, &pDestRtdbColumnAttr[i].nOffset, &pDestRtdbColumnAttr[i].nPosition ); pDestRtdbColumnAttr[i].nBitNums, &pDestRtdbColumnAttr[i].nOffset, &pDestRtdbColumnAttr[i].nPosition );

View File

@ -15,17 +15,16 @@
#include "CRdbConfigMan.h" #include "CRdbConfigMan.h"
#include "CRdbDataSegMan.h" #include "CRdbDataSegMan.h"
#include "pub_logger_api/logger.h" #include "pub_logger_api/logger.h"
#include "CRdbCache.h"
using namespace iot_public; using namespace iot_public;
using namespace iot_dbms; using namespace iot_dbms;
using namespace std; using namespace std;
bool iot_dbms::CRdbMngIntereface::loadAppDb( const std::string& strAppName ) bool iot_dbms::CRdbMngIntereface::loadAppDb( const std::string& strAppname )
{ {
// 创建管理段共享内存 // 创建管理段共享内存
CRdbServerMemMan cServerMemman; CRdbServerMemMan cServerMemman;
int nRet = cServerMemman.init(strAppName); int nRet = cServerMemman.init( strAppname );
if ( 0 == nRet ) if ( 0 == nRet )
{ {
LOGINFO( "共享内存已存在" ); LOGINFO( "共享内存已存在" );
@ -49,7 +48,7 @@ bool iot_dbms::CRdbMngIntereface::loadAppDb( const std::string& strAppName )
return false; return false;
} }
SAppInfo stAppInfo; SAppInfo stAppInfo;
nRet = ptrSysInfo->getAppInfoByName( strAppName, stAppInfo ); nRet = ptrSysInfo->getAppInfoByName( strAppname, stAppInfo );
if ( iotFailed == nRet ) if ( iotFailed == nRet )
{ {
LOGERROR( "getAppInfoByName error" ); LOGERROR( "getAppInfoByName error" );
@ -91,41 +90,11 @@ bool iot_dbms::CRdbMngIntereface::loadAppDb( const std::string& strAppName )
rdbtable->m_stSynParam.bNeedSyn = bTemp; rdbtable->m_stSynParam.bNeedSyn = bTemp;
} }
} }
// 加载缓存
LOGINFO("开始加载缓存");
CRdbCache objCache(strAppName.c_str());
if ( !objCache.load() )
{
LOGERROR("加载缓存失败");
// 加载缓存失败时内存库仍可用,所以此处不返回失败
}
else
{
LOGINFO("加载缓存成功");
}
return true; return true;
} }
int iot_dbms::CRdbMngIntereface::deleteAppDbShm( const std::string& strAppName ) int iot_dbms::CRdbMngIntereface::deleteAppDbShm( const std::string& strAppName )
{ {
if ( isLoadAppDb(strAppName) )
{
// 保存缓存
LOGINFO("开始保存缓存");
CRdbCache objCache(strAppName.c_str());
if ( !objCache.save() )
{
LOGERROR("保存缓存失败");
// 保存缓存失败时仍需执行后续逻辑,所以此处不返回失败
}
else
{
LOGINFO("保存缓存成功");
}
}
CRdbDataSegMan objDataMan( CDbSysInfo::getAppIdByAppName( strAppName ) ); CRdbDataSegMan objDataMan( CDbSysInfo::getAppIdByAppName( strAppName ) );
objDataMan.deleteShm(); objDataMan.deleteShm();
CRdbServerMemMan objMemMan; CRdbServerMemMan objMemMan;
@ -146,15 +115,3 @@ bool iot_dbms::CRdbMngIntereface::isLoadAppDb( const std::string& strAppName )
return objMemMan.isCreatedDb( nAppId ); return objMemMan.isCreatedDb( nAppId );
} }
} }

View File

@ -15,85 +15,79 @@ DEFINES += USING_CUR_SYN
#DEFINES += USE_HASHTABLE #DEFINES += USE_HASHTABLE
SOURCES += \ SOURCES += \
CBaseTable.cpp \ CBaseTable.cpp \
CBptree.cpp \ CBptree.cpp \
CPremalloc.cpp \ CPremalloc.cpp \
CRdbAccessImpl.cpp \ CRdbAccessImpl.cpp \
CRdbColumnInfo.cpp \ CRdbColumnInfo.cpp \
CRdbDataSegMan.cpp \ CRdbDataSegMan.cpp \
CRdbDictionary.cpp \ CRdbDictionary.cpp \
CRdbLocalManager.cpp \ CRdbLocalManager.cpp \
CRdbLocalTable.cpp \ CRdbLocalTable.cpp \
CRdbQuickSortSrch.cpp \ CRdbQuickSortSrch.cpp \
CRdbServerMemMan.cpp \ CRdbServerMemMan.cpp \
CRdbTime.cpp \ CRdbTime.cpp \
CShareMem.cpp \ CShareMem.cpp \
QuickSortSrch.cpp \ QuickSortSrch.cpp \
RdbFunc.cpp \ RdbFunc.cpp \
CVarType.cpp \ CVarType.cpp \
CRdbMngInterface.cpp \ CRdbMngInterface.cpp \
CRdbConfigMan.cpp \ CRdbConfigMan.cpp \
CRdbAccess.cpp \ CRdbAccess.cpp \
CRdbQueryResultImpl.cpp \ CRdbQueryResultImpl.cpp \
RdbMemMan.cpp \ RdbMemMan.cpp \
CRdbLoadTableAttribute.cpp \ CRdbLoadTableAttribute.cpp \
CRdbLoadTableData.cpp \ CRdbLoadTableData.cpp \
CHashTable.cpp \ CHashTable.cpp \
CRdbKey.cpp \ CRdbKey.cpp
CRdbCache.cpp
HEADERS += \ HEADERS += \
../../include/dbms/rdb_api/CRdbAccess.h \ CPreMalloc.h \
../../include/dbms/rdb_api/CRdbMngInterface.h \ CRdbAccessImpl.h \
../../include/dbms/rdb_api/RdbDefine.h \ CRdbDataSegMan.h \
../../include/dbms/rdb_api/RdbExport.h \ CRdbLocalManager.h \
../../include/dbms/rdb_api/RdbMemMan.h \ CRdbQuickSortSrch.h \
../../include/dbms/rdb_api/CVarType.h \ CShareMem.h \
../../include/dbms/rdb_api/CRdbAccessEx.h \ MallocSpace.h \
../../include/dbms/rdb_api/RdbTableMng.h \ QuickSortSrch.h \
../../include/dbms/rdb_api/FuncForNet.h \ RdbFunc.h \
CPreMalloc.h \ CRdbQueryResultImpl.h \
CRdbAccessImpl.h \ CBaseTable.h \
CRdbDataSegMan.h \ CRdbLocalTable.h \
CRdbLocalManager.h \ CRdbServerMemMan.h \
CRdbQuickSortSrch.h \ CBptree.h \
CShareMem.h \ CHashTable.h \
MallocSpace.h \ CRdbDictionary.h \
QuickSortSrch.h \ CRdbTime.h \
RdbFunc.h \ CRdbColumnInfo.h \
CRdbQueryResultImpl.h \ CRdbLoadTableAttribute.h \
CBaseTable.h \ CRdbLoadTableData.h \
CRdbLocalTable.h \ CRdbKey_impl.h \
CRdbServerMemMan.h \ CRdbKey.h \
CBptree.h \ ../../include/dbms/rdb_api/CRdbAccess.h \
CHashTable.h \ ../../include/dbms/rdb_api/CRdbMngInterface.h \
CRdbDictionary.h \ ../../include/dbms/rdb_api/RdbDefine.h \
CRdbTime.h \ ../../include/dbms/rdb_api/RdbExport.h \
CRdbColumnInfo.h \ ../../include/dbms/rdb_api/RdbMemMan.h \
CRdbLoadTableAttribute.h \ ../../include/dbms/rdb_api/CVarType.h \
CRdbLoadTableData.h \ ../../include/dbms/rdb_api/CRdbAccessEx.h \
CRdbKey_impl.h \ ../../include/dbms/rdb_api/RdbTableMng.h \
CRdbKey.h \ ../../include/dbms/rdb_api/FuncForNet.h \
CRdbCache.h \
LIBS += \ LIBS += -ldb_base_api \
-ldb_base_api \ -ldb_api_ex \
-ldb_api_ex \ -lpub_logger_api \
-lpub_logger_api \ -lpub_sysinfo_api \
-lpub_sysinfo_api \ -llog4cplus \
-llog4cplus \ -lboost_system \
-lboost_system \ -lboost_thread \
-lboost_thread \ -ldb_sysinfo_api \
-ldb_sysinfo_api \ -lpub_utility_api
-lpub_utility_api \
-lprotobuf \
win32{ win32{
LIBS += -lAdvAPI32 LIBS += -lAdvAPI32
} }
include($$PWD/../../idl_files/idl_files.pri)
COMMON_PRI=$$PWD/../../common.pri COMMON_PRI=$$PWD/../../common.pri
exists($$COMMON_PRI) { exists($$COMMON_PRI) {
include($$COMMON_PRI) include($$COMMON_PRI)

View File

@ -11,8 +11,8 @@ int CRdbRedundant::redundantSwitch(bool bMaster, bool bSlave)
bool CRdbRedundant::initSwitch(int nAppId) bool CRdbRedundant::initSwitch(int nAppId)
{ {
iot_dbms::CRdbConfigMan objConfigMan(nAppId); iot_dbms::CRdbConfigMan objConfigMan(nAppId);
m_pShmRdbConfig = (iot_dbms::SRdbConfig*)objConfigMan.getConfigAddr(); m_pShmRdbConfig = (iot_dbms::SRdbConfig*)objConfigMan.getConfigAddr();
if (NULL == m_pShmRdbConfig) if (NULL == m_pShmRdbConfig)
{ {
return false; return false;

View File

@ -17,11 +17,11 @@ public:
bool bSlave() const; bool bSlave() const;
void setBSlave(bool bSlave); void setBSlave(bool bSlave);
void bindProcMng(iot_sys::CProcMngInterfacePtr ptrProcMng); void bindProcMng(iot_sys::CProcMngInterfacePtr ptrProcMng);
bool setStatus(bool bMaster = true); bool setStatus(bool bMaster = true);
private: private:
iot_dbms::SRdbConfig *m_pShmRdbConfig; iot_dbms::SRdbConfig *m_pShmRdbConfig;
iot_sys::CProcMngInterfacePtr m_ptrProcMng; iot_sys::CProcMngInterfacePtr m_ptrProcMng;
}; };
#endif // CRDBREDUNDANT_H #endif // CRDBREDUNDANT_H

View File

@ -1,467 +1,468 @@
#include "CRdbUpdateThread.h" #include "CRdbUpdateThread.h"
#include "../rdb_api/CRdbConfigMan.h" #include "../rdb_api/CRdbConfigMan.h"
#include "../rdb_api/CRdbDictionary.h" #include "../rdb_api/CRdbDictionary.h"
#include "../rdb_api/CRdbServerMemMan.h" #include "../rdb_api/CRdbServerMemMan.h"
#include "../rdb_api/QVariant2Vartype.inc" #include "../rdb_api/QVariant2Vartype.inc"
#include "pub_logger_api/logger.h" #include "pub_logger_api/logger.h"
#include "pub_sysinfo_api/SysInfoApi.h" #include "pub_sysinfo_api/SysInfoApi.h"
#include "db_sysinfo_api/CDbSysInfo.h" #include "db_sysinfo_api/CDbSysInfo.h"
#include "rdb_api/CRdbAccessEx.h" #include "rdb_api/CRdbAccessEx.h"
using namespace iot_public; using namespace iot_public;
using namespace iot_dbms; using namespace iot_dbms;
CRdbUpdateThread::CRdbUpdateThread( const iot_public::SRunAppInfo stAppInfo ) CRdbUpdateThread::CRdbUpdateThread( const iot_public::SRunAppInfo stAppInfo )
: CTimerThreadBase( "rdb_server CRdbUpdateThread 关系数据库向内存库更新线程", 1000, 1000*60*5 ), : CTimerThreadBase( "rdb_server CRdbUpdateThread 关系数据库向内存库更新线程", 1000, 1000*60*5 ),
m_objDb(DB_CONN_MODEL_READ) m_objDb(DB_CONN_MODEL_READ)
{ {
m_ptrSysInfo = nullptr; m_ptrSysInfo = nullptr;
m_ullCurId = 0; m_ullCurId = 0;
m_stAppInfo = ( stAppInfo ); m_stAppInfo = ( stAppInfo );
m_ulAppShmIdAddr = NULL; m_ulAppShmIdAddr = NULL;
m_sNodeName = ""; m_sNodeName = "";
} }
CRdbUpdateThread::~CRdbUpdateThread() CRdbUpdateThread::~CRdbUpdateThread()
{ {
quit(); quit();
release(); release();
} }
void CRdbUpdateThread::execute() void CRdbUpdateThread::execute()
{ {
checkCurrentDatabaseChange(); checkCurrentDatabaseChange();
updateRtdb(); updateRtdb();
} }
int CRdbUpdateThread::initialize() int CRdbUpdateThread::initialize()
{ {
m_vecSynNote.clear(); m_vecSynNote.clear();
if ( false == initAppShmId() ) if ( false == initAppShmId() )
{ {
LOGERROR( "模型实时库同步初始化失败, initAppShmId fail." ); LOGERROR( "模型实时库同步初始化失败, initAppShmId fail." );
return false; return false;
} }
m_ullCurId = getMinId(); m_ullCurId = getMinId();
/* /*
if(false == CDbSysInfo::initialize()) if(false == CDbSysInfo::initialize())
{ {
LOGERROR("模型实时库同步初始化失败createSysInfoInstance fail."); LOGERROR("模型实时库同步初始化失败createSysInfoInstance fail.");
return false ; return false ;
} }
if(iot_public::createSysInfoInstance(m_ptrSysInfo) == false) if(iot_public::createSysInfoInstance(m_ptrSysInfo) == false)
{ {
LOGERROR("模型实时库同步初始化失败createSysInfoInstance fail."); LOGERROR("模型实时库同步初始化失败createSysInfoInstance fail.");
return false ; return false ;
} }
if(NULL == m_ptrSysInfo) if(NULL == m_ptrSysInfo)
{ {
LOGERROR("模型实时库同步初始化失败sysInfoPtr == null."); LOGERROR("模型实时库同步初始化失败sysInfoPtr == null.");
return false ; return false ;
}*/ }*/
return true; return true;
} }
void CRdbUpdateThread::release() void CRdbUpdateThread::release()
{ {
m_vecSynNote.clear(); m_vecSynNote.clear();
//m_ptrSysInfo.reset(); //m_ptrSysInfo.reset();
//CDbSysInfo::release(); //CDbSysInfo::release();
} }
int CRdbUpdateThread::getDomainIdByLocaiton( int nLocationId ) int CRdbUpdateThread::getDomainIdByLocaiton( int nLocationId )
{ {
SLocationInfo stLocationInfo; SLocationInfo stLocationInfo;
//m_ptrSysInfo->getLocationInfoById(nLocationId, stLocationInfo) ; //m_ptrSysInfo->getLocationInfoById(nLocationId, stLocationInfo) ;
CDbSysInfo::m_ptrSysInfo->getLocationInfoById( nLocationId, stLocationInfo ); CDbSysInfo::m_ptrSysInfo->getLocationInfoById( nLocationId, stLocationInfo );
return stLocationInfo.nDomainId; return stLocationInfo.nDomainId;
} }
int CRdbUpdateThread::initAppShmId() int CRdbUpdateThread::initAppShmId()
{ {
CRdbServerMemMan objMemMan; CRdbServerMemMan objMemMan;
if ( !objMemMan.isCreatedDb( m_stAppInfo.nAppId ) ) if ( !objMemMan.isCreatedDb( m_stAppInfo.nAppId ) )
{ {
LOGERROR( "app rdb_server not start." ); LOGERROR( "app rdb_server not start." );
return false; return false;
} }
CRdbConfigMan objRtdbConfigMan( m_stAppInfo.nAppId ); CRdbConfigMan objRtdbConfigMan( m_stAppInfo.nAppId );
uint64* pShmCurId = &objRtdbConfigMan.getConfigAddr()->ullDb2RtdbSynId; uint64* pShmCurId = &objRtdbConfigMan.getConfigAddr()->ullDb2RtdbSynId;
//m_mapAppId2Info[m_stAppInfo.nAppId] = pShmCurId; //m_mapAppId2Info[m_stAppInfo.nAppId] = pShmCurId;
m_ulAppShmIdAddr = pShmCurId; m_ulAppShmIdAddr = pShmCurId;
return true; return true;
} }
void CRdbUpdateThread::updateCurId() void CRdbUpdateThread::updateCurId()
{ {
/* /*
for(std::map<int, uint64*>::iterator iter = m_mapAppId2Info.begin(); iter != m_mapAppId2Info.end(); ++iter){ for(std::map<int, uint64*>::iterator iter = m_mapAppId2Info.begin(); iter != m_mapAppId2Info.end(); ++iter){
uint64 *pShmId = iter->second; uint64 *pShmId = iter->second;
*pShmId = m_ullCurId; *pShmId = m_ullCurId;
}*/ }*/
if ( m_ulAppShmIdAddr ) if ( m_ulAppShmIdAddr )
{ {
*m_ulAppShmIdAddr = m_ullCurId; *m_ulAppShmIdAddr = m_ullCurId;
} }
} }
uint64 CRdbUpdateThread::getMinId() uint64 CRdbUpdateThread::getMinId()
{ {
uint64 ullRet = 0; uint64 ullRet = 0;
/* /*
for(std::map<int, uint64*>::iterator iter = m_mapAppId2Info.begin(); iter != m_mapAppId2Info.end(); ++iter){ for(std::map<int, uint64*>::iterator iter = m_mapAppId2Info.begin(); iter != m_mapAppId2Info.end(); ++iter){
uint64 *pShmId = iter->second; uint64 *pShmId = iter->second;
ullRet = *(pShmId)<ullRet ? ullRet : *(pShmId); ullRet = *(pShmId)<ullRet ? ullRet : *(pShmId);
} }
return ullRet;*/ return ullRet;*/
if ( m_ulAppShmIdAddr ) if ( m_ulAppShmIdAddr )
{ {
ullRet = *m_ulAppShmIdAddr; ullRet = *m_ulAppShmIdAddr;
} }
return ullRet; return ullRet;
} }
/** /**
* @brief CRdbUpdateThread::checkCurrentDatabaseChange * @brief CRdbUpdateThread::checkCurrentDatabaseChange
* ip使用的是虚拟ip * ip使用的是虚拟ip
* *
* *
* id为sys_trigger_info表的最大id * id为sys_trigger_info表的最大id
*/ */
void CRdbUpdateThread::checkCurrentDatabaseChange() void CRdbUpdateThread::checkCurrentDatabaseChange()
{ {
if ( !openDb() ) if ( !openDb() )
return; return;
// 检测机器名是否变化 // 检测机器名是否变化
QString sHostName = m_objDb.getHostName(); QString sHostName = m_objDb.getHostName();
if ( sHostName.size() <= 0 ) if ( sHostName.size() <= 0 )
return; return;
if ( m_sNodeName == "" || m_sNodeName == sHostName ) if ( m_sNodeName == "" || m_sNodeName == sHostName )
{ {
m_sNodeName = sHostName; m_sNodeName = sHostName;
return; return;
} }
LOGERROR("数据库所在节点产生变化,原节点【%s】现节点【%s】", LOGERROR("数据库所在节点产生变化,原节点【%s】现节点【%s】",
m_sNodeName.toStdString().c_str(), m_sNodeName.toStdString().c_str(),
sHostName.toStdString().c_str()); sHostName.toStdString().c_str());
m_sNodeName = sHostName; m_sNodeName = sHostName;
// 机器名变化则将已同步到的id重新赋值 // 机器名变化则将已同步到的id重新赋值
QSqlQuery objQuery; QSqlQuery objQuery;
QString sSql = "SELECT max(act_id) AS curid FROM sys_trigger_info"; QString sSql = "SELECT max(act_id) AS curid FROM sys_trigger_info";
if ( !m_objDb.execute(sSql,objQuery) ) if ( !m_objDb.execute(sSql,objQuery) )
return; return;
uint64 ullRet = 0; uint64 ullRet = 0;
bool bOk = false; bool bOk = false;
if ( objQuery.isActive() && objQuery.next() ) if ( objQuery.isActive() && objQuery.next() )
ullRet = objQuery.value( "curid" ).toULongLong( &bOk ); ullRet = objQuery.value( "curid" ).toULongLong( &bOk );
if ( bOk ) if ( bOk )
{ {
LOGERROR("sys_trigger_info表已同步到的id产生变化原id【%lu】现id【%lu】", LOGERROR("sys_trigger_info表已同步到的id产生变化原id【%lu】现id【%lu】",
m_ullCurId, ullRet); m_ullCurId, ullRet);
m_ullCurId = ullRet; m_ullCurId = ullRet;
} }
} }
/** /**
* @brief CRdbUpdateThread::updateRtdb ,线(),. * @brief CRdbUpdateThread::updateRtdb ,线(),.
* @param vecSynNote * @param vecSynNote
*/ */
void CRdbUpdateThread::updateRtdb() void CRdbUpdateThread::updateRtdb()
{ {
if ( !getCurNote() ) if ( !getCurNote() )
{ {
return; return;
} }
CRdbAccessEx objRtdb; CRdbAccessEx objRtdb;
for ( size_t nSynNoteIndex = 0; nSynNoteIndex < m_vecSynNote.size(); ++nSynNoteIndex ) for ( size_t nSynNoteIndex = 0; nSynNoteIndex < m_vecSynNote.size(); ++nSynNoteIndex )
{ {
SSynNoteForModel& refSynNote = m_vecSynNote[nSynNoteIndex]; SSynNoteForModel& refSynNote = m_vecSynNote[nSynNoteIndex];
m_ullCurId = m_ullCurId > refSynNote.ullActId ? m_ullCurId : refSynNote.ullActId; m_ullCurId = m_ullCurId > refSynNote.ullActId ? m_ullCurId : refSynNote.ullActId;
bool bSelectByLocation = false; bool bSelectByLocation = false;
//bool bSelectBySubsystem = false; bool bSelectBySubsystem = false;
//判断当前应用是否和 RDB同步记录 在同一个应用 //判断当前应用是否和 RDB同步记录 在同一个应用
//=========================================================================================================== //===========================================================================================================
std::set<int> setAppId; std::set<int> setAppId;
if ( !CDbSysInfo::getAppIdBySubsystemFlag( refSynNote.unSubsystemFlag, setAppId ) ) if ( !CDbSysInfo::getAppIdBySubsystemFlag( refSynNote.unSubsystemFlag, setAppId ) )
{ {
continue; continue;
} }
//如果是删除记录,直接处理.说明:记录已删除,无法获知属于哪个车站,也无法或者属于哪个应用,只能尝试对每个车站的每个应用进行删除,删除失败无副作用. //如果是删除记录,直接处理.说明:记录已删除,无法获知属于哪个车站,也无法或者属于哪个应用,只能尝试对每个车站的每个应用进行删除,删除失败无副作用.
if ( setAppId.size() == 0 ) if ( setAppId.size() == 0 )
{ {
continue; //此表没有再任何一个应用中加载. continue; //此表没有再任何一个应用中加载.
} }
//没有找到 APP //没有找到 APP
if ( setAppId.find( m_stAppInfo.nAppId ) == setAppId.end() ) if ( setAppId.find( m_stAppInfo.nAppId ) == setAppId.end() )
{ {
continue; continue;
} }
// 组装所有条件 // 组装所有条件
//=========================================================================================================== //===========================================================================================================
std::vector<CONDINFO> vecCondition; std::vector<CONDINFO> vecCondition;
for ( size_t i = 0; i < refSynNote.vecKeyColumnName.size() && i < refSynNote.vecKeyOldValue.size(); ++i ) for ( size_t i = 0; i < refSynNote.vecKeyColumnName.size() && i < refSynNote.vecKeyOldValue.size(); ++i )
{ {
CONDINFO objCondition; CONDINFO objCondition;
objCondition.conditionval = refSynNote.vecKeyOldValue[i].c_str(); objCondition.conditionval = refSynNote.vecKeyOldValue[i].c_str();
objCondition.logicalop = ATTRCOND_AND; objCondition.logicalop = ATTRCOND_AND;
if ( refSynNote.vecKeyColumnName[i].length() > sizeof( objCondition.name ) - 1 ) if ( refSynNote.vecKeyColumnName[i].length() > sizeof( objCondition.name ) - 1 )
{ {
LOGERROR( "%s:%s 字段名超长", refSynNote.strTableName.c_str(), refSynNote.vecKeyColumnName[i].c_str() ); LOGERROR( "%s:%s 字段名超长", refSynNote.strTableName.c_str(), refSynNote.vecKeyColumnName[i].c_str() );
continue; continue;
} }
strncpy( objCondition.name, refSynNote.vecKeyColumnName[i].c_str(), sizeof( objCondition.name ) ); strncpy( objCondition.name, refSynNote.vecKeyColumnName[i].c_str(), sizeof( objCondition.name ) );
objCondition.relationop = ATTRCOND_EQU; objCondition.relationop = ATTRCOND_EQU;
vecCondition.push_back( objCondition ); vecCondition.push_back( objCondition );
} }
//DELETE一条同步记录处理 //DELETE一条同步记录处理
//=========================================================================================================== //===========================================================================================================
if ( EModelSynOptTypeDelete == refSynNote.nOptType ) if ( EModelSynOptTypeDelete == refSynNote.nOptType )
{ //DELETE { //DELETE
if ( !objRtdb.open( m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ) ) if ( !objRtdb.open( m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ) )
{ {
LOGERROR( "同步模型至实时库时,打开表失败,appid:%d, tablename:%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ); LOGERROR( "同步模型至实时库时,打开表失败,appid:%d, tablename:%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() );
continue; continue;
} }
objRtdb.lock(); objRtdb.lock();
objRtdb.remove( vecCondition ); objRtdb.remove( vecCondition );
objRtdb.unLock(); objRtdb.unLock();
continue; continue;
} }
//获取应用表目录地址 是否区分站点id和应用id //获取应用表目录地址 是否区分站点id和应用id
//=========================================================================================================== //===========================================================================================================
CRdbDictionary objDict( m_stAppInfo.nAppId ); CRdbDictionary objDict( m_stAppInfo.nAppId );
SRdbTableAttribute* pTable = objDict.SearchTable( refSynNote.strTableName.c_str() ); SRdbTableAttribute* pTable = objDict.SearchTable( refSynNote.strTableName.c_str() );
if ( 0 == pTable ) if ( 0 == pTable )
{ {
LOGERROR( "应用%d没有加载表%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ); LOGERROR( "应用%d没有加载表%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() );
continue; continue;
} }
bSelectByLocation = pTable->nSelectByLocation; //区分车站 bSelectByLocation = pTable->nSelectByLocation; //区分车站
//bSelectBySubsystem = pTable->nSelectBySubsystem; //区分专业 bSelectBySubsystem = pTable->nSelectBySubsystem; //区分专业
//不属于此站点,return,属于则,查出对应记录,然后确定需要更新此表的应用 //不属于此站点,return,属于则,查出对应记录,然后确定需要更新此表的应用
//=========================================================================================================== //===========================================================================================================
QSqlQuery objQuery; QSqlQuery objQuery;
if ( !openDb() ) if ( !openDb() )
{ {
LOGERROR( "打开数据库失败,openDb()!" ); LOGERROR( "打开数据库失败,openDb()!" );
return; return;
} }
QList<CDbCondition> listCondition; QList<CDbCondition> listCondition;
for ( size_t nCondIndex = 0; for ( size_t nCondIndex = 0;
nCondIndex < refSynNote.vecKeyColumnName.size() && nCondIndex < refSynNote.vecKeyNewValue.size(); nCondIndex < refSynNote.vecKeyColumnName.size() && nCondIndex < refSynNote.vecKeyNewValue.size();
++nCondIndex ) ++nCondIndex )
{ {
CDbCondition objCondition; CDbCondition objCondition;
objCondition.m_eCompare = CDbCondition::COMPARE_EQ; objCondition.m_eCompare = CDbCondition::COMPARE_EQ;
objCondition.m_eLogic = CDbCondition::LOGIC_AND; objCondition.m_eLogic = CDbCondition::LOGIC_AND;
objCondition.m_sColName = refSynNote.vecKeyColumnName[nCondIndex].c_str(); objCondition.m_sColName = refSynNote.vecKeyColumnName[nCondIndex].c_str();
objCondition.m_value = refSynNote.vecKeyNewValue[nCondIndex].c_str(); objCondition.m_value = refSynNote.vecKeyNewValue[nCondIndex].c_str();
listCondition << objCondition; listCondition << objCondition;
} }
if ( !m_objDb.select( refSynNote.strTableName.c_str(), listCondition, objQuery ) if ( !m_objDb.select( refSynNote.strTableName.c_str(), listCondition, objQuery )
|| !objQuery.next() ) || !objQuery.next() )
{ {
LOGERROR( "根据key查找记录失败,act_id:%llu", (unsigned long long)refSynNote.ullActId ); LOGERROR( "根据key查找记录失败,act_id:%llu", (unsigned long long)refSynNote.ullActId );
continue; continue;
} }
//区分车站判断 //区分车站判断
//=========================================================================================================== //===========================================================================================================
if ( bSelectByLocation ) if ( bSelectByLocation )
{ {
bool bConvertRet; bool bConvertRet;
int nLocationId = objQuery.value( STR_LOCATION_ID ).toInt( &bConvertRet ); int nLocationId = objQuery.value( STR_LOCATION_ID ).toInt( &bConvertRet );
if ( !bConvertRet ) if ( !bConvertRet )
{ {
LOGERROR( "同步的记录区分站点,但是获取站点号失败." ); LOGERROR( "同步的记录区分站点,但是获取站点号失败." );
continue; continue;
} }
if ( getDomainIdByLocaiton( nLocationId ) != m_stAppInfo.nDomainId ) if ( getDomainIdByLocaiton( nLocationId ) != m_stAppInfo.nDomainId )
{ {
continue; continue;
} }
} }
//区分专业判断 //区分专业判断
/* //===========================================================================================================
//=========================================================================================================== int nSelectedAppId = m_stAppInfo.nAppId ;
int nSelectedAppId = m_stAppInfo.nAppId ; if(bSelectBySubsystem){
if(bSelectBySubsystem){ bool bConvertRet;
bool bConvertRet; int nSubsystemId = objQuery.value(STR_SUB_SYSTEM).toInt(&bConvertRet);
int nSubsystemId = objQuery.value(STR_SUB_SYSTEM).toInt(&bConvertRet); if(!bConvertRet){
if(!bConvertRet){ LOGERROR("同步记录区分专业,但是获取专业ID失败.");
LOGERROR("同步记录区分专业,但是获取专业ID失败."); continue;
continue; }
} nSelectedAppId = CDbSysInfo::getAppIdBySubsystemId(nSubsystemId);
nSelectedAppId = CDbSysInfo::getAppIdBySubsystemId(nSubsystemId); if(m_stAppInfo.nAppId != nSelectedAppId ){
if(m_stAppInfo.nAppId != nSelectedAppId ){ LOGINFO("修改的记录不需要记录到实时库.id:%llu", (unsigned long long)refSynNote.ullActId);
LOGINFO("修改的记录不需要记录到实时库.id:%d", refSynNote.ullActId); continue;
continue; }
} }
}*/
//从所属任意应用查出表结构
//从所属任意应用查出表结构 //===============================================================================================
//=============================================================================================== SRdbColumnAttribute* pShmColumn = objDict.GetColumnStruct( pTable->nStartColumnNo );
SRdbColumnAttribute* pShmColumn = objDict.GetColumnStruct( pTable->nStartColumnNo ); std::vector<RSQL_UPD_COLUMN> vecColumnValue;
std::vector<RSQL_UPD_COLUMN> vecColumnValue;
for ( int pColumnIndex = 0; pColumnIndex < pTable->nColumnCount; ++pColumnIndex )
for ( int pColumnIndex = 0; pColumnIndex < pTable->nColumnCount; ++pColumnIndex ) {
{ if ( ( pShmColumn + pColumnIndex )->bNotUpdateRtdb )
if ( ( pShmColumn + pColumnIndex )->bNotUpdateRtdb ) {
{ continue;
continue; }
} RSQL_UPD_COLUMN objUpdColumn;
RSQL_UPD_COLUMN objUpdColumn; strncpy( objUpdColumn.updcolname, ( pShmColumn + pColumnIndex )->strName, sizeof( objUpdColumn.updcolname ) );
strncpy( objUpdColumn.updcolname, ( pShmColumn + pColumnIndex )->strName, sizeof( objUpdColumn.updcolname ) ); QVariantToVartypeValue( objQuery.value( objUpdColumn.updcolname ),
QVariantToVartypeValue( objQuery.value( objUpdColumn.updcolname ), ( pShmColumn + pColumnIndex )->nDataType, objUpdColumn.updvalue );
( pShmColumn + pColumnIndex )->nDataType, objUpdColumn.updvalue ); vecColumnValue.push_back( objUpdColumn );
vecColumnValue.push_back( objUpdColumn ); }
}
//对对应应用进行同步
//对对应应用进行同步 //===============================================================================================
//=============================================================================================== if ( !objRtdb.open( m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ) )
if ( !objRtdb.open( m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ) ) {
{ LOGERROR( "同步模型至实时库时,打开表失败,appid:%d, tablename:%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() );
LOGERROR( "同步模型至实时库时,打开表失败,appid:%d, tablename:%s", m_stAppInfo.nAppId, refSynNote.strTableName.c_str() ); continue;
continue; }
} if ( EModelSynOptTypeInsert == refSynNote.nOptType )
if ( EModelSynOptTypeInsert == refSynNote.nOptType ) {
{ objRtdb.lock();
objRtdb.lock(); objRtdb.insert( vecColumnValue );
objRtdb.insert( vecColumnValue ); objRtdb.unLock();
objRtdb.unLock(); }
} else
else {
{ objRtdb.lock();
objRtdb.lock(); objRtdb.update( vecColumnValue, vecCondition );
objRtdb.update( vecColumnValue, vecCondition ); objRtdb.unLock();
objRtdb.unLock(); }
} //m_objRtdb.close();
//m_objRtdb.close(); }
}
updateCurId(); //更新同步到的id到共享内存
updateCurId(); //更新同步到的id到共享内存
m_vecSynNote.clear();
m_vecSynNote.clear();
return;
return; }
}
bool CRdbUpdateThread::openDb()
bool CRdbUpdateThread::openDb() {
{ if ( !m_objDb.isOpen() )
if ( !m_objDb.isOpen() ) {
{ if ( !m_objDb.open() )
if ( !m_objDb.open() ) {
{ LOGERROR( "获取可读数据库连接失败." );
LOGERROR( "获取可读数据库连接失败." ); return false;
return false; }
} }
} return true;
return true; }
}
bool CRdbUpdateThread::getCurNote()
bool CRdbUpdateThread::getCurNote() {
{ m_vecSynNote.clear();
m_vecSynNote.clear(); if ( !openDb() )
if ( !openDb() ) {
{ return false;
return false; }
}
CDbCondition objCondtion0;
CDbCondition objCondtion0; objCondtion0.m_sColName = "act_id";
objCondtion0.m_sColName = "act_id"; objCondtion0.m_value = (qulonglong)m_ullCurId;
objCondtion0.m_value = (qulonglong)m_ullCurId; objCondtion0.m_eCompare = CDbCondition::COMPARE_GT;
objCondtion0.m_eCompare = CDbCondition::COMPARE_GT; objCondtion0.m_eLogic = CDbCondition::LOGIC_AND;
objCondtion0.m_eLogic = CDbCondition::LOGIC_AND; CDbCondition objCondtion1;
CDbCondition objCondtion1; objCondtion1.m_sColName = "act_id";
objCondtion1.m_sColName = "act_id"; objCondtion1.m_value = (qulonglong)m_ullCurId+1000;
objCondtion1.m_value = (qulonglong)m_ullCurId+1000; objCondtion1.m_eCompare = CDbCondition::COMPARE_LT;
objCondtion1.m_eCompare = CDbCondition::COMPARE_LT; QList<CDbCondition> listCondition;
QList<CDbCondition> listCondition; listCondition << objCondtion0 << objCondtion1;
listCondition << objCondtion0 << objCondtion1;
CDbOrder objOrderBy(objCondtion0.m_sColName);
CDbOrder objOrderBy(objCondtion0.m_sColName); QList<CDbOrder> listOrderBy;
QList<CDbOrder> listOrderBy; listOrderBy << objOrderBy;
listOrderBy << objOrderBy;
QSqlQuery objQuery;
QSqlQuery objQuery; if ( !m_objDb.select( "sys_trigger_info", listCondition, listOrderBy, objQuery ) )
if ( !m_objDb.select( "sys_trigger_info", listCondition, listOrderBy, objQuery ) ) {
{ LOGERROR( "select return non zero. %s", objQuery.lastError().databaseText().toUtf8().data() );
LOGERROR( "select return non zero. %s", objQuery.lastError().databaseText().toUtf8().data() ); m_objDb.close();
return false; LOGINFO("close db connect,wait next time to connect");
} return false;
while ( objQuery.next() ) }
{ while ( objQuery.next() )
SSynNoteForModel objModelNote; {
bool bConvertRet; SSynNoteForModel objModelNote;
objModelNote.ullActId = objQuery.value( "act_id" ).toULongLong( &bConvertRet ); bool bConvertRet;
if ( false == bConvertRet ) objModelNote.ullActId = objQuery.value( "act_id" ).toULongLong( &bConvertRet );
{ if ( false == bConvertRet )
LOGERROR( "convert ret:false" ); {
continue; LOGERROR( "convert ret:false" );
} continue;
int nOptType = objQuery.value( "op_type" ).toInt( &bConvertRet ); }
if ( false == bConvertRet || ( nOptType < 0 || nOptType > 2 ) ) int nOptType = objQuery.value( "op_type" ).toInt( &bConvertRet );
{ if ( false == bConvertRet || ( nOptType < 0 || nOptType > 2 ) )
LOGERROR( "convert ret:%s, op_type:%d", bConvertRet ? "true" : "false", objModelNote.nOptType ); {
continue; LOGERROR( "convert ret:%s, op_type:%d", bConvertRet ? "true" : "false", objModelNote.nOptType );
} continue;
objModelNote.nOptType = EModelSynOptType( nOptType ); }
objModelNote.nOptType = EModelSynOptType( nOptType );
objModelNote.strTableName = objQuery.value( "table_name" ).toString().toUtf8().data();
QStringList listColumnName = objQuery.value( "key_column_name" ).toString().split( "," ); objModelNote.strTableName = objQuery.value( "table_name" ).toString().toUtf8().data();
for ( int i = 0; i < listColumnName.size(); ++i ) QStringList listColumnName = objQuery.value( "key_column_name" ).toString().split( "," );
{ for ( int i = 0; i < listColumnName.size(); ++i )
objModelNote.vecKeyColumnName.push_back( listColumnName[i].toUtf8().data() ); {
} objModelNote.vecKeyColumnName.push_back( listColumnName[i].toUtf8().data() );
QStringList listKeyOldValue = objQuery.value( "key_old_value" ).toString().split( "," ); }
for ( int i = 0; i < listKeyOldValue.size(); ++i ) QStringList listKeyOldValue = objQuery.value( "key_old_value" ).toString().split( "," );
{ for ( int i = 0; i < listKeyOldValue.size(); ++i )
objModelNote.vecKeyOldValue.push_back( listKeyOldValue[i].toUtf8().data() ); {
} objModelNote.vecKeyOldValue.push_back( listKeyOldValue[i].toUtf8().data() );
QStringList listKeyNewValue = objQuery.value( "key_new_value" ).toString().split( "," ); }
for ( int i = 0; i < listKeyNewValue.size(); ++i ) QStringList listKeyNewValue = objQuery.value( "key_new_value" ).toString().split( "," );
{ for ( int i = 0; i < listKeyNewValue.size(); ++i )
objModelNote.vecKeyNewValue.push_back( listKeyNewValue[i].toUtf8().data() ); {
} objModelNote.vecKeyNewValue.push_back( listKeyNewValue[i].toUtf8().data() );
}
// 由于数据库中不再有表模式和列模式这两张表故此处从xml文件中获取subsystem_flag
//objModelNote.unSubsystemFlag = objQuery.value( "subsystem_flag" ).toInt( &bConvertRet ); // 由于数据库中不再有表模式和列模式这两张表故此处从xml文件中获取subsystem_flag
if ( false == CDbSysInfo::getSubsystemFlagByTableName(objModelNote.strTableName,objModelNote.unSubsystemFlag) ) //objModelNote.unSubsystemFlag = objQuery.value( "subsystem_flag" ).toInt( &bConvertRet );
{ if ( false == CDbSysInfo::getSubsystemFlagByTableName(objModelNote.strTableName,objModelNote.unSubsystemFlag) )
//LOGERROR( "获取内存表【%s】的subsystemFlag失败", objModelNote.strTableName.c_str() ); {
continue; //LOGERROR( "获取内存表【%s】的subsystemFlag失败", objModelNote.strTableName.c_str() );
} continue;
}
if ( EModelSynOptTypeInsert == objModelNote.nOptType && objModelNote.vecKeyNewValue.size() == 0 )
{ if ( EModelSynOptTypeInsert == objModelNote.nOptType && objModelNote.vecKeyNewValue.size() == 0 )
continue; {
} continue;
if ( EModelSynOptTypeDelete == objModelNote.nOptType && objModelNote.vecKeyOldValue.size() == 0 ) }
{ if ( EModelSynOptTypeDelete == objModelNote.nOptType && objModelNote.vecKeyOldValue.size() == 0 )
continue; {
} continue;
if ( EModelSynOptTypeUpdate == objModelNote.nOptType }
&& ( objModelNote.vecKeyNewValue != objModelNote.vecKeyOldValue || objModelNote.vecKeyNewValue.size() == 0 ) ) if ( EModelSynOptTypeUpdate == objModelNote.nOptType
{ && ( objModelNote.vecKeyNewValue != objModelNote.vecKeyOldValue || objModelNote.vecKeyNewValue.size() == 0 ) )
continue; {
} continue;
if ( 0 == objModelNote.unSubsystemFlag || objModelNote.strTableName.length() == 0 ) }
{ if ( 0 == objModelNote.unSubsystemFlag || objModelNote.strTableName.length() == 0 )
continue; {
} continue;
m_vecSynNote.push_back( objModelNote ); }
} m_vecSynNote.push_back( objModelNote );
return true; }
} return true;
}

View File

@ -2,9 +2,9 @@
#include <QApplication> #include <QApplication>
#include "common/QtAppGlobalSet.h" #include "common/QtAppGlobalSet.h"
#include "pub_logger_api/logger.h" #include "pub_logger_api/logger.h"
#include "net/net_msg_bus_api/MsgBusApi.h"
#include "net/net_msg_bus_api/CMbCommunicator.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "pub_utility_api/FileStyle.h"
#include "pub_widget/PubWidgetInit.h"
int main( int argc, char* argv[] ) int main( int argc, char* argv[] )
{ {
@ -12,10 +12,37 @@ int main( int argc, char* argv[] )
iot_public::StartLogSystem( "default", "rdb_studio" ); iot_public::StartLogSystem( "default", "rdb_studio" );
QApplication a( argc, argv ); QApplication a( argc, argv );
iot_net::initMsgBus( "sfda", "sdfafds" );
iot_net::CMbCommunicator* pCom = new iot_net::CMbCommunicator(); QString qss = QString();
delete pCom; std::string strFullPath = iot_public::CFileStyle::getPathOfStyleFile("public.qss","zh","light");
iot_net::releaseMsgBus();
QFile qssfile1(QString::fromStdString(strFullPath));
qssfile1.open(QFile::ReadOnly);
if (qssfile1.isOpen())
{
qss += QLatin1String(qssfile1.readAll());
qssfile1.close();
}
strFullPath = iot_public::CFileStyle::getPathOfStyleFile("rdb_studio.qss","zh","light");
QFile qssfile2(QString::fromStdString(strFullPath));
qssfile2.open(QFile::ReadOnly);
if (qssfile2.isOpen())
{
qss += QLatin1String(qssfile2.readAll());
qssfile2.close();
}
if (!qss.isEmpty())
{
qApp->setStyleSheet(qss);
}
iot_public::installTranslator("zh");
// qApp->setFont(QFont("Microsoft YaHei",10));
a.setWindowIcon(QIcon(":/icons/rdb_studio.ico"));
MainWindow w; MainWindow w;
w.show(); w.show();
int nRet = a.exec(); int nRet = a.exec();

View File

@ -5,9 +5,10 @@
#include "tablemodel.h" #include "tablemodel.h"
#include "CMemDictionaryM.h" #include "CMemDictionaryM.h"
#include "CMemTableM.h" #include "CMemTableM.h"
#include "pub_widget/MessageBox.h"
MainWindow::MainWindow( QWidget* parent ) MainWindow::MainWindow( QWidget* parent )
: QMainWindow( parent ) : CustomUiMainWindow( parent )
, ui( new Ui::MainWindow ) , ui( new Ui::MainWindow )
{ {
ui->setupUi( this ); ui->setupUi( this );
@ -31,7 +32,8 @@ void MainWindow::initVariable()
void MainWindow::initUi() void MainWindow::initUi()
{ {
this->setWindowTitle( "内存库工具" ); this->setWindowTitle( tr("内存库工具") );
CustomUiMainWindow::setAutoLayout(true);
//隐藏无关组件 //隐藏无关组件
ui->mainToolBar->hide(); ui->mainToolBar->hide();
@ -257,7 +259,7 @@ void MainWindow::slotListWidgetTableClicked( QListWidgetItem* pItem )
} }
else else
{ {
QMessageBox::warning( this, tr( "Error" ), tr( "打开表失败!" ) ); N_MessageBox::warning( this, tr( "Error" ), tr( "打开表失败!" ) );
} }
} }
@ -273,12 +275,12 @@ void MainWindow::slotPushButtonAddFilterClicked()
{ {
if ( ui->comboBox_column->currentText() == "" ) if ( ui->comboBox_column->currentText() == "" )
{ {
QMessageBox::warning( 0, "提示", "列名不能为空" ); N_MessageBox::warning( 0, "提示", "列名不能为空" );
return; return;
} }
if ( ui->lineEdit_in->text() == "" ) if ( ui->lineEdit_in->text() == "" )
{ {
QMessageBox::warning( 0, "提示", "筛选内容不能为空" ); N_MessageBox::warning( 0, "提示", "筛选内容不能为空" );
return; return;
} }
@ -300,7 +302,7 @@ void MainWindow::slotPushButtonDeleteFilterClicked()
{ {
if ( ui->tableWidget_filter->selectedItems().count() <= 0 ) if ( ui->tableWidget_filter->selectedItems().count() <= 0 )
{ {
QMessageBox::warning( 0, "提示", "请先选择一行" ); N_MessageBox::warning( 0, "提示", "请先选择一行" );
return; return;
} }

View File

@ -6,6 +6,7 @@
#include <QListWidget> #include <QListWidget>
#include "CMemTableM.h" #include "CMemTableM.h"
#include "rdb_api/RdbTableMng.h" #include "rdb_api/RdbTableMng.h"
#include "pub_widget/CustomMainWindow.h"
namespace Ui namespace Ui
{ {
@ -21,7 +22,7 @@ using namespace std;
using namespace iot_dbms; using namespace iot_dbms;
using namespace iot_public; using namespace iot_public;
class MainWindow : public QMainWindow class MainWindow : public CustomUiMainWindow
{ {
Q_OBJECT Q_OBJECT

View File

@ -19,16 +19,16 @@
<number>2</number> <number>2</number>
</property> </property>
<property name="leftMargin"> <property name="leftMargin">
<number>2</number> <number>9</number>
</property> </property>
<property name="topMargin"> <property name="topMargin">
<number>2</number> <number>9</number>
</property> </property>
<property name="rightMargin"> <property name="rightMargin">
<number>2</number> <number>9</number>
</property> </property>
<property name="bottomMargin"> <property name="bottomMargin">
<number>2</number> <number>9</number>
</property> </property>
<item> <item>
<widget class="QTabWidget" name="tabWidget"> <widget class="QTabWidget" name="tabWidget">
@ -451,7 +451,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>911</width> <width>911</width>
<height>25</height> <height>23</height>
</rect> </rect>
</property> </property>
</widget> </widget>

View File

@ -22,6 +22,7 @@ DEFINES += QT_DEPRECATED_WARNINGS
# You can also select to disable deprecated APIs only up to a certain version of Qt. # You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
RC_ICONS = icons/rdb_studio.ico
SOURCES += \ SOURCES += \
main.cpp \ main.cpp \
@ -42,9 +43,11 @@ FORMS += \
LIBS += \ LIBS += \
-lrdb_api \ -lrdb_api \
-lpub_logger_api \ -lpub_logger_api \
-lnet_msg_bus_api \
-llog4cplus \ -llog4cplus \
-lboost_system -lboost_system \
-lpub_widget \
-lpub_utility_api
COMMON_PRI=$$PWD/../../common.pri COMMON_PRI=$$PWD/../../common.pri
exists($$COMMON_PRI) { exists($$COMMON_PRI) {

View File

@ -7,5 +7,6 @@
<file>icons/rightArrow.png</file> <file>icons/rightArrow.png</file>
<file>icons/save.png</file> <file>icons/save.png</file>
<file>icons/undo.png</file> <file>icons/undo.png</file>
<file>icons/rdb_studio.ico</file>
</qresource> </qresource>
</RCC> </RCC>

View File

@ -20,6 +20,13 @@ CTsdbConn::CTsdbConn(const char *pchHost, int nPort, const char *pchDb,
m_pImp = new CTsdbConnImp(pchHost, nPort, pchDb, pchUser, pchPwd); m_pImp = new CTsdbConnImp(pchHost, nPort, pchDb, pchUser, pchPwd);
} }
CTsdbConn::CTsdbConn(const STsdbConnParam &stConnParam)
{
m_pImp = new CTsdbConnImp(stConnParam.strIP.c_str(),stConnParam.nPort,
stConnParam.strDbName.c_str(),stConnParam.strUserName.c_str(),
stConnParam.strUserPassword.c_str());
}
CTsdbConn::~CTsdbConn() CTsdbConn::~CTsdbConn()
{ {
delete m_pImp; delete m_pImp;

View File

@ -133,7 +133,13 @@ CTsdbConnPtr getOneUseableConn(bool bLocalDomain)
if (pchIp) if (pchIp)
{ {
//< todo 端口、数据库名、用户名、密码都使用默认值 //< todo 端口、数据库名、用户名、密码都使用默认值
ptrConn.reset(new CTsdbConn(pchIp)); /* 为以后搜索方便,保留此注释 EMS_DEFAULT_DATABASE
* 使,
*/
ptrConn.reset(new CTsdbConn(pchIp,INFLUXDB_DEFAULT_PORT,
stFirstDbInfo.strServiceName.c_str(),
stFirstDbInfo.strServiceName.c_str(),
stFirstDbInfo.strUserPassword.c_str()));
//< 超时时间使用默认值 //< 超时时间使用默认值
if (ptrConn->pingServer()) if (ptrConn->pingServer())

View File

@ -66,17 +66,20 @@ void tsdb_api_test()
LOGINFO("\n******** Complete ********\n"); LOGINFO("\n******** Complete ********\n");
{ {
std::string strResult;
LOGINFO("\n\n******** Test getOneUseableConn() ********"); LOGINFO("\n\n******** Test getOneUseableConn() ********");
iot_dbms::CTsdbConnPtr ptrConn = iot_dbms::getOneUseableConn(true); iot_dbms::CTsdbConnPtr ptrConn = iot_dbms::getOneUseableConn(true);
if (!ptrConn) if (!ptrConn)
{ {
LOGINFO("getOneUseableConn() return NULL !") LOGINFO("getOneUseableConn() return NULL !");
} }
LOGINFO("\n******** Complete ********\n"); LOGINFO("\n******** Complete ********\n");
//< 不使用getOneUseableConn()返回的正式库测试 //< 不使用getOneUseableConn()返回的正式库测试
ptrConn.reset(new iot_dbms::CTsdbConn("127.0.0.1", -1, "ykn_test", "", "")); ptrConn.reset(new iot_dbms::CTsdbConn("127.0.0.1", -1, "ykn_test",
EMS_DEFAULT_DATABASE, EMS_DEFAULT_PASSWD));
LOGINFO("\n\n******** Test pingServer() ********"); LOGINFO("\n\n******** Test pingServer() ********");
if (!ptrConn->pingServer(1000)) if (!ptrConn->pingServer(1000))
@ -86,6 +89,31 @@ void tsdb_api_test()
} }
LOGINFO("\n******** Complete ********\n"); LOGINFO("\n******** Complete ********\n");
LOGINFO( "\n\n******** Test drop user ********" );
if ( !ptrConn->doQuery( "drop user iscs6000", &strResult ))
{
//< 当开启了用户认证又没有admin级别用户的话只允许执行新建admin级别用户的操作
ptrConn->doQuery( QString("create user %1 with password '%2' with all privileges").arg(EMS_DEFAULT_DATABASE).arg(EMS_DEFAULT_PASSWD), &strResult );
}
else
{
LOGINFO( "drop user sucess, result: %s", strResult.c_str());
}
LOGINFO( "\n******** Complete ********\n" );
LOGINFO( "\n\n******** Test create user ********" );
//< 重复建立同名、同密码用户会成功,如果同名但密码不同则会失败
if ( !ptrConn->doQuery(QString("create user %1 with password '%2' with all privileges").arg(EMS_DEFAULT_DATABASE).arg(EMS_DEFAULT_PASSWD), &strResult ))
{
LOGERROR( "create user return false !" );
return;
}
else
{
LOGINFO( "create user sucess, result: %s", strResult.c_str());
}
LOGINFO( "\n******** Complete ********\n" );
LOGINFO("\n\n******** Test createDatabase() ********"); LOGINFO("\n\n******** Test createDatabase() ********");
if (!ptrConn->createDatabase("ykn_test", 1000)) if (!ptrConn->createDatabase("ykn_test", 1000))
{ {
@ -104,8 +132,6 @@ void tsdb_api_test()
LOGINFO("\n\n******** Test doQuery() ********"); LOGINFO("\n\n******** Test doQuery() ********");
{ {
std::string strResult;
if (!ptrConn->doQuery("select * from ai_sample_result", &strResult, 1000)) if (!ptrConn->doQuery("select * from ai_sample_result", &strResult, 1000))
{ {
LOGERROR("doQuery() return false !"); LOGERROR("doQuery() return false !");
@ -127,7 +153,6 @@ void tsdb_api_test()
LOGERROR("doQuery() return false !"); LOGERROR("doQuery() return false !");
} }
LOGINFO("strResult == \n%s", strResult.c_str()); LOGINFO("strResult == \n%s", strResult.c_str());
} }
LOGINFO("\n******** Complete ********\n"); LOGINFO("\n******** Complete ********\n");
@ -138,6 +163,17 @@ void tsdb_api_test()
} }
LOGINFO("\n******** Complete ********\n"); LOGINFO("\n******** Complete ********\n");
// LOGINFO( "\n\n******** Test drop user ********" );
// if ( !ptrConn->doQuery( "drop user iscs6000", &strResult ))
// {
// LOGERROR( "drop user return false !" );
// return;
// }
// else
// {
// LOGINFO( "drop user sucess, result: %s", strResult.c_str());
// }
// LOGINFO( "\n******** Complete ********\n" );
} }
LOGINFO("\n\n******** Test releaseTsdbApi() ********"); LOGINFO("\n\n******** Test releaseTsdbApi() ********");

View File

@ -130,10 +130,14 @@ bool CNodeMng::init()
} }
//< todo 端口号、数据库名、用户名、密码 暂时写死 //< todo 端口号、数据库名、用户名、密码 暂时写死
/* 为以后搜索方便,保留此注释
* EMS_DEFAULT_DATABASE使
*
*/
CNodeThreadPtr ptrNodeThread(new CNodeThread(stDbNodeInfo.strName, CNodeThreadPtr ptrNodeThread(new CNodeThread(stDbNodeInfo.strName,
strIpA, strIpB, strIpA, strIpB,
8086, "iscs6000", 8086, stFirstDbInfo.strServiceName,
"", "")); stFirstDbInfo.strServiceName, stFirstDbInfo.strUserPassword));
m_vecLocalThreads.push_back(ptrNodeThread); m_vecLocalThreads.push_back(ptrNodeThread);
@ -169,10 +173,14 @@ bool CNodeMng::init()
} }
//< todo 端口号、数据库名、用户名、密码 暂时写死 //< todo 端口号、数据库名、用户名、密码 暂时写死
/* 为以后搜索方便,保留此注释
* EMS_DEFAULT_DATABASE使
*
*/
CNodeThreadPtr ptrNodeThread(new CNodeThread(stDbNodeInfo.strName, CNodeThreadPtr ptrNodeThread(new CNodeThread(stDbNodeInfo.strName,
strIpA, strIpB, strIpA, strIpB,
8086, "iscs6000", 8086, stFirstDbInfo.strServiceName,
"", "")); stFirstDbInfo.strServiceName, stFirstDbInfo.strUserPassword));
m_vecRemoteThreads.push_back(ptrNodeThread); m_vecRemoteThreads.push_back(ptrNodeThread);

View File

@ -198,7 +198,9 @@ void CTsdbSaveApiImp::execute()
objMbMsg.setPara2(m_nDomainID); //< 域ID objMbMsg.setPara2(m_nDomainID); //< 域ID
//< 注意: 发送后消息内容被清空 //< 注意: 发送后消息内容被清空
const bool bRc = m_objComm.sendMsgToDomain(objMbMsg, -1); //< 发本域 //const bool bRc = m_objComm.sendMsgToDomain(objMbMsg, -1); //< 发本域
//为了提高大数据量下的处理能力每个应用部署一个tsdb_save服务
const bool bRc = m_objComm.sendMsgToHost(objMbMsg); //< 发本机
if (bRc) if (bRc)
{ {

View File

@ -0,0 +1,357 @@
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDebug>
#include <QMessageBox>
#include <tsdb_api/CTsdbConn.h>
#include <tsdb_api/TsdbApi.h>
#include "dataWorker.h"
#include "db_his_query_api/DbHisQueryApi.h"
#include <QThreadPool>
using namespace iot_dbms;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
dataWorker *worker = new dataWorker;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &MainWindow::operate, worker, &dataWorker::doWork);
connect(worker, &dataWorker::resultReady, this, &MainWindow::handleResults);
connect(this, &MainWindow::startTest, worker, &dataWorker::doTest);
connect(worker, &dataWorker::testResultReady, this, &MainWindow::handleTestResults);
connect(this, &MainWindow::insertEvent, worker, &dataWorker::doInsertEvent);
connect(worker, &dataWorker::InsertEventResultReady, this, &MainWindow::handleEventInsertResults);
connect(this, &MainWindow::deleteWork, worker, &dataWorker::doDel);
connect(worker, &dataWorker::deleteResultReady, this, &MainWindow::handleDeleteResults);
connect(worker, &dataWorker::onErrMsg, this, &MainWindow::onErrMsg);
connect(worker, &dataWorker::onStatus, this, &MainWindow::onStatus);
connect(worker, &dataWorker::onTestStatus, this, &MainWindow::onTestStatus);
connect(worker, &dataWorker::onAddTestRow, this, &MainWindow::onAddTestRow);
workerThread.start();
ui->label_status->setHidden(true);
auto date = ui->calendarWidget_startDate->selectedDate();
date.setDate(date.addYears(-3).year(),date.month(),date.day());
ui->calendarWidget_startDate->setSelectedDate(date);
date = ui->calendarWidget_test->selectedDate();
date.setDate(date.addYears(-2).year(),date.month(),date.day());
ui->calendarWidget_test->setSelectedDate(date);
// QThreadPool::globalInstance()->setMaxThreadCount(10);
}
MainWindow::~MainWindow()
{
workerThread.quit();
workerThread.wait();
delete ui;
}
QString MainWindow::getPointType()
{
if( ui->comboBox_type->currentText() == tr("模拟量")){
return QString("ai_sample_result");
}else if( ui->comboBox_type->currentText() == tr("累积量")){
return QString("acc_sample_result");
}else if( ui->comboBox_type->currentText() == tr("混合量")){
return QString("mix_sample_result");
}else if( ui->comboBox_type->currentText() == tr("数字量")){
return QString("di_sample_result");
}else
return "";
}
int MainWindow::getDeviatType()
{
if (ui->comboBox_deviatType->currentText() == tr("左边")){
return -1;
}else if (ui->comboBox_deviatType->currentText() == tr("两边")){
return 0;
}else {
return 1;
}
}
void MainWindow::on_pushButton_insert_clicked()
{
if(QMessageBox::question(this,"提醒","是否插入") != QMessageBox::Yes)
{
return;
}
QString address = ui->lineEdit_addr->text();
QStringList listPoint = ui->plainTextEdit_point->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
QString pointType = getPointType();
quint64 interval = ui->spinBox_interval->value() * 1000; //ms
int deviatProb = ui->spinBox_deviatProb->value();
double normalBase = ui->doubleSpinBox_base->value();
double normalLength = ui->doubleSpinBox_length->value();
quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
int deviatType = getDeviatType();
bool isDeleteInterval = ui->checkBox_delete->isChecked();
bool isDeleteAll = ui->checkBox_delAll->isChecked();
bool isMT = ui->checkBox_mt->isChecked();
emit operate(listPoint,address,pointType,interval,deviatProb,normalBase,normalLength,starttime,endtime,deviatType,isDeleteInterval,isDeleteAll,isMT);
ui->pushButton_insert->setEnabled(false);
ui->pushButton_delete->setEnabled(false);
ui->label_status->setHidden(false);
}
void MainWindow::onErrMsg(const QString &msg)
{
QMessageBox::critical(this,"提醒",msg);
}
void MainWindow::onStatus(const QString &msg)
{
ui->label_status->setText(msg);
}
void MainWindow::onTestStatus(const QString &msg)
{
ui->plainTextEdit_test_result->appendPlainText(msg);
}
void MainWindow::onAddTestRow(const QStringList &newRow)
{
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
QString newLine;
for(int i = 0; i < newRow.size(); i++)
{
ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, i, new QTableWidgetItem(newRow.at(i)));
newLine += newRow.at(i) + ",";
}
newLine.chop(1);
ui->plainTextEdit_test_result->appendPlainText(newLine);
ui->tableWidget->resizeColumnsToContents();
}
void MainWindow::on_comboBox_type_currentTextChanged(const QString &arg1)
{
if("数字量" == arg1)
{
ui->groupBox->setHidden(true);
}
else
{
ui->groupBox->setHidden(false);
}
}
void MainWindow::handleResults(const QString &msg, bool result) {
ui->label_status->setHidden(true);
if(result)
{
QMessageBox::information(this,"提醒","插入成功");
}
else
{
onErrMsg(QString("插入失败:") + msg);
}
ui->pushButton_insert->setEnabled(true);
ui->pushButton_delete->setEnabled(true);
}
void MainWindow::handleTestResults(const QString &msg, bool result)
{
if(result)
{
QMessageBox::information(this,"提醒","测试结束");
}
else
{
onErrMsg(QString("测试失败:") + msg);
}
ui->pushButton_start_test->setEnabled(true);
}
void MainWindow::handleDeleteResults(const QString &msg, bool result)
{
ui->label_status->setHidden(true);
if(result)
{
QMessageBox::information(this,"提醒","删除成功");
}
else
{
onErrMsg(QString("删除失败:") + msg);
}
ui->pushButton_insert->setEnabled(true);
ui->pushButton_delete->setEnabled(true);
}
void MainWindow::handleEventInsertResults(const QString &msg, bool result)
{
if(result)
{
QMessageBox::information(this,"提醒","生成数据库文件已放至同目录outEvent.sql");
}
else
{
onErrMsg(QString("插入失败:") + msg);
}
}
void MainWindow::on_pushButton_delete_clicked()
{
if(QMessageBox::question(this,"提醒","是否删除") != QMessageBox::Yes)
{
return;
}
QString address = ui->lineEdit_addr->text();
QStringList listPoint = ui->plainTextEdit_point->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
QString pointType = getPointType();
quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
bool isDeleteAll = ui->checkBox_delAll->isChecked();
emit deleteWork(address,pointType,listPoint,starttime,endtime,isDeleteAll);
ui->pushButton_insert->setEnabled(false);
ui->pushButton_delete->setEnabled(false);
ui->label_status->setHidden(false);
}
void MainWindow::on_pushButton_insert_event_clicked()
{
if(QMessageBox::question(this,"提醒","是否插入历史数据") != QMessageBox::Yes)
{
return;
}
QStringList listPoint = ui->plainTextEdit_point_event->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
quint64 starttime = QDateTime(ui->calendarWidget_startDate_event->selectedDate(),ui->timeEdit_start_event->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate_event->selectedDate(),ui->timeEdit_end_event->time()).toMSecsSinceEpoch(); // 结束日期加一天
emit insertEvent(
QStringList()
<< QString::number( ui->spinBox_alm_type->value() ) // 0
<< QString::number( ui->spinBox_alm_status->value() ) // 1
<< QString::number( ui->spinBox_alm_style->value() ) // 2
<< QString::number( ui->spinBox_location_id->value() ) // 3
<< QString::number( ui->spinBox_priority->value() ) // 4
<< QString::number( ui->spinBox_sub_system->value() ) // 5
<< QString::number( ui->spinBox_dev_type->value() ) //6
<< QString::number( ui->spinBox_region_id->value() ) // 7
<< QString::number( ui->spinBox_interval_event->value() ) // 8
,
listPoint,ui->lineEdit_content->text(),starttime,endtime);
}
void MainWindow::on_pushButton_delete_event_clicked()
{
onErrMsg(tr("该功能未实现"));
}
void MainWindow::on_checkBox_delAll_clicked(bool checked)
{
if(checked)
{
ui->checkBox_delete->setChecked(false);
}
}
void MainWindow::on_checkBox_delete_clicked(bool checked)
{
if(checked)
{
ui->checkBox_delAll->setChecked(false);
}
}
void MainWindow::on_pushButton_start_test_clicked()
{
if(QMessageBox::question(this,"提醒","是否查询") != QMessageBox::Yes)
{
return;
}
ui->plainTextEdit_test_result->clear();
QString headerLine;
headerLine += QString("结果") + ",";
headerLine += QString("规模") + ",";
headerLine += QString("周期") + ",";
headerLine += QString("开始日期") + ",";
headerLine += QString("结果日期") + ",";
headerLine += QString("间隔(s)") + ",";
headerLine += QString("结果数量") + ",";
headerLine += QString("方法") + ",";
headerLine += QString("用时(ms)");
ui->plainTextEdit_test_result->appendPlainText(headerLine);
while(ui->tableWidget->rowCount() > 0)
{
ui->tableWidget->removeRow(0);
}
// 一些参数预先设定
int timeout = ui->spinBox_timeout->value();
int base = ui->spinBox_base->value();
int facor = ui->spinBox_factor->value();
QString address = ui->lineEdit_addr_test->text();
qint64 starttime = QDateTime(ui->calendarWidget_test->selectedDate(),QTime(0,0)).toMSecsSinceEpoch();
QStringList listPoint = ui->plainTextEdit_point_test->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
// todo 这里时间间隔和计算方法以后再做,这里固定填充了
emit startTest(timeout,base,facor,listPoint,starttime,address);
ui->pushButton_start_test->setEnabled(false);
}

View File

@ -0,0 +1,86 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
QString getPointType();
int getDeviatType();
void on_pushButton_insert_clicked();
void on_comboBox_type_currentTextChanged(const QString &arg1);
void on_pushButton_delete_clicked();
void on_pushButton_insert_event_clicked();
void on_pushButton_delete_event_clicked();
void on_checkBox_delAll_clicked(bool checked);
void on_checkBox_delete_clicked(bool checked);
void on_pushButton_start_test_clicked();
public slots:
void handleResults(const QString &msg,bool result =true);
void handleTestResults(const QString &msg,bool result =true);
void handleDeleteResults(const QString &msg,bool result =true);
void handleEventInsertResults(const QString &msg,bool result =true);
void onErrMsg(const QString &msg);
void onStatus(const QString &msg);
void onTestStatus(const QString &msg);
void onAddTestRow(const QStringList &newRow);
signals:
void operate(
QStringList listpoint,
QString address,
QString pointType,
quint64 interval,
int deviatProb,
double normalBase,
double normalLength,
quint64 starttime,
quint64 endtime,
int deviatType,
bool isDeleteInterval,
bool isDeleteAll,
bool isMT);
void startTest(
int,int,int,QStringList,qint64,QString);
void deleteWork(QString address,QString pointType,QStringList listPoint,quint64 starttime,quint64 endtime,bool isDeleteAll);
void insertEvent(QStringList listFixedArgs,
QStringList listPoints,
QString content,quint64 starttime,quint64 endtime
);
private:
Ui::MainWindow *ui;
QThread workerThread;
};
#endif // MAINWINDOW_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,114 @@
#pragma once
#include <QtGlobal>
#include <QtCore>
#include "boost/uuid/random_generator.hpp"
#include "boost/regex.hpp"
#include <random>
// 随机生成一个大于 0 小于 10000 的浮点数
inline double generateRandomNumber() {
std::random_device rnd;
std::mt19937 gen(rnd());
std::uniform_real_distribution<> dist(0, 10000);
return dist(gen);
}
inline quint64 quaRand(){ return qrand() * qrand() * qrand();}
inline bool boolGen(int trueProb = 500){
if(trueProb == 0)
{
return false;
}
else if (trueProb == 1000)
{
return true;
}
int result = qrand() % 1000;
if( result < trueProb)
{
return true;
}
else
return false;
}
inline double doubleGen(double base,double length)
{
quint64 lengthx100k = length * 100000;
return base + (quaRand() % lengthx100k ) /100000.0;
}
#define DeviateMax 1000000
inline double doubleGenController(double base,double length,int deviatProb,int deviatType)
{
if( boolGen(deviatProb)){
// 偏离代码
if(deviatType == 0)
{
if(boolGen())
return doubleGen(0,base);
else
return doubleGen(base + length,DeviateMax - (base + length));
}else if(deviatType == -1)
{
return doubleGen(0,base);
}else if(deviatType == 1)
{
return doubleGen(base + length,DeviateMax);
}
else
{
return 0;
}
}else{
return doubleGen(base,length);
}
}
void generateUuidBase64(std::string &strOut)
{
boost::uuids::detail::random_provider randomGen;
boost::uint8_t baUuid[18];
boost::uint8_t baBase64[24];
//< 填充随机数
randomGen.get_random_bytes(&baUuid, 16);
//< 最后填充 0
baUuid[16] = 0;
baUuid[17] = 0;
//< 编码为 base64
{
static const char *szBase64Array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
boost::uint8_t *pData = baUuid;
int nDestIndex = 0;
for (int i = 0; i < 18; i = i + 3)
{
boost::uint32_t nData = ((boost::uint32_t) *pData << 16) +
((boost::uint32_t) *(pData + 1) << 8) + (*(pData + 2));
baBase64[nDestIndex] = szBase64Array[nData >> 18];
baBase64[nDestIndex + 1] = szBase64Array[nData >> 12 & (boost::uint32_t) 0x3f];
baBase64[nDestIndex + 2] = szBase64Array[nData >> 6 & (boost::uint32_t) 0x3f];
baBase64[nDestIndex + 3] = szBase64Array[nData & (boost::uint32_t) 0x3f];
pData = pData + 3;
nDestIndex = nDestIndex + 4;
}
baBase64[22] = 0;
baBase64[23] = 0;
}
//< 输出
strOut.assign((const char *) baBase64, 22);
strOut.shrink_to_fit();
}

View File

@ -0,0 +1,683 @@
#include "dataWorker.h"
#include "RandUtil.h"
#include <tsdb_api/CTsdbConn.h>
#include <tsdb_api/TsdbApi.h>
#include <QDebug>
#include <QElapsedTimer>
#include <QThread>
#include <QtConcurrent>
#include <functional>
#include "db_his_query_api/DbHisQueryApi.h"
enum EnTimeInterval
{
TI_NULL = 0, //< 无,不使用,
TI_DAY, //< 间隔为小时停止时间为24小时后
TI_WEEK, //< 间隔为天停止时间为7天后
TI_MONTH, //< 间隔为天停止时间为30天后
TI_YEAR, //< 间隔为30天停止时间为12个30天后
};
void getTimeInteval(EnTimeInterval emTI,const qint64& starttime,qint64& inteval,qint64 & endtime)
{
switch (emTI) {
case TI_DAY:
inteval = 3600l * 1000l;
endtime = starttime + (inteval * 24l);
break;
case TI_WEEK:
inteval = 24l * 3600l * 1000l;
endtime = starttime + (inteval * 7l);
break;
case TI_MONTH:
inteval = 24l * 3600l * 1000l;
endtime = starttime + (inteval * 30l);
break;
case TI_YEAR:
inteval = 30ll * 24ll * 3600000ll;
endtime = starttime + (inteval * 12ll);
break;
default:
break;
}
}
//< 通过 EnComputeMethod 获取查询的字符串
static QString getStrFromCM(iot_dbms::EnComputeMethod enCM)
{
switch (enCM)
{
case iot_dbms::CM_MAX:
return "最大值";
case iot_dbms::CM_MIN:
return "最小值";
case iot_dbms::CM_LAST:
return "瞬时值";
case iot_dbms::CM_MEAN:
return "平均值";
case iot_dbms::CM_NULL:
return "差值"; // TODO 这里用来临时用来占位差值
}
return "无方法";
}
//< 通过 EnComputeMethod 获取查询的字符串
static QString getStrFromTI(EnTimeInterval enTI)
{
switch (enTI)
{
case TI_DAY:
return "";
case TI_WEEK:
return "";
case TI_MONTH:
return "";
case TI_YEAR:
return "";
}
return "无时间";
}
const int RETRY_TIME = 10;
void dataWorker::doTest(int timeout, int base, int factor, QStringList listpoint, qint64 starttime, QString address)
{
QList<iot_dbms::EnComputeMethod> listCM;
listCM << iot_dbms::CM_NULL << iot_dbms::CM_MAX << iot_dbms::CM_MIN << iot_dbms::CM_LAST << iot_dbms::CM_MEAN;
QList<EnTimeInterval> listTI;
listTI << TI_DAY << TI_WEEK<< TI_MONTH<< TI_YEAR;
// listTI << TI_YEAR;
iot_dbms::CTsdbConn conn(address.toStdString().c_str());
if(!conn.pingServer())
{
emit testResultReady(tr("无法连接数据库"),false);
}
qint64 timeoutMs = timeout * 1000l;
// a lot of loop
// loop 1 listpoint size
for(size_t pointSize = base; pointSize < listpoint.size(); pointSize += factor){
QList<EnTimeInterval> ::const_iterator itTI;
// loop 2 time interval
for (itTI = listTI.constBegin(); itTI != listTI.constEnd(); ++itTI) {
qint64 inteval = 0,endtime = 0;
getTimeInteval(*itTI,starttime,inteval,endtime);
// loop 3 computeMethod
QList<iot_dbms::EnComputeMethod> ::const_iterator itCM;
// loop 2 time interval
for (itCM = listCM.constBegin(); itCM != listCM.constEnd(); ++itCM) {
// add listpoint
std::vector<iot_dbms::SMeasPointKey> vecMpKey;
std::vector<std::vector<iot_dbms::SVarHisValue> *> *vecResult = new std::vector<std::vector<iot_dbms::SVarHisValue> *>();
// 构造随机测点集合
QStringList testPoints;
{
std::vector<int> nums;
for (int i = 0; i < listpoint.size(); i++) {
nums.push_back(i);
}
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(nums.begin(), nums.end(), g);
std::vector<int> random_nums(nums.begin(), nums.begin() + pointSize);
for (int i : random_nums) {
testPoints << listpoint.at(i);
}
}
std::vector<boost::int64_t> vecTimeBegin,vecTimeEnd;
for(int i = 0; i < pointSize; i++)
{
for(boost::int64_t queryTime = starttime;queryTime < endtime;queryTime += inteval )
{
iot_dbms::SMeasPointKey key;
std::string tmp = testPoints[i].toStdString();
char * tag = (char*)malloc(tmp.size() + 1);
memset(tag, 0, tmp.size() + 1);
memcpy(tag, tmp.c_str(), tmp.size());
key.m_pszTagName = tag;
key.m_enType = iot_dbms::MPT_AI;
vecMpKey.push_back(key);
vecResult->push_back(new std::vector<iot_dbms::SVarHisValue>());
vecTimeBegin.push_back(queryTime);
vecTimeEnd.push_back(queryTime + inteval);
}
if( *itCM == iot_dbms::CM_NULL) // TODO NULL 临时占位差值计算 后面替换
{
iot_dbms::SMeasPointKey key;
std::string tmp = listpoint[i].toStdString();
char * tag = (char*)malloc(tmp.size() + 1);
memset(tag, 0, tmp.size() + 1);
memcpy(tag, tmp.c_str(), tmp.size());
key.m_pszTagName = tag;
key.m_enType = iot_dbms::MPT_AI;
vecMpKey.push_back(key);
vecResult->push_back(new std::vector<iot_dbms::SVarHisValue>());
vecTimeBegin.push_back(endtime);
vecTimeEnd.push_back(endtime + inteval);
}
}
// 开始查询
QElapsedTimer timer;
timer.start();
auto actualCM = *itCM;
if( *itCM == iot_dbms::CM_NULL) // TODO NULL 临时占位差值计算 后面替换
{
actualCM = iot_dbms::CM_LAST;
}
if(!iot_dbms::getHisValue(conn, timeoutMs, vecMpKey, &vecTimeBegin, &vecTimeEnd, NULL, NULL, actualCM, 0, iot_dbms::FM_NULL_METHOD, *vecResult))
{
QString testResult;
testResult = QString("超时--%1点,%2[起%5,止%6,间隔:%7s,结果共:%8],%3,共%4ms")
.arg(QString::number(pointSize))
.arg(getStrFromTI(*itTI))
.arg(getStrFromCM(*itCM))
.arg(QString::number(timer.elapsed() ))
.arg(QDateTime::fromMSecsSinceEpoch(starttime).toString("yyyyMMdd"))
.arg(QDateTime::fromMSecsSinceEpoch(endtime).toString("yyyyMMdd"))
.arg(inteval /1000)
.arg(QString::number(vecResult->size()))
;
QStringList listResult;
listResult << "超时";
listResult << QString::number(pointSize);
listResult << getStrFromTI(*itTI);
listResult << QDateTime::fromMSecsSinceEpoch(starttime).toString("yyyyMMdd");
listResult << QDateTime::fromMSecsSinceEpoch(endtime).toString("yyyyMMdd");
listResult << QString::number(inteval /1000);
listResult << QString::number(vecResult->size());
listResult << getStrFromCM(*itCM);
listResult << QString::number(timer.elapsed()) ;
emit onAddTestRow(listResult);
// emit onTestStatus(testResult);
emit testResultReady(tr("测试完毕"));
return;
}
if( *itCM == iot_dbms::CM_NULL)
{
for(int i = 1; i < vecResult->at(0)->size() ; i ++)
{
auto result = boost::get<boost::float64_t>(vecResult->at(0)->at(i).m_varValue) - boost::get<boost::float64_t>(vecResult->at(0)->at(i - 1).m_varValue);
}
}
QString testResult;
testResult = QString("完成:%1点,%2[起%5,止%6,间隔:%7s,结果共:%8],%3,共%4ms")
.arg(QString::number(pointSize))
.arg(getStrFromTI(*itTI))
.arg(getStrFromCM(*itCM))
.arg(QString::number(timer.elapsed()))
.arg(QDateTime::fromMSecsSinceEpoch(starttime).toString("yyyyMMdd"))
.arg(QDateTime::fromMSecsSinceEpoch(endtime).toString("yyyyMMdd"))
.arg(inteval /1000)
.arg(QString::number(vecResult->size()))
;
QStringList listResult;
listResult << "完成";
listResult << QString::number(pointSize);
listResult << getStrFromTI(*itTI);
listResult << QDateTime::fromMSecsSinceEpoch(starttime).toString("yyyyMMdd");
listResult << QDateTime::fromMSecsSinceEpoch(endtime).toString("yyyyMMdd");
listResult << QString::number(inteval /1000);
listResult << QString::number(vecResult->size());
listResult << getStrFromCM(*itCM);
listResult << QString::number(timer.elapsed()) ;
emit onAddTestRow(listResult);
// emit onTestStatus(testResult);
foreach(iot_dbms::SMeasPointKey key, vecMpKey)
{
free((char*)key.m_pszTagName);
}
std::vector<std::vector<iot_dbms::SVarHisValue> *>::iterator res = vecResult->begin();
while(vecResult->end() != res)
{
delete (*res);
++res;
}
vecResult->clear();
delete vecResult;
}
}
}
//
emit testResultReady("success");
}
void dataWorker::doWork(QStringList listPoint, QString address, QString pointType, quint64 interval, int deviatProb, double normalBase, double normalLength, quint64 starttime, quint64 endtime, int deviatType, bool isDeleteInterval, bool isDeleteAll, bool isMT)
{
// 删除
if(isDeleteAll || isDeleteInterval)
{
if(!deletePoint(address,pointType,listPoint,starttime,endtime,isDeleteAll))
{
emit resultReady(tr("删除测点失败"),false);
return;
}else{
}
}
// 插入
// 生成QString
bool result = false;
if(isMT)
{
result = getGenSqlAndInsertMT(listPoint,pointType,address,interval,deviatProb,normalBase,normalLength,starttime,endtime,deviatType);
}
else
{
result = getGenSqlAndInsertST(listPoint,pointType,address,interval,deviatProb,normalBase,normalLength,starttime,endtime,deviatType);
}
if(!result)
{
emit resultReady("插入失败",false);
return;
}
else{
emit resultReady("插入成功",true);
}
}
void dataWorker::doDel(QString address, QString pointType, QStringList listPoint, quint64 starttime, quint64 endtime, bool isDeleteAll)
{
if(!deletePoint(address,pointType,listPoint,starttime,endtime,isDeleteAll))
{
emit deleteResultReady(tr("删除测点失败"),false);
return;
}
emit deleteResultReady(tr("删除测点成功"),true);
}
void dataWorker::doInsertEvent(QStringList listFixedArgs, QStringList listPoints, QString content, quint64 starttime, quint64 endtime)
{
QFile file("outEvent.sql");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream out(&file);
//out << "The magic number is: " << 49 << "\n";
quint64 interval = listFixedArgs.at(8).toInt() * 1000;
QString sqltext;
// 第一层测点循环
for(int pointIdx = 0; pointIdx < listPoints.size(); pointIdx += 1){
emit onStatus( QString("正在插入点%1(%2/%3)").arg( listPoints.at(pointIdx) ).arg(pointIdx + 1).arg(listPoints.size()) );
QString tag_name = listPoints.at(pointIdx);
QString key_id_tag = "digital." + tag_name + ".value";
QString contentToFilled = content;
contentToFilled = contentToFilled.replace("[tag_name]",tag_name);
QString dev_group_tag = tag_name.split('.')[0] % QChar('.') % tag_name.split('.')[1].split('_')[0];
QString arg0 = listFixedArgs[0];
QString arg1 = listFixedArgs[1];
QString arg2 = listFixedArgs[2];
QString arg3 = listFixedArgs[3];
QString arg4 = listFixedArgs[4];
QString arg5 = listFixedArgs[5];
QString arg6 = listFixedArgs[6];
QString arg7 = listFixedArgs[7];
// 第二层时间循环
for(quint64 timestamp = starttime; timestamp < endtime; timestamp += interval )
{
std::string uuid;
generateUuidBase64(uuid);
//insert into HIS_EVENT (UUID_BASE64,ALM_TYPE,ALM_STATUS
//,ALM_STYLE,TIME_STAMP,LOCATION_ID,CONTENT,PRIORITY,
//SUB_SYSTEM,DEV_TYPE,REGION_ID,DEV_GROUP_TAG,KEY_ID_TAG,
//CONFIRM_TIME,CONFIRM_USER_ID,CONFIRM_NODE_NAME,
//WAVE_FILE,IA_UUID) values ('B0P7XbDw7mACiqFAnT36YU'
//,3,201,0,1663027300645,1,'dev3 yx34 中断',2,4,7,1,'occ.dev3',
//'digital.occ.dev3_ht100.yx34.value',0,0,'','','B0Pp6cIUMGw+bZBtbMy5JU');
out << "insert into HIS_EVENT (UUID_BASE64,ALM_TYPE,ALM_STATUS"
",ALM_STYLE,TIME_STAMP,LOCATION_ID,CONTENT,PRIORITY"
",SUB_SYSTEM,DEV_TYPE,REGION_ID,DEV_GROUP_TAG"
",KEY_ID_TAG,CONFIRM_TIME,CONFIRM_USER_ID"
",CONFIRM_NODE_NAME,WAVE_FILE,IA_UUID) values ("
% QChar('\'') % uuid.c_str() % QString("',")
% arg0 % ","
% arg1 % ","
% arg2 % ","
% QString::number( timestamp ) % ","
% arg3 % ","
% QChar('\'') % contentToFilled % QString("',")
% arg4 % ","
% arg5 % ","
% arg6 % ","
% arg7 % ","
% QChar('\'') % dev_group_tag % QString("',")
% QChar('\'') % key_id_tag % QString("',")
% QStringLiteral("0,0,'','','');\n");
}
}
//out << "The magic number is: " << 49 << "\n";
// 两层循环,一层测点循环 一层时间循环
//qDebug() << uuid.c_str() << listFixedArgs << listPoints << content << starttime << endtime << interval;
emit InsertEventResultReady("nice",true);
}
bool dataWorker::insertHisDataWithRetry(iot_dbms::CTsdbConn &conn, const QString &insertSqlTxt)
{
int retryTime = RETRY_TIME;
while(retryTime > 0 )
{
if(retryTime <= RETRY_TIME -1)
{
QThread::msleep(500);
}
if(!conn.doInsert(insertSqlTxt.toStdString().c_str())){
retryTime -= 1;
continue;
}
break;
}
if(retryTime <= 0)
{
return false;
}
return true;
}
bool dataWorker::getGenSqlAndInsertMT(QStringList listpoint, QString pointType, QString address, quint64 interval, int deviatProb, double normalBase, double normalLength, quint64 starttime, quint64 endtime, int deviatType)
{
QElapsedTimer timer;
timer.start();
QList<STaskUnit> taskList;
m_strTimestamp.clear();
int totalCalc = ((endtime - starttime) / interval ) + 1;
m_strTimestamp.reserve(totalCalc);
for(quint64 timestamp = starttime; timestamp < endtime; timestamp += interval)
{
m_strTimestamp.append(QString::number(timestamp));
}
for(int pointIdx = 0; pointIdx < listpoint.size(); pointIdx += 1){
STaskUnit task;
task.pointtag = listpoint.at(pointIdx);
task.pointtype = pointType;
task.address = address;
task.deviatProb = deviatProb;
task.normalBase = normalBase;
task.normalLength = normalLength;
task.deviatType = deviatType;
taskList << task;
}
m_ft = QtConcurrent::mapped(taskList
,std::bind(&dataWorker::getGenSqlAndInsertSingleTask,this,std::placeholders::_1));
while(true)
{
if( m_ft.isFinished())
{
break;
}
int progress = m_ft.progressValue();
if(progress > 0)
{
emit onStatus( QString("已完成插入测点(%1/%2),平均耗时:%3 s")
.arg( progress)
.arg( listpoint.size() )
.arg( (timer.elapsed() / 1000.0) / progress )
);
}
else
{
emit onStatus( QString("已完成插入测点(%1/%2)")
.arg( progress)
.arg( listpoint.size() )
);
}
QThread::msleep(500);
}
if( m_ft.resultCount() != taskList.size())
{
return false;
}
return true;
}
bool dataWorker::getGenSqlAndInsertST(QStringList listpoint, QString pointType, QString address, quint64 interval, int deviatProb, double normalBase, double normalLength, quint64 starttime, quint64 endtime, int deviatType)
{
QElapsedTimer timer;
timer.start();
bool isDi = false;
if( pointType == "di_sample_result" )
{
isDi = true;
}
iot_dbms::CTsdbConn conn(address.toStdString().c_str());
if(!conn.pingServer())
{
emit onErrMsg(tr("无法连接数据库"));
qDebug() << "无法连接数据库";
return false;
}
QString insertSqlTxt;
insertSqlTxt.reserve( 100000000 );
// 第一层测点循环
for(int pointIdx = 0; pointIdx < listpoint.size(); pointIdx += 1){
QString pointHeader = pointType % QStringLiteral(",tag_name=") % listpoint.at(pointIdx) % QStringLiteral(" status=2i,value=");
// 第二层时间循环
long long totalCalc = ((endtime - starttime) / interval ) + 1;
int sqlCnt = 0;
long totalCnt = 0;
for(quint64 timestamp = starttime; timestamp < endtime; timestamp += interval)
{
if(isDi){
insertSqlTxt.append( pointHeader %
(boolGen(deviatProb) ? QStringLiteral("1i ") : QStringLiteral("0i ") )
% QString::number(timestamp) % "\n" );
}else{
insertSqlTxt += pointHeader;
insertSqlTxt += QString::number( doubleGenController(normalBase,normalLength,deviatProb,deviatType) );
insertSqlTxt += QStringLiteral(" ");
insertSqlTxt += QString::number(timestamp);
insertSqlTxt += QStringLiteral("\n");
}
totalCnt += 1;
if( ++sqlCnt >= 10000 || insertSqlTxt.size() >= 950000 )
{
sqlCnt = 0;
if(!insertHisDataWithRetry(conn,insertSqlTxt))
{
return false;
}
insertSqlTxt.clear();
}
// qDebug() << insertSqlTxt.size();
}
if(pointIdx > 0)
{
emit onStatus( QString("已完成插入测点(%1/%2),平均耗时:%3 s")
.arg( pointIdx)
.arg( listpoint.size() )
.arg( (timer.elapsed() / 1000.0) / pointIdx )
);
}
else
{
emit onStatus( QString("已完成插入测点(%1/%2),耗时:%3 s")
.arg( pointIdx)
.arg( listpoint.size() )
.arg( (timer.elapsed() / 1000.0) )
);
}
}
// 剩余sql语句插入
if(!insertHisDataWithRetry(conn,insertSqlTxt))
{
return false;
}
return true;
}
bool dataWorker::getGenSqlAndInsertSingleTask(dataWorker::STaskUnit task)
{
QString insertSqlTxt;
insertSqlTxt.reserve( 400000 );
bool isDi = false;
if( task.pointtype == "di_sample_result" )
{
isDi = true;
}
iot_dbms::CTsdbConn conn(task.address.toStdString().c_str());
QString pointHeader = task.pointtype % QStringLiteral(",tag_name=") % task.pointtag % QStringLiteral(" status=2i,value=");
// 第二层时间循环
int sqlCnt = 0,totalCnt = 0;
QVector<QString>::const_iterator it;
for (it = m_strTimestamp.constBegin(); it != m_strTimestamp.constEnd(); ++it) {
if(isDi){
insertSqlTxt += pointHeader;
insertSqlTxt += (boolGen(task.deviatProb) ? QStringLiteral("1i ") : QStringLiteral("0i ") );
insertSqlTxt += *it;
insertSqlTxt += "\n";
}else{
insertSqlTxt += pointHeader;
insertSqlTxt += QString::number( doubleGenController(task.normalBase,task.normalLength,task.deviatProb,task.deviatType) );
insertSqlTxt += QStringLiteral(" ");
insertSqlTxt += *it;
insertSqlTxt += QStringLiteral("\n");
}
totalCnt++;
// sql语句大于10000句时
if( ++sqlCnt >= 5000 || m_strTimestamp.size() == totalCnt)
{
sqlCnt = 0;
if(!insertHisDataWithRetry(conn,insertSqlTxt))
{
m_ft.cancel();
return false;
}
insertSqlTxt.clear();
}
}
return true;
}
bool dataWorker::deletePoint(QString address, QString pointType, QStringList listPoint, quint64 starttime, quint64 endtime, bool isDeleteAll)
{
using namespace iot_dbms;
CTsdbConn conn(address.toStdString().c_str());
if(!conn.pingServer())
{
emit onErrMsg(tr("无法连接数据库"));
return false;
}
// 获得删除语句
qDebug()<< "start delete";
{
// 第一层测点循环
for(int pointIdx = 0; pointIdx < listPoint.size(); pointIdx += 1){
emit onStatus( QString("正在删除点%1(%2/%3)").arg(listPoint.at(pointIdx)).arg(pointIdx + 1).arg(listPoint.size()) );
QString singlePoint;
singlePoint += "delete from " + pointType;
singlePoint += " where tag_name='" + listPoint.at(pointIdx);
if( !isDeleteAll ) {
singlePoint += "' and time >= " + QString::number(starttime);
singlePoint += "ms and time < " + QString::number(endtime) + "ms;";
}else{
singlePoint += "';";
}
qDebug() << singlePoint;
//emit onStatus( QString("正在执行删除语句到数据库") );
int retryTime = RETRY_TIME;
while(retryTime > 0 )
{
if(retryTime <= RETRY_TIME - 1)
{
QThread::msleep(500);
}
std::string result;
if(!conn.doQuery(singlePoint.toStdString().c_str(),&result)){
retryTime -= 1;
continue;
}
if( result.find("error") != std::string::npos){ // 找到eror则错误
retryTime -= 1;
continue;
}
break;
}
if(retryTime <= 0)
{
onErrMsg( QString("无法删除测点%1").arg(listPoint.at(pointIdx)) );
return false;
}
}
}
return true;
}

View File

@ -0,0 +1,95 @@
#ifndef DATAWORKER_H
#define DATAWORKER_H
#include <QObject>
#include <QFuture>
#include <tsdb_api/CTsdbConn.h>
class dataWorker : public QObject
{
Q_OBJECT
typedef struct taskUnit
{
QString pointtag;
QString pointtype;
QString address;
int deviatProb;
double normalBase;
double normalLength;
int deviatType;
} STaskUnit;
public slots:
void doTest(
int timeout,
int base,
int factor,
QStringList listpoint,
qint64 starttime,
QString address);
void doWork(
QStringList listPoint,
QString address,
QString pointType,
quint64 interval,
int deviatProb,
double normalBase,
double normalLength,
quint64 starttime,
quint64 endtime,
int deviatType,
bool isDeleteInterval,
bool isDeleteAll,
bool isMT);
void doDel(QString address,QString pointType,QStringList listPoint,quint64 starttime,quint64 endtime,bool isDeleteAll);
void doInsertEvent(QStringList listFixedArgs,
QStringList listPoints,
QString content,
quint64 starttime,quint64 endtime);
bool insertHisDataWithRetry(iot_dbms::CTsdbConn& conn, const QString &insertSqlTxt);
signals:
void resultReady(const QString &msg,bool result =true);
void testResultReady(const QString &msg,bool result =true);
void deleteResultReady(const QString &msg,bool result =true);
void InsertEventResultReady(const QString &msg,bool result =true);
void onErrMsg(const QString &msg);
void onStatus(const QString &msg);
void onTestStatus(const QString &msg);
void onAddTestRow(const QStringList &newRow);
private:
bool getGenSqlAndInsertMT(QStringList listpoint,
QString pointType,
QString address,
quint64 interval,
int deviatProb,
double normalBase,
double normalLength,
quint64 starttime,
quint64 endtime,
int deviatType);
bool getGenSqlAndInsertST(QStringList listpoint,
QString pointType,
QString address,
quint64 interval,
int deviatProb,
double normalBase,
double normalLength,
quint64 starttime,
quint64 endtime,
int deviatType);
bool getGenSqlAndInsertSingleTask(STaskUnit task);
bool deletePoint(QString address,QString pointType,QStringList listPoint,quint64 starttime,quint64 endtime,bool isDeleteAll);
QFuture<bool> m_ft;
QVector<QString> m_strTimestamp;
};
#endif // DATAWORKER_H

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

@ -0,0 +1,18 @@
#include "MainWindow.h"
#include <QApplication>
#include "tsdb_api/TsdbApi.h"
#include "pub_logger_api/logger.h"
int main(int argc, char *argv[])
{
using namespace iot_dbms;
initTsdbApi();
iot_public::StartLogSystem("TEST","tsdbDataSim");
QApplication a(argc, argv);
MainWindow w;
w.show();
int result = a.exec();
releaseTsdbApi();
return result;
}

View File

@ -0,0 +1,56 @@
#-------------------------------------------------
#
# Project created by QtCreator 2021-04-07T16:28:26
#
#-------------------------------------------------
QT += core gui concurrent
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = tsdbDataSim
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
MainWindow.cpp \
dataWorker.cpp
HEADERS += \
MainWindow.h \
RandUtil.h \
dataWorker.h
FORMS += \
MainWindow.ui
LIBS += -ltsdb_api -ldb_base_api -ldb_his_query_api -lboost_system -llog4cplus \
-lpub_logger_api
win32:RC_ICONS += download.ico
win32{
LIBS += -lbcrypt
}
#-------------------------------------------------------------------
COMMON_PRI=$$PWD/../../common.pri
exists($$COMMON_PRI) {
include($$COMMON_PRI)
}else {
error("FATAL error: can not find common.pri")
}

View File

@ -0,0 +1,254 @@
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDebug>
#include <QMessageBox>
#include <tsdb_api/CTsdbConn.h>
#include <tsdb_api/TsdbApi.h>
#include "dataWorker.h"
using namespace iot_dbms;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
dataWorker *worker = new dataWorker;
worker->moveToThread(&workerThread);
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
connect(this, &MainWindow::operate, worker, &dataWorker::doWork);
connect(worker, &dataWorker::resultReady, this, &MainWindow::handleResults);
connect(this, &MainWindow::insertEvent, worker, &dataWorker::doInsertEvent);
connect(worker, &dataWorker::InsertEventResultReady, this, &MainWindow::handleEventInsertResults);
connect(this, &MainWindow::deleteWork, worker, &dataWorker::doDel);
connect(worker, &dataWorker::deleteResultReady, this, &MainWindow::handleDeleteResults);
connect(worker, &dataWorker::onErrMsg, this, &MainWindow::onErrMsg);
connect(worker, &dataWorker::onStatus, this, &MainWindow::onStatus);
workerThread.start();
ui->label_status->setHidden(true);
}
MainWindow::~MainWindow()
{
workerThread.quit();
workerThread.wait();
delete ui;
}
QString MainWindow::getPointType()
{
if( ui->comboBox_type->currentText() == tr("模拟量")){
return QString("ANALOG");
}else if( ui->comboBox_type->currentText() == tr("累积量")){
return QString("ACCRUE");
}else
return "";
}
int MainWindow::getDeviatType()
{
if (ui->comboBox_deviatType->currentText() == tr("左边")){
return -1;
}else if (ui->comboBox_deviatType->currentText() == tr("两边")){
return 0;
}else {
return 1;
}
}
void MainWindow::on_pushButton_insert_clicked()
{
if(QMessageBox::question(this,"提醒","是否插入") != QMessageBox::Yes)
{
return;
}
QString address = ui->lineEdit_addr->text();
QStringList listPoint = ui->plainTextEdit_point->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
QString pointType = getPointType();
quint64 interval = ui->spinBox_interval->value() * 1000; //ms
int deviatProb = ui->spinBox_deviatProb->value();
double normalBase = ui->doubleSpinBox_base->value();
double normalLength = ui->doubleSpinBox_length->value();
quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
int deviatType = getDeviatType();
bool isDeleteInterval = ui->checkBox_delete->isChecked();
bool isDeleteAll = ui->checkBox_delAll->isChecked();
emit operate(listPoint,address,pointType,interval,deviatProb,normalBase,normalLength,starttime,endtime,deviatType,isDeleteInterval,isDeleteAll);
ui->pushButton_insert->setEnabled(false);
ui->pushButton_delete->setEnabled(false);
ui->label_status->setHidden(false);
}
void MainWindow::onErrMsg(const QString &msg)
{
QMessageBox::critical(this,"提醒",msg);
}
void MainWindow::onStatus(const QString &msg)
{
ui->label_status->setText(msg);
}
void MainWindow::on_comboBox_type_currentTextChanged(const QString &arg1)
{
if("数字量" == arg1)
{
ui->groupBox->setHidden(true);
}
else
{
ui->groupBox->setHidden(false);
}
}
void MainWindow::handleResults(const QString &msg, bool result) {
ui->label_status->setHidden(true);
if(result)
{
QMessageBox::information(this,"提醒","插入成功");
}
else
{
onErrMsg(QString("插入失败:") + msg);
}
ui->pushButton_insert->setEnabled(true);
ui->pushButton_delete->setEnabled(true);
}
void MainWindow::handleDeleteResults(const QString &msg, bool result)
{
ui->label_status->setHidden(true);
if(result)
{
QMessageBox::information(this,"提醒","删除成功");
}
else
{
onErrMsg(QString("删除失败:") + msg);
}
ui->pushButton_insert->setEnabled(true);
ui->pushButton_delete->setEnabled(true);
}
void MainWindow::handleEventInsertResults(const QString &msg, bool result)
{
if(result)
{
QMessageBox::information(this,"提醒","生成数据库文件已放至同目录outEvent.sql");
}
else
{
onErrMsg(QString("插入失败:") + msg);
}
}
void MainWindow::on_pushButton_delete_clicked()
{
if(QMessageBox::question(this,"提醒","是否删除") != QMessageBox::Yes)
{
return;
}
QString address = ui->lineEdit_addr->text();
QStringList listPoint = ui->plainTextEdit_point->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
QString pointType = getPointType();
quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
bool isDeleteAll = ui->checkBox_delAll->isChecked();
emit deleteWork(address,pointType,listPoint,starttime,endtime,isDeleteAll);
ui->pushButton_insert->setEnabled(false);
ui->pushButton_delete->setEnabled(false);
ui->label_status->setHidden(false);
}
void MainWindow::on_pushButton_insert_event_clicked()
{
if(QMessageBox::question(this,"提醒","是否插入历史数据") != QMessageBox::Yes)
{
return;
}
QStringList listPoint = ui->plainTextEdit_point_event->toPlainText().simplified().split(',');
listPoint.removeAll("");
for(int i = 0; i < listPoint.size(); i++)
{
listPoint[i] = listPoint[i].trimmed();
}
quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
emit insertEvent(
QStringList()
<< QString::number( ui->spinBox_alm_type->value() ) // 0
<< QString::number( ui->spinBox_alm_status->value() ) // 1
<< QString::number( ui->spinBox_alm_style->value() ) // 2
<< QString::number( ui->spinBox_location_id->value() ) // 3
<< QString::number( ui->spinBox_priority->value() ) // 4
<< QString::number( ui->spinBox_sub_system->value() ) // 5
<< QString::number( ui->spinBox_dev_type->value() ) //6
<< QString::number( ui->spinBox_region_id->value() ) // 7
<< QString::number( ui->spinBox_interval_event->value() ) // 8
,
listPoint,ui->lineEdit_content->text(),starttime,endtime);
// QString address = ui->lineEdit_addr->text();
// QStringList listPoint = ui->plainTextEdit_point->toPlainText().simplified().split(',');
// listPoint.removeAll("");
// for(int i = 0; i < listPoint.size(); i++)
// {
// listPoint[i] = listPoint[i].trimmed();
// }
// QString pointType = getPointType();
// quint64 starttime = QDateTime(ui->calendarWidget_startDate->selectedDate(),ui->timeEdit_start->time()).toMSecsSinceEpoch();
// quint64 endtime = QDateTime(ui->calendarWidget_endDate->selectedDate(),ui->timeEdit_end->time()).toMSecsSinceEpoch(); // 结束日期加一天
// bool isDeleteAll = ui->checkBox_delAll->isChecked();
// emit deleteWork(address,pointType,listPoint,starttime,endtime,isDeleteAll);
// ui->pushButton_insert->setEnabled(false);
// ui->pushButton_delete->setEnabled(false);
// ui->label_status->setHidden(false);
}
void MainWindow::on_pushButton_delete_event_clicked()
{
onErrMsg(tr("该功能未实现"));
}

View File

@ -0,0 +1,71 @@
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
QString getPointType();
int getDeviatType();
void on_pushButton_insert_clicked();
void on_comboBox_type_currentTextChanged(const QString &arg1);
void on_pushButton_delete_clicked();
void on_pushButton_insert_event_clicked();
void on_pushButton_delete_event_clicked();
public slots:
void handleResults(const QString &msg,bool result =true);
void handleDeleteResults(const QString &msg,bool result =true);
void handleEventInsertResults(const QString &msg,bool result =true);
void onErrMsg(const QString &msg);
void onStatus(const QString &msg);
signals:
void operate(
QStringList listpoint,
QString address,
QString pointType,
quint64 interval,
int deviatProb,
double normalBase,
double normalLength,
quint64 starttime,
quint64 endtime,
int deviatType,
bool isDeleteInterval,
bool isDeleteAll);
void deleteWork(QString address,QString pointType,QStringList listPoint,quint64 starttime,quint64 endtime,bool isDeleteAll);
void insertEvent(QStringList listFixedArgs,
QStringList listPoints,
QString content,quint64 starttime,quint64 endtime
);
private:
Ui::MainWindow *ui;
QThread workerThread;
};
#endif // MAINWINDOW_H

Some files were not shown because too many files have changed in this diff Show More