blib/lib/DBIx/NamedParams.pm

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