Most of our current codebase is written in Perl with some CMMI level 5 compliant and with it comes a whole slew of metrics that need to be collected and analysed. The term “metrics” is used as a statistical measure for the most part. Business folks love throwing words around that really don’t mean what they think they mean. More on that later.
The point is that I’ve been tasked to write tests for a Perl script that queries our database for some records. I’ve had very little experience creating Perl scripts from scratch but that hasn’t been a problem. I also know that there must be testing frameworks for Perl out there that would make my life a lot easier. I just haven’t spent the time investigating them. With that said, I’m not using a framework. I want some way to abstract the database stuff from the testing code so I wanted to create an object that handles all the database stuff. The Code Project has a good post which starts off with Camel POOP which gives a pretty good intro to object-oriented programming (OOP) in Perl.
Since I was abstracting out the datbase nonsense, I wanted some way to be able to insert data into the database without having to construct an SQL query by hand each time. The solution I found was to create a method that takes in a hash of all the data values for the row to be inserted. Being a Perl noob, I found Alex Batko’s post on hashes.
Here’s the code I came up with:
sub insert {
my ( $self, $tablename, %hash ) = @_;
if(defined($tablename)) {
my $insertquery = “INSERT INTO $tablename (“;
for my $key ( keys %hash ) {
$insertquery .= “$key,”;
}
$insertquery = substr($insertquery, 0, -1); # remove the last ,
$insertquery .= “) VALUES (“;
for my $key ( keys %hash ) {
my $value = $hash{$key};
$insertquery .= “‘$value’,”;
}
$insertquery = substr($insertquery, 0, -1); # remove the last ,
$insertquery .= “);”;
return true if($self->{_dbconn}->Query($insertquery)) ;
return nil;
}
}
UPDATE:
I forget to mention why this is of any use to me. It allows me to insert test records into my database easily and have it very readable. Ultimately, it would be nice to put all the test records into a fixture file like how Rails does it. It makes it nice and clean that way. However, I don’t want to waste time trying to decide on how to represent the data in the fixture and then how I’m to parse it. For now, this is easiest for me. So when I use this method I do something like this:
%hash = (
some_num => ‘10.00′,
date_created => time(),
date_acted => time(),
type => ‘test’,
category => ‘incorrect category’,
status => ‘working’,
severity => ‘2′,
);
$conn->insert(“some_table”, %hash);