From c69f48e890a819ba4d4c600d17fd00f0508bb0a7 Mon Sep 17 00:00:00 2001
From: Ramon Novoa <rnovoa@artica.es>
Date: Wed, 13 Apr 2011 16:28:59 +0000
Subject: [PATCH] 2011-04-13  Ramon Novoa  <rnovoa@artica.es>

	* lib/PandoraFMS/SNMPServer.pm,
	  lib/PandoraFMS/Config.pm,
	  lib/PandoraFMS/NetworkServer.pm,
	  lib/PandoraFMS/WMIServer.pm,
	  lib/PandoraFMS/PluginServer.pm,
	  lib/PandoraFMS/DB.pm,
	  lib/PandoraFMS/ProducerConsumerServer.pm,
	  lib/PandoraFMS/PredictionServer.pm,
	  lib/PandoraFMS/Core.pm,
	  lib/PandoraFMS/ReconServer.pm,
	  bin/pandora_server,
	  util/pandora_db.pl,
	  util/pandora_manage.pl,
	  util/recon_scripts/snmpdevices.pl: Adding support for PostgreSQL and
	  Oracle (not complete).



git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@4213 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f
---
 pandora_server/ChangeLog                      | 18 +++++
 pandora_server/bin/pandora_server             |  2 +-
 pandora_server/lib/PandoraFMS/Config.pm       |  4 ++
 pandora_server/lib/PandoraFMS/Core.pm         | 45 +++++++------
 pandora_server/lib/PandoraFMS/DB.pm           | 65 ++++++++++++++++---
 .../lib/PandoraFMS/NetworkServer.pm           |  4 +-
 pandora_server/lib/PandoraFMS/PluginServer.pm |  4 +-
 .../lib/PandoraFMS/PredictionServer.pm        |  4 +-
 .../lib/PandoraFMS/ProducerConsumerServer.pm  |  4 +-
 pandora_server/lib/PandoraFMS/ReconServer.pm  |  8 +--
 pandora_server/lib/PandoraFMS/SNMPServer.pm   |  2 +-
 pandora_server/lib/PandoraFMS/WMIServer.pm    |  4 +-
 pandora_server/util/pandora_db.pl             |  2 +-
 pandora_server/util/pandora_manage.pl         |  6 +-
 .../util/recon_scripts/snmpdevices.pl         |  4 +-
 15 files changed, 123 insertions(+), 53 deletions(-)

diff --git a/pandora_server/ChangeLog b/pandora_server/ChangeLog
index 89def1a39d..b194875f40 100644
--- a/pandora_server/ChangeLog
+++ b/pandora_server/ChangeLog
@@ -1,3 +1,21 @@
+2011-04-13  Ramon Novoa  <rnovoa@artica.es>
+
+	* lib/PandoraFMS/SNMPServer.pm,
+	  lib/PandoraFMS/Config.pm,
+	  lib/PandoraFMS/NetworkServer.pm,
+	  lib/PandoraFMS/WMIServer.pm,
+	  lib/PandoraFMS/PluginServer.pm,
+	  lib/PandoraFMS/DB.pm,
+	  lib/PandoraFMS/ProducerConsumerServer.pm,
+	  lib/PandoraFMS/PredictionServer.pm,
+	  lib/PandoraFMS/Core.pm,
+	  lib/PandoraFMS/ReconServer.pm,
+	  bin/pandora_server,
+	  util/pandora_db.pl,
+	  util/pandora_manage.pl,
+	  util/recon_scripts/snmpdevices.pl: Adding support for PostgreSQL and
+	  Oracle (not complete).
+
 2011-04-13  Sancho Lerena <slerena@artica.es>
 
         * lib/PandoraFMS/ReconServer.pm: Fixed bug #3286027. Fix also
diff --git a/pandora_server/bin/pandora_server b/pandora_server/bin/pandora_server
index a049ad1bd6..d333a3f276 100755
--- a/pandora_server/bin/pandora_server
+++ b/pandora_server/bin/pandora_server
@@ -68,7 +68,7 @@ sub pandora_startup () {
 	pandora_start_log (\%Config);
 
 	# Connect to the DB
-	$DBH = db_connect ('mysql', $Config{'dbname'}, $Config{'dbhost'}, 3306,
+	$DBH = db_connect ($Config{'dbengine'}, $Config{'dbname'}, $Config{'dbhost'}, 3306,
 					$Config{'dbuser'}, $Config{'dbpass'});
 
 	# Grab config tokens shared with the console and not in the .conf
diff --git a/pandora_server/lib/PandoraFMS/Config.pm b/pandora_server/lib/PandoraFMS/Config.pm
index 22fd16edbb..c97ade4328 100644
--- a/pandora_server/lib/PandoraFMS/Config.pm
+++ b/pandora_server/lib/PandoraFMS/Config.pm
@@ -174,6 +174,7 @@ sub pandora_load_config {
 	# Default values
 	$pa_config->{'version'} = $pandora_version;
 	$pa_config->{'build'} = $pandora_build;
+	$pa_config->{"dbengine"} = "mysql";
 	$pa_config->{"dbuser"} = "pandora";
 	$pa_config->{"dbpass"} = "pandora";
 	$pa_config->{"dbhost"} = "localhost";
@@ -383,6 +384,9 @@ sub pandora_load_config {
 		elsif ($parametro =~ m/^snmp_logfile\s(.*)/i) { 
 			$pa_config->{'snmp_logfile'}= clean_blank($1); 
 		}
+		elsif ($parametro =~ m/^dbengine\s(.*)/i) { 
+			$pa_config->{'dbengine'}= clean_blank($1); 
+		}
 		elsif ($parametro =~ m/^dbname\s(.*)/i) { 
 			$pa_config->{'dbname'}= clean_blank($1); 
 		}
diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm
index d141b807f0..4290a725b2 100644
--- a/pandora_server/lib/PandoraFMS/Core.pm
+++ b/pandora_server/lib/PandoraFMS/Core.pm
@@ -707,7 +707,7 @@ sub pandora_access_update ($$$) {
 	if ($pa_config->{"agentaccess"} == 0){
 		return;
 	}
-	db_insert ($dbh, "INSERT INTO tagent_access (`id_agent`, `utimestamp`) VALUES (?, ?)", $agent_id, time ());
+	db_do ($dbh, "INSERT INTO tagent_access (id_agent, utimestamp) VALUES (?, ?)", $agent_id, time ());
 }
 
 ##########################################################################
@@ -793,8 +793,8 @@ sub pandora_process_module ($$$$$$$$$;$) {
 		logger($pa_config, "Alerts inhibited for agent '" . $agent->{'nombre'} . "'.", 10);
 	}
 	
-	# tagente_estado.last_try defaults to NULL, should default to '0000-00-00 00:00:00'
-	$agent_status->{'last_try'} = '0000-00-00 00:00:00' unless defined ($agent_status->{'last_try'});
+	# tagente_estado.last_try defaults to NULL, should default to '1970-01-01 00:00:00'
+	$agent_status->{'last_try'} = '1970-01-01 00:00:00' unless defined ($agent_status->{'last_try'});
 
 	# Do we have to save module data?
 	if ($agent_status->{'last_try'} !~ /(\d+)\-(\d+)\-(\d+) +(\d+):(\d+):(\d+)/) {
@@ -912,7 +912,7 @@ sub pandora_update_server ($$$$$;$$) {
 
 	# Create an entry in tserver
 	if (! defined ($server)){ 
-		my $server_id = db_insert ($dbh, 'INSERT INTO tserver (`name`, `server_type`, `description`, `version`, `threads`, `queued_modules`)
+		my $server_id = db_insert ($dbh, 'id_server', 'INSERT INTO tserver (name, server_type, description, version, threads, queued_modules)
 						VALUES (?, ?, ?, ?, ?, ?)', $server_name, $server_type,
 						'Autocreated at startup', $pa_config->{'version'} . ' (P) ' . $pa_config->{'build'}, $num_threads, $queue_size);
 		$server = get_db_single_row ($dbh, 'SELECT * FROM tserver
@@ -1103,9 +1103,8 @@ sub pandora_audit ($$$$$) {
 	my $utimestamp = time();
 	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime($utimestamp));
 
-	db_insert($dbh, 'INSERT INTO tsesion (`ID_usuario`, `IP_origen`, `accion`, `fecha`, `descripcion`, `utimestamp`) 
-			VALUES (?, ?, ?, ?, ?, ?)', 
-			'SYSTEM', $name, $action , $timestamp , $description , $utimestamp);
+	db_do($dbh, 'INSERT INTO tsesion (' . db_reserved_word ('ID_usuario') .', ' . db_reserved_word ('IP_origen') . ', accion, fecha, descripcion, utimestamp) 
+			VALUES (?, ?, ?, ?, ?, ?)', 'SYSTEM', $name, $action , $timestamp , $description , $utimestamp);
 
 	db_disconnect($dbh) if ($disconnect == 1);
 }
@@ -1128,9 +1127,9 @@ sub pandora_create_module ($$$$$$$$$$) {
 	$min = 0 if ($min eq '');
 	$post_process = 0 if ($post_process eq '');
 
-	my $module_id = db_insert($dbh, 'INSERT INTO tagente_modulo (`id_agente`, `id_tipo_modulo`, `nombre`, `max`, `min`, `post_process`, `descripcion`, `module_interval`, `id_modulo`)
+	my $module_id = db_insert($dbh, 'id_agente_modulo', 'INSERT INTO tagente_modulo (id_agente, id_tipo_modulo, nombre, max, min, post_process, descripcion, module_interval, id_modulo)
 			VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)', $agent_id, $module_type_id, safe_input($module_name), $max, $min, $post_process, $description, $interval);
-	db_do ($dbh, 'INSERT INTO tagente_estado (`id_agente_modulo`, `id_agente`, `last_try`) VALUES (?, ?, \'0000-00-00 00:00:00\')', $module_id, $agent_id);
+	db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, last_try) VALUES (?, ?, \'1970-01-01 00:00:00\')', $module_id, $agent_id);
 	return $module_id;
 }
 
@@ -1163,9 +1162,9 @@ sub pandora_create_module_from_hash ($$$) {
 
  	logger($pa_config, "Creating module '$parameters->{'nombre'}' for agent ID $parameters->{'id_agente'}.", 10);
 
-	my $module_id = db_process_insert($dbh, 'tagente_modulo', $parameters);
+	my $module_id = db_process_insert($dbh, 'id_agente_modulo', 'tagente_modulo', $parameters);
 
-	db_do ($dbh, 'INSERT INTO tagente_estado (`id_agente_modulo`, `id_agente`, `last_try`) VALUES (?, ?, \'0000-00-00 00:00:00\')', $module_id, $parameters->{'id_agente'});
+	db_do ($dbh, 'INSERT INTO tagente_estado (`id_agente_modulo`, `id_agente`, `last_try`) VALUES (?, ?, \'1970-01-01 00:00:00\')', $module_id, $parameters->{'id_agente'});
 
 	return $module_id;
 }
@@ -1206,12 +1205,12 @@ sub pandora_create_agent ($$$$$$$$$$;$$$$$) {
 	my $agent_id;
 	# Test if the optional positional parameters are defined or GIS is disabled
 	if (!defined ($timezone_offset) ) {
-		$agent_id = db_insert ($dbh, 'INSERT INTO tagente (`nombre`, `direccion`, `comentarios`, `id_grupo`, `id_os`, `server_name`, `intervalo`, `id_parent`, `modo`)
+		$agent_id = db_insert ($dbh, 'id_agente', 'INSERT INTO tagente (nombre, direccion, comentarios, id_grupo, id_os, server_name, intervalo, id_parent, modo)
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)', safe_input($agent_name), $address, $description, $group_id, $os_id, $server_name, $interval, $parent_id);
 	}
 	else {
-		 $agent_id = db_insert ($dbh, 'INSERT INTO tagente (`nombre`, `direccion`, `comentarios`, `id_grupo`, `id_os`, `server_name`, `intervalo`, `id_parent`, 
-				`timezone_offset`, `modo` ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)', safe_input($agent_name), $address, 
+		 $agent_id = db_insert ($dbh, 'id_agente', 'INSERT INTO tagente (nombre, direccion, comentarios, id_grupo, id_os, server_name, intervalo, id_parent, 
+				timezone_offset, modo ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)', safe_input($agent_name), $address, 
 				 $description, $group_id, $os_id, $server_name, $interval, $parent_id, $timezone_offset);	
 	}
 	if (defined ($longitude) && defined ($latitude ) && $pa_config->{'activate_gis'} == 1 ) {
@@ -1283,8 +1282,8 @@ sub pandora_event ($$$$$$$$$$) {
 	my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime ($utimestamp));
 	$id_agentmodule = 0 unless defined ($id_agentmodule);
 
-	db_do ($dbh, 'INSERT INTO tevento (`id_agente`, `id_grupo`, `evento`, `timestamp`, `estado`, `utimestamp`, `event_type`, `id_agentmodule`, `id_alert_am`, `criticity`)
-		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', $id_agente, $id_grupo, safe_input ($evento), $timestamp, $event_status, $utimestamp, $event_type, $id_agentmodule, $id_alert_am, $severity);
+	db_do ($dbh, 'INSERT INTO tevento (id_agente, id_grupo, evento, timestamp, estado, utimestamp, event_type, id_agentmodule, id_alert_am, criticity, user_comment)
+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', $id_agente, $id_grupo, safe_input ($evento), $timestamp, $event_status, $utimestamp, $event_type, $id_agentmodule, $id_alert_am, $severity, '');
 }
 
 ##########################################################################
@@ -1360,7 +1359,7 @@ sub pandora_module_keep_alive_nd {
 					AND tagente.disabled = 0 
 					AND tagente_modulo.id_tipo_modulo = 100 
 					AND tagente_modulo.disabled = 0 
-					AND (tagente_estado.datos = 1 OR tagente_estado.datos = \'\')
+					AND (tagente_estado.datos = \'1\' OR tagente_estado.datos = \'\')
 					AND tagente_modulo.id_agente_modulo = tagente_estado.id_agente_modulo 
 					AND ( tagente_estado.utimestamp + (tagente.intervalo * 2) < UNIX_TIMESTAMP())');
 
@@ -1416,7 +1415,7 @@ sub pandora_evaluate_snmp_alerts ($$$$$$$$$) {
 		}
 		
 		# Check time threshold
-		$alert->{'last_fired'} = '0000-00-00 00:00:00' unless defined ($alert->{'last_fired'});
+		$alert->{'last_fired'} = '1970-01-01 00:00:00' unless defined ($alert->{'last_fired'});
 		return unless ($alert->{'last_fired'} =~ /(\d+)\-(\d+)\-(\d+) +(\d+):(\d+):(\d+)/);
 		my $last_fired = ($1 > 0) ? timelocal($6, $5, $4, $3, $2 - 1, $1 - 1900) : 0;
 
@@ -1575,7 +1574,7 @@ sub process_inc_data ($$$$) {
 
 	# No previous data
 	if (! defined ($data_inc)) {
-		db_insert ($dbh, 'INSERT INTO tagente_datos_inc
+		db_do ($dbh, 'INSERT INTO tagente_datos_inc
 				(`id_agente_modulo`, `datos`, `utimestamp`)
 				VALUES (?, ?, ?)', $module->{'id_agente_modulo'}, $data, $utimestamp);
 		return undef;
@@ -1584,7 +1583,7 @@ sub process_inc_data ($$$$) {
 	# Negative increment, reset inc data
 	if ($data < $data_inc->{'datos'}) {
 		db_do ($dbh, 'DELETE FROM tagente_datos_inc WHERE id_agente_modulo = ?', $module->{'id_agente_modulo'});		
-		db_insert ($dbh, 'INSERT INTO tagente_datos_inc
+		db_do ($dbh, 'INSERT INTO tagente_datos_inc
 				(`id_agente_modulo`, `datos`, `utimestamp`)
 				VALUES (?, ?, ?)', $module->{'id_agente_modulo'}, $data, $utimestamp);
 		return undef;
@@ -1832,14 +1831,14 @@ sub save_agent_position($$$$$$;$$) {
 	
 	if (defined($start_timestamp)) {
 		# Upadate the timestamp of the received agent
-		db_insert ($dbh, 'INSERT INTO tgis_data_status (tagente_id_agente, current_longitude , current_latitude, current_altitude, 
+		db_do ($dbh, 'INSERT INTO tgis_data_status (tagente_id_agente, current_longitude , current_latitude, current_altitude, 
 					 stored_longitude , stored_latitude, stored_altitude, start_timestamp, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
 					$agent_id, $current_longitude, $current_latitude, $current_altitude, $current_longitude, 
 					$current_latitude, $current_altitude, $start_timestamp, $description);
 	}
 	else {
 		# Upadate the data of the received agent using the default timestamp
-		db_insert ($dbh, 'INSERT INTO tgis_data_status (tagente_id_agente, current_longitude , current_latitude, current_altitude, 
+		db_do ($dbh, 'INSERT INTO tgis_data_status (tagente_id_agente, current_longitude , current_latitude, current_altitude, 
 					 stored_longitude , stored_latitude, stored_altitude, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ',
 					$agent_id, $current_longitude, $current_latitude, $current_altitude, $current_longitude, 
 					$current_latitude, $current_altitude, , $description);
@@ -1891,7 +1890,7 @@ sub archive_agent_position($$$$$$$$$$) {
 
 	logger($pa_config, "Saving new agent position: start_timestamp=$start_timestamp longitude=$longitude latitude=$latitude altitude=$altitude", 10);
 
-	db_insert($dbh, 'INSERT INTO tgis_data_history (`longitude`, `latitude`, `altitude`, `tagente_id_agente`, `start_timestamp`,
+	db_do($dbh, 'INSERT INTO tgis_data_history (`longitude`, `latitude`, `altitude`, `tagente_id_agente`, `start_timestamp`,
 					`end_timestamp`, `description`, `number_of_packages`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', 
 					$longitude, $latitude, $altitude, $agent_id, $start_timestamp, $end_timestamp, $description, $number_packages);
 
diff --git a/pandora_server/lib/PandoraFMS/DB.pm b/pandora_server/lib/PandoraFMS/DB.pm
index af2525dfb8..bdb4a98774 100644
--- a/pandora_server/lib/PandoraFMS/DB.pm
+++ b/pandora_server/lib/PandoraFMS/DB.pm
@@ -31,9 +31,11 @@ our @EXPORT = qw(
 		db_connect
 		db_disconnect
 		db_do
+		db_insert
 		db_process_insert
 		db_process_update
-		db_insert
+		db_reserved_word
+		db_string
 		db_update
 		get_action_id
 		get_agent_id
@@ -60,10 +62,12 @@ our @EXPORT = qw(
 ##########################################################################
 ## Connect to the DB.
 ##########################################################################
+my $RDBMS = '';
 sub db_connect ($$$$$$) {
 	my ($rdbms, $db_name, $db_host, $db_port, $db_user, $db_pass) = @_;
 
 	if ($rdbms eq 'mysql') {
+		$RDBMS = 'mysql';
 		
 		# Connect to MySQL
 		my $dbh = DBI->connect("DBI:mysql:$db_name:$db_host:3306", $db_user, $db_pass, { RaiseError => 1, AutoCommit => 1 });
@@ -75,6 +79,14 @@ sub db_connect ($$$$$$) {
 		# Enable character semantics
 		$dbh->{'mysql_enable_utf8'} = 1;
 
+		return $dbh;
+	} elsif ($rdbms eq 'postgresql') {
+		$RDBMS = 'postgresql';
+		
+		# Connect to PostgreSQL
+		my $dbh = DBI->connect("DBI:Pg:dbname=$db_name;host=$db_host;port=5432", $db_user, $db_pass);
+		return undef unless defined ($dbh);
+		
 		return $dbh;
 	}
 	
@@ -331,11 +343,21 @@ sub get_db_rows ($$;@) {
 ##########################################################################
 ## SQL insert. Returns the ID of the inserted row.
 ##########################################################################
-sub db_insert ($$;@) {
-	my ($dbh, $query, @values) = @_;
+sub db_insert ($$$;@) {
+	my ($dbh, $index, $query, @values) = @_;
+	my $insert_id = undef;
 
-	$dbh->do($query, undef, @values);
-	return $dbh->{'mysql_insertid'};
+	# MySQL
+	if ($RDBMS eq 'mysql') {
+		$dbh->do($query, undef, @values);
+		$insert_id = $dbh->{'mysql_insertid'};
+	}
+	# PostgreSQL
+	elsif ($RDBMS eq 'postgresql') {
+		$insert_id = get_db_value ($dbh, $query . ' RETURNING ' . db_reserved_word ($index), undef, @values); 
+	}
+
+	return $insert_id;
 }
 
 ##########################################################################
@@ -352,8 +374,8 @@ sub db_update ($$;@) {
 ##########################################################################
 ## SQL insert. Returns the ID of the inserted row.
 ##########################################################################
-sub db_process_insert($$$;@) {
-	my ($dbh, $table, $parameters, @values) = @_;
+sub db_process_insert($$$$;@) {
+	my ($dbh, $index, $table, $parameters, @values) = @_;
 		
 	my @columns_array = keys %$parameters;
 	my @values_array = values %$parameters;
@@ -378,7 +400,7 @@ sub db_process_insert($$$;@) {
 			
 	my $columns_string = join(',',@columns_array);
 	
-	my $res = db_insert ($dbh, "INSERT INTO $table (".$columns_string.") VALUES ".$wildcards, @values_array);
+	my $res = db_insert ($dbh, $index, "INSERT INTO $table (".$columns_string.") VALUES ".$wildcards, @values_array);
 
 	return $res;
 }
@@ -426,6 +448,33 @@ sub db_do ($$;@) {
 	$dbh->do($query, undef, @values);
 }
 
+##########################################################################
+## Escape the given reserved word. 
+##########################################################################
+sub db_reserved_word ($) {
+	my $reserved_word = shift;
+	
+	# MySQL
+	return '`' . $reserved_word . '`' if ($RDBMS eq 'mysql');
+
+	# PostgreSQL
+	return '"' . $reserved_word . '"' if ($RDBMS eq 'postgresql');
+	
+	return $reserved_word;
+}
+
+##########################################################################
+## Quote the given string. 
+##########################################################################
+sub db_string ($) {
+	my $string = shift;
+	
+	# MySQL and PostgreSQL
+	return "'" . $string . "'" if ($RDBMS eq 'mysql' || $RDBMS eq 'postgresql');
+	
+	return $string;
+}
+
 # End of function declaration
 # End of defined Code
 
diff --git a/pandora_server/lib/PandoraFMS/NetworkServer.pm b/pandora_server/lib/PandoraFMS/NetworkServer.pm
index cb542858dd..96ca2c7013 100644
--- a/pandora_server/lib/PandoraFMS/NetworkServer.pm
+++ b/pandora_server/lib/PandoraFMS/NetworkServer.pm
@@ -89,7 +89,7 @@ sub data_producer ($) {
 	my @rows;
 
 	if ($pa_config->{'pandora_master'} == 0) {
-		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try AS time_left  
+		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try AS time_left, last_execution_try
 		FROM tagente, tagente_modulo, tagente_estado
 		WHERE server_name = ?
 		AND tagente_modulo.id_agente = tagente.id_agente
@@ -101,7 +101,7 @@ sub data_producer ($) {
 		AND (tagente_modulo.flag = 1 OR ((tagente_estado.last_execution_try + tagente_estado.current_interval) < UNIX_TIMESTAMP())) 
 		ORDER BY tagente_modulo.flag DESC, time_left DESC, last_execution_try ASC ', $pa_config->{'servername'});
     } else {
-		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, tagente_estado.last_execution_try, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left  
+		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, tagente_estado.last_execution_try, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left, last_execution_try
 		FROM tagente, tagente_modulo, tagente_estado
 		WHERE ((server_name = ?) OR (server_name = ANY(SELECT name FROM tserver WHERE status = 0))) 
 		AND tagente_modulo.id_agente = tagente.id_agente
diff --git a/pandora_server/lib/PandoraFMS/PluginServer.pm b/pandora_server/lib/PandoraFMS/PluginServer.pm
index ce6f3aff97..a5d6a93d93 100644
--- a/pandora_server/lib/PandoraFMS/PluginServer.pm
+++ b/pandora_server/lib/PandoraFMS/PluginServer.pm
@@ -89,7 +89,7 @@ sub data_producer ($) {
 	my @rows;
 
 	if ($pa_config->{'pandora_master'} != 1) {
-		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left  
+		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left, last_execution_try
 			FROM tagente, tagente_modulo, tagente_estado
 			WHERE server_name = ?
 			AND tagente_modulo.id_agente = tagente.id_agente
@@ -100,7 +100,7 @@ sub data_producer ($) {
 			AND (tagente_modulo.flag = 1 OR (tagente_estado.last_execution_try + tagente_estado.current_interval) < UNIX_TIMESTAMP())
 			ORDER BY tagente_modulo.flag DESC, time_left DESC, last_execution_try ASC', $pa_config->{'servername'});
     } else {
-		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left  
+		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left, last_execution_try
 			FROM tagente, tagente_modulo, tagente_estado
 			WHERE ((server_name = ?) OR (server_name = ANY(SELECT name FROM tserver WHERE status = 0)))
 			AND tagente_modulo.id_agente = tagente.id_agente
diff --git a/pandora_server/lib/PandoraFMS/PredictionServer.pm b/pandora_server/lib/PandoraFMS/PredictionServer.pm
index 51f9879c5e..dfb35ea27d 100644
--- a/pandora_server/lib/PandoraFMS/PredictionServer.pm
+++ b/pandora_server/lib/PandoraFMS/PredictionServer.pm
@@ -83,7 +83,7 @@ sub data_producer ($) {
 	my @rows;
 
 	if ($pa_config->{'pandora_master'} != 1) {
-		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag
+		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, last_execution_try
 			FROM tagente, tagente_modulo, tagente_estado
 			WHERE server_name = ?
 			AND tagente_modulo.id_agente = tagente.id_agente
@@ -95,7 +95,7 @@ sub data_producer ($) {
 			  OR (tagente_estado.last_execution_try + tagente_estado.current_interval) < UNIX_TIMESTAMP())
 			ORDER BY last_execution_try ASC ', $pa_config->{'servername'});
     } else {
-		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag
+		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, last_execution_try
                                 FROM tagente, tagente_modulo, tagente_estado
 								WHERE ((server_name = ?) OR (server_name = ANY(SELECT name FROM tserver WHERE status = 0)))
                                 AND tagente_modulo.id_agente = tagente.id_agente
diff --git a/pandora_server/lib/PandoraFMS/ProducerConsumerServer.pm b/pandora_server/lib/PandoraFMS/ProducerConsumerServer.pm
index ac6623002b..7e5711983f 100644
--- a/pandora_server/lib/PandoraFMS/ProducerConsumerServer.pm
+++ b/pandora_server/lib/PandoraFMS/ProducerConsumerServer.pm
@@ -104,7 +104,7 @@ sub data_producer ($$$$$) {
 
 	eval {
 		# Connect to the DB
-		my $dbh = db_connect ('mysql', $pa_config->{'dbname'}, $pa_config->{'dbhost'}, 3306,
+		my $dbh = db_connect ($pa_config->{'dbengine'}, $pa_config->{'dbname'}, $pa_config->{'dbhost'}, 3306,
 							  $pa_config->{'dbuser'}, $pa_config->{'dbpass'});
 		$self->setDBH ($dbh);
 
@@ -151,7 +151,7 @@ sub data_consumer ($$$$$) {
 
 	eval {
 		# Connect to the DB
-		my $dbh = db_connect ('mysql', $pa_config->{'dbname'}, $pa_config->{'dbhost'}, 3306,
+		my $dbh = db_connect ($pa_config->{'dbengine'}, $pa_config->{'dbname'}, $pa_config->{'dbhost'}, 3306,
 							  $pa_config->{'dbuser'}, $pa_config->{'dbpass'});
 		$self->setDBH ($dbh);
 
diff --git a/pandora_server/lib/PandoraFMS/ReconServer.pm b/pandora_server/lib/PandoraFMS/ReconServer.pm
index e25140b52b..84994082e8 100644
--- a/pandora_server/lib/PandoraFMS/ReconServer.pm
+++ b/pandora_server/lib/PandoraFMS/ReconServer.pm
@@ -244,7 +244,7 @@ sub data_consumer ($$) {
 		}
 
 		# Assign the new address to the agent
-		db_insert ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`)
+		db_do ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`)
 		                  VALUES (?, ?)', $addr_id, $agent_id);
 
 		# Create network profile modules for the agent
@@ -355,7 +355,7 @@ sub update_recon_task ($$$) {
 sub add_address ($$) {
 	my ($dbh, $ip_address) = @_;
 
-	return db_insert ($dbh, 'INSERT INTO taddress (ip) VALUES (?)', $ip_address);
+	return db_insert ($dbh, 'id_a', 'INSERT INTO taddress (ip) VALUES (?)', $ip_address);
 }
 
 ##########################################################################
@@ -384,13 +384,13 @@ sub create_network_profile_modules {
         $component->{'snmp_community'} = $snmp_community;
 
 		# Create the module
-		my $module_id = db_insert ($dbh, 'INSERT INTO tagente_modulo (id_agente, id_tipo_modulo, descripcion, nombre, max, min, module_interval, tcp_port, tcp_send, tcp_rcv, snmp_community, snmp_oid, ip_target, id_module_group, flag, disabled, plugin_user, plugin_pass, plugin_parameter, max_timeout, id_modulo )
+		my $module_id = db_insert ($dbh, 'id_agente_modulo', 'INSERT INTO tagente_modulo (id_agente, id_tipo_modulo, descripcion, nombre, max, min, module_interval, tcp_port, tcp_send, tcp_rcv, snmp_community, snmp_oid, ip_target, id_module_group, flag, disabled, plugin_user, plugin_pass, plugin_parameter, max_timeout, id_modulo )
 		                                              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?, ?, ?, ?)',
 		                                             $agent_id, $component->{'type'}, $component->{'description'}, safe_input($component->{'name'}), $component->{'max'}, $component->{'min'}, $component->{'module_interval'}, $component->{'tcp_port'}, $component->{'tcp_send'}, $component->{'tcp_rcv'}, $component->{'snmp_community'},
 		                                             $component->{'snmp_oid'}, $addr, $component->{'id_module_group'}, $component->{'plugin_user'}, $component->{'plugin_pass'}, $component->{'plugin_parameter'}, $component->{'max_timeout'}, $component->{'id_modulo'});
 
 		# An entry in tagente_estado is necessary for the module to work
-        db_do ($dbh, 'INSERT INTO tagente_estado (`id_agente_modulo`, `id_agente`, `last_try`, current_interval) VALUES (?, ?, \'0000-00-00 00:00:00\', ?)', $module_id, $agent_id, $component->{'module_interval'});
+        	db_do ($dbh, 'INSERT INTO tagente_estado (`id_agente_modulo`, `id_agente`, `last_try`, current_interval) VALUES (?, ?, \'1970-01-01 00:00:00\', ?)', $module_id, $agent_id, $component->{'module_interval'});
 
 		logger($pa_config, 'Creating module ' . $component->{'name'} . " for agent $addr from network component '" . $component->{'name'} . "'.", 10);
 	}
diff --git a/pandora_server/lib/PandoraFMS/SNMPServer.pm b/pandora_server/lib/PandoraFMS/SNMPServer.pm
index 0586981dae..e545defad1 100644
--- a/pandora_server/lib/PandoraFMS/SNMPServer.pm
+++ b/pandora_server/lib/PandoraFMS/SNMPServer.pm
@@ -144,7 +144,7 @@ sub pandora_snmptrapd {
 
 				# Insert the trap into the DB
 				if (! defined(enterprise_hook ('snmp_insert_trap', [$pa_config, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type, $timestamp, $self->getServerID (), $dbh]))) {
-					my $trap_id = db_insert ($dbh, 'INSERT INTO ttrap (timestamp, source, oid, type, value, oid_custom, value_custom,  type_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
+					my $trap_id = db_insert ($dbh, 'id_trap', 'INSERT INTO ttrap (timestamp, source, oid, type, value, oid_custom, value_custom,  type_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
 											 $timestamp, $source, $oid, $type, $value, $custom_oid, $custom_value, $custom_type);
 					logger ($pa_config, "Received SNMP Trap from $source", 4);
 
diff --git a/pandora_server/lib/PandoraFMS/WMIServer.pm b/pandora_server/lib/PandoraFMS/WMIServer.pm
index b17f6059a0..8e6f173467 100644
--- a/pandora_server/lib/PandoraFMS/WMIServer.pm
+++ b/pandora_server/lib/PandoraFMS/WMIServer.pm
@@ -89,7 +89,7 @@ sub data_producer ($) {
 	my @rows;
 
 	if ($pa_config->{'pandora_master'} != 1) {
-		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left 
+		@rows = get_db_rows ($dbh, 'SELECT tagente_modulo.id_agente_modulo, tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try  AS time_left, last_execution_try
 			FROM tagente, tagente_modulo, tagente_estado
 			WHERE server_name = ?
 			AND tagente_modulo.id_agente = tagente.id_agente
@@ -101,7 +101,7 @@ sub data_producer ($) {
 			OR tagente_modulo.flag = 1)				
 			ORDER BY tagente_modulo.flag DESC, time_left DESC, last_execution_try ASC', $pa_config->{'servername'});		
 	} else {
-		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try AS time_left 
+		@rows = get_db_rows ($dbh, 'SELECT DISTINCT(tagente_modulo.id_agente_modulo), tagente_modulo.flag, UNIX_TIMESTAMP() - tagente_estado.current_interval - tagente_estado.last_execution_try AS time_left, last_execution_try
 			FROM tagente, tagente_modulo, tagente_estado, tserver
 			WHERE ((server_name = ?) OR (server_name = ANY(SELECT name FROM tserver WHERE status = 0)))
 			AND tagente_modulo.id_agente = tagente.id_agente
diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl
index 34c322cca5..5e76d92bac 100755
--- a/pandora_server/util/pandora_db.pl
+++ b/pandora_server/util/pandora_db.pl
@@ -479,7 +479,7 @@ sub pandora_checkdb_consistency {
 		my $count = get_db_value ($dbh, 'SELECT COUNT(*) FROM tagente_estado WHERE id_agente_modulo = ?', $id_agente_modulo);
 		next if (defined ($count) && $count > 0);
 
-		db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, datos, timestamp, estado, id_agente, last_try, utimestamp, current_interval, running_by, last_execution_try) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', $id_agente_modulo, 0, '0000-00-00 00:00:00', 1, $id_agente, '0000-00-00 00:00:00', 0, 0, 0, 0);
+		db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, datos, timestamp, estado, id_agente, last_try, utimestamp, current_interval, running_by, last_execution_try) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', $id_agente_modulo, 0, '1970-01-01 00:00:00', 1, $id_agente, '1970-01-01 00:00:00', 0, 0, 0, 0);
 		print "[CHECKDB] Inserting module $id_agente_modulo in state table \n";
 	}
 
diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl
index 78786abc0f..26d9f72cf9 100755
--- a/pandora_server/util/pandora_manage.pl
+++ b/pandora_server/util/pandora_manage.pl
@@ -226,7 +226,7 @@ sub pandora_delete_all_template_module_actions ($$) {
 sub pandora_create_user ($$$$$) {
 my ($dbh, $name, $password, $is_admin, $comments) = @_;
 
-return db_insert ($dbh, 'INSERT INTO tusuario (id_user, fullname, password, comments, is_admin)
+return db_insert ($dbh, 'id_user', 'INSERT INTO tusuario (id_user, fullname, password, comments, is_admin)
                          VALUES (?, ?, ?, ?, ?)', $name, $name, $password, $comments, $is_admin);
 }
 
@@ -258,7 +258,7 @@ sub pandora_create_template_module_action ($$$) {
 			
  	logger($pa_config, "Creating module alert action to alert '$parameters->{'id_alert_template_module'}'.", 10);
 	
-	my $action_id = db_process_insert($dbh, 'talert_template_module_actions', $parameters);
+	my $action_id = db_process_insert($dbh, 'id', 'talert_template_module_actions', $parameters);
 	
 	return $action_id;
 }
@@ -269,7 +269,7 @@ sub pandora_create_template_module_action ($$$) {
 sub pandora_create_user_profile ($$$$) {
         my ($dbh, $user_id, $profile_id, $group_id) = @_;
         
-        return db_insert ($dbh, 'INSERT INTO tusuario_perfil (id_usuario, id_perfil, id_grupo) VALUES (?, ?, ?)', $user_id, $profile_id, $group_id);
+        return db_insert ($dbh, 'id_up', 'INSERT INTO tusuario_perfil (id_usuario, id_perfil, id_grupo) VALUES (?, ?, ?)', $user_id, $profile_id, $group_id);
 }
 
 ##########################################################################
diff --git a/pandora_server/util/recon_scripts/snmpdevices.pl b/pandora_server/util/recon_scripts/snmpdevices.pl
index 4a9cb0dfe6..5d44ffd306 100755
--- a/pandora_server/util/recon_scripts/snmpdevices.pl
+++ b/pandora_server/util/recon_scripts/snmpdevices.pl
@@ -94,7 +94,7 @@ sub get_agent_from_addr ($$) {
 sub add_address ($$) {
 	my ($dbh, $ip_address) = @_;
 
-	return db_insert ($dbh, 'INSERT INTO taddress (ip) VALUES (?)', $ip_address);
+	return db_insert ($dbh, 'id_a', 'INSERT INTO taddress (ip) VALUES (?)', $ip_address);
 }
 
 ##########################################################################
@@ -234,7 +234,7 @@ for (my $i = 1, $net_addr++; $net_addr < $net_addr->broadcast; $i++, $net_addr++
 	$agent_id = pandora_create_agent (\%conf, $conf{'servername'}, $host_name, $addr, $target_group,									  0, 11, '', 300, $dbh);
 	
 	# Assign the new address to the agent
-	db_insert ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`) VALUES (?, ?)', $addr_id, $agent_id);
+	db_do ($dbh, 'INSERT INTO taddress_agent (`id_a`, `id_agent`) VALUES (?, ?)', $addr_id, $agent_id);
 					  
 	# Generate an event
 	pandora_event (\%conf, "[RECON] New SNMP host [$host_name] detected on network [" . $target_network . ']',                      $target_group, $agent_id, 2, 0, 0, 'recon_host_detected', 0, $dbh);