WebSource/DB.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 70 CC 3 SCAR 13.9
CC
3
Cov
0%
_init_
6.0
handle
6.0
BEGIN
2.0
CRAP 4.0
1 package WebSource::DB;
2  
3 use strict;
4 use WebSource::Module;
5 use Carp;
6 use DBI;
7  
8 our @ISA = ('WebSource::Module');
9  
10 =head1 NAME
11  
12 WebSource::DB : For each input execute a query and return the result as output
13  
14 =head1 DESCRIPTION
15  
16 A DB operator allows to execute a parameterized SQL query for each input.
17 This allows, for example, to populate a database with extracted data.
18  
19 A typical DB operator declaration is as follows :
20  
21 <ws:database name="db" forward-to="format">
22 <parameters>
23 <param name="db" value="factbook" />
24 <param name="user" value="username" />
25 <param name="pass" value="password" />
26 </parameters>
27 <query>
28 INSERT INTO country(name, population, coordinates)
29 VALUES ('$country','$population','$coordinates')
30 </query>
31 </ws:database>
32  
33 When the query is active (results are produced), the operator returns
34 these results. Otherwise, the input is simply forwarded on for further
35 treatment.
36  
37 =head1 SYNOPSIS
38  
39 $cache = WebSource::DB->new(wsnode => $node);
40  
41 # for the rest it works as a WebSource::Module
42  
43 =head1 METHODS
44  
45 =over 2
46  
47 =item B<< $source = WebSource->new(desc => $node); >>
48  
49 Create a new DB operator;
50  
51 =cut
52  
53 sub _init_ {
54 my $self = shift;
55 $self->SUPER::_init_;
56  
57 $self->{db} or croak("No database selected for ", $self->{name});
58 $self->{host} or $self->{host} = "localhost";
59 $self->{user} or $self->{user} = getlogin;
60 $self->{dsn} = "DBI:mysql:" .
61 "database=". $self->{db} . ";" .
62 "host=" . $self->{host};
63 if(my $wsd = $self->{wsdnode}) {
64 $self->{query} = $wsd->findvalue("query");
65 }
66 $self->{query} or croak("No query for ",$self->{name});
67 }
68  
69 sub handle {
70 my ($self,$env) = @_;
71 my $query = $self->{query};
72
73 foreach my $key (keys(%$env)) {
74 my $val = $env->{$key};
75 $val =~ s/'/''/g;
76 $query =~ s/\$$key/$val/g;
77 }
78 $self->log(3,"Executing...\n",$query,"\n");
79  
80 my @res;
81 my $dbh = DBI->connect($self->{dsn},$self->{user},$self->{pass});
82 my $sth = $dbh->prepare($query);
83 $sth->execute();
84 if($sth->{Active}) {
85 while (my $ref = $sth->fetchrow_hashref()) {
86 push @res, (WebSource::Envelope->new(
87 %$ref,
88 data => undef,
89 type => "empty"
90 ));
91 }
92 $sth->finish();
93 } else {
94 # just forward the envelope for further treament
95 push @res, $env;
96 }
97 $dbh->disconnect();
98 return @res;
99 }
100  
101 =back
102  
103 =head1 SEE ALSO
104  
105 WebSource::Module
106  
107 =cut
108  
109 1;