blib/lib/SQL/Inserter.pm

filter: Statementstmt 100% 156 / 156 Branchbran 100% 54 / 54 Conditioncond 100% 27 / 27 MC/DCmcdc 87.5% 14 / 16 Subroutinesub 100% 20 / 20 Podpod 100% 4 / 4 totaltotal 99.2% 275 / 277 SCAR 36.9
CC
40
Cov
100%
insert
11.0
new
7.0
_row_placeholders
6.0
CRAP 40.0
↑ Summary
1 package SQL::Inserter;
2  
3 5 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 SQL::Inserter - Efficient buffered DBI inserter and fast INSERT SQL builder
13  
14 =head1 VERSION
15  
16 Version 0.01
17  
18 =cut
19  
20 5 our $VERSION = '0.01';
21  
22 5 our @EXPORT_OK = qw(simple_insert multi_insert_sql);
23  
24 =head1 SYNOPSIS
25  
26 use SQL::Inserter;
27  
28 my $sql = SQL::Inserter->new(
29 dbh => $dbh,
30 table => 'table',
31 cols => [qw/column1 column2.../]?,
32 buffer => 100? # No. of rows for multi-row insert
33 );
34  
35 # Fastest method: pass single or multiple rows of data as an array
36 $sql->insert($col1_row1, $col2_row1, $col1_row2...);
37  
38 # You can manually flush the buffer at any time with no argument on insert
39 # (otherwise there is auto-flush on the object's destruction)
40 $sql->insert();
41  
42 # Alternative, pass a single row as a hash, allows SQL code passed as references
43 # instead of values
44 $sql->insert({
45 column1 => $data1,
46 column2 => \'NOW()',
47 ...
48 });
49  
50 # There are also functions to just get the SQL statement and its bind vars
51 # similar to SQL::Abstract or SQL::Maker insert, but with much less overhead:
52 my ($sql, @bind) = simple_insert($table, {col1=>$val...});
53  
54 # Multi-row variant:
55 my ($sql, @bind) = simple_insert($table, [{col1=>$row1_val...},{col1=>$row2_val...},...]);
56  
57 # Or, construct an SQL statement with placeholders for a given number of rows:
58 my $sql = multi_insert_sql('table', [qw/col1 col2.../], $num_of_rows);
59  
60 =head1 DESCRIPTION
61  
62 SQL::Inserter's main lightweight OO interface will let you do L<DBI> inserts as
63 efficiently as possible by managing a multi-row buffer and prepared statements.
64  
65 You only have to select the number of rows for the buffered writes (default is 100)
66 and choose whether to pass your data in arrays (fastest, requires all data to be bind
67 values, will execute the same prepared statement every time the buffer is full) or
68 hashes (allows SQL code apart from plain values).
69  
70 It also provides lightweight functions that return the SQL queries to be used manually,
71 similar to C<SQL::Abstract::insert>, but much faster.
72  
73 =head1 EXPORTS
74  
75 On request: C<simple_insert> C<multi_insert_sql>.
76  
77 =head1 CONSTRUCTOR
78  
79 =head2 C<new>
80  
81 my $sql = SQL::Inserter->new(
82 dbh => $dbh,
83 table => $table,
84 cols => \@column_names?,
85 buffer => 100?,
86 duplicates => $ignore_or_update?,
87 null_undef => $convert_undef_to_NULL?
88 );
89  
90 Creates an object to insert data to a specific table. Buffering is enabled by default
91 and anything left on it will be written when the object falls out of scope / is destroyed.
92  
93 Required parameters:
94  
95 =over 4
96  
97 =item * C<dbh> : A L<DBI> database handle.
98  
99 =item * C<table> : The name of the db table to insert to. See L</"NOTES"> if you
100 are using a restricted word for a table name.
101  
102 =back
103  
104 Optional parameters:
105  
106 =over 4
107  
108 =item * C<cols> : The names of the columns to insert. It is required if arrays are
109 used to pass the data. With hashes they are optional (the order will be followed
110 if they are defined). See L</"NOTES"> if you are using any restricted words for
111 column names.
112  
113 =item * C<buffer> : Max number of rows to be held in buffer before there is a write.
114 The buffer flushes (writes contents) when the object is destroyed. Setting it to 1
115 writes each row separately (least efficient). For small rows you can set buffer to
116 thousands. The default is a (conservative) 100 which works with big data rows.
117  
118 =item * C<duplicates> : For MySQL, define as C<'ignore'> or C<'update'> to get an
119 C<INSERT IGNORE> or C<ON DUPLICATE KEY UPDATE> query respectively. See L</"NOTES">
120 for details on the latter.
121  
122 =item * C<null_undef> : Applies to the hash inserts only. If true, any undefined
123 values will be converted to SQL's C<NULL> (similar to the C<SQL::Abstract> default).
124 The default behaviour will leave an undef as the bind variable, which may either
125 create an empty string in the db or give an error depending on your column type and
126 db settings.
127  
128 =back
129  
130 =cut
131  
132 sub new {
133 13 ▶ my $class = shift;
Subroutine new: called CC=7 SCAR=19.5
Pod documented
134 13 my %args = @_;
135  
136 13 my $self = {};
137 13 bless($self, $class);
138  
139 13 ▶ $self->{dbh} = $args{dbh} || croak("dbh parameter (db handle) required.");
Condition100%3/3
$args{'dbh'} || croak('dbh parameter (db handle) required.')
l!l&&r!l&&!r
1111
MC/DC50%1/2
$args{'dbh'} || croak('dbh parameter (db handle) required.')
$args{'dbh'} croak('dbh parameter (db handle) required.')
Truth table66%2/3
A || B
A= $args{'dbh'}B= croak('dbh parameter (db handle) required.')
ABresult
1X1
011
000
140 12 ▶ $self->{table} = $args{table} || croak("table parameter required.");
Condition100%3/3
$args{'table'} || croak('table parameter required.')
l!l&&r!l&&!r
912
MC/DC50%1/2
$args{'table'} || croak('table parameter required.')
$args{'table'} croak('table parameter required.')
Truth table66%2/3
A || B
A= $args{'table'}B= croak('table parameter required.')
ABresult
1X1
011
000
141 11 $self->{cols} = $args{cols};
142 11 ▶ $self->{buffer} = $args{buffer} || 100;
Condition100%2/2
$args{'buffer'} || 100
l!l
65
MC/DC100%1/1
$args{'buffer'} || 100
$args{'buffer'}
Truth table100%2/2
A
A= $args{'buffer'}
Aresult
11
00
143 11 $self->{dupes} = $args{duplicates};
144 11 $self->{null} = $args{null_undef};
145 11 ▶ if ($self->{dupes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"dupes"}) 2 9 11
146 2 ▶ $self->{ignore} = 1 if $self->{dupes} eq "ignore";
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"dupes"} eq "ignore" 1 1 2
147 2 ▶ $self->{update} = 1 if $self->{dupes} eq "update";
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"dupes"} eq "update" 1 1 2
148 }
149 11 $self->_cleanup();
150  
151 11 return $self;
152 }
153  
154 =head1 METHODS
155  
156 =head2 insert
157  
158 # Fastest array method. Only bind data is passed.
159 my $ret = $sql->insert(@column_data_array);
160  
161 # Alternative, allows SQL code as values in addition to bind variables
162 my $ret = $sql->insert(\%row_data);
163  
164 # No parameters will force emtying of buffer (db write)
165 my $ret = $sql->insert();
166  
167 The main insert method. Returns the return value of the last C<execute> statement
168 if there was one called, 0 otherwise (buffer not full.
169  
170 It works in two main modes, by passing an array or a hashref:
171  
172 =over 4
173  
174 =item Array mode
175  
176 Pass the data for one or more rows in a flat array, buffering will work automatically
177 based on your C<buffer> settings. Obviously your C<@column_data_array> has to contain
178 a multiple of the number of C<cols> defined on the constructor.
179  
180 This is the fastest mode, but it only allows simple bind values. Any undefined values
181 will be passed directly to DBI->execute, which may or may not be what you expect -
182 there will not be any explicit conversion to SQL C<NULL>.
183  
184 =item Hash mode
185  
186 Pass a reference to a hash containing the column names & values for a single row
187 of data. If C<cols> was not defined on the constructor, the columns from the first
188 data row will be used instead. For subsequent rows any extra columns will be disregarded
189 and any missing columns will be considered to have an C<undef> (which can be
190 automatically converted to C<NULL> if the C<null_undef> option was set).
191  
192 =item Flushing the buffer
193  
194 Calling C<insert> with no arguments forces a write to the db, flushing the buffer.
195 You don't have to call this manually as the buffer will be flushed when the object
196 is destroyed (e.g. your object falls out of scope).
197  
198 =item Mixing modes
199  
200 You can theoretically mix modes, but only when the buffer is empty e.g. you can start
201 with the array mode, flush the buffer and continue with hash mode (C<cols> will be
202 defined from the array mode). Or you can start with hash mode (so C<cols> will be defined
203 from the very first hash), and after flushing the buffer you can switch to array mode.
204  
205 =back
206  
207 =cut
208  
209 sub insert {
210 31 ▶ my $self = shift;
Subroutine insert: called CC=11 SCAR=24.0
Pod documented
211  
212 31 ▶ return $self->_hash_insert(@_) if $_[0] and ref($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] and ref $_[0] 13 18 31
Condition100%3/3
$_[0] and ref $_[0]
!ll&&!rl&&r
41413
MC/DC100%2/2
$_[0] and ref $_[0]
$_[0] ref $_[0]
Truth table100%3/3
A and B
A= $_[0]B= ref $_[0]
ABresult
0X0
100
111
213  
214 18 my $ret = 0;
215 18 ▶ if (@_) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_) { } 14 4 18
elsif ($self->{'buffer_counter'}) { } 2 2 4
216  
217 croak("Calling insert without a hash requires cols defined in constructor")
218 14 ▶ unless $self->{cols};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cols"} 1 13 14
219
220 croak("Insert arguments must be multiple of cols")
221 13 ▶ if scalar(@_) % scalar @{$self->{cols}};
Branch: 1 branch
BranchTrueFalseTotal
if scalar(@_) % scalar(@{$self->{"cols"};}) 2 11 13
222  
223 croak("Insert was previously called with hash argument (still in buffer)")
224 11 ▶ if $self->{hash_buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"hash_buffer"} 1 10 11
225  
226 10 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 14 10 24
227 14 my $rows = scalar(@_) / scalar @{$self->{cols}};
228 14 my $left = $self->{buffer} - $self->{buffer_counter}; # Space left in buffer
229  
230 14 ▶ if ($rows > $left) { # Can't fit buffer
Branch: 1 branch
BranchTrueFalseTotal
if ($rows > $left) { } 4 10 14
231 4 my $max = $left * scalar @{$self->{cols}};
232 4 push @{$self->{bind}}, splice(@_,0,$max);
233 4 $self->{buffer_counter} = $self->{buffer};
234 } else {
235 10 push @{$self->{bind}}, splice(@_);
236 10 $self->{buffer_counter} += $rows;
237 }
238 14 ▶ $ret = $self->_write_full_buffer() if $self->{buffer_counter} == $self->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"buffer_counter"} == $self->{"buffer"} 9 5 14
239 }
240 } elsif ($self->{buffer_counter}) { # Empty the buffer
241 2 $ret = $self->_empty_buffer();
242 }
243 14 return $ret;
244 }
245  
246 =head1 ATTRIBUTES
247  
248 =head2 C<last_retval>
249  
250 my $val = $sql->{last_retval}
251  
252 The return value of the last DBI C<execute()> is stored in this attribute. On a successful
253 insert it should contain the number of rows of that statement. Note that an C<insert>
254 call, depending on the buffering, may call C<execute()> zero, one or more times.
255  
256 =head2 C<row_total>
257  
258 my $total = $sql->{row_total}
259  
260 Basically a running total of the return values, for successful inserts it shows you
261 how many rows were inserted into the database. It will be undef if no C<execute()> has
262 been called.
263  
264 =head2 C<buffer_counter>
265  
266 my $count = $sql->{buffer_counter}
267  
268 Check how many un-inserted data rows the buffer currently holds.
269  
270 =head1 FUNCTIONS
271  
272 =head2 simple_insert
273  
274 # Single row
275 my ($sql, @bind) = simple_insert($table, \%fieldvals, \%options);
276  
277 # Multi-row
278 my ($sql, @bind) = simple_insert($table, [\%fieldvals_row1,...], \%options);
279  
280 Returns the SQL statement and bind variable array for a hash containing the row
281 columns and values. Values are treated as bind variables unless they are references
282 to SQL code strings. E.g. :
283  
284 my ($sql, @bind) = simple_insert('table', {foo=>"bar",when=>\"NOW()"});
285 ### INSERT INTO table (foo, when) VALUES (?,NOW())
286  
287 The function also accepts an array of hashes to allow multi-row inserts:
288  
289 my ($sql, @bind) = simple_insert('table', [{foo=>"foo"},{foo=>"bar"}]);
290 ### INSERT INTO table (foo) VALUES (?),(?)
291  
292 The first row (element in array) needs to contain the superset of all the columns
293 that you want to insert, if some of your rows have undefined column data.
294  
295 Options:
296  
297 =over 4
298
299 =item * C<null_undef> : If true, any undefined values will be converted to SQL's
300 C<NULL> (similar to the C<SQL::Abstract> default). The default behaviour will leave
301 an undef as the bind variable, which may either create an empty string in the db or
302 give an error depending on your column type and db settings.
303  
304 =item * C<duplicates> : For MySQL, define as C<'ignore'> or C<'update'> to get an
305 C<INSERT IGNORE> or C<ON DUPLICATE KEY UPDATE> query respectively. See L</"NOTES">
306 for details on the latter.
307  
308 =back
309  
310 =cut
311  
312 sub simple_insert {
313 10 ▶ my $table = shift;
Subroutine simple_insert: called CC=3 SCAR=11.0
Pod documented
314 10 my $fields = shift;
315 10 my $opt = shift;
316  
317 10 my ($placeh, @bind, @cols);
318 10 ▶ if (ref($fields) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fields eq 'ARRAY') { } 3 7 10
319 3 @cols = keys %{$fields->[0]};
320 3 my @rows;
321 3 foreach my $f (@$fields) {
322 5 my ($row, @b) = _row_placeholders($f, \@cols, $opt->{null_undef});
323 5 push @rows, $row;
324 5 push @bind, @b;
325 }
326 3 $placeh = join(",\n", @rows);
327 } else {
328 7 @cols = keys %$fields;
329 7 ($placeh, @bind) = _row_placeholders($fields, \@cols, $opt->{null_undef});
330 }
331  
332 return _create_insert_sql(
333 $table, \@cols, $placeh, $opt->{duplicates}
334 10 ), @bind;
335 }
336  
337 =head2 multi_insert_sql
338  
339 my $sql = multi_insert_sql(
340 $table,
341 \@columns, # names of table columns
342 $num_of_rows?, # default = 1
343 $duplicates? # can be set as ignore/update in case of duplicate key (MySQL)
344 );
345  
346 Builds bulk insert query (single insert is possible too), with ability for
347 ignore/on duplicate key update variants for MySQL.
348  
349 Requires at least the name of the table C<$table> and an arrayref with the column
350 names C<\@columns>. See L</"NOTES"> if you want to quote table or column names.
351  
352 Optional parameters:
353  
354 =over 4
355
356 =item * C<$num_of_rows> : By default it returns SQL with bind value placeholders
357 for a single row. You can define any number of rows to use with multi-row bind
358 variable arrays.
359  
360 =item * C<$duplicate> : For MySQL, passing C<'ignore'> as the 4th argument returns
361 an C<INSERT IGNORE> query. Passing C<'update'> as the argument returns a query
362 containing an `ON DUPLICATE KEY UPDATE` clause (see L</"NOTES"> for further details).
363  
364 =back
365  
366 =cut
367  
368 sub multi_insert_sql {
369 18 ▶ my $table = shift;
Subroutine multi_insert_sql: called CC=5 SCAR=16.1
Pod documented
370 18 my $columns = shift;
371 18 ▶ my $num_rows = shift || 1;
Condition100%2/2
shift() || 1
l!l
126
MC/DC100%1/1
shift() || 1
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
372 18 my $dupe = shift;
373  
374 18 ▶ return unless $table && $columns && @$columns;
Branch: 1 branch
BranchTrueFalseTotal
unless $table and $columns and @$columns 2 15 17
Condition100%6/6
$table and $columns and @$columns
!ll&&!rl&&r
2115
$table and $columns
!ll&&!rl&&r
1116
MC/DC100%3/3
$table and $columns and @$columns
$table $columns @$columns
Truth table100%4/4
A and B and C
A= $tableB= $columnsC= @$columns
ABCresult
0XX0
10X0
1100
1111
375  
376 15 my $placeholders =
377 join(",\n", ('(' . join(',', ('?') x @$columns) . ')') x $num_rows);
378  
379 15 return _create_insert_sql($table, $columns, $placeholders, $dupe);
380 }
381  
382 ## Private methods
383  
384 sub _hash_insert {
385 13 ▶ my $self = shift;
Subroutine _hash_insert: called CC=5 SCAR=16.1
386 13 my $fields = shift;
387 13 my $ret = 0;
388  
389 croak("Insert was previously called with an array argument (still in buffer)")
390 13 ▶ if $self->{buffer_counter} && !$self->{hash_buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"buffer_counter"} and not $self->{"hash_buffer"} 1 12 13
Condition100%3/3
$self->{"buffer_counter"} and not $self->{"hash_buffer"}
!ll&&!rl&&r
751
MC/DC100%2/2
$self->{"buffer_counter"} and not $self->{"hash_buffer"}
$self->{"buffer_counter"} not $self->{"hash_buffer"}
Truth table100%3/3
A and not(B)
A= $self->{"buffer_counter"}B= not $self->{"hash_buffer"}
ABresult
0X0
100
111
391  
392 12 $self->{buffer_counter}++;
393 12 ▶ $self->{cols} = [keys %$fields] if !defined($self->{cols});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"cols"} 1 11 12
394 12 my ($row, @bind) = _row_placeholders($fields, $self->{cols}, $self->{null});
395 12 push @{$self->{hash_buffer}}, $row;
396 12 push @{$self->{bind}}, @bind;
397  
398 12 ▶ $ret = $self->_write_hash_buffer() if $self->{buffer_counter} == $self->{buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"buffer_counter"} == $self->{"buffer"} 5 7 12
399  
400 12 return $ret;
401 }
402  
403 sub _write_full_buffer {
404 9 ▶ my $self = shift;
Subroutine _write_full_buffer: called CC=2 SCAR=6.9
405  
406 $self->{full_buffer_insert} = $self->_prepare_full_buffer_insert()
407 9 ▶ if !$self->{full_buffer_insert};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"full_buffer_insert"} 6 3 9
408  
409 9 $self->_execute($self->{full_buffer_insert});
410 9 $self->_cleanup();
411  
412 9 return $self->{last_retval};
413 }
414  
415 sub _prepare_full_buffer_insert {
416 6 ▶ my $self = shift;
Subroutine _prepare_full_buffer_insert: called CC=1 SCAR=0.0
417 $self->{full_buffer_insert} = $self->{dbh}->prepare(
418 6 multi_insert_sql(map {$self->{$_}} qw/table cols buffer dupes/)
419 );
420 }
421  
422 sub _empty_buffer {
423 5 ▶ my $self = shift;
Subroutine _empty_buffer: called CC=2 SCAR=6.9
424  
425 5 ▶ return $self->_write_hash_buffer() if $self->{hash_buffer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"hash_buffer"} 2 3 5
426  
427 3 my $rows = scalar(@{$self->{bind}}) / scalar @{$self->{cols}};
428 my $sth = $self->{dbh}->prepare(
429 multi_insert_sql(
430 $self->{table},
431 $self->{cols},
432 $rows,
433 $self->{dupes}
434 )
435 3 );
436 3 $self->_execute($sth);
437 3 $self->_cleanup();
438  
439 3 return $self->{last_retval};
440 }
441  
442 sub _write_hash_buffer {
443 7 ▶ my $self = shift;
Subroutine _write_hash_buffer: called CC=1 SCAR=0.0
444  
445 7 my $placeh = join(",\n", @{$self->{hash_buffer}});
446 my $sth = $self->{dbh}->prepare(
447 _create_insert_sql(
448 $self->{table}, $self->{cols}, $placeh, $self->{dupe}
449 )
450 7 );
451 7 $self->_execute($sth);
452 7 $self->_cleanup();
453  
454 7 return $self->{last_retval};
455 }
456  
457 sub _execute {
458 19 ▶ my $self = shift;
Subroutine _execute: called CC=3 SCAR=11.0
459 19 my $sth = shift;
460  
461 19 ▶ $self->{row_total} = 0 if !defined($self->{row_total});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"row_total"} 8 11 19
462 19 $self->{last_retval} = $sth->execute(@{$self->{bind}});
463 19 ▶ $self->{row_total} += $self->{last_retval} if $self->{last_retval};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"last_retval"} 17 2 19
464 }
465  
466 sub _cleanup {
467 30 ▶ my $self = shift;
Subroutine _cleanup: called CC=1 SCAR=0.0
468 30 $self->{bind} = undef;
469 30 $self->{hash_buffer} = undef;
470 30 $self->{buffer_counter} = 0;
471 }
472  
473 sub DESTROY {
474 13 ▶ my $self = shift;
Subroutine DESTROY: called CC=2 SCAR=6.9
475 # Empty buffer
476 13 ▶ $self->_empty_buffer() if $self->{buffer_counter};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"buffer_counter"} 3 10 13
477 }
478  
479 ## Private functions
480  
481 sub _create_insert_sql {
482 36 ▶ my $table = shift;
Subroutine _create_insert_sql: called CC=4 SCAR=13.9
483 36 my $columns = shift;
484 36 my $placeh = shift;
485 36 ▶ my $dupe = shift || "";
Condition100%2/2
shift() || ''
l!l
828
MC/DC100%1/1
shift() || ''
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
486  
487 36 ▶ my $ignore = ($dupe eq 'ignore') ? ' IGNORE' : '';
Branch: 1 branch
BranchTrueFalseTotal
$dupe eq 'ignore' ? : 4 32 36
488 36 my $cols = join(',', @$columns);
489 36 my $sql = "INSERT$ignore INTO $table ($cols)\nVALUES $placeh";
490  
491 36 ▶ $sql .= _on_duplicate_key_update($columns) if $dupe eq 'update';
Branch: 1 branch
BranchTrueFalseTotal
if $dupe eq "update" 4 32 36
492  
493 36 return $sql;
494 }
495  
496 sub _row_placeholders {
497 32 ▶ my $fields = shift;
Subroutine _row_placeholders: called CC=6 SCAR=17.9
498 32 my $cols = shift;
499 32 my $null = shift;
500 32 my @bind = ();
501 32 my $sql = "(";
502  
503 32 my $val;
504  
505 32 foreach my $key (@$cols) {
506 52 ▶ $fields->{$key} = \"NULL" if $null && !defined($fields->{$key});
Branch: 1 branch
BranchTrueFalseTotal
if $null and not defined $fields->{$key} 7 45 52
Condition100%3/3
$null and not defined $fields->{$key}
!ll&&!rl&&r
3877
MC/DC100%2/2
$null and not defined $fields->{$key}
$null not defined $fields->{$key}
Truth table100%3/3
A and not(B)
A= $nullB= not defined $fields->{$key}
ABresult
0X0
100
111
507  
508 52 ▶ if (ref($fields->{$key})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fields->{$key}) { } 12 40 52
509 12 $val = ${$fields->{$key}};
510 } else {
511 40 $val = "?";
512 40 push @bind, $fields->{$key};
513 }
514 52 $sql .= "$val,";
515 }
516  
517 32 ▶ chop($sql) if @$cols;
Branch: 1 branch
BranchTrueFalseTotal
if @$cols 31 1 32
518  
519 32 return "$sql)", @bind;
520 }
521  
522 sub _on_duplicate_key_update {
523 7 ▶ my $columns = shift;
Subroutine _on_duplicate_key_update: called CC=1 SCAR=0.0
524 return "\nON DUPLICATE KEY UPDATE "
525 7 . join(',', map {"$_=VALUES($_)"} @$columns);
526 }
527  
528 =head1 NOTES
529  
530 =head2 Using reserved words as object names
531  
532 If you are using reserved words as table/column names (which is strongly discouraged),
533 just include the appropriate delimiter in the C<table> or C<cols> parameter. E.g. for
534 MySQL with columns named C<from> and C<to> you can do:
535  
536 cols => [qw/`from` `to`/]
537  
538 For PostgreSQL or Oracle you'd do C<[qw/"from" "to"/]>, for SQL Server C<[qw/[from] [to]/]> etc.
539  
540 =head2 On duplicate key update
541  
542 The C<duplicates =E<gt> 'update'> option creates an C<ON DUPLICATE KEY UPDATE> clause
543 for the query. E.g.:
544  
545 my $sql = multi_insert_sql('table_name', [qw/col1 col2/], 2, 'update');
546  
547 will produce:
548  
549 ## INSERT INTO table_name (col1,col2) VALUES (?,?),(?,?) ON DUPLICATE KEY UPDATE col1=VALUES(col1),col2=VALUES(col2)
550  
551 Note that as of MySQL 8.0.20 the C<VALUES> in C<UPDATE> is deprecated (row alias is
552 used instead), so this functionality might need to be updated some day if C<VALUES> is
553 removed completely.
554  
555 =head2 Output whitespace
556  
557 No spaces are added to the output string beyond the minimum. However, there is a new
558 line (C<\n>) added for each row of value placeholders - mainly to easily count the
559 number of rows from the string.
560 Also, the C<ON DUPLICATE KEY UPDATE> clause is on a new line.
561  
562 =head2 Error handling
563  
564 The module does not do any error handling on C<prepare>/C<execute> statements,
565 you should use L<DBI>'s C<RaiseError> and C<HandleErrror>.
566  
567 =head2 Performance
568  
569 The OO interface has minimal overhead. The only consideration is that if your rows
570 do not contain particularly large amounts of data, you may want to increase the buffer
571 size which is at a modest 100 rows.
572  
573 Internally, to construct the prepared statements it uses similar logic to the public
574 functions. C<simple_insert> is of particular interest as it is a minimalistic function
575 that may replace (similar interface / feature set) the C<insert> functions from
576 C<SQL::Abstract> or C<SQL::Maker> while being over 40x faster than the former and
577 around 3x faster than the latter. The included C<bench/benchmark.pl> script gives
578 an idea (results on an M1 Pro Macbook):
579  
580 Compare SQL::Abstract, SQL::Maker, simple_insert:
581 Rate Abstract Abstract cached Maker Maker cached simple_insert
582 Abstract 4207/s -- -6% -90% -91% -98%
583 Abstract cached 4482/s 7% -- -90% -90% -98%
584 Maker 44245/s 952% 887% -- -4% -76%
585 Maker cached 46205/s 998% 931% 4% -- -75%
586 simple_insert 187398/s 4355% 4081% 324% 306% --
587
588 Compare simple_insert, multi_insert_sql for single row:
589 Rate simple_insert multi_insert_sql
590 simple_insert 190037/s -- -76%
591 multi_insert_sql 797596/s 320% --
592  
593 =head1 AUTHOR
594  
595 Dimitrios Kechagias, C<< <dkechag at cpan.org> >>
596  
597 =head1 BUGS
598  
599 Please report any bugs or feature requests either on L<GitHub|https://github.com/SpareRoom/SQL-Inserter> (preferred), or on RT
600 (via the email <bug-sql-inserter at rt.cpan.org>, or L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=SQL-Inserter>).
601  
602 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
603  
604 =head1 GIT
605  
606 L<https://github.com/SpareRoom/SQL-Inserter>
607  
608 =head1 CPAN
609  
610 L<https://metacpan.org/pod/SQL::Inserter>
611  
612 =head1 LICENSE AND COPYRIGHT
613  
614 Copyright (C) 2023, SpareRoom
615  
616 This is free software; you can redistribute it and/or modify it under
617 the same terms as the Perl 5 programming language system itself.
618  
619 =cut
620  
621 5 1; # End of SQL::Inserter
↑ Summary