DBIx/SearchProfiles.pm untested

filter: Statementstmt 0.0% 0 / 360 Branchbran 0.0% 0 / 160 Conditioncond 0.0% 0 / 84 MC/DCmcdc 0.0% 0 / 45 Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 27 totaltotal 0.0% 0 / 706 CC 81 SCAR 40.0
CC
81
Cov
0%
template_search
132.0
template_get
90.0
record_get
72.0
CRAP 54.3
1 #
2 # SearchProfiles.pm - Profiles based DBI access.
3 #
4 # This file is part of DBIx::SearchProfiles.
5 #
6 # Author: Francis J. Lacoste <francis.lacoste@iNsu.COM>
7 #
8 # Copyright (C) 1999 Francis J. Lacoste, iNsu Innovations
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms same terms as perl itself.
12 #
13 package DBIx::SearchProfiles;
14  
15 use DBI;
16  
17 use strict;
18  
19 use vars qw( $VERSION );
20  
21 BEGIN {
22 ($VERSION) = '$Revision: 1.9 $' =~ /Revision: ([\d.]+)/;
23 }
24  
25 =pod
26  
27 =head1 NAME
28  
29 DBIx::SearchProfiles - Access to SQL database via template query.
30  
31 =head1 SYNOPSIS
32  
33 use DBIx::SearchProfiles;
34  
35 my $DB = new DBIx::SearchProfiles( $dbh, $profiles);
36  
37 my $record = $DB->record_get( "customer", 1024 );
38  
39 my $records = $DB->template_search( "cust_low_balance",
40 { low_balance => 50 } );
41  
42 $DB->record_insert( "customer", $customer_data );
43  
44 =head1 DESCRIPTION
45  
46 DBIx::SearchProfiles is a module which wraps around a DBI database
47 handle and provides another way than raw SQL to access the database.
48 Its aims is to take the SQL out of the code in well defined and
49 documented search profiles which has easier to maintain than embedded
50 SQL all over the application. Moreover, this decoupling of the
51 application logic from the SQL programming makes it possible to review
52 the SQL by a DBA which might not be a programmer. It may also makes
53 the application's code more obvious and clearer which is a Good
54 Thing (tm)
55  
56 =head1 ACCESS METHODS
57  
58 The DBIx::SearchProfiles module offers three method of access to
59 the underlying database :
60  
61 =over
62  
63 =item RAW SQL ACCESS
64  
65 This is the lowest level and is thin wrapper around the underlying DBI
66 methods. The caller specifies the SQL statement and the params to use
67 for the query.
68  
69 Ex: $DB->sql_insert( "INSERT INTO customer (?,?,?)", @params );
70  
71 =item RECORD ACCESS
72  
73 This class of access generates automatically the SQL statement to use
74 based on the fields present in the table and the fields passed as
75 parameters. This type of access is very handy for insert or update where
76 you don't want to specify all the fields.
77  
78 Ex: $DB->record_insert( "customer", $customer_data );
79  
80 Where I<customer> is the name of the profile definition to use and
81 $customer_data is a reference to an hash which contains the customer's
82 infos.
83  
84  
85 =item TEMPLATE ACCESS
86  
87 This is the most interesting type of access. The problem with the
88 previous type of access is that it is convenivent and efficient for
89 simple query but when you want something more complex it fails
90 miserably. (Say one where you want other operators than =, and where
91 you are joining 6 tables together) In the template based access, you
92 use a template query in which the parameters will be substituted. The
93 query can be as complex as you want and the parameter subsitutions
94 also.
95  
96 Ex: $DB->template_search( "troublesome_customers", $search_spec );
97  
98 =back
99  
100 Each class of access provides 5 methods to access the data. (SQL has
101 an extra one, but its the exception) :
102  
103 =over
104  
105 =item *_get
106  
107 The C<*_get> methods ( C<sql_get()>, C<record_get()> and
108 C<template_get()> ) will return only one record in the form of an hash
109 reference. Each keys corresponds to one column of the table. (So two
110 columns must not have the same name.)
111  
112 =item *_search
113  
114 The C<*_search> methods (C<sql_search()>, C<record_search()> and
115 C<template_search()>) will return a reference to an array of hash.
116 Each hash is a table row where the keys are the column's names.
117  
118 Also the C<record_search()> and C<template_search()> methods have support
119 for limiting the number of rows returned and to results offset.
120 (1-50,51-100,etc).
121  
122  
123 =item *_insert
124  
125 The C<*_insert> methods are for inserting one record in a table.
126  
127 =item *_update
128  
129 The C<*_update> methods are for updating records in a table.
130  
131 =item *_delete
132  
133 The C<*_delete> methods are for deleting records from the table.
134  
135 =back
136  
137 =head1 INITIALIZATION
138  
139 To get a database search profiles handle, you use the C<new> method.
140  
141 Ex: my $DB = new DBIx::SearchProfiles( $dsn, $profiles );
142  
143 The $dsn parameter can either be an already connected DBI handle or a
144 reference to an hash which contains three parameters I<DataSource>,
145 I<UserName> and I<Password> which will be used to open one. Note that
146 on destruction, the connection will only be closed if the connection
147 was established by the DBIx::SearchProfiles modules.
148  
149 The $profiles parameter can either be a reference to an hash which
150 contains the search profiles, or the name of a file which will be
151 evaluated and that must return a reference to an hash which will
152 contains the search profiles. Note that whenever the search profiles'
153 file changes on disk, the profiles are reloaded.
154  
155 =cut
156  
157 sub new {
158 my $proto = shift;
159 my $class = ref $proto || $proto;
160  
161 my $dsn = shift;
162 my $profiles = shift;
163  
164 my $self = {};
165 if ( ref $dsn eq "HASH" ) {
166 my $dbh = DBI->connect( $dsn->{DataSource}, $dsn->{UserName},
167 $dsn->{Password}, { RaiseError => 1 } );
168 $self->{dbh} = $dbh;
169 $self->{did_connect} = 1;
170 } else {
171 $self->{dbh} = $dsn;
172 }
173  
174 my $profiles_file = undef;
175 unless ( ref $profiles eq "HASH" ) {
176 $profiles_file = $profiles;
177 $profiles = undef;
178 }
179 $self->{profiles} = $profiles;
180 $self->{profiles_file} = $profiles_file;
181  
182 bless $self, $class;
183 }
184  
185 sub DESTROY {
186 my $self = shift;
187  
188 # Disconnect from database, if we opened the connection.
189 if ( $self->{did_connect} ) {
190 $self->{dbh}->disconnect;
191 }
192 }
193  
194 =pod
195  
196 =head1 DBI WRAPPER METHODS
197  
198 =head2 commit
199  
200 Simply call commit on the underlying DBI handle.
201  
202 =cut
203  
204 sub commit {
205 my $self = shift;
206  
207 $self->{dbh}->commit;
208 }
209  
210 =pod
211  
212 =head2 rollback
213  
214 Simply call rollback on the underlying DBI handle.
215  
216 =cut
217  
218 sub rollback {
219 my $self = shift;
220  
221 $self->{dbh}->rollback;
222 }
223  
224 =pod
225  
226 =head1 PROFILE DEFINITIONS
227  
228 A search profiles collection is a reference to an hash where each key points
229 ta profile definition. A search profile definition is an hash which contains
230 several elements which will be used to build query automatically.
231  
232 Here is an example profiles :
233  
234 {
235 category =>
236 {
237 query => q{ SELECT id,category FROM category
238 WHERE category_id = ? },
239 params => [ "category_id" ],
240 },
241 product_srch =>
242 {
243 query => q{ SELECT DISTINCT code,code_manu,category_id,category,
244 manufacturer_id,manufacturer,
245 price,description
246 FROM products p ,manufacturer m ,category c
247 WHERE ( ? = -1 OR c.id = ? ) AND
248 ( ? = -1 OR m.id = ? ) AND
249 category_id = c.id AND
250 manufacturer_id = m.id AND
251 ( code = ? OR code_manu = ?
252 OR category LIKE ?
253 OR manufacturer LIKE ?
254 OR description LIKE ?
255 )
256 },
257 params => [ qw( category_id category_id manufacturer_id
258 manufacturer_id
259 search search search search search ) ],
260 order => "category_id,manufacturer_id,code",
261 defaults => { category_id => -1, manufacturer_id => -1 },
262 limit => 25,
263 },
264 order_items =>
265 {
266 fields => [qw( quantity subtotal ) ],
267 keys => [ qw( order_no code ) ],
268 table => "order_items",
269 },
270 }
271  
272 In this example, you have a simple query profile (category), a complex
273 template search (product_srch) and an example of a profile for record based
274 access.
275  
276 Here is the meaning of the different fields :
277  
278 =over
279  
280 =item table (RECORD ACCESS ONLY)
281  
282 The name of the table on which we will operate.
283  
284 =item keys (RECORD ACCESS ONLY)
285  
286 A reference to an array which contains the name of the fields which
287 are the primary key for the table.
288  
289 =item fields (RECORD ACCESS ONLY)
290  
291 A reference to an array which contains the name of the fields which
292 are not primary keys in the table.
293  
294 =item defaults
295  
296 Reference to an hash of parameter defaults. This will be used to
297 complete when no values are present.
298  
299 =item limit
300  
301 Used by C<record_search> and C<template_search> as the default
302 number of records to return at a time for this query.
303  
304 =item max
305  
306 Used by C<record_search> and C<template_search> as the default
307 maximum total number of records to return for a query.
308  
309 =item order
310  
311 Used by C<record_search> and C<template_search> as the default ordering
312 for the query.
313  
314 =item query (TEMPLATE ACCESS ONLY)
315  
316 This is the query template. It should contains the SQL that will be
317 executed with the standard DBI (?) placeholders embedded in it.
318  
319 =item params (TEMPLATE ACCESS ONLY)
320  
321 A reference to an array which contains the name of the params that will
322 be substituted in the template. There should be one element for every
323 placeholder in the query.
324  
325 =back
326  
327 =cut
328  
329 sub has_profile {
330 my ( $self, $name ) = @_;
331  
332 $self->load_profiles;
333 return exists $self->{profiles}{$name};
334 }
335  
336 sub list_profile {
337 my $self = shift;
338  
339 $self->load_profiles;
340 return keys %{$self->{profiles}};
341 }
342  
343 sub get_profile {
344 my ($self,$name) = shift;
345  
346 $self->load_profiles;
347 return $self->{profiles}{$name};
348 }
349  
350 sub profiles {
351 my $self = shift;
352  
353 $self->load_profiles;
354 return values %{$self->{profiles}};
355 }
356  
357 sub load_profiles {
358 my $self = shift;
359  
360 my $file = $self->{profiles_file};
361 return unless $file;
362  
363 die "No such file: $file\n" unless -f $file;
364 die "Can't read $file\n" unless -r _;
365  
366 my $mtime = (stat _)[9];
367 return if $self->{profiles} and $self->{profiles_mtime} <= $mtime;
368  
369 $self->{profiles} = do $file;
370 die "Error in search profiles: $@\n" if $@;
371 die "Search profiles didn't return an hash ref\n"
372 unless ref $self->{profiles} eq "HASH";
373  
374 $self->{profiles_mtime} = $mtime;
375 }
376  
377 =pod
378  
379 =head1 SQL ACCESS METHODS
380  
381 =head2 sql_do ( $statement, @params );
382  
383 Thin wrapper around DBI C<do> method. The first argument is the SQL to
384 be executed and the remaining arguments are passed as params to the query.
385  
386 =cut
387  
388 sub sql_do {
389 my $self = shift;
390 my $statement = shift;
391  
392 my $dbh = $self->{dbh};
393  
394 $dbh->do( $statement, undef, @_ );
395 }
396  
397 =pod
398  
399 =head2 sql_get ( $statement, @params );
400  
401 This method will execute the SELECT query passed in the first argument
402 using the remaining parameters as placeholder substitutions.
403  
404 It returns an hash ref (or undef if the query didn't match any record)
405 corresponding to the first row returned.
406  
407 =cut
408  
409 sub sql_get {
410 my $self = shift;
411 my $statement = shift;
412  
413 die "Statement doesn't start with SELECT"
414 unless $statement =~ /^\s*SELECT /i;
415  
416 my $dbh = $self->{dbh};
417  
418 my $sth = $dbh->prepare( $statement );
419 $sth->execute( @_ );
420  
421 my @fields = @{$sth->{NAME}};
422 my $record = $sth->fetch;
423 return undef unless $record;
424  
425 my $i = 0;
426 return { map { $fields[$i++] => $_ } @$record };
427 }
428  
429 =pod
430  
431 =head2 sql_search ( $statement, @params );
432  
433 This method will execute the SELECT query passed in the first argument
434 using the remaining parameters as placeholder substitutions.
435  
436 It returns a reference to an array of hash.
437  
438 =cut
439  
440 sub sql_search {
441 my $self = shift;
442 my $statement = shift;
443  
444 die "Statement doesn't start with SELECT"
445 unless $statement =~ /^\s*SELECT /i;
446  
447 my $dbh = $self->{dbh};
448  
449 my $sth = $dbh->prepare( $statement );
450 $sth->execute( @_ );
451  
452 my $result = [];
453 my @fields = @{$sth->{NAME}};
454 while ( my $record = $sth->fetch ) {
455 my $i = 0;
456 push @$result, { map { $fields[$i++] => $_ } @$record };
457 }
458  
459 return $result;
460 }
461  
462 =pod
463  
464 =head2 sql_insert ( $statement, @params );
465  
466 This method will execute the INSERT query passed in the first argument
467 using the remaining parameters as placeholder substitutions.
468  
469 Return value is undefined.
470  
471 =cut
472  
473 sub sql_insert {
474 my $self = shift;
475 my $statement = shift;
476  
477 die "Statement doesn't start with INSERT"
478 unless $statement =~ /^\s*(INSERT) /i;
479  
480 $self->sql_do( $statement, @_ );
481 }
482  
483 =pod
484  
485 =head2 sql_update ( $statement, @params );
486  
487 This method will execute the UPDATE query passed in the first argument
488 using the remaining parameters as placeholder substitutions.
489  
490 Return value is undefined.
491  
492 =cut
493  
494 sub sql_update {
495 my $self = shift;
496 my $statement = shift;
497  
498 die "Statement doesn't start with UPDATE"
499 unless $statement =~ /^\s*(UPDATE) /i;
500  
501 $self->sql_do( $statement, @_ );
502 }
503  
504 =pod
505  
506 =head2 sql_delete ( $statement, @params );
507  
508 This method will execute the DELETE query passed in the first argument
509 using the remaining parameters as placeholder substitutions.
510  
511 Return value is undefined.
512  
513 =cut
514  
515 sub sql_delete {
516 my $self = shift;
517 my $statement = shift;
518  
519 die "Query doesn't start with DELETE"
520 unless $statement =~ /^\s*(DELETE) /i;
521  
522 $self->sql_do( $statement, @_ );
523 }
524  
525 =pod
526  
527 =head1 RECORD BASED ACCESS
528  
529 =over
530  
531 =head2 record_get ( $name, params );
532  
533 This method will return an hash reference to a record. The first argument
534 is the name of the profile where the table information will be found. The params argument can either be :
535  
536 =over
537  
538 =item ARRAY OR ARRAY REF
539  
540 Each element of the array is mapped to an element of the I<keys> field
541 of the profile. It is an error if the number of elements is different than
542 the number of keys defined in the table.
543  
544 =item HASH REF
545  
546 The key will be built by using the name of the keys as specified in the
547 I<keys> field of the profile, or by using the I<defaults> hash if present.
548  
549 It is an error if some portion of the key is missing.
550  
551 =back
552  
553 =cut
554  
555 sub record_get {
556 my $self = shift;
557 my $name = shift;
558  
559 my $fdat;
560 my @values;
561 if ( ref $_[0] eq "HASH" ) {
562 $fdat = shift;
563 } elsif ( ref $_[0] eq "ARRAY" ) {
564 @values = @{$_[0]};
565 } else {
566 @values = @_;
567 }
568 $fdat ||= {};
569  
570 $self->load_profiles;
571  
572 my $profile = $self->{profiles}{$name};
573 die "No such profile: $name\n" unless $profile;
574  
575 my $table = $profile->{table};
576 my $keys = $profile->{keys};
577  
578 my @keys = ();
579 unless (@values) {
580 for my $name ( @$keys ) {
581 my $value = defined $fdat->{$name} ? $fdat->{$name} :
582 $profile->{defaults}{$name};
583 die "Missing key attribute $name\n"
584 unless defined $value;
585 push @keys, $name . " = ?";
586 push @values, $value;
587 }
588 } else {
589 die "Number of values doesn't match the number of keys\n"
590 unless @$keys == @values;
591 for my $name ( @$keys ) {
592 push @keys, $name . " = ?";
593 }
594 }
595  
596 my $query = "SELECT * FROM $table WHERE " . join ( " AND ", @keys );
597 $self->sql_get( $query, @values );
598 }
599  
600 =pod
601  
602 =head2 record_search ( $name, \%params );
603  
604 This method will build a search on the table specified in the profile
605 $name. $params is a reference to an hash where each keys that is
606 present in the I<fields> or I<keys> of the profile will be used as a
607 constraint in the query. The test is for equality, if you want
608 something more complex, use C<template_search>.
609  
610 There are a few magic parameters :
611  
612 =over
613  
614 =item dbix_sp_order
615  
616 Will override the order clause of the query. If not present the I<order>
617 field of the profile will be used.
618  
619 =item dbix_sp_limit
620  
621 Limit the number of records returned by the query. If not present the
622 I<limit> field of the profile will be used.
623  
624 =item dbix_sp_max
625  
626 Set the maximum number of records that the query may fetch, this override
627 the I<max> field of the profile but cannot be set higher.
628  
629 =item dbix_sp_start
630  
631 If there is a I<limit> set for the query, this parameter will start
632 returning records from that offset in the result. Offset is 0 indexed.
633  
634 =back
635  
636 The I<params> argument is modified on return. Here is a list of the
637 modified elements :
638  
639 =over
640  
641 =item dbix_sp_found
642  
643 The number of record returned.
644  
645 =item dbix_sp_total
646  
647 The total number of record matching the query.
648  
649 =back
650  
651 Like all *_search methods C<record_search> will return a reference to
652 an array of hash.
653  
654 =cut
655  
656 sub record_search {
657 my $self = shift;
658 my $name = shift;
659 my $fdat = shift || {};
660  
661 $self->load_profiles;
662  
663 my $profile = $self->{profiles}{$name};
664 die "No such profile: $name\n" unless $profile;
665  
666 my $table = $profile->{table};
667 my $fields = $profile->{fields};
668 my $keys = $profile->{keys};
669 my $order_by = $fdat->{dbix_sp_order} || $profile->{order};
670  
671 # Set defaults value for do_bounded_search
672 $fdat->{dbix_sp_start} ||= 0;
673 $fdat->{dbix_sp_limit} ||= $profile->{limit} || 0;
674  
675 my $max = $fdat->{dbix_sp_max} ||= $profile->{max} || 0;
676 # Maximum cannot be set higher than the one set in the profile.
677 if ( defined $profile->{max} && $max > $profile->{max} ) {
678 $max = $fdat->{dbix_sp_max} = $profile->{max};
679 }
680  
681 my %fields = map { $_ => 1 } @$fields, @$keys;
682 my @names = ();
683 my @values = ();
684 while ( my ($name,$value) = each %$fdat ) {
685 next unless $fields{$name};
686 push @names, $name . " = ?";
687 push @values, $value;
688 }
689  
690 # Build query
691 my $query = "SELECT * FROM $table";
692 $query .= " WHERE " . join( " AND ", @names ) if @names;
693 $query .= " ORDER BY $order_by" if $order_by;
694 $query .= " LIMIT $max" if $max;
695  
696 $self->do_bounded_search( $fdat, $query, @values );
697 }
698  
699 sub do_bounded_search {
700 my ($self,$fdat,$statement) = @_[0,1,2];
701  
702 die "Statement doesn't start with SELECT"
703 unless $statement =~ /^\s*SELECT /i;
704  
705 my $dbh = $self->{dbh};
706  
707 my $sth = $dbh->prepare( $statement );
708 $sth->execute( @_[3 .. $#_] );
709  
710 my $result = [];
711 my @fields = @{$sth->{NAME}};
712  
713 my $start = $fdat->{dbix_sp_start};
714 my $limit = $fdat->{dbix_sp_limit};
715  
716 my $total = 0;
717 my $offset = 0;
718 my $found = 0;
719 while ( my $record = $sth->fetch ) {
720 # Check if this record is between the bounds we are looking for
721 if ( ! $limit || ($offset >= $start && $offset < $start + $limit ) ) {
722 my $i = 0;
723 push @$result, { map { $fields[$i++] => $_ } @$record };
724 $found++;
725 }
726 $offset++,$total++;
727 }
728 $fdat->{dbix_sp_found} = $found;
729 $fdat->{dbix_sp_total} = $total;
730 return $result;
731 }
732  
733 =pod
734  
735 =head2 record_insert ( $name, \%params );
736  
737 This method will insert a record in the table specified by the profile
738 $name. The I<params> argument is a reference to an hash which contains
739 the record data to be inserted. The hash should contains one element
740 for each key specified in the I<keys> field of the profile. Each
741 elements in the fields that is a valid table fields (as specified by
742 the I<fields> element of the profile) will be inserted. Any elements
743 specified I<defaults> and not present in the I<params> hash will also
744 be inserted.
745  
746 Return value is undefined.
747  
748 =cut
749  
750 sub record_insert {
751 my $self = shift;
752 my $name = shift;
753 my $fdat = shift || {};
754  
755 $self->load_profiles;
756  
757 my $profile = $self->{profiles}{$name};
758 die "No such profile: $name\n" unless $profile;
759  
760 my $table = $profile->{table};
761 my @fields = (@{$profile->{keys}}, @{$profile->{fields}} );
762  
763 my @names = ();
764 my @values = ();
765 for my $name ( @fields ) {
766 my $value = defined $fdat->{$name} ? $fdat->{$name} :
767 $profile->{defaults}{$name};
768 next unless defined $value;
769 push @names, $name;
770 push @values, $value;
771 }
772  
773 die "Nothing to insert\n" unless @values;
774  
775 my $statement = "INSERT INTO $table ( " . join (", ", @names ) .
776 ") VALUES (" . join ( ",", ("?") x @names ) . ")";
777  
778 $self->sql_do( $statement, @values );
779 }
780  
781 =pod
782  
783 =head2 record_update ( $name, \%params );
784  
785 This method will update a record in the table specified by the profile
786 $name. The I<params> argument is a reference to an hash which contains
787 the record data to be updated. The hash should contains one element
788 for each key specified in the I<keys> field of the profile. Each
789 elements in the fields that is a valid table fields (as specified by
790 the I<fields> element of the profile) will be updated. Any elements
791 specified I<defaults> and not present in the I<params> hash will also
792 be updated.
793  
794 Return value is undefined.
795  
796 =cut
797  
798 sub record_update {
799 my $self = shift;
800 my $name = shift;
801 my $fdat = shift || {};
802  
803 $self->load_profiles;
804  
805 my $profile = $self->{profiles}{$name};
806 die "No such profile: $name\n" unless $profile;
807  
808 my $table = $profile->{table};
809 my $fields = $profile->{fields};
810 my $keys = $profile->{keys};
811  
812 my @names = ();
813 my @values = ();
814 for my $name ( @$fields ) {
815 my $value = defined $fdat->{$name} ? $fdat->{$name} :
816 $profile->{defaults}{$name};
817 next unless defined $value;
818 push @names, $name . " = ?";
819 push @values, $value;
820 }
821  
822 die "Nothing to update\n" unless @values;
823  
824 my @keys = ();
825 for my $name ( @$keys ) {
826 my $value = $fdat->{$name};
827 die "Missing key attribute $name\n"
828 unless defined $value;
829 push @keys, $name . " = ?";
830 push @values, $value;
831 }
832  
833 my $query = "UPDATE $table SET " . join( ", ", @names ) .
834 " WHERE " . join ( " AND ", @keys );
835  
836 $self->sql_do( $query, @values );
837 }
838  
839 =pod
840  
841 =head2 record_delete ( $name, $keys );
842  
843 This method will delete a record in the table specified by the profile
844 $name. The I<keys> argument is a reference to an hash which contains
845 the keys to the record to delete. The hash should contains one element
846 for each key specified in the I<keys> field of the profile.
847  
848 Return value is undefined.
849  
850 =cut
851  
852 sub record_delete {
853 my $self = shift;
854 my $name = shift;
855 my $fdat = shift || {};
856  
857 $self->load_profiles;
858  
859 my $profile = $self->{profiles}{$name};
860 die "No such profile: $name\n" unless $profile;
861  
862 my $table = $profile->{table};
863 my $keys = $profile->{keys};
864  
865 my @keys = ();
866 my @values = ();
867 for my $name ( @$keys ) {
868 my $value = $fdat->{$name};
869 die "Missing key attribute $name\n"
870 unless defined $value;
871 push @keys, $name . " = ?";
872 push @values, $value;
873 }
874  
875 my $query = "DELETE FROM $table WHERE " . join ( " AND ", @keys );
876 $self->sql_do( $query, @values );
877 }
878  
879 =pod
880  
881 =head1 TEMPLATE BASED ACCESS
882  
883 All of the C<template_*> methods accepts two parameters, $name and
884 params. The $name parameter specified the profile to use as a template
885 for the operation (get,search,insert,update or delete). The other
886 parameter is used as substitutions for the placeholders of the
887 template. Those substitutions can be specified in three manners :
888  
889 =over
890  
891 =item ARRAY OR ARRAY REF
892  
893 Each element of the array is mapped to an element of the I<params> field
894 of the profile. It is an error if the number of elements is different than
895 the number of params defined in the profile.
896  
897 =item HASH REF
898  
899 Each substitutions will be mapped to one of the element of the
900 I<params> hash in the order specified by the I<params> element of the
901 profile. If a params element isn't present, a default one will be
902 used. (Either the value specified in the profile's defaults element or
903 NULL).
904  
905 =back
906  
907 =head2 template_get ( $name, params )
908  
909 This method will return an hash reference to a record using the
910 profile $name.
911  
912 =cut
913  
914 sub template_get {
915 my $self = shift;
916 my $name = shift;
917  
918 my ( $fdat, @params );
919  
920 # Params is either an hash ref in which we will look
921 # for named base params or it can be an array (or array ref)
922 # of which the elements will be used for substitutions in
923 # the SQL query
924 if ( ref $_[0] eq "HASH" ) {
925 $fdat = shift;
926 } elsif ( ref $_[0] eq "ARRAY" ) {
927 @params = @{$_[0]};
928 } else {
929 @params = @_;
930 }
931 $fdat ||= {};
932  
933 $self->load_profiles;
934  
935 my $profile = $self->{profiles}{$name};
936 die "No such profile: $name\n" unless $profile;
937  
938 my $query_spec = $profile->{query};
939 die "Query doesn't start with SELECT"
940 unless $query_spec =~ /^\s*SELECT /i;
941  
942 # Fetch the params from the query
943 my $params_spec = $profile->{params} || [];
944 if ( @params ) {
945 die "Number of params doesn't match the number of specs\n"
946 unless @params == @$params_spec;
947 } else {
948 @params = map {
949 defined $fdat->{$_} ? $fdat->{$_} : $profile->{defaults}{$_}
950 } @$params_spec;
951 }
952 $query_spec .= " LIMIT 1" unless $query_spec =~ /LIMIT/;
953  
954 $self->sql_get( $query_spec, @params );
955 }
956  
957 =pod
958  
959 =head2 template_search ( $name, params )
960  
961 This method will run a search using the query template specified in
962 the profile named $name and return the results in a reference to an
963 array of hashes.
964  
965 This methods accept the same magic parameters in the %params element
966 as the C<record_search> method. It also modifies the same element in
967 %params as that method.
968  
969 =cut
970  
971 sub template_search {
972 my $self = shift;
973 my $name = shift;
974  
975 my ( $fdat, @params );
976  
977 # Params is either an hash ref in which we will look
978 # for named base params or it can be an array (or array ref)
979 # of which the elements will be used for substitutions in
980 # the SQL query
981 if ( ref $_[0] eq "HASH" ) {
982 $fdat = shift;
983 } elsif ( ref $_[0] eq "ARRAY" ) {
984 @params = @{$_[0]};
985 } else {
986 @params = @_;
987 }
988 $fdat ||= {};
989  
990 $self->load_profiles;
991  
992 my $profile = $self->{profiles}{$name};
993 die "No such profile: $name\n" unless $profile;
994  
995 my $query_spec = $profile->{query};
996 die "Query doesn't start with SELECT"
997 unless $query_spec =~ /^\s*SELECT /i;
998  
999 my $params_spec = $profile->{params} || [];
1000 my $order_by = $fdat->{dbix_sp_order} || $profile->{order};
1001  
1002 # Set defaults value for do_bounded_search
1003 $fdat->{dbix_sp_start} ||= 0;
1004 $fdat->{dbix_sp_limit} ||= $profile->{limit} || 0;
1005  
1006 my $max = $fdat->{dbix_sp_max} ||= $profile->{max} || 0;
1007 # Maximum cannot be set higher than the one set in the profile.
1008 if ( defined $profile->{max} && $max > $profile->{max} ) {
1009 $max = $fdat->{dbix_sp_max} = $profile->{max};
1010 }
1011  
1012 # Fetch the param from the query
1013 if ( @params ) {
1014 die "Number of params doesn't match the number of specs\n"
1015 unless @params == @$params_spec;
1016 } else {
1017 @params = map {
1018 defined $fdat->{$_} ? $fdat->{$_} : $profile->{defaults}{$_}
1019 } @$params_spec;
1020 }
1021  
1022 # Set ORDER and LIMIT clause
1023 unless ( !defined $order_by || $query_spec =~ /ORDER\s+BY/i) {
1024 $query_spec .= " ORDER BY $order_by";
1025 }
1026  
1027 unless ( ! $max || $query_spec =~ /\bLIMIT\b/i ) {
1028 $query_spec .= " LIMIT $max";
1029 }
1030  
1031 $self->do_bounded_search( $fdat, $query_spec, @params );
1032 }
1033  
1034 =pod
1035  
1036 =head2 template_insert ( $name, params )
1037  
1038 This method will insert a record according to the profile in $name.
1039 Normal template substitutions will be used.
1040  
1041 Return value is undefined.
1042  
1043 =cut
1044  
1045 sub template_insert {
1046 my $self = shift;
1047 my $name = shift;
1048  
1049 my ( $fdat, @params );
1050  
1051 # Params is either an hash ref in which we will look
1052 # for named base params or it can be an array (or array ref)
1053 # of which the elements will be used for substitutions in
1054 # the SQL query
1055 if ( ref $_[0] eq "HASH" ) {
1056 $fdat = shift;
1057 } elsif ( ref $_[0] eq "ARRAY" ) {
1058 @params = @{$_[0]};
1059 } else {
1060 @params = @_;
1061 }
1062 $fdat ||= {};
1063  
1064 $self->load_profiles;
1065  
1066 my $profile = $self->{profiles}{$name};
1067 die "No such profile: $name\n" unless $profile;
1068  
1069 my $statement_spec = $profile->{query};
1070 die "Query doesn't start with INSERT"
1071 unless $statement_spec =~ /^\s*INSERT /;
1072  
1073 my $params_spec = $profile->{params} || [];
1074  
1075 # Fetch the param from the query
1076 if ( @params ) {
1077 die "Number of params doesn't match the number of specs\n"
1078 unless @params == @$params_spec;
1079 } else {
1080 @params = map {
1081 defined $fdat->{$_} ? $fdat->{$_} : $profile->{defaults}{$_}
1082 } @$params_spec;
1083 }
1084  
1085 $self->sql_do( $statement_spec, @params );
1086 }
1087  
1088 =pod
1089  
1090 =head2 template_update ( $name, params )
1091  
1092 This method will update records according to the profile $name and
1093 using standard template's placholders substitutions semantics.
1094  
1095 Return value is the number of rows updated.
1096  
1097 =cut
1098  
1099 sub template_update {
1100 my $self = shift;
1101 my $name = shift;
1102  
1103 my ( $fdat, @params );
1104  
1105 # Params is either an hash ref in which we will look
1106 # for named base params or it can be an array (or array ref)
1107 # of which the elements will be used for substitutions in
1108 # the SQL query
1109 if ( ref $_[0] eq "HASH" ) {
1110 $fdat = shift;
1111 } elsif ( ref $_[0] eq "ARRAY" ) {
1112 @params = @{$_[0]};
1113 } else {
1114 @params = @_;
1115 }
1116 $fdat ||= {};
1117  
1118 $self->load_profiles;
1119  
1120 my $profile = $self->{profiles}{$name};
1121 die "No such profile: $name\n" unless $profile;
1122  
1123 my $statement_spec = $profile->{query};
1124 die "Query doesn't start with UPDATE"
1125 unless $statement_spec =~ /^\s*UPDATE /;
1126  
1127 my $params_spec = $profile->{params} || [];
1128  
1129 # Fetch the param from the query
1130 if ( @params ) {
1131 die "Number of params doesn't match the number of specs\n"
1132 unless @params == @$params_spec;
1133 } else {
1134 @params = map {
1135 defined $fdat->{$_} ? $fdat->{$_} : $profile->{defaults}{$_}
1136 } @$params_spec;
1137 }
1138  
1139 $self->sql_do( $statement_spec, @params );
1140 }
1141  
1142 =pod
1143  
1144 =head2 template_delete ( $name, params )
1145  
1146 This method will delete records according to the template $name and
1147 using regular template's placeholders substitutions semantics.
1148  
1149 Return value is the number of records deleted.
1150  
1151 =cut
1152  
1153 sub template_delete {
1154 my $self = shift;
1155 my $name = shift;
1156  
1157 my ( $fdat, @params );
1158  
1159 # Params is either an hash ref in which we will look
1160 # for named base params or it can be an array (or array ref)
1161 # of which the elements will be used for substitutions in
1162 # the SQL query
1163 if ( ref $_[0] eq "HASH" ) {
1164 $fdat = shift;
1165 } elsif ( ref $_[0] eq "ARRAY" ) {
1166 @params = @{$_[0]};
1167 } else {
1168 @params = @_;
1169 }
1170 $fdat ||= {};
1171  
1172 $self->load_profiles;
1173  
1174 my $profile = $self->{profiles}{$name};
1175 die "No such profile: $name\n" unless $profile;
1176  
1177 my $statement_spec = $profile->{query};
1178 die "Query doesn't start with DELETE"
1179 unless $statement_spec =~ /^\s*DELETE /;
1180  
1181 my $params_spec = $profile->{params} || [];
1182  
1183 # Fetch the param from the query
1184 if ( @params ) {
1185 die "Number of params doesn't match the number of specs\n"
1186 unless @params == @$params_spec;
1187 } else {
1188 @params = map {
1189 defined $fdat->{$_} ? $fdat->{$_} : $profile->{defaults}{$_}
1190 } @$params_spec;
1191 }
1192  
1193 $self->sql_do( $statement_spec, @params );
1194 }
1195  
1196 1;
1197  
1198 __END__