# Copyright (C) 2005 FishGrove Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: DBroutines.pm,v 1.3 2006/03/07 14:39:11 slash5234 Exp $

package Affelio::misc::DBroutines;
{
    use lib("../../../lib/");
    use DBI;

    use Exporter;
    @Affelio::misc::DBroutines::ISA = "Exporter";
    @Affelio::misc::DBroutines::EXPORT = qw (db_value_replace);

    sub db_value_replace{
	my $db = shift; 
	my $dbname = shift;
	my $key_col = shift;
	my $target_col = shift;
	my $old = shift;
	my $new = shift;

	my $key_data;
	my $target_data;
	my $target_data_new;
	my %tmphash;

	Affelio::misc::Debug::debug_print("db_replace: start.");
	######################################
	#Retrieve data
	######################################
	my $q1 = "SELECT $key_col, $target_col FROM $dbname";

	Affelio::misc::Debug::debug_print("db_replace: [$q1]");

	my $s1 = $db->prepare($q1);
	if($@){
	    Affelio::misc::Debug::debug_print("db_replace:".$db->errstr);
	    die $db->errstr;
	}

	$s1->execute();
	if($@){
	    Affelio::misc::Debug::debug_print("db_replace:".$db->errstr);
	    die $db->errstr;
	}

	while( ($key_data, $target_data) = $s1->fetchrow_array){
	    $tmphash{$key_data} = $target_data;
	}
	undef($q1);
	undef($s1);

	######################################
	#Distill each line, replace, and store 
	######################################
	Affelio::misc::Debug::debug_print("db_replace: distilling...");
	while (($key_data, $target_data) = each(%tmphash)) {

	    $target_data_new = $target_data;
	    $old =~ s/\-/\\\-/g;
	    $target_data_new =~ s/$old/$new/g; 

	    Affelio::misc::Debug::debug_print("db_replace: [$key_data] [$target_data]->[$target_data_new]");

	    my $q2 = "update $dbname set $target_col = '$target_data_new' where $key_col = $key_data";
	    Affelio::misc::Debug::debug_print("db_replace: [$q2]");
	    
	    my $s2 = $db->prepare($q2);
	    if($@){
	    Affelio::misc::Debug::debug_print("db_replace:".$db->errstr);
	    die $db->errstr;
	    }

	    $s2->execute();
	    if($@){
	    Affelio::misc::Debug::debug_print("db_replace:".$db->errstr);
	    die $db->errstr;
	    }   

	}

	Affelio::misc::Debug::debug_print("db_replace: end.");
    }
    


}
1;
