blib/lib/DBIx/NamedParams.pm

filter: Statementstmt 91.7% 122 / 133 Branchbran 69.0% 29 / 42 Conditioncond 51.4% 18 / 35 MC/DCmcdc 31.5% 6 / 19 Subroutinesub 95.6% 22 / 23 Podpod 100% 5 / 5 totaltotal 78.6% 202 / 257 SCAR 37.2
CC
33
Cov
80%
bind_param_ex
11.0
_parse_ex2
8.7
driver_typename_map
7.5
CRAP 41.1
↑ Summary Build »
1 package DBIx::NamedParams;
2  
3 3 ▶use 5.008001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use parent qw( DBI );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use DBI::Const::GetInfoType;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Log::Dispatch;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use POSIX qw( strftime );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Term::Encoding qw( term_encoding );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 3 ▶use version 0.77; our $VERSION = version->declare("v0.0.9");
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 3 our $KeepBindingIfNoKey = 0;
18  
19 3 ▶my $_default_log_filename = $ENV{'HOME'} || $ENV{'USERPROFILE'} || $ENV{'TMP'} || '/tmp';
Condition37%3/8
$ENV{'HOME'} || $ENV{'USERPROFILE'} || $ENV{'TMP'} || '/tmp'
l!l
30
$ENV{"HOME"} or $ENV{"USERPROFILE"} or $ENV{"TMP"}
l!l&&r!l&&!r
300
$ENV{"HOME"} or $ENV{"USERPROFILE"}
l!l&&r!l&&!r
300
MC/DC0%0/3
$ENV{'HOME'} || $ENV{'USERPROFILE'} || $ENV{'TMP'} || '/tmp'
$ENV{"HOME"} $ENV{"USERPROFILE"} $ENV{"TMP"}
Truth table0%0/4
A or B or C
A= $ENV{"HOME"}B= $ENV{"USERPROFILE"}C= $ENV{"TMP"}
ABCresult
1XX1
01X1
0011
0000
20 3 $_default_log_filename =~ s#\\#/#g;
21 3 $_default_log_filename .= '/DBIx-NamedParams.log';
22  
23 3 my %_SQL_TypeRefs = ();
24 3 my %_SQL_TypeInvs = ();
25 3 my $_SQL_Types = '';
26 3 my @_NamedParams = ();
27 3 my $_index;
28 3 my $_log = undef;
29  
30 sub import {
31 3 ▶ DBI->import();
Subroutine import: called CC=1 SCAR=0.0
32 3 *{DBI::db::driver_typename_map} = \&driver_typename_map;
33 3 *{DBI::db::prepare_ex} = \&prepare_ex;
34 3 *{DBI::st::bind_param_ex} = \&bind_param_ex;
35 3 _init();
36 }
37  
38 sub _init {
39 3 ▶ foreach ( @{ $DBI::EXPORT_TAGS{sql_types} } ) {
Subroutine _init: called CC=3 SCAR=11.0
40 174 my $refFunc = \&{"DBI::$_"};
41 174 ▶ if (/^SQL_(.*)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^SQL_(.*)$/i) 174 0 174
42 174 $_SQL_TypeRefs{$1} = &{$refFunc};
43 174 $_SQL_TypeInvs{ &{$refFunc} } = $1;
44 }
45 }
46 3 $_SQL_Types = all_sql_types();
47 }
48  
49 sub _thisFuncName {
50 13 ▶ ( caller(1) )[3] =~ /([^:]+)$/;
Subroutine _thisFuncName: called CC=1 SCAR=0.0
51 13 return $1;
52 }
53  
54 sub debug_log {
55 0 ▶ my $filename = shift || $_default_log_filename;
Subroutine debug_log: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/3
shift() || $_default_log_filename
l!l&&r!l&&!r
000
MC/DC0%0/2
shift() || $_default_log_filename
shift() $_default_log_filename
Truth table0%0/3
A || B
A= shift()B= $_default_log_filename
ABresult
1X1
011
000
56 0 $_log = Log::Dispatch->new(
57 outputs => [
58 [ 'File',
59 min_level => 'debug',
60 filename => encode( term_encoding, $filename ),
61 binmode => ":utf8",
62 permissions => 0666,
63 newline => 1,
64 ],
65 ],
66 );
67 0 $_log->info( _thisFuncName(), strftime( "%Y-%m-%d %H:%M:%S", localtime ) );
68 }
69  
70 sub all_sql_types {
71 return wantarray
72 4 ▶ ? sort( keys(%_SQL_TypeRefs) )
Subroutine all_sql_types: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 3 4
73 : join( "|", sort( keys(%_SQL_TypeRefs) ) );
74 }
75  
76 sub driver_typename_map {
77 1 ▶ my $self = shift;
Subroutine driver_typename_map: called CC=6 SCAR=20.2
Pod documented
78 my %map = map {
79 1 my $datatype = $_->{'SQL_DATA_TYPE'} # MS SQL Server
80 || $_->{'SQL_DATATYPE'} # MySQL
81 5 ▶ || $_->{'DATA_TYPE'}; # SQLite
Condition50%3/6
$_->{'SQL_DATA_TYPE'} || $_->{'SQL_DATATYPE'} || $_->{'DATA_TYPE'}
l!l&&r!l&&!r
041
$_->{"SQL_DATA_TYPE"} or $_->{"SQL_DATATYPE"}
l!l&&r!l&&!r
005
MC/DC33%1/3
$_->{'SQL_DATA_TYPE'} || $_->{'SQL_DATATYPE'} || $_->{'DATA_TYPE'}
$_->{"SQL_DATA_TYPE"} $_->{"SQL_DATATYPE"} $_->{'DATA_TYPE'}
Truth table50%2/4
A or B || C
A= $_->{"SQL_DATA_TYPE"}B= $_->{"SQL_DATATYPE"}C= $_->{'DATA_TYPE'}
ABCresult
1XX1
01X1
0011
0000
82 5 ▶ ( $_->{'TYPE_NAME'} || '' ) => $_SQL_TypeInvs{$datatype} || 'WVARCHAR';
Branch: 2 branches
BranchTrueFalseTotal
$_->{"TYPE_NAME"} or "" 1 4 5
$_SQL_TypeInvs{$datatype} or "WVARCHAR" 0 5 5
83 } $self->type_info();
84 1 ▶ if ( $self->get_info( $GetInfoType{'SQL_DBMS_NAME'} ) eq 'Microsoft SQL Server' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->get_info($DBIx::NamedParams::GetInfoType{"SQL_DBMS_NAME"}) eq "Microsoft SQL Server") 0 1 1
85 0 $map{'datetime'} = 'WVARCHAR';
86 0 $map{'smalldatetime'} = 'WVARCHAR';
87 }
88 1 return %map;
89 }
90  
91 sub prepare_ex {
92 7 ▶ my ( $self, $sqlex, $refHash ) = @_;
Subroutine prepare_ex: called CC=7 SCAR=20.0
Pod documented
93 7 my $ret = undef;
94 7 ▶ my $validHash = defined($refHash) && ref($refHash) eq 'HASH';
Condition66%2/3
defined $refHash && ref $refHash eq 'HASH'
!ll&&!rl&&r
502
MC/DC50%1/2
defined $refHash && ref $refHash eq 'HASH'
defined $refHash ref $refHash eq 'HASH'
Truth table66%2/3
A && B
A= defined $refHashB= ref $refHash eq 'HASH'
ABresult
0X0
100
111
95 7 ▶ if ( $sqlex =~ /\:([\w]+)\+-($_SQL_Types)\b/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sqlex =~ /\:([\w]+)\+-($_SQL_Types)\b/) 2 5 7
96 2 ▶ if ($validHash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($validHash) { } 2 0 2
97 2 $sqlex =~ s/\:([\w]+)\+-($_SQL_Types)\b/_parse_ex1($refHash,$1,$2);/ge;
98 } else {
99 0 croak("prepare_ex need a hash reference when SQL is variable length.");
100 }
101 }
102 7 @_NamedParams = ();
103 7 $_index = 1;
104 7 $sqlex =~ s/\:([\w]+)(?:\{(\d+)\})?-($_SQL_Types)\b/_parse_ex2($1,$2,$3);/ge;
105 7 ▶ if ($_log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_log) 0 7 7
106 0 $_log->info( _thisFuncName(), 'sql_raw', "{{$sqlex}}" );
107 }
108 7 ▶ $ret = $self->prepare($sqlex) or croak($DBI::errstr);
Branch: 1 branch
BranchTrueFalseTotal
$ret = $self->prepare($sqlex) or croak($DBI::errstr) 0 7 7
109 7 ▶ if ($validHash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($validHash) 2 5 7
110 2 $ret->bind_param_ex($refHash);
111 }
112 7 return $ret;
113 }
114  
115 sub _parse_ex1 {
116 2 ▶ my ( $refHash, $name, $type ) = @_;
Subroutine _parse_ex1: called CC=2 SCAR=7.1
117 2 my $numOfArray = 0;
118 2 ▶ if ( ref( $refHash->{$name} ) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $refHash->{$name} eq 'ARRAY') { } 2 0 2
119 2 $numOfArray = scalar( @{ $refHash->{$name} } );
120 } else {
121 0 croak("Must be array: ${name}");
122 }
123 2 return ":${name}{${numOfArray}}-${type}";
124 }
125  
126 sub _parse_ex2 {
127 10 ▶ my $name = shift || '';
Subroutine _parse_ex2: called CC=8 SCAR=21.6
Condition50%1/2
shift() || ''
l!l
100
MC/DC0%0/1
shift() || ''
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
128 10 ▶ my $repeat = shift || 0;
Condition100%2/2
shift() || 0
l!l
37
MC/DC100%1/1
shift() || 0
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
129 10 ▶ my $type = shift || '';
Condition50%1/2
shift() || ''
l!l
100
MC/DC0%0/1
shift() || ''
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
130 10 my $ret = '';
131  
132 10 ▶ if ($_log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_log) 0 10 10
133 0 ▶ $_log->info( _thisFuncName(), "[$_index]", "\"$name\"",
Branch: 1 branch
BranchTrueFalseTotal
!$repeat ? : 0 0 0
134 ( !$repeat ) ? "scalar" : "array[$repeat]", $type );
135 }
136 10 ▶ if ( !$repeat ) { # scalar
Branch: 1 branch
BranchTrueFalseTotal
if (not $repeat) { } 7 3 10
137 $_NamedParams[ $_index++ ] = {
138 Name => $name,
139 7 Type => $_SQL_TypeRefs{$type},
140 Array => -1,
141 };
142 7 $ret = '?';
143 } else { # array
144 3 ▶ for ( my $i = 0; $i < $repeat; ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $repeat) 10 3 13
145 $_NamedParams[ $_index++ ] = {
146 Name => $name,
147 10 Type => $_SQL_TypeRefs{$type},
148 Array => $i,
149 };
150 }
151 3 $ret = substr( '?,' x $repeat, 0, -1 );
152 }
153 10 return $ret;
154 }
155  
156 sub bind_param_ex {
157 3 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
158 13 ▶ my ( $self, $refHash ) = @_;
Subroutine bind_param_ex: called CC=10 SCAR=24.0
Pod documented
159 13 ▶ if ( !defined($refHash) || ref($refHash) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $refHash or ref $refHash ne "HASH") 0 13 13
Condition33%1/3
not defined $refHash or ref $refHash ne "HASH"
l!l&&r!l&&!r
0013
MC/DC0%0/2
not defined $refHash or ref $refHash ne "HASH"
not defined $refHash ref $refHash ne "HASH"
Truth table33%1/3
not(A) or B
A= not defined $refHashB= ref $refHash ne "HASH"
ABresult
1X1
011
000
160 0 croak("bind_param_ex need a hash reference.");
161 }
162 13 my $thisFunc = _thisFuncName();
163 13 ▶ for ( my $i = 1; $i < @_NamedParams; ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @_NamedParams) 45 13 58
164 45 my $param = $_NamedParams[$i];
165 45 ▶ if ( $KeepBindingIfNoKey && !exists( $refHash->{ $param->{'Name'} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DBIx::NamedParams::KeepBindingIfNoKey and not exists $$refHash{$param->{"Name"}}) 14 31 45
Condition100%3/3
$DBIx::NamedParams::KeepBindingIfNoKey and not exists $$refHash{$param->{"Name"}}
!ll&&!rl&&r
161514
MC/DC100%2/2
$DBIx::NamedParams::KeepBindingIfNoKey and not exists $$refHash{$param->{"Name"}}
$DBIx::NamedParams::KeepBindingIfNoKey not exists $$refHash{$param->{"Name"}}
Truth table100%3/3
A and not(B)
A= $DBIx::NamedParams::KeepBindingIfNoKeyB= not exists $$refHash{$param->{"Name"}}
ABresult
0X0
100
111
166 14 next;
167 }
168 31 my $idx = $param->{'Array'};
169 31 my $value1 = $refHash->{ $param->{'Name'} };
170 31 ▶ my $value2
Branch: 1 branch
BranchTrueFalseTotal
$idx < 0 || ref $value1 ne 'ARRAY' ? : 21 10 31
Condition66%2/3
$idx < 0 or ref $value1 ne "ARRAY"
l!l&&r!l&&!r
21010
MC/DC50%1/2
$idx < 0 or ref $value1 ne "ARRAY"
$idx < 0 ref $value1 ne "ARRAY"
Truth table66%2/3
A or B
A= $idx < 0B= ref $value1 ne "ARRAY"
ABresult
1X1
011
000
171 = ( $idx < 0 || ref($value1) ne 'ARRAY' )
172 ? $value1
173 : $value1->[$idx];
174 31 my $datatype = $param->{'Type'};
175 31 ▶ if ($_log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_log) 0 31 31
176 0 $_log->info( $thisFunc, "[$i]", "\"$value2\"", $_SQL_TypeInvs{$datatype} );
177 }
178 31 ▶ $self->bind_param( $i, $value2, { TYPE => $datatype } )
Branch: 1 branch
BranchTrueFalseTotal
$self->bind_param($i, $value2, {"TYPE", $datatype}) or croak($DBI::errstr) 0 31 31
179 or croak($DBI::errstr);
180 }
181 13 return $self;
182 }
183  
184 3 1;
185 __END__
186  
187 =encoding utf-8
188  
189 =head1 NAME
190  
191 DBIx::NamedParams - use named parameters instead of '?'
192  
193 =head1 SYNOPSIS
194  
195 This module allows you to use named parameters as the placeholders instead of '?'.
196  
197 use DBIx::NamedParams;
198  
199 # Connect DB
200 my $dbh = DBI->connect( ... ) or die($DBI::errstr);
201  
202 # Bind scalar
203 # :<Name>-<Type>
204 my $sql_insert = qq{
205 INSERT INTO `Users` ( `Name`, `Status` ) VALUES ( :Name-VARCHAR, :State-INTEGER );
206 };
207 my $sth_insert = $dbh->prepare_ex( $sql_insert ) or die($DBI::errstr);
208 $sth_insert->bind_param_ex( { 'Name' => 'Rio', 'State' => 1, } ) or die($DBI::errstr);
209 my $rv = $sth_insert->execute() or die($DBI::errstr);
210  
211 # Bind fixed array
212 # :<Name>{Number}-<Type>
213 my $sql_select1 = qq{
214 SELECT `ID`, `Name`, `Status`
215 FROM `Users`
216 WHERE `Status` in ( :State{4}-INTEGER );
217 };
218 my $sth_select1 = $dbh->prepare_ex( $sql_select1 ) or die($DBI::errstr);
219 $sth_select1->bind_param_ex( { 'State' => [ 1,2,4,8 ], } ) or die($DBI::errstr);
220 my $rv = $sth_select1->execute() or die($DBI::errstr);
221  
222 # Bind variable array
223 # :<Name>+-<Type>
224 my $sql_select2 = qq{
225 SELECT `ID`, `Name`, `Status`
226 FROM `Users`
227 WHERE `Status` in ( :State+-INTEGER );
228 };
229 my $sth_select2 = $dbh->prepare_ex( $sql_select2, { 'State' => [ 1,2,4,8 ], } )
230 or die($DBI::errstr);
231 my $rv = $sth_select2->execute() or die($DBI::errstr);
232  
233 =head1 DESCRIPTION
234  
235 DBIx::NamedParams helps binding SQL parameters.
236  
237 =head1 FLAGS
238  
239 =head2 $DBIx::NamedParams::KeepBindingIfNoKey
240  
241 In C<bind_param_ex()>, this flag controls the behavior when the hash reference doesn't have the key
242 in the SQL statement.
243  
244 Defaults to false. The placeholders according to the missing keys are set to C<undef>.
245 All of the placeholders have to be set at once.
246  
247 Setting this to a true value, the placeholders according to the missing keys are kept.
248 You can set some placeholders at first, and set other placeholders later.
249 If you want to set a placeholder to null, you have to set C<undef> explicitly.
250  
251 =head1 METHODS
252  
253 =head2 DBIx::NamedParams Class Methods
254  
255 =head3 all_sql_types
256  
257 Returns the all SQL data types defined in L<DBI> .
258  
259 my @types = DBIx::NamedParams::all_sql_types();
260  
261 =head3 debug_log
262  
263 Writes the parsed SQL statement and the values at the parameter positions into the log file.
264 When omitting the filename, creates the log file in the home directory.
265  
266 DBIx::NamedParams::debug_log( '/tmp/testNamedParams.log' );
267  
268 =head2 Database Handle Methods
269  
270 =head3 driver_typename_map
271  
272 Returns the hash from the driver type names to the DBI typenames.
273  
274 my %map = $dbh->driver_typename_map();
275  
276 =head3 prepare_ex
277  
278 Prepares a statement for later execution by the database engine and returns a reference to a statement handle object.
279 When the SQL statement has the variable array C<:E<lt>NameE<gt>+-E<lt>TypeE<gt>>, the hash reference as the second argument is mandatory.
280 When the SQL statement doesn't have the variable array C<:E<lt>NameE<gt>+-E<lt>TypeE<gt>>, the hash reference as the second argument is optional.
281  
282 my $sth = $dbh->prepare_ex( $statement, $hashref ) or die($DBI::errstr);
283  
284 =head2 Database Handle Methods
285  
286 =head3 bind_param_ex
287  
288 Binds each parameters at once according to the hash reference.
289 The hash reference should have the keys that are same names to the parameter names in the SQL statement.
290 When the hash reference doesn't have the key that is same to the parameter name, the parameter is not set.
291  
292 $sth->bind_param_ex( $hashref ) or die($DBI::errstr);
293  
294 =head1 SEE ALSO
295  
296 =head2 Similar modules
297  
298 L<Tao::DBI>
299  
300 L<DBIx::NamedBinding>
301  
302 =head2 DBD informations
303  
304 L<SQLite Keywords|https://www.sqlite.org/lang_keywords.html> explains how to quote the identifier.
305  
306 =head1 LICENSE
307  
308 Copyright (C) TakeAsh.
309  
310 This library is free software; you can redistribute it and/or modify
311 it under the same terms as Perl itself.
312  
313 =head1 AUTHOR
314  
315 L<TakeAsh|https://github.com/TakeAsh/>
316  
317 =cut
318  
↑ Summary Build »