1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "db_ido_pgsql/idopgsqlconnection.hpp"
4 #include "db_ido_pgsql/idopgsqlconnection-ti.cpp"
5 #include "db_ido/dbtype.hpp"
6 #include "db_ido/dbvalue.hpp"
7 #include "base/logger.hpp"
8 #include "base/objectlock.hpp"
9 #include "base/convert.hpp"
10 #include "base/utility.hpp"
11 #include "base/perfdatavalue.hpp"
12 #include "base/application.hpp"
13 #include "base/configtype.hpp"
14 #include "base/exception.hpp"
15 #include "base/context.hpp"
16 #include "base/statsfunction.hpp"
19 using namespace icinga;
21 REGISTER_TYPE(IdoPgsqlConnection);
23 REGISTER_STATSFUNCTION(IdoPgsqlConnection, &IdoPgsqlConnection::StatsFunc);
25 IdoPgsqlConnection::IdoPgsqlConnection()
27 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
30 void IdoPgsqlConnection::OnConfigLoaded()
32 ObjectImpl<IdoPgsqlConnection>::OnConfigLoaded();
34 m_QueryQueue.SetName("IdoPgsqlConnection, " + GetName());
36 Library shimLibrary{"pgsql_shim"};
38 auto create_pgsql_shim = shimLibrary.GetSymbolAddress<create_pgsql_shim_ptr>("create_pgsql_shim");
40 m_Pgsql.reset(create_pgsql_shim());
42 std::swap(m_Library, shimLibrary);
45 void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
49 for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
50 size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength();
51 double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0;
53 nodes.emplace_back(idopgsqlconnection->GetName(), new Dictionary({
54 { "version", idopgsqlconnection->GetSchemaVersion() },
55 { "instance_name", idopgsqlconnection->GetInstanceName() },
56 { "connected", idopgsqlconnection->GetConnected() },
57 { "query_queue_items", queryQueueItems },
58 { "query_queue_item_rate", queryQueueItemRate }
61 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
62 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
63 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
64 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
65 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", queryQueueItems));
66 perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
69 status->Set("idopgsqlconnection", new Dictionary(std::move(nodes)));
72 void IdoPgsqlConnection::Resume()
74 Log(LogInformation, "IdoPgsqlConnection")
75 << "'" << GetName() << "' resumed.";
79 m_QueryQueue.SetExceptionCallback(std::bind(&IdoPgsqlConnection::ExceptionHandler, this, _1));
81 /* Immediately try to connect on Resume() without timer. */
82 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Reconnect, this), PriorityImmediate);
84 m_TxTimer = new Timer();
85 m_TxTimer->SetInterval(1);
86 m_TxTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::TxTimerHandler, this));
89 m_ReconnectTimer = new Timer();
90 m_ReconnectTimer->SetInterval(10);
91 m_ReconnectTimer->OnTimerExpired.connect(std::bind(&IdoPgsqlConnection::ReconnectTimerHandler, this));
92 m_ReconnectTimer->Start();
94 /* Start with queries after connect. */
95 DbConnection::Resume();
97 ASSERT(m_Pgsql->isthreadsafe());
100 void IdoPgsqlConnection::Pause()
102 DbConnection::Pause();
104 m_ReconnectTimer.reset();
106 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Disconnect, this), PriorityLow);
108 /* Work on remaining tasks but never delete the threads, for HA resuming later. */
111 Log(LogInformation, "IdoPgsqlConnection")
112 << "'" << GetName() << "' paused.";
115 void IdoPgsqlConnection::ExceptionHandler(boost::exception_ptr exp)
117 Log(LogWarning, "IdoPgsqlConnection", "Exception during database operation: Verify that your database is operational!");
119 Log(LogDebug, "IdoPgsqlConnection")
120 << "Exception during database operation: " << DiagnosticInformation(std::move(exp));
122 if (GetConnected()) {
123 m_Pgsql->finish(m_Connection);
128 void IdoPgsqlConnection::AssertOnWorkQueue()
130 ASSERT(m_QueryQueue.IsWorkerThread());
133 void IdoPgsqlConnection::Disconnect()
142 m_Pgsql->finish(m_Connection);
145 Log(LogInformation, "IdoPgsqlConnection")
146 << "Disconnected from '" << GetName() << "' database '" << GetDatabase() << "'.";
149 void IdoPgsqlConnection::TxTimerHandler()
154 void IdoPgsqlConnection::NewTransaction()
159 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalNewTransaction, this), PriorityNormal, true);
162 void IdoPgsqlConnection::InternalNewTransaction()
173 void IdoPgsqlConnection::ReconnectTimerHandler()
175 /* Only allow Reconnect events with high priority. */
176 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::Reconnect, this), PriorityHigh);
179 void IdoPgsqlConnection::Reconnect()
183 CONTEXT("Reconnecting to PostgreSQL IDO database '" + GetName() + "'");
185 double startTime = Utility::GetTime();
187 SetShouldConnect(true);
189 bool reconnect = false;
191 if (GetConnected()) {
192 /* Check if we're really still connected */
196 } catch (const std::exception&) {
197 m_Pgsql->finish(m_Connection);
205 String host = GetHost();
206 String port = GetPort();
207 String user = GetUser();
208 String password = GetPassword();
209 String database = GetDatabase();
211 String sslMode = GetSslMode();
212 String sslKey = GetSslKey();
213 String sslCert = GetSslCert();
214 String sslCa = GetSslCa();
219 conninfo += " host=" + host;
221 conninfo += " port=" + port;
223 conninfo += " user=" + user;
224 if (!password.IsEmpty())
225 conninfo += " password=" + password;
226 if (!database.IsEmpty())
227 conninfo += " dbname=" + database;
229 if (!sslMode.IsEmpty())
230 conninfo += " sslmode=" + sslMode;
231 if (!sslKey.IsEmpty())
232 conninfo += " sslkey=" + sslKey;
233 if (!sslCert.IsEmpty())
234 conninfo += " sslcert=" + sslCert;
235 if (!sslCa.IsEmpty())
236 conninfo += " sslrootcert=" + sslCa;
239 m_Connection = m_Pgsql->connectdb(conninfo.CStr());
244 if (m_Pgsql->status(m_Connection) != CONNECTION_OK) {
245 String message = m_Pgsql->errorMessage(m_Connection);
246 m_Pgsql->finish(m_Connection);
249 Log(LogCritical, "IdoPgsqlConnection")
250 << "Connection to database '" << database << "' with user '" << user << "' on '" << host << ":" << port
251 << "' failed: \"" << message << "\"";
253 BOOST_THROW_EXCEPTION(std::runtime_error(message));
258 IdoPgsqlResult result;
260 /* explicitely require legacy mode for string escaping in PostgreSQL >= 9.1
261 * changing standard_conforming_strings to on by default
263 if (m_Pgsql->serverVersion(m_Connection) >= 90100)
264 result = Query("SET standard_conforming_strings TO off");
266 String dbVersionName = "idoutils";
267 result = Query("SELECT version FROM " + GetTablePrefix() + "dbversion WHERE name=E'" + Escape(dbVersionName) + "'");
269 Dictionary::Ptr row = FetchRow(result, 0);
272 m_Pgsql->finish(m_Connection);
275 Log(LogCritical, "IdoPgsqlConnection", "Schema does not provide any valid version! Verify your schema installation.");
277 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid schema."));
280 String version = row->Get("version");
282 SetSchemaVersion(version);
284 if (Utility::CompareVersion(IDO_COMPAT_SCHEMA_VERSION, version) < 0) {
285 m_Pgsql->finish(m_Connection);
288 Log(LogCritical, "IdoPgsqlConnection")
289 << "Schema version '" << version << "' does not match the required version '"
290 << IDO_COMPAT_SCHEMA_VERSION << "' (or newer)! Please check the upgrade documentation at "
291 << "https://docs.icinga.com/icinga2/latest/doc/module/icinga2/chapter/upgrading-icinga-2#upgrading-postgresql-db";
293 BOOST_THROW_EXCEPTION(std::runtime_error("Schema version mismatch."));
296 String instanceName = GetInstanceName();
298 result = Query("SELECT instance_id FROM " + GetTablePrefix() + "instances WHERE instance_name = E'" + Escape(instanceName) + "'");
299 row = FetchRow(result, 0);
302 Query("INSERT INTO " + GetTablePrefix() + "instances (instance_name, instance_description) VALUES (E'" + Escape(instanceName) + "', E'" + Escape(GetInstanceDescription()) + "')");
303 m_InstanceID = GetSequenceValue(GetTablePrefix() + "instances", "instance_id");
305 m_InstanceID = DbReference(row->Get("instance_id"));
308 Endpoint::Ptr my_endpoint = Endpoint::GetLocalEndpoint();
310 /* we have an endpoint in a cluster setup, so decide if we can proceed here */
311 if (my_endpoint && GetHAMode() == HARunOnce) {
312 /* get the current endpoint writing to programstatus table */
313 result = Query("SELECT UNIX_TIMESTAMP(status_update_time) AS status_update_time, endpoint_name FROM " +
314 GetTablePrefix() + "programstatus WHERE instance_id = " + Convert::ToString(m_InstanceID));
315 row = FetchRow(result, 0);
317 String endpoint_name;
320 endpoint_name = row->Get("endpoint_name");
322 Log(LogNotice, "IdoPgsqlConnection", "Empty program status table");
324 /* if we did not write into the database earlier, another instance is active */
325 if (endpoint_name != my_endpoint->GetName()) {
326 double status_update_time;
329 status_update_time = row->Get("status_update_time");
331 status_update_time = 0;
333 double now = Utility::GetTime();
335 double status_update_age = now - status_update_time;
336 double failoverTimeout = GetFailoverTimeout();
338 if (status_update_age < GetFailoverTimeout()) {
339 Log(LogInformation, "IdoPgsqlConnection")
340 << "Last update by endpoint '" << endpoint_name << "' was "
341 << status_update_age << "s ago (< failover timeout of " << failoverTimeout << "s). Retrying.";
343 m_Pgsql->finish(m_Connection);
345 SetShouldConnect(false);
350 /* activate the IDO only, if we're authoritative in this zone */
352 Log(LogNotice, "IdoPgsqlConnection")
353 << "Local endpoint '" << my_endpoint->GetName() << "' is not authoritative, bailing out.";
355 m_Pgsql->finish(m_Connection);
361 SetLastFailover(now);
363 Log(LogInformation, "IdoPgsqlConnection")
364 << "Last update by endpoint '" << endpoint_name << "' was "
365 << status_update_age << "s ago. Taking over '" << GetName() << "' in HA zone '" << Zone::GetLocalZone()->GetName() << "'.";
368 Log(LogNotice, "IdoPgsqlConnection", "Enabling IDO connection.");
371 Log(LogInformation, "IdoPgsqlConnection")
372 << "PGSQL IDO instance id: " << static_cast<long>(m_InstanceID) << " (schema version: '" + version + "')"
373 << (!sslMode.IsEmpty() ? ", sslmode='" + sslMode + "'" : "");
377 /* update programstatus table */
378 UpdateProgramStatus();
380 /* record connection */
381 Query("INSERT INTO " + GetTablePrefix() + "conninfo " +
382 "(instance_id, connect_time, last_checkin_time, agent_name, agent_version, connect_type, data_start_time) VALUES ("
383 + Convert::ToString(static_cast<long>(m_InstanceID)) + ", NOW(), NOW(), E'icinga2 db_ido_pgsql', E'" + Escape(Application::GetAppVersion())
384 + "', E'" + (reconnect ? "RECONNECT" : "INITIAL") + "', NOW())");
386 /* clear config tables for the initial config dump */
389 std::ostringstream q1buf;
390 q1buf << "SELECT object_id, objecttype_id, name1, name2, is_active FROM " + GetTablePrefix() + "objects WHERE instance_id = " << static_cast<long>(m_InstanceID);
391 result = Query(q1buf.str());
393 std::vector<DbObject::Ptr> activeDbObjs;
396 while ((row = FetchRow(result, index))) {
399 DbType::Ptr dbtype = DbType::GetByID(row->Get("objecttype_id"));
404 DbObject::Ptr dbobj = dbtype->GetOrCreateObjectByName(row->Get("name1"), row->Get("name2"));
405 SetObjectID(dbobj, DbReference(row->Get("object_id")));
406 bool active = row->Get("is_active");
407 SetObjectActive(dbobj, active);
410 activeDbObjs.push_back(dbobj);
413 SetIDCacheValid(true);
415 EnableActiveChangedHandler();
417 for (const DbObject::Ptr& dbobj : activeDbObjs) {
418 if (dbobj->GetObject())
421 Log(LogNotice, "IdoPgsqlConnection")
422 << "Deactivate deleted object name1: '" << dbobj->GetName1()
423 << "' name2: '" << dbobj->GetName2() + "'.";
424 DeactivateObject(dbobj);
429 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::ClearTablesBySession, this), PriorityNormal);
431 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::FinishConnect, this, startTime), PriorityNormal);
434 void IdoPgsqlConnection::FinishConnect(double startTime)
441 Log(LogInformation, "IdoPgsqlConnection")
442 << "Finished reconnecting to '" << GetName() << "' database '" << GetDatabase() << "' in "
443 << std::setw(2) << Utility::GetTime() - startTime << " second(s).";
449 void IdoPgsqlConnection::ClearTablesBySession()
451 /* delete all comments and downtimes without current session token */
452 ClearTableBySession("comments");
453 ClearTableBySession("scheduleddowntime");
456 void IdoPgsqlConnection::ClearTableBySession(const String& table)
458 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
459 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND session_token <> " +
460 Convert::ToString(GetSessionToken()));
463 IdoPgsqlResult IdoPgsqlConnection::Query(const String& query)
467 Log(LogDebug, "IdoPgsqlConnection")
468 << "Query: " << query;
470 IncreaseQueryCount();
472 PGresult *result = m_Pgsql->exec(m_Connection, query.CStr());
475 String message = m_Pgsql->errorMessage(m_Connection);
476 Log(LogCritical, "IdoPgsqlConnection")
477 << "Error \"" << message << "\" when executing query \"" << query << "\"";
479 BOOST_THROW_EXCEPTION(
481 << errinfo_message(message)
482 << errinfo_database_query(query)
486 char *rowCount = m_Pgsql->cmdTuples(result);
487 m_AffectedRows = atoi(rowCount);
489 if (m_Pgsql->resultStatus(result) == PGRES_COMMAND_OK) {
490 m_Pgsql->clear(result);
491 return IdoPgsqlResult();
494 if (m_Pgsql->resultStatus(result) != PGRES_TUPLES_OK) {
495 String message = m_Pgsql->resultErrorMessage(result);
496 m_Pgsql->clear(result);
498 Log(LogCritical, "IdoPgsqlConnection")
499 << "Error \"" << message << "\" when executing query \"" << query << "\"";
501 BOOST_THROW_EXCEPTION(
503 << errinfo_message(message)
504 << errinfo_database_query(query)
508 return IdoPgsqlResult(result, std::bind(&PgsqlInterface::clear, std::cref(m_Pgsql), _1));
511 DbReference IdoPgsqlConnection::GetSequenceValue(const String& table, const String& column)
515 IdoPgsqlResult result = Query("SELECT CURRVAL(pg_get_serial_sequence(E'" + Escape(table) + "', E'" + Escape(column) + "')) AS id");
517 Dictionary::Ptr row = FetchRow(result, 0);
521 Log(LogDebug, "IdoPgsqlConnection")
522 << "Sequence Value: " << row->Get("id");
524 return {Convert::ToLong(row->Get("id"))};
527 int IdoPgsqlConnection::GetAffectedRows()
531 return m_AffectedRows;
534 String IdoPgsqlConnection::Escape(const String& s)
538 String utf8s = Utility::ValidateUTF8(s);
540 size_t length = utf8s.GetLength();
541 auto *to = new char[utf8s.GetLength() * 2 + 1];
543 m_Pgsql->escapeStringConn(m_Connection, to, utf8s.CStr(), length, nullptr);
545 String result = String(to);
552 Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int row)
556 if (row >= m_Pgsql->ntuples(result.get()))
559 int columns = m_Pgsql->nfields(result.get());
563 for (int column = 0; column < columns; column++) {
566 if (!m_Pgsql->getisnull(result.get(), row, column))
567 value = m_Pgsql->getvalue(result.get(), row, column);
569 dict.emplace_back(m_Pgsql->fname(result.get(), column), value);
572 return new Dictionary(std::move(dict));
575 void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj)
580 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalActivateObject, this, dbobj), PriorityNormal);
583 void IdoPgsqlConnection::InternalActivateObject(const DbObject::Ptr& dbobj)
590 DbReference dbref = GetObjectID(dbobj);
591 std::ostringstream qbuf;
593 if (!dbref.IsValid()) {
594 if (!dbobj->GetName2().IsEmpty()) {
595 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, name2, is_active) VALUES ("
596 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
597 << "E'" << Escape(dbobj->GetName1()) << "', E'" << Escape(dbobj->GetName2()) << "', 1)";
599 qbuf << "INSERT INTO " + GetTablePrefix() + "objects (instance_id, objecttype_id, name1, is_active) VALUES ("
600 << static_cast<long>(m_InstanceID) << ", " << dbobj->GetType()->GetTypeID() << ", "
601 << "E'" << Escape(dbobj->GetName1()) << "', 1)";
605 SetObjectID(dbobj, GetSequenceValue(GetTablePrefix() + "objects", "object_id"));
607 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 1 WHERE object_id = " << static_cast<long>(dbref);
612 void IdoPgsqlConnection::DeactivateObject(const DbObject::Ptr& dbobj)
617 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalDeactivateObject, this, dbobj), PriorityNormal);
620 void IdoPgsqlConnection::InternalDeactivateObject(const DbObject::Ptr& dbobj)
627 DbReference dbref = GetObjectID(dbobj);
629 if (!dbref.IsValid())
632 std::ostringstream qbuf;
633 qbuf << "UPDATE " + GetTablePrefix() + "objects SET is_active = 0 WHERE object_id = " << static_cast<long>(dbref);
636 /* Note that we're _NOT_ clearing the db refs via SetReference/SetConfigUpdate/SetStatusUpdate
637 * because the object is still in the database. */
640 bool IdoPgsqlConnection::FieldToEscapedString(const String& key, const Value& value, Value *result)
642 if (key == "instance_id") {
643 *result = static_cast<long>(m_InstanceID);
645 } else if (key == "session_token") {
646 *result = GetSessionToken();
650 Value rawvalue = DbValue::ExtractValue(value);
652 if (rawvalue.IsObjectType<ConfigObject>()) {
653 DbObject::Ptr dbobjcol = DbObject::GetOrCreateByObject(rawvalue);
660 if (!IsIDCacheValid())
663 DbReference dbrefcol;
665 if (DbValue::IsObjectInsertID(value)) {
666 dbrefcol = GetInsertID(dbobjcol);
668 if (!dbrefcol.IsValid())
671 dbrefcol = GetObjectID(dbobjcol);
673 if (!dbrefcol.IsValid()) {
674 InternalActivateObject(dbobjcol);
676 dbrefcol = GetObjectID(dbobjcol);
678 if (!dbrefcol.IsValid())
683 *result = static_cast<long>(dbrefcol);
684 } else if (DbValue::IsTimestamp(value)) {
686 std::ostringstream msgbuf;
687 msgbuf << "TO_TIMESTAMP(" << ts << ") AT TIME ZONE 'UTC'";
688 *result = Value(msgbuf.str());
689 } else if (DbValue::IsObjectInsertID(value)) {
690 auto id = static_cast<long>(rawvalue);
700 if (rawvalue.IsBoolean())
701 fvalue = Convert::ToLong(rawvalue);
705 *result = "E'" + Escape(fvalue) + "'";
711 void IdoPgsqlConnection::ExecuteQuery(const DbQuery& query)
716 ASSERT(query.Category != DbCatInvalid);
718 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority, true);
721 void IdoPgsqlConnection::ExecuteMultipleQueries(const std::vector<DbQuery>& queries)
729 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), queries[0].Priority, true);
732 bool IdoPgsqlConnection::CanExecuteQuery(const DbQuery& query)
734 if (query.Object && !IsIDCacheValid())
737 if (query.WhereCriteria) {
738 ObjectLock olock(query.WhereCriteria);
741 for (const Dictionary::Pair& kv : query.WhereCriteria) {
742 if (!FieldToEscapedString(kv.first, kv.second, &value))
748 ObjectLock olock(query.Fields);
750 for (const Dictionary::Pair& kv : query.Fields) {
753 if (kv.second.IsEmpty() && !kv.second.IsString())
756 if (!FieldToEscapedString(kv.first, kv.second, &value))
764 void IdoPgsqlConnection::InternalExecuteMultipleQueries(const std::vector<DbQuery>& queries)
774 for (const DbQuery& query : queries) {
775 ASSERT(query.Type == DbQueryNewTransaction || query.Category != DbCatInvalid);
777 if (!CanExecuteQuery(query)) {
778 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteMultipleQueries, this, queries), query.Priority);
783 for (const DbQuery& query : queries) {
784 InternalExecuteQuery(query);
788 void IdoPgsqlConnection::InternalExecuteQuery(const DbQuery& query, int typeOverride)
798 if (query.Type == DbQueryNewTransaction) {
799 InternalNewTransaction();
803 /* check whether we're allowed to execute the query first */
804 if (GetCategoryFilter() != DbCatEverything && (query.Category & GetCategoryFilter()) == 0)
807 if (query.Object && query.Object->GetObject()->GetExtension("agent_check").ToBool())
810 /* check if there are missing object/insert ids and re-enqueue the query */
811 if (!CanExecuteQuery(query)) {
812 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, typeOverride), query.Priority);
816 std::ostringstream qbuf, where;
819 if (query.WhereCriteria) {
822 ObjectLock olock(query.WhereCriteria);
826 for (const Dictionary::Pair& kv : query.WhereCriteria) {
827 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
828 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
835 where << kv.first << " = " << value;
842 type = (typeOverride != -1) ? typeOverride : query.Type;
846 if ((type & DbQueryInsert) && (type & DbQueryUpdate)) {
850 if (query.ConfigUpdate)
851 hasid = GetConfigUpdate(query.Object);
852 else if (query.StatusUpdate)
853 hasid = GetStatusUpdate(query.Object);
859 type = DbQueryUpdate;
862 if ((type & DbQueryInsert) && (type & DbQueryDelete)) {
863 std::ostringstream qdel;
864 qdel << "DELETE FROM " << GetTablePrefix() << query.Table << where.str();
867 type = DbQueryInsert;
872 qbuf << "INSERT INTO " << GetTablePrefix() << query.Table;
875 qbuf << "UPDATE " << GetTablePrefix() << query.Table << " SET";
878 qbuf << "DELETE FROM " << GetTablePrefix() << query.Table;
881 VERIFY(!"Invalid query type.");
884 if (type == DbQueryInsert || type == DbQueryUpdate) {
885 std::ostringstream colbuf, valbuf;
887 if (type == DbQueryUpdate && query.Fields->GetLength() == 0)
890 ObjectLock olock(query.Fields);
894 for (const Dictionary::Pair& kv : query.Fields) {
895 if (kv.second.IsEmpty() && !kv.second.IsString())
898 if (!FieldToEscapedString(kv.first, kv.second, &value)) {
899 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalExecuteQuery, this, query, -1), query.Priority);
903 if (type == DbQueryInsert) {
915 qbuf << " " << kv.first << " = " << value;
922 if (type == DbQueryInsert)
923 qbuf << " (" << colbuf.str() << ") VALUES (" << valbuf.str() << ")";
926 if (type != DbQueryInsert)
931 if (upsert && GetAffectedRows() == 0) {
932 InternalExecuteQuery(query, DbQueryDelete | DbQueryInsert);
937 if (type == DbQueryInsert && query.Object) {
938 if (query.ConfigUpdate) {
939 String idField = query.IdColumn;
941 if (idField.IsEmpty())
942 idField = query.Table.SubStr(0, query.Table.GetLength() - 1) + "_id";
944 SetInsertID(query.Object, GetSequenceValue(GetTablePrefix() + query.Table, idField));
946 SetConfigUpdate(query.Object, true);
947 } else if (query.StatusUpdate)
948 SetStatusUpdate(query.Object, true);
951 if (type == DbQueryInsert && query.Table == "notifications" && query.NotificationInsertID) {
952 DbReference seqval = GetSequenceValue(GetTablePrefix() + query.Table, "notification_id");
953 query.NotificationInsertID->SetValue(static_cast<long>(seqval));
957 void IdoPgsqlConnection::CleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
962 m_QueryQueue.Enqueue(std::bind(&IdoPgsqlConnection::InternalCleanUpExecuteQuery, this, table, time_column, max_age), PriorityLow, true);
965 void IdoPgsqlConnection::InternalCleanUpExecuteQuery(const String& table, const String& time_column, double max_age)
972 Query("DELETE FROM " + GetTablePrefix() + table + " WHERE instance_id = " +
973 Convert::ToString(static_cast<long>(m_InstanceID)) + " AND " + time_column +
974 " < TO_TIMESTAMP(" + Convert::ToString(static_cast<long>(max_age)) + ") AT TIME ZONE 'UTC'");
977 void IdoPgsqlConnection::FillIDCache(const DbType::Ptr& type)
979 String query = "SELECT " + type->GetIDColumn() + " AS object_id, " + type->GetTable() + "_id, config_hash FROM " + GetTablePrefix() + type->GetTable() + "s";
980 IdoPgsqlResult result = Query(query);
985 while ((row = FetchRow(result, index))) {
987 DbReference dbref(row->Get("object_id"));
988 SetInsertID(type, dbref, DbReference(row->Get(type->GetTable() + "_id")));
989 SetConfigHash(type, dbref, row->Get("config_hash"));
993 int IdoPgsqlConnection::GetPendingQueryCount() const
995 return m_QueryQueue.GetLength();