blib/lib/SQL/Inserter.pm

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