db: Adjust the query methods to accept std::strings

This commit is contained in:
Peter Keresztes Schmidt 2021-07-01 09:16:26 +02:00
parent c60b577aec
commit 65656de6ce
14 changed files with 62 additions and 67 deletions

View File

@ -75,7 +75,7 @@ void zmLoadDBConfig() {
std::string sql = stringtf("SELECT `Id` FROM `Servers` WHERE `Name`='%s'",
staticConfig.SERVER_NAME.c_str());
zmDbRow dbrow;
if (dbrow.fetch(sql.c_str())) {
if (dbrow.fetch(sql)) {
staticConfig.SERVER_ID = atoi(dbrow[0]);
} else {
Fatal("Can't get ServerId for Server %s", staticConfig.SERVER_NAME.c_str());
@ -87,7 +87,7 @@ void zmLoadDBConfig() {
std::string sql = stringtf("SELECT `Name` FROM `Servers` WHERE `Id`='%d'", staticConfig.SERVER_ID);
zmDbRow dbrow;
if (dbrow.fetch(sql.c_str())) {
if (dbrow.fetch(sql)) {
staticConfig.SERVER_NAME = std::string(dbrow[0]);
} else {
Fatal("Can't get ServerName for Server ID %d", staticConfig.SERVER_ID);

View File

@ -38,8 +38,6 @@
#define ZM_SCALE_BASE 100 // The factor by which we bump up 'scale' to simulate FP
#define ZM_RATE_BASE 100 // The factor by which we bump up 'rate' to simulate FP
#define ZM_SQL_MED_BUFSIZ 1024 // Size of SQL buffer
#define ZM_NETWORK_BUFSIZ 32768 // Size of network buffer
#define ZM_MAX_FPS 30 // The maximum frame rate we expect to handle

View File

@ -117,25 +117,25 @@ void zmDbClose() {
}
}
MYSQL_RES * zmDbFetch(const char * query) {
MYSQL_RES *zmDbFetch(const std::string &query) {
std::lock_guard<std::mutex> lck(db_mutex);
if (!zmDbConnected) {
Error("Not connected.");
return nullptr;
}
if (mysql_query(&dbconn, query)) {
if (mysql_query(&dbconn, query.c_str())) {
Error("Can't run query: %s", mysql_error(&dbconn));
return nullptr;
}
MYSQL_RES *result = mysql_store_result(&dbconn);
if (!result) {
Error("Can't use query result: %s for query %s", mysql_error(&dbconn), query);
Error("Can't use query result: %s for query %s", mysql_error(&dbconn), query.c_str());
}
return result;
} // end MYSQL_RES * zmDbFetch(const char * query);
}
zmDbRow *zmDbFetchOne(const char *query) {
zmDbRow *zmDbFetchOne(const std::string &query) {
zmDbRow *row = new zmDbRow();
if (row->fetch(query)) {
return row;
@ -144,13 +144,13 @@ zmDbRow *zmDbFetchOne(const char *query) {
return nullptr;
}
MYSQL_RES *zmDbRow::fetch(const char *query) {
MYSQL_RES *zmDbRow::fetch(const std::string &query) {
result_set = zmDbFetch(query);
if (!result_set) return result_set;
int n_rows = mysql_num_rows(result_set);
if (n_rows != 1) {
Error("Bogus number of lines return from query, %d returned for query %s.", n_rows, query);
Error("Bogus number of lines return from query, %d returned for query %s.", n_rows, query.c_str());
mysql_free_result(result_set);
result_set = nullptr;
return result_set;
@ -160,23 +160,23 @@ MYSQL_RES *zmDbRow::fetch(const char *query) {
if (!row) {
mysql_free_result(result_set);
result_set = nullptr;
Error("Error getting row from query %s. Error is %s", query, mysql_error(&dbconn));
Error("Error getting row from query %s. Error is %s", query.c_str(), mysql_error(&dbconn));
} else {
Debug(5, "Success");
}
return result_set;
}
int zmDbDo(const char *query) {
int zmDbDo(const std::string &query) {
std::lock_guard<std::mutex> lck(db_mutex);
if (!zmDbConnected)
return 0;
int rc;
while ((rc = mysql_query(&dbconn, query)) and !zm_terminate) {
while ((rc = mysql_query(&dbconn, query.c_str())) and !zm_terminate) {
Logger *logger = Logger::fetch();
Logger::Level oldLevel = logger->databaseLevel();
logger->databaseLevel(Logger::NOLOG);
Error("Can't run query %s: %s", query, mysql_error(&dbconn));
Error("Can't run query %s: %s", query.c_str(), mysql_error(&dbconn));
logger->databaseLevel(oldLevel);
if ( (mysql_errno(&dbconn) != ER_LOCK_WAIT_TIMEOUT) ) {
return rc;
@ -186,36 +186,36 @@ int zmDbDo(const char *query) {
Logger::Level oldLevel = logger->databaseLevel();
logger->databaseLevel(Logger::NOLOG);
Debug(1, "Success running sql query %s", query);
Debug(1, "Success running sql query %s", query.c_str());
logger->databaseLevel(oldLevel);
return 1;
}
int zmDbDoInsert(const char *query) {
int zmDbDoInsert(const std::string &query) {
std::lock_guard<std::mutex> lck(db_mutex);
if (!zmDbConnected) return 0;
int rc;
while ( (rc = mysql_query(&dbconn, query)) and !zm_terminate) {
Error("Can't run query %s: %s", query, mysql_error(&dbconn));
while ( (rc = mysql_query(&dbconn, query.c_str())) and !zm_terminate) {
Error("Can't run query %s: %s", query.c_str(), mysql_error(&dbconn));
if ( (mysql_errno(&dbconn) != ER_LOCK_WAIT_TIMEOUT) )
return 0;
}
int id = mysql_insert_id(&dbconn);
Debug(2, "Success running sql insert %s. Resulting id is %d", query, id);
Debug(2, "Success running sql insert %s. Resulting id is %d", query.c_str(), id);
return id;
}
int zmDbDoUpdate(const char *query) {
int zmDbDoUpdate(const std::string &query) {
std::lock_guard<std::mutex> lck(db_mutex);
if (!zmDbConnected) return 0;
int rc;
while ( (rc = mysql_query(&dbconn, query)) and !zm_terminate) {
Error("Can't run query %s: %s", query, mysql_error(&dbconn));
while ( (rc = mysql_query(&dbconn, query.c_str())) and !zm_terminate) {
Error("Can't run query %s: %s", query.c_str(), mysql_error(&dbconn));
if ( (mysql_errno(&dbconn) != ER_LOCK_WAIT_TIMEOUT) )
return -rc;
}
int affected = mysql_affected_rows(&dbconn);
Debug(2, "Success running sql update %s. Rows modified %d", query, affected);
Debug(2, "Success running sql update %s. Rows modified %d", query.c_str(), affected);
return affected;
}
@ -255,7 +255,7 @@ void zmDbQueue::process() {
// My idea for leaving the locking around each sql statement is to allow
// other db writers to get a chance
lock.unlock();
zmDbDo(sql.c_str());
zmDbDo(sql);
lock.lock();
}
}

View File

@ -38,7 +38,6 @@ class zmDbQueue {
public:
zmDbQueue();
~zmDbQueue();
void push(const char *sql) { return push(std::string(sql)); };
void push(std::string &&sql);
void process();
void stop();
@ -50,7 +49,7 @@ class zmDbRow {
MYSQL_ROW row;
public:
zmDbRow() : result_set(nullptr), row(nullptr) { };
MYSQL_RES *fetch(const char *query);
MYSQL_RES *fetch(const std::string &query);
zmDbRow(MYSQL_RES *, MYSQL_ROW *row);
~zmDbRow();
@ -67,16 +66,14 @@ extern zmDbQueue dbQueue;
extern bool zmDbConnected;
extern bool zmDbConnected;
bool zmDbConnect();
void zmDbClose();
int zmDbDo(const char *query);
int zmDbDoInsert(const char *query);
int zmDbDoUpdate(const char *query);
int zmDbDo(const std::string &query);
int zmDbDoInsert(const std::string &query);
int zmDbDoUpdate(const std::string &query);
MYSQL_RES * zmDbFetch(const char *query);
zmDbRow *zmDbFetchOne(const char *query);
MYSQL_RES * zmDbFetch(const std::string &query);
zmDbRow *zmDbFetchOne(const std::string &query);
std::string zmDbEscapeString(const std::string& to_escape);

View File

@ -125,7 +125,7 @@ Event::Event(
storage->SchemeString().c_str()
);
id = zmDbDoInsert(sql.c_str());
id = zmDbDoInsert(sql);
if ( !SetPath(storage) ) {
// Try another
@ -138,7 +138,7 @@ Event::Event(
Debug(1, "%s", sql.c_str());
storage = nullptr;
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if ( result ) {
for ( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row(result); i++ ) {
storage = new Storage(atoi(dbrow[0]));
@ -157,7 +157,7 @@ Event::Event(
if ( monitor->ServerId() )
sql += stringtf(" OR ServerId != %u", monitor->ServerId());
result = zmDbFetch(sql.c_str());
result = zmDbFetch(sql);
if ( result ) {
for ( int i = 0; MYSQL_ROW dbrow = mysql_fetch_row(result); i++ ) {
storage = new Storage(atoi(dbrow[0]));
@ -175,7 +175,7 @@ Event::Event(
Warning("Failed to find a storage area to save events.");
}
sql = stringtf("UPDATE Events SET StorageId = '%d' WHERE Id=%" PRIu64, storage->Id(), id);
zmDbDo(sql.c_str());
zmDbDo(sql);
} // end if ! setPath(Storage)
Debug(1, "Using storage area at %s", path.c_str());
@ -211,11 +211,11 @@ Event::Event(
if ( ! ( save_jpegs & 1 ) ) {
save_jpegs |= 1; // Turn on jpeg storage
sql = stringtf("UPDATE Events SET SaveJpegs=%d WHERE Id=%" PRIu64, save_jpegs, id);
zmDbDo(sql.c_str());
zmDbDo(sql);
}
} else {
sql = stringtf("UPDATE Events SET Videoed=1, DefaultVideo = '%s' WHERE Id=%" PRIu64, video_name.c_str(), id);
zmDbDo(sql.c_str());
zmDbDo(sql);
}
} // end if GetOptVideoWriter
}
@ -253,7 +253,7 @@ Event::~Event() {
tot_score, static_cast<uint32>(alarm_frames ? (tot_score / alarm_frames) : 0), max_score,
id);
if (!zmDbDoUpdate(sql.c_str())) {
if (!zmDbDoUpdate(sql)) {
// Name might have been changed during recording, so just do the update without changing the name.
sql = stringtf(
"UPDATE Events SET EndDateTime = from_unixtime(%ld), Length = %.2f, Frames = %d, AlarmFrames = %d, TotScore = %d, AvgScore = %d, MaxScore = %d WHERE Id = %" PRIu64,
@ -262,7 +262,7 @@ Event::~Event() {
frames, alarm_frames,
tot_score, static_cast<uint32>(alarm_frames ? (tot_score / alarm_frames) : 0), max_score,
id);
zmDbDoUpdate(sql.c_str());
zmDbDoUpdate(sql);
} // end if no changed rows due to Name change during recording
} // Event::~Event()
@ -425,7 +425,7 @@ void Event::WriteDbFrames() {
} // end while frames
// The -1 is for the extra , added for values above
frame_insert_sql.erase(frame_insert_sql.size()-1);
//zmDbDo(frame_insert_sql.c_str());
//zmDbDo(frame_insert_sql);
dbQueue.push(std::move(frame_insert_sql));
if (stats_insert_sql.size() > 208) {
// The -1 is for the extra , added for values above

View File

@ -46,7 +46,7 @@ bool EventStream::loadInitialEventData(int monitor_id, SystemTimePoint event_tim
"`MonitorId` = %d AND unix_timestamp(`EndDateTime`) > %ld "
"ORDER BY `Id` ASC LIMIT 1", monitor_id, event_time);
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result)
exit(-1);
@ -117,7 +117,7 @@ bool EventStream::loadEventData(uint64_t event_id) {
"(SELECT max(`Delta`)-min(`Delta`) FROM `Frames` WHERE `EventId`=`Events`.`Id`) AS FramesDuration, "
"`DefaultVideo`, `Scheme`, `SaveJPEGs`, `Orientation`+0 FROM `Events` WHERE `Id` = %" PRIu64, event_id);
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
exit(-1);
}
@ -229,7 +229,7 @@ bool EventStream::loadEventData(uint64_t event_id) {
sql = stringtf("SELECT `FrameId`, unix_timestamp(`TimeStamp`), `Delta` "
"FROM `Frames` WHERE `EventId` = %" PRIu64 " ORDER BY `FrameId` ASC", event_id);
result = zmDbFetch(sql.c_str());
result = zmDbFetch(sql);
if (!result) {
exit(-1);
}
@ -640,7 +640,7 @@ bool EventStream::checkEventLoaded() {
if ( forceEventChange || ( (mode != MODE_SINGLE) && (mode != MODE_NONE) ) ) {
Debug(1, "Checking for next event %s", sql.c_str());
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
exit(-1);
}

View File

@ -46,7 +46,7 @@ Group::Group(unsigned int p_id) {
std::string sql = stringtf("SELECT `Id`, `ParentId`, `Name` FROM `Group` WHERE `Id`=%u", p_id);
Debug(2, "Loading Group for %u using %s", p_id, sql.c_str());
zmDbRow dbrow;
if (!dbrow.fetch(sql.c_str())) {
if (!dbrow.fetch(sql)) {
Error("Unable to load group for id %u: %s", p_id, mysql_error(&dbconn));
} else {
unsigned int index = 0;

View File

@ -880,7 +880,7 @@ std::shared_ptr<Monitor> Monitor::Load(unsigned int p_id, bool load_zones, Purpo
std::string sql = load_monitor_sql + stringtf(" WHERE Id=%d", p_id);
zmDbRow dbrow;
if ( !dbrow.fetch(sql.c_str()) ) {
if (!dbrow.fetch(sql)) {
Error("Can't use query result: %s", mysql_error(&dbconn));
return nullptr;
}
@ -1288,14 +1288,14 @@ void Monitor::actionEnable() {
shared_data->action |= RELOAD;
std::string sql = stringtf("UPDATE `Monitors` SET `Enabled` = 1 WHERE `Id` = %u", id);
zmDbDo(sql.c_str());
zmDbDo(sql);
}
void Monitor::actionDisable() {
shared_data->action |= RELOAD;
std::string sql = stringtf("UPDATE `Monitors` SET `Enabled` = 0 WHERE `Id` = %u", id);
zmDbDo(sql.c_str());
zmDbDo(sql);
}
void Monitor::actionSuspend() {
@ -1452,7 +1452,7 @@ void Monitor::DumpZoneImage(const char *zone_string) {
// Grab the most revent event image
std::string sql = stringtf("SELECT MAX(`Id`) FROM `Events` WHERE `MonitorId`=%d AND `Frames` > 0", id);
zmDbRow eventid_row;
if ( eventid_row.fetch(sql.c_str()) ) {
if (eventid_row.fetch(sql)) {
uint64_t event_id = atoll(eventid_row[0]);
Debug(3, "Got event %" PRIu64, event_id);
@ -2283,7 +2283,7 @@ void Monitor::Reload() {
}
std::string sql = load_monitor_sql + stringtf(" WHERE Id=%d", id);
zmDbRow *row = zmDbFetchOne(sql.c_str());
zmDbRow *row = zmDbFetchOne(sql);
if (!row) {
Error("Can't run query: %s", mysql_error(&dbconn));
} else if (MYSQL_ROW dbrow = row->mysql_row()) {
@ -2369,7 +2369,7 @@ void Monitor::ReloadLinkedMonitors(const char *p_linked_monitors) {
" AND `Enabled`=1",
link_ids[i]);
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
continue;
}
@ -2393,7 +2393,7 @@ std::vector<std::shared_ptr<Monitor>> Monitor::LoadMonitors(const std::string &w
std::string sql = load_monitor_sql + " WHERE " + where;
Debug(1, "Loading Monitors with %s", sql.c_str());
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
Error("Can't load local monitors: %s", mysql_error(&dbconn));
return {};
@ -3139,7 +3139,7 @@ std::vector<Group *> Monitor::Groups() {
std::string sql = stringtf(
"SELECT `Id`, `ParentId`, `Name` FROM `Groups` WHERE `Groups.Id` IN "
"(SELECT `GroupId` FROM `Groups_Monitors` WHERE `MonitorId`=%d)", id);
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
Error("Can't load groups: %s", mysql_error(&dbconn));
return groups;

View File

@ -89,7 +89,7 @@ int RtspThread::requestPorts() {
//FIXME Why not load specifically by Id? This will get ineffeicient with a lot of monitors
std::string sql = "SELECT `Id` FROM `Monitors` WHERE `Function` != 'None' AND `Type` = 'Remote' AND `Protocol` = 'rtsp' AND `Method` = 'rtpUni' ORDER BY `Id` ASC";
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
int nMonitors = mysql_num_rows(result);
int position = 0;

View File

@ -60,7 +60,7 @@ Storage::Storage(unsigned int p_id) : id(p_id) {
std::string sql = stringtf("SELECT `Id`, `Name`, `Path`, `Type`, `Scheme` FROM `Storage` WHERE `Id`=%u", id);
Debug(2, "Loading Storage for %u using %s", id, sql.c_str());
zmDbRow dbrow;
if (!dbrow.fetch(sql.c_str())) {
if (!dbrow.fetch(sql)) {
Error("Unable to load storage area for id %d: %s", id, mysql_error(&dbconn));
} else {
unsigned int index = 0;

View File

@ -93,7 +93,7 @@ User *zmLoadUser(const char *username, const char *password) {
" FROM `Users` WHERE `Username` = '%s' AND `Enabled` = 1",
escaped_username.c_str());
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result)
return nullptr;
@ -144,7 +144,7 @@ User *zmLoadTokenUser(const std::string &jwt_token_str, bool use_remote_addr) {
" `Control`+0, `Monitors`+0, `System`+0, `MonitorIds`, `TokenMinExpiry`"
" FROM `Users` WHERE `Username` = '%s' AND `Enabled` = 1", username.c_str());
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result)
return nullptr;
@ -187,7 +187,7 @@ User *zmLoadAuthUser(const char *auth, bool use_remote_addr) {
" `Stream`+0, `Events`+0, `Control`+0, `Monitors`+0, `System`+0,"
" `MonitorIds` FROM `Users` WHERE `Enabled` = 1";
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result)
return nullptr;

View File

@ -135,7 +135,7 @@ void Zone::RecordStats(const Event *event) {
stats.alarm_box_.Hi().y_,
stats.score_
);
zmDbDo(sql.c_str());
zmDbDo(sql);
} // end void Zone::RecordStats( const Event *event )
bool Zone::CheckOverloadCount() {
@ -829,7 +829,7 @@ std::vector<Zone> Zone::Load(Monitor *monitor) {
"OverloadFrames,ExtendAlarmFrames"
" FROM Zones WHERE MonitorId = %d ORDER BY Type, Id", monitor->Id());
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
return {};
}

View File

@ -247,7 +247,7 @@ int main(int argc, char *argv[]) {
"INSERT INTO Monitor_Status (MonitorId,Status,CaptureFPS,AnalysisFPS)"
" VALUES (%u, 'Running',0,0) ON DUPLICATE KEY UPDATE Status='Running',CaptureFPS=0,AnalysisFPS=0",
monitor->Id());
zmDbDo(sql.c_str());
zmDbDo(sql);
Seconds sleep_time = Seconds(0);
while (monitor->PrimeCapture() <= 0) {
@ -275,7 +275,7 @@ int main(int argc, char *argv[]) {
sql = stringtf(
"INSERT INTO Monitor_Status (MonitorId,Status) VALUES (%u, 'Connected') ON DUPLICATE KEY UPDATE Status='Connected'",
monitor->Id());
zmDbDo(sql.c_str());
zmDbDo(sql);
} // end foreach monitor
if (zm_terminate){
@ -362,7 +362,7 @@ int main(int argc, char *argv[]) {
std::string sql = stringtf(
"INSERT INTO Monitor_Status (MonitorId,Status) VALUES (%u, 'NotRunning') ON DUPLICATE KEY UPDATE Status='NotRunning'",
monitor->Id());
zmDbDo(sql.c_str());
zmDbDo(sql);
}
Image::Deinitialise();

View File

@ -736,7 +736,7 @@ int main(int argc, char *argv[]) {
}
sql += " ORDER BY Id ASC";
MYSQL_RES *result = zmDbFetch(sql.c_str());
MYSQL_RES *result = zmDbFetch(sql);
if (!result) {
exit_zmu(-1);
}