Exemplo n.º 1
0
		bool set_fields_if_equals(uint32_t do_id, const map<DCField*, vector<uint8_t> > &equals,
		                          map<DCField*, vector<uint8_t> > &values)
		{
			// Get class from the objects table
			DCClass* dcc = get_class(do_id);
			if(!dcc)
			{
				return false; // Object does not exist
			}

			bool stored = is_storable(dcc->get_number());
			if(!stored)
			{
				return false; // Class has no database fields
			}

			bool failed = false;
			string value;
			indicator ind;
			vector<DCField*> null_fields;
			try
			{
				m_sql.begin(); // Start transaction
				for(auto it = equals.begin(); it != equals.end(); ++it)
				{
					DCField* field = it->first;
					if(field->is_db())
					{
						m_sql << "SELECT " << field->get_name() << " FROM fields_" << dcc->get_name()
						      << " WHERE object_id=" << do_id << ";", into(value, ind);
						if(ind != i_ok)
						{
							null_fields.push_back(field);
							failed = true;
							continue;
						}

						string packed_equal(it->second.begin(), it->second.end());
						string equal = field->format_data(packed_equal, false);
						if(value == equal)
						{
							string packed_data(values[field].begin(), values[field].end());
							string insert = field->format_data(packed_data, false);
							m_sql << "UPDATE fields_" << dcc->get_name() << " SET " << field->get_name()
							      << "='" << insert << "' WHERE object_id=" << do_id << ";";
							\
						}
						else
						{
							failed = true;
						}
						value = field->parse_string(value);
						values[field] = vector<uint8_t>(value.begin(), value.end());
					}
				}

				if(failed)
				{
					for(auto it = null_fields.begin(); it != null_fields.end(); ++it)
					{
						values.erase(*it);
					}
					m_sql.rollback(); // Revert transaction
					return false;
				}
				else
				{
					m_sql.commit(); // End transaction
					return true;
				}
			}
			catch(const exception &e)
			{
				m_sql.rollback(); // Revert transaction
				values.clear();
				return false;
			}
		}