blib/lib/VUser/ExtLib/SQL.pm untested

filter: Statementstmt 0.0% 0 / 145 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 33 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 288 CC 31 SCAR 47.5
CC
31
Cov
0%
execute
306.0
Log
20.0
new
12.0
CRAP 116.0
1 package VUser::ExtLib::SQL;
2 use warnings;
3 use strict;
4  
5 # Copyright 2006 Randy Smith <perlstalker@vuser.org>
6 # $Id: SQL.pm,v 1.11 2007/04/10 22:38:39 perlstalker Exp $
7  
8 our $VERSION = "0.1.1";
9  
10 use Exporter;
11 our @ISA = qw(Exporter);
12  
13 our @EXPORT = (); # Export nothing by default
14 our @EXPORT_OK = qw(execute);
15 our %EXPORT_TAGS = ();
16  
17 use VUser::Log qw(:levels);
18 use DBI;
19  
20 =head1 NAME
21  
22 VUser::ExtLib::SQL - Common functions for handling SQL with in vuser
23  
24 =head1 DESCRIPTION
25  
26 VUser::ExtLib::SQL contains common functions and features for working
27 with databases. It has both a functional and an object-oriented interface.
28 The OO interface offers more features such as macros.
29  
30 =head1 Class Methods
31  
32 =head2 new
33  
34 VUser::ExtLib::SQL->new($cfg, $paramters);
35
36 =over 4
37  
38 =item $cfg
39  
40 The config hash
41  
42 =item $paramters
43  
44 { user => 'foo',
45 password => 'bar',
46 dsn => 'dbi:mysql:database=baz',
47 macros => { 'u' => 'username',
48 'p' => 'password'
49 }
50 }
51  
52 =back
53  
54 =cut
55  
56 sub new {
57 my $class = shift;
58 my $cfg = shift;
59 my $params = shift;
60
61 my $self = {dsn => undef,
62 user => undef,
63 password => undef,
64 macros => {},
65 _log => undef
66 };
67 bless $self, $class;
68  
69 if (ref $class && UNIVERSAL::isa($class, 'VUser::ExtLib::SQL')) {
70 $self->dsn($class->dsn());
71 $self->user($class->user());
72 $self->password($class->password());
73 $self->macros($class->macros());
74 $self->{_log} = $class->Log();
75 } else {
76 if (defined $main::log
77 and UNIVERSAL::isa($main::log, 'VUser::Log'))
78 {
79 $self->{_log} = $main::log;
80 } else {
81 $self->{_log} = VUser::Log->new($cfg, 'VUser::ExtLib::SQL');
82 }
83 }
84
85 $self->dsn($params->{dsn});
86 $self->user($params->{user});
87 $self->password($params->{password});
88 $self->macros($params->{macros});
89 return $self;
90 }
91  
92 =pod
93  
94 =head2 execute
95  
96 Execute a SQL query.
97  
98 There are a few predefined macros that you can use in your
99 SQL. The values will be quoted and escaped before being inserted into
100 the SQL. You can specify your own custom macros if you use the OO
101 interface for VUser::ExtLib::SQL. See L<new|the new() method> above.
102  
103 =over 4
104  
105 =item %%
106  
107 Unquoted %
108  
109 =item %-option
110  
111 This will be replaced by the value of --option passed in when vuser is called.
112  
113 =item %$option
114  
115 This will be replaced by the value of $args{option} passed to execute().
116 option may only match I<\w> or I<->. For example:
117  
118 my $db = VUser::ExtUtil::SQL->new(...);
119 my $sth = $db->execute($opts,
120 "select * from foo where bar = %$bar",
121 {bar => 'baz'} );
122 # Possibly get results with $sth->fetchrow_*
123 $sth->finish;
124  
125 execute() returns the statement handle after $sth->execute() has been run.
126 Remember to run $sth->finish() on the returned statement handle when you're
127 done with it.
128  
129 =item %\option
130  
131 B<WARNING:> This is a very dangerous option and must be handled with care.
132 If you don't need to use it, don't use it.
133  
134 Replace the option with the unescaped value of the option. This does not
135 use placeholders like the other options above. All quoting, escaping, etc.
136 is left to the caller to handle before passing the value to execute().
137  
138 =back
139  
140 =cut
141  
142 sub execute {
143 my $self;
144 my $dbh;
145  
146 my $macros = '';
147 my %macros = ();
148  
149 if (UNIVERSAL::isa($_[0], 'VUser::ExtLib::SQL')) {
150 $self = shift;
151 $dbh = $self->db_connect();
152 $macros = join('|', keys %{$self->macros()});
153 %macros = %{ $self->macros() };
154 } elsif (UNIVERSAL::isa($_[0], '')) {
155 $dbh = shift;
156 }
157
158 my $opts = shift;
159 my $sql = shift;
160 my $argsref = shift;
161 my $overridesref = shift;
162  
163 my %args = ();
164 if (defined $argsref and ref $argsref eq 'HASH') {
165 %args = %{ $argsref };
166 }
167  
168 my %overrides = ();
169 if (defined $overridesref and ref $overridesref eq 'HASH') {
170 %overrides = %{ $overridesref };
171 }
172  
173 if ( not defined $sql or $sql =~ /^\s*$/ ) {
174 Log()->log( LOG_ERROR, "No SQL command given." );
175 die "No SQL command given\n";
176 }
177  
178 Log()->log( LOG_DEBUG, "Original SQL: $sql" );
179  
180 # This will match the macros we are using
181 my $re = qr/(?:%($macros|%|-[\w-]+|\$[\w-]+))/;
182  
183 Log()->log( LOG_DEBUG, "Macros: $macros; RE: $re");
184  
185 # Pull the options out of the query
186 my @options = $sql =~ /$re/g;
187  
188 # replace the options with ? placeholders
189 $sql =~ s/$re/?/g;
190  
191 # Now replace the manually escaped options. %\option-name
192 my @man_opts = $sql =~ /(?:%\\([\w-]+))/;
193 foreach my $opt (@man_opts) {
194 if (defined $overrides{$opt}) {
195 $sql =~ s/%\\$opt/$overrides{$opt}/e;
196 } elsif (defined $args{$opt}) {
197 $sql =~ s/%\\$opt/$args{$opt}/e;
198 } elsif (defined $macros{$opt}) {
199 $sql =~ s/%\\$opt/$opts->{$macros{$opt}}/e;
200 }
201 }
202  
203 Log()->log( LOG_DEBUG, "Options (" .scalar @options .'): ' . join( ', ', @options ) );
204 Log()->log( LOG_DEBUG, "New SQL: $sql" );
205  
206 my @passed_options = ();
207 foreach my $opt (@options) {
208 if ( $opt eq '%') {
209 push @passed_options, '%';
210 } elsif ( $opt =~ /^-([\w-]+)/ ) {
211 push @passed_options, $opts->{$1};
212 } elsif ( $opt =~ /^\$([\w-]+)/ ) {
213 push @passed_options, $args{$1};
214 } elsif ( defined $macros{$opt} ) {
215 if (exists $args{$opt}) {
216 push @passed_options, $overrides{$opt};
217 } else {
218 push @passed_options, $opts->{$macros{$opt}};
219 }
220 }
221 }
222  
223 Log()->log( LOG_DEBUG, "Passed Options (" . scalar @passed_options .'): '
224 . join( ', ', map { defined $_? $_ : 'undef' } @passed_options ) );
225  
226 my $sth = $dbh->prepare($sql)
227 or die "Cannot prepare SQL: ", $dbh->errstr, "\n";
228 my $rc;
229 if (@passed_options) {
230 $rc = $sth->execute( @passed_options )
231 } else {
232 $rc = $sth->execute( )
233 }
234 die ("Cannot execute SQL: ", $sth->errstr, "\n") unless $rc;
235  
236 return $sth;
237 }
238  
239 =pod
240  
241 =head2 db_connect
242  
243 Connect to the database.
244  
245 Returns a DBI database handle.
246  
247 =cut
248  
249 sub db_connect {
250 my $self;
251
252 my $dsn;
253 my $user;
254 my $password;
255
256 my $scope;
257
258 if (ref $_[0] and UNIVERSAL::isa($_[0], 'VUser::ExtLib::SQL')) {
259 $self = shift;
260 $dsn = $self->dsn();
261 $user = $self->user();
262 $password = $self->password();
263 } else {
264 ($dsn, $user, $password) = @_;
265 }
266
267 $scope = shift || 'VUser::ExtLib::SQL';
268  
269 die "No DSN specified\n" unless $dsn;
270  
271 Log()->log(LOG_DEBUG, "Connecting to $dsn as $user");
272
273 my $dbh =
274 DBI->connect_cached( $dsn, $user, $password,
275 { private_vuser_cachekey => $scope } )
276 or die $DBI::errstr;
277 return $dbh;
278 }
279  
280 =pod
281  
282 =head1 Instance Methods
283  
284 =head2 dsn
285  
286 =head2 user
287  
288 =head2 password
289  
290 =cut
291  
292 sub dsn { $_[0]->{dsn} = $_[1] if defined $_[1]; return $_[0]->{dsn}; }
293 sub user { $_[0]->{user} = $_[1] if defined $_[1]; return $_[0]->{user}; }
294 sub password { $_[0]->{password} = $_[1] if defined $_[1]; return $_[0]->{password}; }
295 sub macros { $_[0]->{macros} = $_[1] if defined $_[1]; return $_[0]->{macros}; }
296  
297 sub Log {
298 my $self = shift;
299 if (defined $self and UNIVERSAL::isa($self, 'VUser::ExtLib::SQL')) {
300 return $self->{_log};
301 } else {
302 if (defined ($main::log) and UNIVERSAL::isa($main::log, 'VUser::Log')) {
303 return $main::log;
304 } elsif (defined $VUser::ExtLog::log
305 and UNIVERSAL::isa($main::log, 'VUser::Log')
306 ) {
307 return $VUser::ExtLog::log;
308 } else {
309 # I need to create VUser::ExtLib::log but don't have a $cfg. Hmmm.
310 die "I can't find a VUser::Log\n";
311 }
312 }
313 }
314  
315 sub begin {
316 my $self = shift;
317 if (UNIVERSAL::isa($self, "VUser::ExtLib::SQL")) {
318 Log()->log(LOG_DEBUG, "Beginning transaction");
319 $self->db_connect()->begin_work();
320 } else {
321 Log()->log(LOG_DEBUG, "Cannot begin transaction in function mode");
322 }
323 }
324  
325 sub commit {
326 my $self = shift;
327 if (UNIVERSAL::isa($self, "VUser::ExtLib::SQL")) {
328 Log()->log(LOG_DEBUG, "Committing transaction");
329 $self->db_connect()->commit();
330 } else {
331 Log()->log(LOG_DEBUG, "Cannot commit transaction in function mode");
332 }
333 }
334  
335 sub rollback {
336 my $self = shift;
337 if (UNIVERSAL::isa($self, "VUser::ExtLib::SQL")) {
338 Log()->log(LOG_DEBUG, "Rolling back transaction");
339 $self->db_connect()->rollback();
340 } else {
341 Log()->log(LOG_DEBUG, "Cannot rollback transaction in function mode");
342 }
343 }
344  
345 # Clean up after ourself
346 sub DESTROY {
347 my $self = shift;
348 #my $cached_connections = $self->db_connect();
349 #%$cached_connections = () if $cached_connections;
350 }
351  
352 1;
353  
354 __END__