blib/lib/SQL/Inserter.pm

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