File Coverage

blib/lib/DBIx/InsertHash.pm
Criterion Covered Total %
statement 49 59 83.0
branch 15 28 53.5
condition 14 35 40.0
subroutine 7 7 100.0
pod 3 3 100.0
total 88 132 66.6


line stmt bran cond sub pod time code
1             package DBIx::InsertHash;
2             our $VERSION = '0.011';
3              
4              
5             =head1 NAME
6              
7             DBIx::InsertHash - insert/update a database record from a hash
8              
9             =head1 VERSION
10              
11             version 0.011
12              
13             =head1 SYNOPSIS
14              
15             use DBIx::InsertHash;
16              
17             # insert
18             DBIx::InsertHash->insert({USERNAME => 'foo',
19             PASSWORD => 'bar',
20             }, 'table', $dbh);
21              
22             # update
23             DBIx::InsertHash->update({PASSWORD => 'foobar'},
24             [12],'USERID = ?',
25             'table', $dbh);
26              
27             # constructor usage
28             my $dbix = DBIx::InsertHash->new(quote => 1,
29             dbh => $dbh,
30             table => 'table',
31             where => 'USERID = ?',
32             );
33             $dbix->insert($hash);
34             $dbix->update($hash, [12]);
35              
36             =cut
37              
38 3     3   103356 use strict;
  3         6  
  3         107  
39 3     3   14 use warnings;
  3         6  
  3         97  
40              
41 3     3   14 use Carp qw(carp croak);
  3         14  
  3         200  
42              
43 3     3   21 use base 'Class::Accessor::Fast';
  3         6  
  3         2909  
44              
45             __PACKAGE__->mk_accessors(qw(quote quote_char quote_func
46             dbh table where
47             ));
48              
49             =head1 DESCRIPTION
50              
51             If you have data in a hash (which keys are matching the column names) and
52             want to insert it in a database, then this is the right module for you.
53             It frees you from having to construct the SQL statement.
54              
55             It really only does a simple insert (or update) from a hash into a single
56             table. For anything beyond I suggest a ORM (object-relational mapper),
57             like L or L.
58              
59             =head1 INTERFACE
60              
61             =head2 new
62              
63             Constructor (optional). Only needed to store default values or set
64             quoting options.
65              
66             =over 4
67              
68             =item quote (BOOL)
69              
70             Turn quoting of column names on (off by default). This switch affects
71             all column names (see L below to only quote specific names).
72              
73             If you use MySQL, quoting is recommended. It is needed when column names
74             clash with reserved words.
75              
76             =item quote_char (STRING)
77              
78             Quoting character/string (default is backtick).
79              
80             =item qoute_func (CODEREF)
81              
82             This function is given the column name as first (and only) parameter. It
83             has to return a boolean, indicating if the column has to be quoted.
84              
85             The following example uses L:
86              
87             my $quote = sub { SQL::ReservedWords->is_reserved($_[0]) };
88              
89             my $dbix = DBIx::InsertHash->new(quote_func => $quote);
90              
91             $dbix->insert(...);
92              
93             =back
94              
95             =cut
96              
97             sub new {
98 3     3 1 5282 my ($class, %arg) = @_;
99 3   100     19 $arg{quote_char} ||= '`';
100              
101 3         20 return $class->SUPER::new(\%arg);
102             }
103              
104             =head2 insert
105              
106             Insert hash in database. Returns L.
107              
108             =over 4
109              
110             =item data (HASHREF)
111              
112             Row data. The keys have to match with the column names of your table.
113             This parameter is mandatory. If an empty hashref is given, no record is
114             inserted and a warning is given.
115              
116             =item table (STRING)
117              
118             Table name. If this parameter is missing, the object default (see L
119             is used). Otherwise it dies.
120              
121             =item dbh (OBJECT)
122              
123             DBI database handle (you have to L yourself). If
124             this parameter is missing, the object default (see L) is used).
125             Otherwise it dies.
126              
127             =back
128              
129             =cut
130              
131             sub insert {
132 5     5 1 5916 my ($self, $data, $table, $dbh) = @_;
133              
134             # object defaults
135 5 100       19 if (ref $self) {
136 3   33     17 $table ||= $self->table;
137 3   66     36 $dbh ||= $self->dbh;
138             }
139              
140             # warnings/errors
141 5 50       41 unless (%$data) {
142 0         0 carp 'No data (empty hash)';
143 0         0 return;
144             }
145 5 50       16 croak 'No table name' unless $table;
146 5 50       18 croak 'No DBI handle' unless $dbh;
147              
148             # sort by hash key (predictable results)
149 5         20 my @column = sort keys %$data;
150 5         12 my @value = map { $data->{$_} } @column;
  7         17  
151              
152             # quote column names?
153 5 100 100     22 if (ref $self and ($self->quote or $self->quote_func)) {
      66        
154 2         20 foreach my $col (@column) {
155 3 100 100     14 next unless $self->quote or $self->quote_func->($col);
156 2         127 $col = $self->quote_char . $col . $self->quote_char;
157             }
158             }
159              
160 5         51 my $sql = 'INSERT INTO '.$table.' (';
161 5         25 $sql .= join(', ', @column).') VALUES (';
162 5         12 $sql .= join(', ', ('?') x (scalar @column)).')';
163              
164 5         22 $dbh->do($sql, {}, @value);
165              
166 5         56 return $dbh->last_insert_id(undef, undef, $table, undef);
167             }
168              
169             =head2 update
170              
171             Update record from hash. Returns L.
172              
173             =over 4
174              
175             =item data (HASHREF)
176              
177             Row data. The keys have to match with the column names of your table.
178             This parameter is mandatory. If an empty hashref is given, no record is
179             inserted and a warning is given.
180              
181             =item bind_values (ARRAYREF)
182              
183             L for the WHERE clause. If
184             you do not use or need them, just pass a false value (C or empty
185             string) or an empty arrayref. This parameter is optional and has no object
186             defaults.
187              
188             =item where (STRING)
189              
190             Where clause (with optional placeholders C). If this parameter is
191             missing, the object default (see L) is used. Otherwise it dies.
192              
193             =item table (STRING)
194              
195             Table name. If this parameter is missing, the object default (see L
196             is used). Otherwise it dies.
197              
198             =item dbh (OBJECT)
199              
200             DBI database handle (you have to L yourself). If
201             this parameter is missing, the object default (see L) is used).
202             Otherwise it dies.
203              
204             =back
205              
206             =cut
207              
208             sub update {
209 1     1 1 31 my ($self, $data, $vars, $where, $table, $dbh) = @_;
210 1 50       6 my @vars = ($vars ? @$vars : ());
211              
212             # object defaults
213 1 50       3 if (ref $self) {
214 0   0     0 $where ||= $self->where;
215 0   0     0 $table ||= $self->table;
216 0   0     0 $dbh ||= $self->dbh;
217             }
218              
219 1 50       10 unless (%$data) {
220 0         0 carp 'No data (empty hash)';
221 0         0 return;
222             }
223 1 50       7 croak 'No where clause' unless $where;
224 1 50       4 croak 'No table name' unless $table;
225 1 50       21 croak 'No DBI handle' unless $dbh;
226              
227             # sort by hash key (predictable results)
228 1         13 my @column = sort keys %$data;
229 1         3 my @value = map { $data->{$_} } @column;
  2         6  
230              
231             # quote column names?
232 1 0 0     4 if (ref $self and ($self->quote or $self->quote_func)) {
      33        
233 0         0 foreach my $col (@column) {
234 0 0 0     0 next unless $self->quote or $self->quote_func->($col);
235 0         0 $col = $self->quote_char . $col . $self->quote_char;
236             }
237             }
238              
239 1         3 my $sql = 'UPDATE '.$table.' SET ';
240 1         3 $sql .= join(', ', map { "$_ = ?" } @column).' WHERE '.$where;
  2         7  
241              
242 1         8 return $dbh->do($sql, {}, @value, @vars);
243             }
244              
245              
246             1;
247              
248             __END__