blib/lib/Dancer/Plugin/SimpleCRUD.pm

filter: Statementstmt 59.0% 322 / 545 Branchbran 44.7% 111 / 248 Conditioncond 36.4% 43 / 118 MC/DCmcdc 5.8% 4 / 69 Subroutinesub 82.3% 28 / 34 Podpod n/a totaltotal 50.1% 508 / 1014 CC 191 SCAR 56.5
CC
191
Cov
52%
_create_list_handler
611.3
_create_add_edit_route
243.5
_return_downloadable_query
132.0
CRAP 284.1
↑ Summary
1 # First, a dead simple object that can be fed a hashref of params from the
2 # Dancer params() keyword, and returns then when its param() method is called,
3 # so that we can feed it to CGI::FormBuilder:
4 package Dancer::Plugin::SimpleCRUD::ParamsObject;
5  
6 sub new {
7 0 ▶ my ($class, $params) = @_;
Subroutine new: not called CC=1 SCAR=6.9
8 0 return bless { params => $params }, $class;
9 }
10  
11 sub param {
12 0 ▶ my ($self, @args) = @_;
Subroutine param: not called CC=5 SCAR=34.0
13  
14 # If called with no args, return all param names
15 0 ▶ if (!@args) {
Branch: 3 branches
BranchTrueFalseTotal
if (not @args) { } 0 0 0
elsif (@args == 1) { } 0 0 0
elsif ($args == 2) { } 0 0 0
16 0 ▶ return $self->{params} if !$paramname;
Branch: 1 branch
BranchTrueFalseTotal
if not $paramname 0 0 0
17  
18 # With one arg, act as an accessor
19 } elsif (@args == 1) {
20 0 return $self->{params}{ $args[0] };
21  
22 # With two args, act as a mutator
23 } elsif ($args == 2) {
24 0 return $self->{params}{ $args[0] } = $args[1];
25 }
26 }
27  
28 # Now, on to the real stuff
29 package Dancer::Plugin::SimpleCRUD;
30  
31 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 3 ▶use Dancer::Plugin;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 3 ▶use Dancer qw(:syntax);
Subroutine BEGIN: called CC=1 SCAR=0.0
35 3 ▶use Dancer::Plugin::Database;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 3 ▶use HTML::Table::FromDatabase;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 3 ▶use CGI::FormBuilder;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 3 ▶use HTML::Entities;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 3 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 3 ▶use List::MoreUtils qw( first_index uniq );
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 3 our $VERSION = '1.14';
43  
44 =encoding utf8
45  
46 =head1 NAME
47  
48 Dancer::Plugin::SimpleCRUD - very simple CRUD (create/read/update/delete)
49  
50  
51 =head1 DESCRIPTION
52  
53 A plugin for Dancer web applications, to use a few lines of code to create
54 appropriate routes to support creating/editing/deleting/viewing records within a
55 database table. Uses L<CGI::FormBuilder> to generate, process and validate forms,
56 L<Dancer::Plugin::Database> for database interaction and
57 L<HTML::Table::FromDatabase> to display lists of records.
58  
59 Setting up forms and code to display and edit database records is a very common
60 requirement in web apps; this plugin tries to make something basic trivially
61 easy to set up and use.
62  
63  
64 =head1 SYNOPSIS
65  
66 The following assumes that you already have a working L<Dancer> app and have
67 put your database connection details in your C<config.yml> to be read by
68 L<Dancer::Plugin::Database>, which this plugin uses in order to obtain a database
69 connection.
70  
71 # In your Dancer app,
72 use Dancer::Plugin::SimpleCRUD;
73  
74 # Simple example:
75 simple_crud(
76 record_title => 'Widget',
77 prefix => '/widgets',
78 db_table => 'widgets',
79 editable => 1,
80 );
81  
82 # The above would create a route to handle C</widgets>, listing all widgets,
83 # with options to add/edit entries (linking to C</widgets/add> and
84 # C</widgets/edit/:id> respectively) where a form to add a new entry or edit
85 # an existing entry will be created.
86 # All fields in the database table would be editable.
87 #
88 # There is also a view route, C</widgets/view/:id>, which shows all the values
89 # for the fields of a single database entry.
90  
91 # A more in-depth synopsis, using all options (of course, usually you'd only
92 # need to use a few of the options where you need to change the default
93 # behaviour):
94  
95 simple_crud(
96 record_title => 'Team',
97 prefix => '/teams',
98 db_table => 'team',
99 labels => { # More human-friendly labels for some columns
100 venue_id => 'Home Venue',
101 name => 'Team Name',
102 },
103 validation => { # validate values entered for some columns
104 division => qr/\d+/,
105 },
106 input_types => { # overriding form input type for some columns
107 supersecret => 'password',
108 lotsoftext' => 'textarea',
109 },
110 key_column => 'id', # id is default anyway
111 editable_columns => [ qw( venue_id name division ) ],
112 display_columns => [ qw( id venue_id name division ) ],
113 deleteable => 1,
114 editable => 1,
115 addable => 0, # does not allow adding rows
116 sortable => 1,
117 paginate => 300,
118 template => 'simple_crud.tt',
119 query_auto_focus => 1,
120 downloadable => 1,
121 foreign_keys => {
122 columnname => {
123 table => 'venues',
124 key_column => 'id',
125 label_column => 'name',
126 },
127 },
128 table_class => 'table table-bordered',
129 paginate_table_class => 'table table-borderless',
130 custom_columns => [
131 {
132 name => "division_news",
133 raw_column => "division",
134 transform => sub {
135 my $division_name = shift;
136 my $label = "News about $division_name";
137 $division_name =~ s/([^-_.~A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
138 my $search = qq{http://news.google.com/news?q="$division_name"};
139 return "<a href='$search'>$label</a>";
140 },
141 column_class => "column-class",
142 },
143 ],
144 auth => {
145 view => {
146 require_login => 1,
147 },
148 edit => {
149 require_role => 'Admin',
150 },
151 },
152 );
153  
154  
155  
156 =head1 USAGE
157  
158 This plugin provides a C<simple_crud> keyword, which takes a hash of options as
159 described below, and sets up the appropriate routes to present add/edit/delete
160 options.
161  
162 =head1 OPTIONS
163  
164 The options you can pass to simple_crud are:
165  
166 =over 4
167  
168 =item C<record_title> (required)
169  
170 What we're editing, for instance, if you're editing widgets, use 'Widget'. Will
171 be used in form titles (for instance "Add a ...", "Edit ..."), and button
172 labels.
173  
174 =item C<prefix> (required)
175  
176 The prefix for the routes which will be created. Given a prefix of C</widgets>,
177 then you can go to C</widgets/new> to create a new Widget, and C</widgets/42> to
178 edit the widget with the ID (see key_column) 42.
179  
180 Don't confuse this with Dancer's C<prefix> setting, which would be prepended
181 before the prefix you pass to this plugin. For example, if you used:
182  
183 prefix '/foo';
184 simple_crud(
185 prefix => 'bar',
186 ...
187 );
188  
189 ... then you'd end up with e.g. C</foo/bar> as the record listing page.
190  
191 =item C<db_table> (required)
192  
193 The name of the database table.
194  
195 =item C<key_column> (optional, default: 'id')
196  
197 Specify which column in the table is the primary key. If not given, defaults to
198 id.
199  
200 =item C<where_filter> (optional)
201  
202 Specify one or more 'where' clauses to use to filter the table. For example:
203  
204 simple_crud(
205 prefix => 'bar',
206 where_filter => {user_id => 1000},
207 ...
208 );
209  
210 This would cause only rows with an user_id of 1000 to be displayed in listings
211 and search results, viewed, edited etc.
212  
213 The C<where_filter> parameter takes a hashref describing the WHERE clause, as
214 used by L<Dancer::Plugin::Database>'s C<quick_select> convenience method for
215 example - see the
216 L<where clause documentation in Dancer::Plugin::Database::Core::Handle|Dancer::Plugin::Database::Core::Handle/WHERE-clauses-as-hashrefs>.
217  
218 Alternatively, if the filter condition needs to be calculated at runtime (for
219 example, based on the logged in user calling it), then you can provide a coderef
220 which returns the WHERE clause hashref - for instance:
221  
222 where_filter => sub { { customer_id => logged_in_user()->{customer_id} } },
223  
224 =item C<db_connection_name> (optional)
225  
226 We use L<Dancer::Plugin::Database> to obtain database connections. This option
227 allows you to specify the name of a connection defined in the config file to
228 use. See the documentation for L<Dancer::Plugin::Database> for how multiple
229 database configurations work. If this is not supplied or is empty, the default
230 database connection details in your config file will be used - this is often
231 what you want, so unless your app is dealing with multiple DBs, you probably
232 won't need to worry about this option.
233  
234 =item C<labels> (optional)
235  
236 A hashref of field_name => 'Label', if you want to provide more user-friendly
237 labels for some or all fields. As we're using CGI::FormBuilder, it will do a
238 reasonable job of figuring these out for itself usually anyway - for instance, a
239 field named C<first_name> will be shown as C<First Name>.
240  
241 =item C<input_types> (optional)
242  
243 A hashref of field_name => input type, if you want to override the default type
244 of input which would be selected by L<CGI::FormBuilder> or by our DWIMmery (by
245 default, password fields will be used for field names like 'password', 'passwd'
246 etc, and text area inputs will be used for columns with type 'TEXT').
247  
248 Valid values include anything allowed by HTML, e.g. C<text>, C<select>,
249 C<textarea>, C<radio>, C<checkbox>, C<password>, C<hidden>.
250  
251 Example:
252  
253 input_types => {
254 first_name => 'text',
255 secret => 'password',
256 gender => 'radio',
257 }
258  
259 =item C<validation> (optional)
260  
261 A hashref of field_name => validation criteria which should be passed to
262 L<CGI::FormBuilder>.
263  
264 Example:
265  
266 validation => {
267 email_address => 'EMAIL',
268 age => '/^\d+$/',
269 }
270  
271  
272 =item C<message> (optional)
273  
274 A hashref of field_name => messages to show if validation failed.
275  
276 Default is "Invalid entry".
277  
278 Example:
279  
280 message => {
281 age => 'Please enter your age in years',
282 email => 'That is not a valid email address',
283 },
284  
285 =item C<jsmessage> (optional)
286  
287 A hashref of field_name => message to show when Javascript validation fails.
288  
289 Default message is "- Invalid entry for the "$fieldname" field". See above for
290 example.
291  
292 =item C<sort_options> (optional)
293  
294 A hashref of field_name => optionspec indicating how select options should be sorted
295  
296 This is currently a passthrough to L<CGI::FormBuilder>'s L<sortopts|CGI::FormBuilder/sortopts>. There are several
297 built-in values:
298  
299 NAME Sort option values by name
300 NUM Sort option values numerically
301 LABELNAME Sort option labels by name
302 LABELNUM Sort option labels numerically
303  
304 See the documentation for L<CGI::FormBuilder/sortopts> for more.
305  
306 =item C<acceptable_values> (optional)
307  
308 A hashref of arrayrefs to declare that certain fields can take only a set of
309 acceptable values.
310  
311 Example:
312  
313 acceptable_values => {
314 gender => ['Male', 'Female'],
315 status => [qw(Alive Dead Zombie Unknown)],
316 }
317  
318 You can automatically create option groups (on a field of type C<select>) by specifying
319 the acceptable values in CGI::FormBuilder's C<[value, label, category]> format, like this:
320  
321 acceptable_values => {
322 gender => ['Male', 'Female'],
323 status => [qw(Alive Dead Zombie Unknown)],
324 threat_level => [
325 [ 'child_puke', 'Regurgitation', 'Child'],
326 [ 'child_knee', 'Knee Biter', 'Child'],
327 [ 'teen_eye', 'Eye Roll', 'Adolescent'],
328 [ 'teen_lip', 'Withering Sarcasm', 'Adolescent'],
329 [ 'adult_silent', 'Pointedly Ignore', 'Adult'],
330 [ 'adult_freak', 'Become Very Put Out', 'Adult'],
331 ],
332 }
333  
334 If you are letting FormBuilder choose the field type, you won't see these categories
335 unless you have enough options that it makes the field into a select. If you want to
336 see the categories all the time, you can use the L</input_types> option to force your
337 field to be rendered as a select.
338  
339 =item C<default_value> (optional)
340  
341 A hashref of default values to have pre-selected on the add form.
342  
343 Example:
344  
345 default_value => {
346 gender => 'Female',
347 status => 'Unknown',
348 }
349  
350  
351 =item C<editable_columns> (optional)
352  
353 Specify an arrayref of fields which the user can edit. By default, this is all
354 columns in the database table, with the exception of the key column.
355  
356 =item C<not_editable_columns> (optional)
357  
358 Specify an arrayref of fields which should not be editable.
359  
360 =item C<required> (optional)
361  
362 Specify an arrayref of fields which must be completed. If this is not provided,
363 DWIMmery based on whether the field is set to allow null values in the database
364 will be used - i.e. if that column can contain null, then it doesn't have to be
365 completed, otherwise, it does.
366  
367 =item C<deletable>
368  
369 Specify whether to support deleting records. If set to a true value, a route
370 will be created for C</prefix/delete/:id> to delete the record with the ID
371 given, and the edit form will have a "Delete $record_title" button.
372  
373 =item C<editable>
374  
375 Specify whether to support editing records. Defaults to true. If set to a
376 false value, it will not be possible to add or edit rows in the table. See also C<addable>.
377  
378 =item C<addable>
379  
380 Specify whether to support adding records. Defaults to the value of C<editable> if set,
381 or true otherwise. If set to a false value, it will not be possible to add rows in the table.
382  
383 =item C<sortable>
384  
385 Specify whether to support sorting the table. Defaults to false. If set to a
386 true value, column headers will become clickable, allowing the user to sort
387 the output by each column, and with ascending/descending order.
388  
389 =item C<paginate>
390  
391 Specify whether to show results in pages (with next/previous buttons). Defaults
392 to undef, meaning all records are shown on one page (not useful for large
393 tables). When defined as a number, only this number of results will be shown.
394  
395 =item C<display_columns>
396  
397 Specify an arrayref of columns that should show up in the list. Defaults to all.
398  
399 =item C<template>
400  
401 Specify a template that will be applied to all output. This template must have
402 a "simple_crud" placeholder defined or you won't get any output. This template
403 must be located in your "views" directory.
404  
405 Any global layout will be applied automatically because this option causes the
406 module to use the C<template> keyword. If you don't use this option, the
407 C<template> keyword is not used, which implies that any
408 C<before_template_render> and C<after_template_render> hooks won't be called.
409  
410 =item C<query_auto_focus>
411  
412 Specify whether to automatically set input focus to the query input field.
413 Defaults to true. If set to a false value, focus will not be set.
414 The focus is set using a simple inlined javascript.
415  
416 =item C<downloadable>
417  
418 Specify whether to support downloading the results. Defaults to false. If set
419 to a true value, The results show on the HTML page can be downloaded as
420 CSV/TSV/JSON/XML. The download links will appear at the top of the page.
421  
422 =item C<foreign_keys>
423  
424 A hashref to specify columns in the table which are foreign keys; for each one,
425 the value should be a hashref containing the keys C<table>, C<key_column> and
426 C<label_column>.
427  
428 =item C<custom_columns>
429  
430 An arrayref of hashrefs to specify custom columns to appear in the list view
431 of an entity. (Previously, this was just a hashref of column names and specs,
432 and this style is still supported for backwards compatibility, but is deprecated
433 because it leaves the order of the columns unpredictable.)
434  
435 The keys of each hash are C<name>, the name to use for this custom column,
436 C<raw_column> indicating a column from the table that should be selected to
437 build the custom column from, C<transform>, a subref to be used as a
438 HTML::Table::FromDatabase callback on the resulting column, and C<column_class>,
439 to specify a CSS class for the the column. C<column_class> is optional, and if
440 no C<transform> is provided, sub { return shift; } will be used.
441  
442 If your custom column has the same name as an existing column, your customizations
443 will be used in-place to override the display of the content in that column.
444 If sorting is enabled, the column will be sorted by the
445 underlying database content for that row, and not by the output of your transform function.
446  
447 For a somewhat spurious example:
448  
449 ...
450 custom_columns => [
451 {
452 name => 'email_provider',
453 raw_column => 'email',
454 transform => sub {
455 my $value = shift;
456 return (split /@/, 1)[1];
457 },
458 column_class => 'column-class',
459 },
460 ],
461 ...
462  
463  
464 The C<transform> code ref is passed to L<HTML::Table::FromDatabase> as a
465 callback for that column, so it can do anything a
466 L<HTML::Table::FromDatabase callback|HTML::Table::FromDatabase/CALLBACKS>
467 can do. In particular, the coderef will receive the value of the
468 column as the first parameter, but also a reference to the whole row hashref
469 as the second parameter, so you can do a variety of cunning things.
470  
471 An example of a custom column whose C<transform> coderef uses the row
472 hashref to get other values for the same row could be:
473  
474 ...
475 custom_columns => [
476 {
477 name => 'salutation',
478 raw_column => 'name',
479 transform => sub {
480 my ($name_value, $row) = @_;
481 return "Hi, $row->{title} $name_value!";
482 },
483 }
484 ],
485 ...
486  
487 =item C<auth>
488  
489 You can require that users be authenticated to view/edit records using the C<auth>
490 option to enable authentication powered by L<Dancer::Plugin::Auth::Extensible>.
491  
492 You can set different requirements for viewing and editing, for example:
493  
494 auth => {
495 view => {
496 require_login => 1,
497 },
498 edit => {
499 require_role => 'Admin',
500 },
501 },
502  
503 The example above means that any logged in user can view records, but only users
504 with the 'Admin' role are able to create/edit/delete records.
505  
506 Or, to just require login for anything (same requirements for both viewing and
507 editing), you can use the shorthand:
508  
509 auth => {
510 require_login => 1,
511 },
512  
513  
514 =item C<table_class>
515  
516 This provides a CSS class for the tables.
517  
518 =item C<paginate_table_class>
519  
520 This provides a CSS class for the tables paginate buttons.
521  
522 =cut
523  
524 sub simple_crud {
525 7 ▶ my (%args) = @_;
Subroutine simple_crud: called CC=21 SCAR=40.0
526  
527 # Get a database connection to verify that the table name is OK, etc.
528 7 my $dbh = database($args{db_connection_name});
529  
530 7 ▶ if (!$dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dbh) 0 7 7
531 0 warn "No database handle";
532 0 return;
533 }
534  
535 7 ▶ if (!$args{prefix}) { die "Need prefix to create routes!"; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"prefix"}) 0 7 7
536 7 ▶ if ($args{prefix} !~ m{^/}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"prefix"} =~ m[^/]) 0 7 7
537 0 $args{prefix} = '/' . $args{prefix};
538 }
539  
540 # If there's a Dancer prefix in use, as well as a prefix we're told about,
541 # then _construct_url() will need to be told about that later so it can
542 # construct URLs. It can't just call Dancer::App->current->prefix itself,
543 # though, as the prefix may have changed by the time the code is actually
544 # running. (See RT #73620.) So, we need to grab it here and add it to
545 # %args, so it can see it later.
546 7 ▶ $args{dancer_prefix} = Dancer::App->current->prefix || '';
Condition50%1/2
'Dancer::App'->current->prefix || ''
l!l
07
MC/DC0%0/1
'Dancer::App'->current->prefix || ''
'Dancer::App'->current->prefix
Truth table50%1/2
A
A= 'Dancer::App'->current->prefix
Aresult
11
00
547  
548 7 ▶ if (!$args{db_table}) { die "Need table name!"; }
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"db_table"}) 0 7 7
549  
550 # Accept deleteable as a synonym for deletable
551 $args{deletable} = delete $args{deleteable}
552 7 ▶ if !exists $args{deletable} && exists $args{deleteable};
Branch: 1 branch
BranchTrueFalseTotal
if not exists $args{"deletable"} and exists $args{"deleteable"} 0 7 7
Condition33%1/3
not exists $args{"deletable"} and exists $args{"deleteable"}
!ll&&!rl&&r
070
MC/DC0%0/2
not exists $args{"deletable"} and exists $args{"deleteable"}
not exists $args{"deletable"} exists $args{"deleteable"}
Truth table33%1/3
not(A) and B
A= not exists $args{"deletable"}B= exists $args{"deleteable"}
ABresult
0X0
100
111
553  
554 # Sane default values:
555 7 ▶ $args{key_column} ||= 'id';
Condition50%1/2
$args{"key_column"} ||= "id"
l!l
07
MC/DC0%0/1
$args{"key_column"} ||= "id"
$args{"key_column"}
Truth table50%1/2
A
A= $args{"key_column"}
Aresult
11
00
556 7 ▶ $args{record_title} ||= 'record';
Condition50%1/2
$args{"record_title"} ||= "record"
l!l
70
MC/DC0%0/1
$args{"record_title"} ||= "record"
$args{"record_title"}
Truth table50%1/2
A
A= $args{"record_title"}
Aresult
11
00
557 7 ▶ $args{editable} = 1 unless exists $args{editable};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"editable"} 0 7 7
558 7 ▶ $args{addable} = $args{editable} unless exists $args{addable};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"addable"} 6 1 7
559 7 ▶ $args{query_auto_focus} = 1 unless exists $args{query_auto_focus};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"query_auto_focus"} 7 0 7
560  
561 # Sanitise things we'll have to interpolate into queries (yes, that makes me
562 # feel bad, but you can't use params for field/table names):
563 7 my $table_name = $args{db_table};
564 7 my $key_column = $args{key_column};
565 7 for ($table_name, $key_column) {
566 14 ▶ die "Invalid table name/key column - SQL injection attempt?"
Branch: 1 branch
BranchTrueFalseTotal
if /--/ 0 14 14
567 if /--/;
568 14 s/[^a-zA-Z0-9_-]//g;
569 }
570  
571 # OK, create a route handler to deal with adding/editing:
572 my $handler
573 7 ▶ = sub { _create_add_edit_route(\%args, $table_name, $key_column); };
Subroutine __ANON__: called CC=1 SCAR=0.0
574  
575 7 ▶ if ($args{editable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"editable"}) 2 5 7
576 2 _ensure_auth('edit', $handler, \%args);
577 2 for ('/edit/:id') {
578 2 my $url = _construct_url($args{prefix}, $_);
579 2 Dancer::Logger::debug("Setting up route for $url");
580 2 any ['get', 'post'] => $url => $handler;
581 }
582 }
583 7 ▶ if ($args{addable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"addable"}) 1 6 7
584 1 _ensure_auth('edit', $handler, \%args);
585 1 for ('/add') {
586 1 my $url = _construct_url($args{prefix}, $_);
587 1 Dancer::Logger::debug("Setting up route for $url");
588 1 any ['get', 'post'] => $url => $handler;
589 }
590 }
591  
592 # And a route to list records already in the table:
593 my $list_handler
594 = _ensure_auth(
595 'view',
596 14 ▶ sub { _create_list_handler(\%args, $table_name, $key_column); },
Subroutine __ANON__: called CC=1 SCAR=0.0
597 7 \%args,
598 );
599 get _construct_url(
600 $args{prefix},
601 7 ) => $list_handler;
602  
603 # If we should allow deletion of records, set up routes to handle that,
604 # too.
605 7 ▶ if ($args{editable} && $args{deletable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"editable"} and $args{"deletable"}) 0 7 7
Condition66%2/3
$args{"editable"} and $args{"deletable"}
!ll&&!rl&&r
520
MC/DC0%0/2
$args{"editable"} and $args{"deletable"}
$args{"editable"} $args{"deletable"}
Truth table66%2/3
A and B
A= $args{"editable"}B= $args{"deletable"}
ABresult
0X0
100
111
606  
607 # A route for GET requests, to present a "Do you want to delete this"
608 # message with a form to submit (this is only for browsers which didn't
609 # support Javascript, otherwise the list page will have POSTed the ID
610 # to us) (or they just came here directly for some reason)
611 get _construct_url(
612 $args{prefix}, "/delete/:id"
613 ) => sub {
614 0 ▶ return _apply_template(<<CONFIRMDELETE, $args{'template'}, $args{'record_title'});
Subroutine __ANON__: not called CC=1 SCAR=6.9
615 <p>
616 Do you really wish to delete this record?
617 </p>
618  
619 <form method="post">
620 <input type="button" value="Cancel" onclick="history.back();">
621 <input type="submit" value="Delete record">
622 </form>
623 CONFIRMDELETE
624  
625 0 };
626  
627 # A route for POST requests, to actually delete the record
628 my $del_url_stub = _construct_url(
629 0 $args{prefix}, '/delete'
630 );
631 my $delete_handler = sub {
632 0 ▶ my ($id) = params->{record_id} || splat;
Subroutine __ANON__: not called CC=4 SCAR=30.0
Condition0%0/3
params()->{'record_id'} || splat()
l!l&&r!l&&!r
000
MC/DC0%0/2
params()->{'record_id'} || splat()
params()->{'record_id'} splat()
Truth table0%0/3
A || B
A= params()->{'record_id'}B= splat()
ABresult
1X1
011
000
633 0 my $dbh = database($args{db_connection_name});
634 0 my $where = _get_where_filter_from_args(\%args);
635 0 $where->{$key_column} = $id;
636  
637 0 my %params = params;
638 0 my $meta_for_hook = {
639 args => \%args,
640 params => \%params,
641 table_name => $table_name,
642 key_column => $key_column,
643 };
644 # fire the pre-delete hook, in case user wants to perform trickery before the delete
645 0 execute_hook('delete_row_pre_delete', $meta_for_hook );
646  
647 my $rows_deleted = $dbh->quick_delete($table_name, $where)
648 or return _apply_template("<p>Failed to delete!</p>",
649 0 ▶ $args{'template'});
Branch: 1 branch
BranchTrueFalseTotal
my $rows_deleted = $dbh->quick_delete($table_name, $where) or return _apply_template("<p>Failed to delete!</p>", $args{"template"}) 0 0 0
650  
651 0 $meta_for_hook->{success} = $rows_deleted;
652 0 ▶ if ($rows_deleted) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rows_deleted) 0 0 0
653 # post-delete hook, in case user wants to do cunning things after the delete
654 0 execute_hook('delete_row_post_delete', $meta_for_hook );
655 }
656  
657 0 redirect _external_url($args{dancer_prefix}, $args{prefix});
658 0 };
659 0 _ensure_auth('edit', $delete_handler, \%args);
660 0 post qr[$del_url_stub/?(.+)?$] => $delete_handler;
661 }
662 my $view_url_stub = _construct_url(
663 7 $args{prefix}, '/view'
664 );
665 my $view_handler = _ensure_auth(
666 'view',
667 2 ▶ sub { _create_view_handler(\%args, $table_name, $key_column); },
Subroutine __ANON__: called CC=1 SCAR=0.0
668 7 \%args,
669 );
670  
671 7 get $view_url_stub.'/:id' => $view_handler;
672 }
673  
674 sub _create_view_handler {
675 2 ▶ my ($args, $table_name, $key_column) = @_;
Subroutine _create_view_handler: called CC=4 SCAR=13.9
676 2 my $params = params;
677 2 ▶ my $id = $params->{id} or return _apply_template("<p>Need id to view!</p>", $args->{'template'});
Branch: 1 branch
BranchTrueFalseTotal
my $id = $params->{"id"} or return _apply_template("<p>Need id to view!</p>", $args->{"template"}) 0 2 2
678  
679 2 my $dbh = database($args->{db_connection_name});
680  
681 # a hash containing the current values in the database. Take where_filter
682 # into account, so we can't fetch a row if it doesn't match the filter
683 # (otherwise people could load any record they wished just by changing the
684 # ID in the URL, which would be considered a Bad Thing)
685 2 my $where = _get_where_filter_from_args($args);
686 2 $where->{$key_column} = $id;
687 2 my $values_from_database = $dbh->quick_select($table_name, $where);
688  
689 # Find out about table columns:
690 2 my $all_table_columns = _find_columns($dbh, $args->{db_table});
691 2 my @rows = (['Column Name', 'Value']);
692 2 my $table = HTML::Table->new( -border=>1 );
693 2 $table->addSectionRow('thead', 0, 'Column Name', 'Value');
694 2 $table->setSectionCellHead('thead', 0, 1, 1, 1);
695 2 $table->setSectionCellHead('thead', 0, 1, 2, 1);
696 2 foreach my $col (@$all_table_columns) {
697 6 $table->addSectionRow('tbody', 0, $col->{COLUMN_NAME}, $values_from_database->{$col->{COLUMN_NAME}});
698 }
699 2 ▶ my $html = $table->getTable || '';
Condition50%1/2
$table->getTable || ''
l!l
20
MC/DC0%0/1
$table->getTable || ''
$table->getTable
Truth table50%1/2
A
A= $table->getTable
Aresult
11
00
700 2 return _apply_template($html, $args->{'template'});
701 }
702  
703 3 register simple_crud => \&simple_crud;
704 3 register_hook(qw(
705 add_edit_row
706 add_edit_row_pre_save
707 add_edit_row_post_save
708 delete_row_pre_delete
709 delete_row_post_delete
710 ));
711 3 register_plugin;
712  
713 sub _create_add_edit_route {
714 6 ▶ my ($args, $table_name, $key_column) = @_;
Subroutine _create_add_edit_route: called CC=41 SCAR=55.0
715 6 my $params = params;
716 6 my $id = $params->{id};
717  
718 6 my $dbh = database($args->{db_connection_name});
719  
720 # a hash containing the current values in the database
721 6 my $values_from_database;
722 6 ▶ if (defined $id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $id) 5 1 6
723 5 my $where = _get_where_filter_from_args($args);
724 5 $where->{$key_column} = $id;
725 5 $values_from_database
726 = $dbh->quick_select($table_name, $where);
727 5 ▶ if (!$values_from_database) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($values_from_database) 3 2 5
728 3 send_error "$params->{title} $id not found", 404;
729  
730 }
731 }
732  
733 # Find out about table columns:
734 3 my $all_table_columns = _find_columns($dbh, $args->{db_table});
735 3 my @editable_columns;
736  
737 # Now, find out which ones we can edit.
738 3 ▶ if ($args->{editable_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'editable_columns'}) { } 0 3 3
739  
740 # We were given an explicit list of fields we can edit, so this is
741 # easy:
742 0 @editable_columns = @{ $args->{editable_columns} };
743 } else {
744  
745 # OK, take all the columns from the table, except the key field:
746 9 @editable_columns = grep { $_ ne $key_column }
747 3 map { $_->{COLUMN_NAME} } @$all_table_columns;
748 }
749  
750 3 ▶ if ($args->{not_editable_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"not_editable_columns"}) 0 3 3
751 0 for my $col (@{ $args->{not_editable_columns} }) {
752 0 @editable_columns = grep { $_ ne $col } @editable_columns;
753 }
754 }
755  
756 # Some DWIMery: if we don't have a validation rule specified for a
757 # field, and it's pretty clear what it is supposed to be, just do it:
758 3 ▶ my $validation = $args->{validation} || {};
Condition100%2/2
$args->{'validation'} || {}
l!l
21
MC/DC100%1/1
$args->{'validation'} || {}
$args->{'validation'}
Truth table100%2/2
A
A= $args->{'validation'}
Aresult
11
00
759 3 for my $field (grep { $_ ne $key_column } @editable_columns) {
760 6 ▶ next if $validation->{$field};
Branch: 1 branch
BranchTrueFalseTotal
if $validation->{$field} 0 6 6
761 6 ▶ if ($field =~ /email/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /email/) 0 6 6
762 0 $validation->{$field} = 'EMAIL';
763 }
764 }
765  
766 # More DWIMmery: if the user hasn't supplied a list of required fields,
767 # work out what fields are required by whether they're nullable in the
768 # DB:
769 3 my %required_fields;
770 3 ▶ if (exists $args->{required}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{'required'}) { } 0 3 3
771 0 $required_fields{$_}++ for @{ $args->{required} };
772 } else {
773 $_->{NULLABLE} || $required_fields{ $_->{COLUMN_NAME} }++
774 3 ▶ for @$all_table_columns;
Branch: 1 branch
BranchTrueFalseTotal
$_->{"NULLABLE"} or ++$required_fields{$_->{"COLUMN_NAME"}} 0 9 9
775 }
776  
777 # If the user didn't supply a list of acceptable values for a field, but
778 # it's an ENUM column, use the possible values declared in the ENUM.
779 # Also remember field types for easy reference later
780 3 my %constrain_values;
781 my %field_type;
782 3 for my $field (@$all_table_columns) {
783 9 my $name = $field->{COLUMN_NAME};
784 9 $field_type{$name} = $field->{TYPE_NAME};
785 9 ▶ if (my $values_specified = $args->{acceptable_values}->{$name}) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $values_specified = $args->{'acceptable_values'}{$name}) { } 0 9 9
elsif (my $foreign_key = $args->{'foreign_keys'}{$name}) { } 0 9 9
elsif (my $values_from_db = $field->{'mysql_values'}) { } 0 9 9
786  
787 # It may have been given to us as a coderef; if so, execute it to
788 # get the results
789 0 ▶ if (ref $values_specified eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $values_specified eq "CODE") 0 0 0
790 0 $values_specified = $values_specified->();
791 }
792 0 $constrain_values{$name} = $values_specified;
793  
794 } elsif (my $foreign_key = $args->{foreign_keys}{$name}) {
795  
796 # Find out the possible values for this column from the other table:
797 0 my %possible_values;
798 0 debug "Looking for rows for foreign relation: " => $foreign_key;
799 0 for my $row ($dbh->quick_select($foreign_key->{table}, {})) {
800 0 debug "Row from foreign relation: " => $row;
801 $possible_values{ $row->{ $foreign_key->{key_column} } }
802 0 = $row->{ $foreign_key->{label_column} };
803 }
804 0 $constrain_values{$name} = \%possible_values;
805  
806 } elsif (my $values_from_db = $field->{mysql_values}) {
807 0 $constrain_values{$name} = $values_from_db;
808 }
809 }
810  
811 # Only give CGI::FormBuilder our fake CGI object if the form has been
812 # POSTed to us already; otherwise, it will ignore default values from
813 # the DB, it seems.
814 my $paramsobj
815 3 ▶ = request->{method} eq 'POST'
Branch: 1 branch
BranchTrueFalseTotal
request()->{'method'} eq 'POST' ? : 0 3 3
816 ? Dancer::Plugin::SimpleCRUD::ParamsObject->new({ params() })
817 : undef;
818  
819 my $form = CGI::FormBuilder->new(
820 fields => \@editable_columns,
821 params => $paramsobj,
822 values => $values_from_database,
823 validate => $validation,
824 method => 'post',
825 action => _external_url(
826 $args->{dancer_prefix},
827 $args->{prefix},
828 (
829 params->{id}
830 ? '/edit/' . params->{id}
831 3 ▶ : '/add'
Branch: 1 branch
BranchTrueFalseTotal
params()->{'id'} ? : 1 2 3
832 )
833 ),
834 );
835 3 for my $field (@editable_columns) {
836 # first check if there's data from the database for this field,
837 # then if there's a value in params() for this field,
838 # then if args->{default_value} was set for this field via the
839 # 'default_value' hash when the route was created.
840 my $default =
841 exists $values_from_database->{$field}
842 ? $values_from_database->{$field}
843 : exists params->{$field}
844 ? uri_unescape(params->{$field})
845 : exists $args->{default_value}->{$field}
846 6 ▶ ? $args->{default_value}->{$field}
Branch: 3 branches
BranchTrueFalseTotal
exists $values_from_database->{$field} ? : 4 2 6
exists params()->{$field} ? : 0 2 2
exists $args->{'default_value'}{$field} ? : 0 2 2
847 : '';
848 6 my %field_params = (
849 name => $field,
850 value => $default,
851 );
852  
853 6 $field_params{required} = $required_fields{$field};
854  
855 6 ▶ if ($constrain_values{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($constrain_values{$field}) 0 6 6
856 0 $field_params{options} = $constrain_values{$field};
857 }
858  
859 # Certain options in $args simply cause that value to be added to the
860 # params for this field we'll pass to $form->field:
861 6 my %option_map = (
862 labels => 'label',
863 validation => 'validate',
864 message => 'message',
865 jsmessage => 'jsmessage',
866 sort_options => 'sortopts',
867 );
868 6 ▶ while (my ($arg_name, $field_param_name) = each(%option_map)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %option_map) 30 6 36
869 30 ▶ if (my $val = $args->{$arg_name}{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $val = $args->{$arg_name}{$field}) 0 30 30
870 0 $field_params{$field_param_name} = $val;
871 }
872 }
873  
874 # Normally, CGI::FormBuilder can guess the type of field perfectly,
875 # but give it some extra DWIMmy help:
876 6 ▶ if ($field =~ /pass(?:wd|word)?$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field =~ /pass(?:wd|word)?$/i) 3 3 6
877 3 $field_params{type} = 'password';
878 }
879  
880 # use a <textarea> for large text fields.
881 6 ▶ if ($field_type{$field} eq 'TEXT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($field_type{$field} eq "TEXT") 0 6 6
882 0 $field_params{type} = 'textarea';
883 }
884  
885 # ... unless the user specified a type for this field, in which case,
886 # use what they said
887 6 ▶ if (my $override_type = $args->{input_types}{$field}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $override_type = $args->{"input_types"}{$field}) 0 6 6
888 0 $field_params{type} = $override_type;
889 }
890  
891 # if the constraint on this is an array of arrays,
892 # and there are three elements in the first array in that list,
893 # (which will be intepreted as: value, label, category)
894 # we are going to assume you want optgroups, with the
895 # third element in each being the category.
896 #
897 # (See the optgroups option in CGI::FormBuilder)
898 6 ▶ if (ref($field_params{options}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $field_params{"options"} eq "ARRAY") 0 6 6
899 0 ▶ if (ref( $field_params{options}->[0] ) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $field_params{"options"}[0] eq "ARRAY") 0 0 0
900 0 ▶ if (@{ $field_params{options}->[0] } == 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$field_params{"options"}[0];} == 3) 0 0 0
901 0 $field_params{optgroups} = 1;
902 }
903 }
904 }
905  
906  
907 # OK, add the field to the form:
908 6 $form->field(%field_params);
909 }
910  
911 # Now, if all is OK, go ahead and process:
912 3 ▶ if (request->{method} eq 'POST' && $form->submitted && $form->validate) {
Branch: 1 branch
BranchTrueFalseTotal
if (request()->{'method'} eq 'POST' and $form->submitted and $form->validate) { } 0 3 3
Condition33%2/6
request()->{"method"} eq "POST" and $form->submitted and $form->validate
!ll&&!rl&&r
300
request()->{"method"} eq "POST" and $form->submitted
!ll&&!rl&&r
300
MC/DC0%0/3
request()->{"method"} eq "POST" and $form->submitted and $form->validate
request()->{"method"} eq "POST" $form->submitted $form->validate
Truth table25%1/4
A and B and C
A= request()->{"method"} eq "POST"B= $form->submittedC= $form->validate
ABCresult
0XX0
10X0
1100
1111
913  
914 # Assemble a hash of only fields from the DB (if other fields were
915 # submitted with the form which don't belong in the DB, ignore them)
916 0 my %params;
917 0 $params{$_} = params('body')->{$_} for @editable_columns;
918  
919 0 my $meta_for_hook = {
920 args => $args,
921 params => \%params,
922 table_name => $table_name,
923 key_column => $key_column,
924 };
925 # Fire a hook so the user can manipulate the data in a whole range of
926 # cunning ways, if they wish
927 0 execute_hook('add_edit_row', \%params);
928 0 execute_hook('add_edit_row_pre_save', $meta_for_hook);
929  
930 0 my $verb;
931 my $success;
932 0 ▶ if (exists params('route')->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists params('route')->{'id'}) { } 0 0 0
933  
934 # We're editing an existing record - make sure the WHERE clause
935 # hashref incorporates where_filter, if in use, so that users can't
936 # edit stuff they shouldn't be able to
937 0 my $where = _get_where_filter_from_args($args);
938 0 $where->{$key_column} = params('route')->{id};
939 0 $success = $dbh->quick_update($table_name, $where, \%params);
940 0 $verb = 'update';
941 } else {
942 0 $success = $dbh->quick_insert($table_name, \%params);
943 # pass them *this* dbh instance so that they can call last_insert_id()
944 # against it if they need to. last_insert_id in some instances requires
945 # catalog, schema, etc args, so we can't just call it and save the result.
946 # important that we don't do any more database operations that would change
947 # last_insert_id between here and the hook, or this won't work.
948 0 $meta_for_hook->{dbh} = $dbh;
949 0 $verb = 'create new';
950 }
951  
952 0 $meta_for_hook->{success} = $success;
953 0 $meta_for_hook->{verb} = $verb;
954 0 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 0 0 0
955  
956 # Redirect to the list page
957 # TODO: pass a param to cause it to show a message?
958 0 execute_hook('add_edit_row_post_save', $meta_for_hook);
959 0 redirect _external_url($args->{dancer_prefix}, $args->{prefix});
960 0 return;
961 } else {
962 0 execute_hook('add_edit_row_post_save', $meta_for_hook);
963 # TODO: better error handling - options to provide error templates
964 # etc
965 # (below is one approach to that TODO--this, or perhaps the hook could return a hash
966 # that would specify these overrides? Probably best to come up with a complete mechanism
967 # consistent across hooks before we implement.)
968 # return _apply_template(
969 # $meta_for_hook->{return}{error_message} || "<p>Unable to $verb $args->{record_title}</p>",
970 # $meta_for_hook->{return}{error_template} || $args->{error_template} || $args->{'template'}
971 #);
972 return _apply_template(
973 "<p>Unable to $verb $args->{record_title}</p>",
974 0 $args->{'template'}, $args->{'record_title'});
975 }
976  
977 } else {
978 3 return _apply_template($form->render, $args->{'template'}, $args->{'record_title'});
979 }
980 }
981  
982 sub _create_list_handler {
983 14 ▶ my ($args, $table_name, $key_column) = @_;
Subroutine _create_list_handler: called CC=82 SCAR=64.2
984  
985 14 my $dbh = database($args->{db_connection_name});
986 14 my $columns = _find_columns($dbh, $table_name);
987  
988 14 my $display_columns = $args->{'display_columns'};
989  
990 14 ▶ my $table_class = $args->{'table_class'} || '';
Condition50%1/2
$args->{'table_class'} || ''
l!l
014
MC/DC0%0/1
$args->{'table_class'} || ''
$args->{'table_class'}
Truth table50%1/2
A
A= $args->{'table_class'}
Aresult
11
00
991 14 ▶ my $paginate_table_class = $args->{'paginate_table_class'} || '';
Condition50%1/2
$args->{'paginate_table_class'} || ''
l!l
014
MC/DC0%0/1
$args->{'paginate_table_class'} || ''
$args->{'paginate_table_class'}
Truth table50%1/2
A
A= $args->{'paginate_table_class'}
Aresult
11
00
992  
993 # If display_columns argument was passed, filter the column list to only
994 # have the ones we asked for.
995 14 ▶ if (ref $display_columns eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $display_columns eq "ARRAY") 0 14 14
996 0 my @filtered_columns;
997  
998 0 foreach my $col (@$columns) {
999 0 ▶ if (grep { $_ eq $col->{'COLUMN_NAME'} } @$display_columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ eq $col->{"COLUMN_NAME"};} @$display_columns) 0 0 0
1000 0 push @filtered_columns, $col;
1001 }
1002 }
1003  
1004 0 ▶ if (@filtered_columns) {
Branch: 1 branch
BranchTrueFalseTotal
if (@filtered_columns) 0 0 0
1005 0 $columns = \@filtered_columns;
1006 }
1007 }
1008  
1009 14 ▶ my $searchfield = params->{searchfield} || $key_column;
Condition66%2/3
params()->{'searchfield'} || $key_column
l!l&&r!l&&!r
3110
MC/DC0%0/2
params()->{'searchfield'} || $key_column
params()->{'searchfield'} $key_column
Truth table66%2/3
A || B
A= params()->{'searchfield'}B= $key_column
ABresult
1X1
011
000
1010 my $searchfield_options = join(
1011 "\n",
1012 map {
1013 14 my $friendly_name = $_->{COLUMN_NAME};
1014 42 ▶ if ($args->{labels}{$_->{COLUMN_NAME}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"labels"}{$_->{"COLUMN_NAME"}}) 0 42 42
1015 0 $friendly_name = $args->{labels}{$_->{COLUMN_NAME}};
1016 }
1017 my $sel
1018 = ($searchfield eq $_->{COLUMN_NAME})
1019 42 ▶ ? "selected"
Branch: 1 branch
BranchTrueFalseTotal
$searchfield eq $_->{'COLUMN_NAME'} ? : 14 28 42
1020 : "";
1021 42 "<option $sel value='$_->{COLUMN_NAME}'>$friendly_name</option>"
1022 } @$columns
1023 );
1024 14 my $default_searchtype = "e";
1025 14 my @searchtypes = (
1026 [ e => { name => "Equals", cmp => "=" } ],
1027 [ c => { name => "Contains", cmp => "like" } ],
1028 [ b => { name => "Begins With", cmp => "like" } ],
1029 [ ne => { name => "Does Not Equal", cmp => "!=" } ],
1030 [ nc => { name => "Does Not Contain", cmp => "not like" } ],
1031  
1032 [ lt => { name => "Less Than", cmp => "<" } ],
1033 [ lte => { name => "Less Than or Equal To", cmp => "<=" } ],
1034 [ gt => { name => "Greater Than", cmp => ">" } ],
1035 [ gte => { name => "Greater Than or Equal To", cmp => ">=" } ],
1036  
1037 [ like => { name => "Like", cmp => "LIKE" } ],
1038 );
1039 my $searchtype_options = join( "\n",
1040 map {
1041 14 my ($search_code, $hashref) = @$_;
1042 140 my $name = $hashref->{name};
1043 140 ▶ my $sel = (params->{searchtype} || $default_searchtype) eq $search_code;
Condition66%2/3
params()->{'searchtype'} || $default_searchtype
l!l&&r!l&&!r
301100
MC/DC0%0/2
params()->{'searchtype'} || $default_searchtype
params()->{'searchtype'} $default_searchtype
Truth table66%2/3
A || B
A= params()->{'searchtype'}B= $default_searchtype
ABresult
1X1
011
000
1044 140 ▶ sprintf("<option value='%s'%s>%s</option>", $search_code, $sel ? " selected" : "", $name);
Branch: 1 branch
BranchTrueFalseTotal
$sel ? : 14 126 140
1045 } @searchtypes
1046 );
1047  
1048 14 ▶ my $order_by_param = params->{'o'} || "";
Condition50%1/2
params()->{'o'} || ''
l!l
014
MC/DC0%0/1
params()->{'o'} || ''
params()->{'o'}
Truth table50%1/2
A
A= params()->{'o'}
Aresult
11
00
1049 14 ▶ my $order_by_direction = params->{'d'} || "";
Condition50%1/2
params()->{'d'} || ''
l!l
014
MC/DC0%0/1
params()->{'d'} || ''
params()->{'d'}
Truth table50%1/2
A
A= params()->{'d'}
Aresult
11
00
1050 14 my $q = _defined_or_empty(params->{'q'});
1051 14 my $display_q = encode_entities( $q );
1052 14 my $html = <<"SEARCHFORM";
1053 <p><form name="searchform" method="get">
1054 Field: <select name="searchfield">$searchfield_options</select> &nbsp;&nbsp;
1055 <select name="searchtype">$searchtype_options</select>&nbsp;&nbsp;
1056 <input name="q" id="searchquery" type="text" size="30" value="$display_q" /> &nbsp;&nbsp;
1057 <input name="o" type="hidden" value="$order_by_param"/>
1058 <input name="d" type="hidden" value="$order_by_direction"/>
1059 <input name="searchsubmit" type="submit" value="Search"/>
1060 </form></p>
1061 SEARCHFORM
1062  
1063 14 ▶ if ($args->{query_auto_focus}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"query_auto_focus"}) 14 0 14
1064 14 $html
1065 .= "<script>document.getElementById(\"searchquery\").focus();</script>";
1066 }
1067  
1068 # Explicitly select the columns we are displaying. (May have been filtered
1069 # by display_columns above.)
1070  
1071 14 my @select_cols = map { $_->{COLUMN_NAME} } @$columns;
1072  
1073 # If we have some columns declared as foreign keys, though, we don't want to
1074 # see the raw values in the result; we'll add JOIN clauses to fetch the info
1075 # from the related table, so for now just select the defined label column
1076 # from the related table instead of the raw ID value.
1077  
1078 # This _as_simplecrud_fk_ mechanism is clearly a bit of a hack. At some point we
1079 # might want to pull in an existing solution for this--this is simple and
1080 # may have pitfalls that have already been solved in Catalyst/DBIC code.
1081 # For now, we're going with simple. git show 14cec4ea647 to see the
1082 # basic change (that's previous to the add of LEFT to the JOIN, though), if you want
1083 # to know exactly what to pull out when replacing this
1084  
1085 14 my @foreign_cols;
1086 my %fk_alias; # foreign key aliases for cases where we might have collisions
1087 14 ▶ if ($args->{foreign_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"foreign_keys"}) 1 13 14
1088 1 my $seen_table = {$table_name=>1};
1089 1 ▶ while (my ($col, $foreign_key) = each(%{ $args->{foreign_keys} })) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$args{"foreign_keys"};}) 0 1 1
1090 0 @select_cols = grep { $_ ne $col } @select_cols;
1091 0 my $raw_ftable = $foreign_key->{table};
1092 0 my $ftable_alias;
1093 0 ▶ if ($seen_table->{$raw_ftable}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen_table->{$raw_ftable}++) 0 0 0
1094 0 $ftable_alias = $fk_alias{ $col } = $dbh->quote_identifier($raw_ftable. "_as_simplecrud_fk_$seen_table->{$raw_ftable}");
1095 }
1096 0 my $ftable = $dbh->quote_identifier($raw_ftable);
1097 my $fcol
1098 0 = $dbh->quote_identifier($foreign_key->{label_column});
1099 my $lcol
1100 0 ▶ = $dbh->quote_identifier($args->{labels}{$col} || $col);
Condition0%0/3
$args->{'labels'}{$col} || $col
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{'labels'}{$col} || $col
$args->{'labels'}{$col} $col
Truth table0%0/3
A || B
A= $args->{'labels'}{$col}B= $col
ABresult
1X1
011
000
1101  
1102 0 ▶ my $table_or_alias = $fk_alias{ $col } || $ftable;
Condition0%0/3
$fk_alias{$col} || $ftable
l!l&&r!l&&!r
000
MC/DC0%0/2
$fk_alias{$col} || $ftable
$fk_alias{$col} $ftable
Truth table0%0/3
A || B
A= $fk_alias{$col}B= $ftable
ABresult
1X1
011
000
1103 0 push @foreign_cols, "$table_or_alias.$fcol AS $lcol";
1104 }
1105 }
1106  
1107 14 my @custom_cols;
1108  
1109 # For backwards compatibility, understand custom_columns being a hashref,
1110 # and translate it
1111 14 ▶ if (ref $args->{custom_columns} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args->{"custom_columns"} eq "HASH") 0 14 14
1112 0 my @custom_cols_list;
1113 0 for my $column_alias (keys %{ $args->{custom_columns} }) {
1114 push @custom_cols_list, {
1115 name => $column_alias,
1116 0 %{ $args->{custom_columns}{$column_alias} }
1117 };
1118 }
1119 0 $args->{custom_columns} = \@custom_cols_list;
1120 }
1121  
1122 # If we're not overriding a column with the same name, then add custom column
1123 14 ▶ for my $custom_col_spec (@{ $args->{custom_columns} || [] }) {
Branch: 1 branch
BranchTrueFalseTotal
$args->{"custom_columns"} or [] 3 11 14
1124 11 my $column_alias = $custom_col_spec->{name};
1125 11 ▶ if( ! grep { $column_alias eq $_ } @select_cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$column_alias eq $_;} @select_cols) 4 7 11
1126 my $raw_column = $custom_col_spec->{raw_column}
1127 4 ▶ or die "you must specify a raw_column that "
Branch: 1 branch
BranchTrueFalseTotal
my $raw_column = $custom_col_spec->{"raw_column"} or die 'you must specify a raw_column that ' . "$column_alias will be built using" 0 4 4
1128 . "$column_alias will be built using";
1129 4 ▶ if ($raw_column =~ /^[\w_]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_column =~ /^[\w_]+$/) { } 4 0 4
1130 4 push @custom_cols, "$table_name."
1131 . $dbh->quote_identifier($raw_column)
1132 . " AS ". $dbh->quote_identifier($column_alias);
1133 } else {
1134 0 push @custom_cols, "$raw_column AS $column_alias";
1135 }
1136 }
1137 }
1138  
1139 my $col_list = join(
1140 ',',
1141 map(
1142 14 { $table_name . "." . $dbh->quote_identifier($_) }
1143 @select_cols
1144 ),
1145 @foreign_cols, # already assembled from quoted identifiers
1146 @custom_cols,
1147 );
1148 my $add_actions
1149 = $args->{editable}
1150 14 ▶ ? ", $table_name.$key_column AS actions"
Branch: 1 branch
BranchTrueFalseTotal
$args->{'editable'} ? : 2 12 14
1151 : '';
1152 14 my $query = "SELECT $col_list $add_actions FROM $table_name";
1153 14 my @binds;
1154  
1155 # If we have foreign key relationship info, we need to join on those tables:
1156 14 ▶ if ($args->{foreign_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"foreign_keys"}) 1 13 14
1157 1 ▶ while (my ($col, $foreign_key) = each %{ $args->{foreign_keys} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$args{"foreign_keys"};}) 0 1 1
1158 0 my $ftable = $dbh->quote_identifier($foreign_key->{table});
1159 0 my $lkey = $dbh->quote_identifier($col);
1160 0 my $rkey = $dbh->quote_identifier($foreign_key->{key_column});
1161  
1162 # Identifiers quoted above, and $table_name quoted further up, so
1163 # all safe to interpolate
1164 0 my $what_to_join = $ftable;
1165 0 my $join_reference = $ftable;
1166 0 ▶ if (my $alias = $fk_alias{$col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $alias = $fk_alias{$col}) 0 0 0
1167 0 $what_to_join = " $ftable AS $alias ";
1168 0 $join_reference = $alias;
1169 }
1170 # If this join is not a left join, the list view only shows rows where the
1171 # foreign key is defined and matching a row
1172 0 $query .= " LEFT JOIN $what_to_join ON $table_name.$lkey = $join_reference.$rkey ";
1173 }
1174 }
1175  
1176 # If we have a query or a where_filter, we need to assemble a WHERE clause...
1177 14 my $where_filter = _get_where_filter_from_args($args);
1178 14 ▶ if (length $q || $where_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $q or $where_filter) 4 10 14
Condition66%2/3
length $q or $where_filter
l!l&&r!l&&!r
4010
MC/DC50%1/2
length $q or $where_filter
length $q $where_filter
Truth table66%2/3
A or B
A= length $qB= $where_filter
ABresult
1X1
011
000
1179
1180 # Turn the $where_filter hashref into some SQL clauses and bind params,
1181 # which we'll add to with the user's search params shortly
1182 4 my ($where_filter_sql, @where_filter_binds)
1183 = $dbh->generate_where_clauses($where_filter);
1184  
1185 4 my (@search_wheres, @search_binds);
1186 4 ▶ if (length $q) { # this nested code is all for queries in $q
Branch: 1 branch
BranchTrueFalseTotal
if (length $q) 4 0 4
1187 my ($column_data)
1188 12 = grep { lc $_->{COLUMN_NAME} eq lc $searchfield }
1189 4 @{$columns};
1190 4 debug(
1191 "Searching on $column_data->{COLUMN_NAME} which is a "
1192 . "$column_data->{TYPE_NAME}"
1193 );
1194 4 ▶ my $st = params->{searchtype} || $default_searchtype;
Condition66%2/3
params()->{'searchtype'} || $default_searchtype
l!l&&r!l&&!r
310
MC/DC0%0/2
params()->{'searchtype'} || $default_searchtype
params()->{'searchtype'} $default_searchtype
Truth table66%2/3
A || B
A= params()->{'searchtype'}B= $default_searchtype
ABresult
1X1
011
000
1195  
1196 4 ▶ if ($column_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($column_data) 4 0 4
1197 4 my $search_value = $q;
1198 4 ▶ if ($st eq 'c' || $st eq 'nc') { # contains or does not contain
Branch: 2 branches
BranchTrueFalseTotal
if ($st eq 'c' or $st eq 'nc') { } 0 4 4
elsif ($st eq 'b') { } 0 4 4
Condition33%1/3
$st eq "c" or $st eq "nc"
l!l&&r!l&&!r
004
MC/DC0%0/2
$st eq "c" or $st eq "nc"
$st eq "c" $st eq "nc"
Truth table33%1/3
A or B
A= $st eq "c"B= $st eq "nc"
ABresult
1X1
011
000
1199 0 $search_value = '%' . $search_value . '%';
1200 } elsif ($st eq 'b') { # begins with
1201 0 $search_value = $search_value . '%';
1202 }
1203  
1204 4 my ($searchtype_row) = grep { $_->[0] eq $st } @searchtypes;
1205 4 ▶ my $cmp = $searchtype_row->[1]->{cmp} || '=';
Condition50%1/2
$searchtype_row->[1]{'cmp'} || '='
l!l
40
MC/DC0%0/1
$searchtype_row->[1]{'cmp'} || '='
$searchtype_row->[1]{'cmp'}
Truth table50%1/2
A
A= $searchtype_row->[1]{'cmp'}
Aresult
11
00
1206 4 push(@search_wheres,
1207 "$table_name."
1208 . $dbh->quote_identifier($searchfield)
1209 . " $cmp ?" );
1210 4 push(@search_binds, $search_value);
1211  
1212 4 ▶ my $matchtype = lc($searchtype_row->[1]->{name} || "equals");
Condition50%1/2
$searchtype_row->[1]{'name'} || 'equals'
l!l
40
MC/DC0%0/1
$searchtype_row->[1]{'name'} || 'equals'
$searchtype_row->[1]{'name'}
Truth table50%1/2
A
A= $searchtype_row->[1]{'name'}
Aresult
11
00
1213 4 $html
1214 .= sprintf(
1215 "<p>Showing results from searching for '%s' %s '%s'",
1216 encode_entities($searchfield), $matchtype, encode_entities($q)
1217 );
1218 $html .= sprintf '&mdash;<a href="%s">Reset search</a></p>',
1219 4 _external_url($args->{dancer_prefix}, $args->{prefix});
1220 }
1221 }
1222 # add the 'where' clauses to $query and the binds to @binds
1223 4 $query .= " where " . join( " AND ", grep { length $_ } ($where_filter_sql, @search_wheres));
1224 4 push(@binds, @where_filter_binds, @search_binds);
1225 }
1226  
1227 14 ▶ if ($args->{downloadable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"downloadable"}) 0 14 14
1228 0 my $qt = uri_escape($q);
1229 0 my $sf = uri_escape($searchfield);
1230 0 ▶ my $st = uri_escape(params->{searchtype} || $default_searchtype);
Condition0%0/3
params()->{'searchtype'} || $default_searchtype
l!l&&r!l&&!r
000
MC/DC0%0/2
params()->{'searchtype'} || $default_searchtype
params()->{'searchtype'} $default_searchtype
Truth table0%0/3
A || B
A= params()->{'searchtype'}B= $default_searchtype
ABresult
1X1
011
000
1231 0 ▶ my $o = uri_escape(params->{'o'} || "");
Condition0%0/2
params()->{'o'} || ''
l!l
00
MC/DC0%0/1
params()->{'o'} || ''
params()->{'o'}
Truth table0%0/2
A
A= params()->{'o'}
Aresult
11
00
1232 0 ▶ my $d = uri_escape(params->{'d'} || "");
Condition0%0/2
params()->{'d'} || ''
l!l
00
MC/DC0%0/1
params()->{'d'} || ''
params()->{'d'}
Truth table0%0/2
A
A= params()->{'d'}
Aresult
11
00
1233 0 ▶ my $page = uri_escape(params->{'p'} || 0);
Condition0%0/2
params()->{'p'} || 0
l!l
00
MC/DC0%0/1
params()->{'p'} || 0
params()->{'p'}
Truth table0%0/2
A
A= params()->{'p'}
Aresult
11
00
1234  
1235 0 my @formats = qw/csv tabular json xml/;
1236  
1237 my $url = _external_url($args->{dancer_prefix}, $args->{prefix})
1238 0 . "?o=$o&d=$d&q=$qt&searchfield=$sf&searchtype=$st&p=$page";
1239  
1240 $html
1241 .= "<p>Download as: "
1242 0 . join(", ", map { "<a href=\"$url&format=$_\">$_</a>" } @formats)
1243 . "<p>";
1244 }
1245  
1246 14 my %columns_sort_options;
1247 14 ▶ if ($args->{sortable}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"sortable"}) 4 10 14
1248 4 my $qt = uri_escape($q);
1249 4 my $sf = uri_escape($searchfield);
1250 4 ▶ my $st = uri_escape(params->{searchtype} || $default_searchtype);
Condition33%1/3
params()->{'searchtype'} || $default_searchtype
l!l&&r!l&&!r
040
MC/DC0%0/2
params()->{'searchtype'} || $default_searchtype
params()->{'searchtype'} $default_searchtype
Truth table33%1/3
A || B
A= params()->{'searchtype'}B= $default_searchtype
ABresult
1X1
011
000
1251 4 ▶ my $order_by_column = uri_escape(params->{'o'}) || $key_column;
Condition33%1/3
uri_escape(params()->{'o'}) || $key_column
l!l&&r!l&&!r
040
MC/DC0%0/2
uri_escape(params()->{'o'}) || $key_column
uri_escape(params()->{'o'}) $key_column
Truth table33%1/3
A || B
A= uri_escape(params()->{'o'})B= $key_column
ABresult
1X1
011
000
1252  
1253 # Invalid column name ? discard it
1254 4 my $valid = grep { $_->{COLUMN_NAME} eq $order_by_column } @$columns;
1255 4 ▶ $order_by_column = $key_column unless $valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $valid 0 4 4
1256 4 my $order_by_table = $table_name;
1257  
1258 my $order_by_direction
1259 4 ▶ = (exists params->{'d'} && params->{'d'} eq "desc")
Branch: 1 branch
BranchTrueFalseTotal
exists params()->{'d'} && params()->{'d'} eq 'desc' ? : 0 4 4
Condition33%1/3
exists params()->{"d"} and params()->{"d"} eq "desc"
!ll&&!rl&&r
400
MC/DC0%0/2
exists params()->{"d"} and params()->{"d"} eq "desc"
exists params()->{"d"} params()->{"d"} eq "desc"
Truth table33%1/3
A and B
A= exists params()->{"d"}B= params()->{"d"} eq "desc"
ABresult
0X0
100
111
1260 ? "desc"
1261 : "asc";
1262 4 ▶ my $opposite_order_by_direction
Branch: 1 branch
BranchTrueFalseTotal
$order_by_direction eq 'asc' ? : 4 0 4
1263 = ($order_by_direction eq "asc") ? "desc" : "asc";
1264  
1265 # Get a list of all columns (normal, and custom_columns), then assemble
1266 # the names and labels to pass to HTML::Table::FromDatabase
1267 4 my @all_cols = map { $_->{COLUMN_NAME} } @$columns;
1268 %columns_sort_options = map {
1269 4 my $col_name = $_;
1270 12 my $direction = $order_by_direction;
1271 12 my $direction_char = "";
1272 12 my $friendly_name = $col_name;
1273 12 ▶ if ($args->{labels}{$col_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'labels'}{$col_name}) { } 0 12 12
1274 0 $friendly_name = $args->{labels}{$col_name};
1275 } else {
1276 12 $friendly_name = _prettify_column_name($friendly_name);
1277 }
1278 12 ▶ if ($col_name eq $order_by_column) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col_name eq $order_by_column) 4 8 12
1279 4 $direction = $opposite_order_by_direction;
1280 4 ▶ $direction_char = ($direction eq "asc") ? "&uarr;" : "&darr;";
Branch: 1 branch
BranchTrueFalseTotal
$direction eq 'asc' ? : 0 4 4
1281 }
1282 my $url = _external_url($args->{dancer_prefix}, $args->{prefix})
1283 12 . "?o=$col_name&d=$direction&q=$q&searchfield=$sf&searchtype=$st";
1284 12 $col_name =>
1285 "<a href=\"$url\">$friendly_name&nbsp;$direction_char</a>";
1286 } @all_cols;
1287  
1288 # And for custom columns, do the prettification, but don't include a
1289 # link for sorting unless we're overriding the display of an already
1290 # sortable column. We can't sort non-overridden custom columns (sorting is
1291 # done by SQL, and the custom column values are calculated after we get
1292 # the results from the SQL query, so to support sorting by them we'd
1293 # have to stop getting the database to sort the data and sort it
1294 # ourselves afterwards).
1295 4 ▶ if (exists $args->{custom_columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"custom_columns"}) 4 0 4
1296 4 for my $custom_column_name (
1297 7 map { $_->{name} } @{ $args->{custom_columns} }
1298 ) {
1299 7 ▶ if ( !grep { $_ eq $custom_column_name } @all_cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$_ eq $custom_column_name;} @all_cols) 2 5 7
1300 2 $columns_sort_options{$custom_column_name}
1301 = _prettify_column_name($custom_column_name);
1302 }
1303 }
1304 }
1305  
1306 4 ▶ if (exists $args->{foreign_keys} and exists $args->{foreign_keys}{$order_by_column}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"foreign_keys"} and exists $args->{"foreign_keys"}{$order_by_column}) 0 4 4
Condition33%1/3
exists $args->{"foreign_keys"} and exists $args->{"foreign_keys"}{$order_by_column}
!ll&&!rl&&r
400
MC/DC0%0/2
exists $args->{"foreign_keys"} and exists $args->{"foreign_keys"}{$order_by_column}
exists $args->{"foreign_keys"} exists $args->{"foreign_keys"}{$order_by_column}
Truth table33%1/3
A and B
A= exists $args->{"foreign_keys"}B= exists $args->{"foreign_keys"}{$order_by_column}
ABresult
0X0
100
111
1307 0 my $fk = $args->{foreign_keys}{$order_by_column};
1308 0 $order_by_column = $fk->{label_column};
1309 0 $order_by_table = $fk->{table};
1310 }
1311  
1312 4 $query .= " ORDER BY "
1313 . $dbh->quote_identifier($order_by_table) . "."
1314 . $dbh->quote_identifier($order_by_column)
1315 . " $order_by_direction ";
1316 }
1317  
1318 14 ▶ if ($args->{paginate} && $args->{paginate} =~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"paginate"} and $args->{"paginate"} =~ /^\d+$/) 0 14 14
Condition33%1/3
$args->{"paginate"} and $args->{"paginate"} =~ /^\d+$/
!ll&&!rl&&r
1400
MC/DC0%0/2
$args->{"paginate"} and $args->{"paginate"} =~ /^\d+$/
$args->{"paginate"} $args->{"paginate"} =~ /^\d+$/
Truth table33%1/3
A and B
A= $args->{"paginate"}B= $args->{"paginate"} =~ /^\d+$/
ABresult
0X0
100
111
1319 0 my $page_size = $args->{paginate};
1320  
1321 0 my $qt = uri_escape($q);
1322 0 my $sf = uri_escape($searchfield);
1323 0 ▶ my $st = uri_escape(params->{searchtype} || $default_searchtype);
Condition0%0/3
params()->{'searchtype'} || $default_searchtype
l!l&&r!l&&!r
000
MC/DC0%0/2
params()->{'searchtype'} || $default_searchtype
params()->{'searchtype'} $default_searchtype
Truth table0%0/3
A || B
A= params()->{'searchtype'}B= $default_searchtype
ABresult
1X1
011
000
1324 0 ▶ my $o = uri_escape(params->{'o'} || "");
Condition0%0/2
params()->{'o'} || ''
l!l
00
MC/DC0%0/1
params()->{'o'} || ''
params()->{'o'}
Truth table0%0/2
A
A= params()->{'o'}
Aresult
11
00
1325 0 ▶ my $d = uri_escape(params->{'d'} || "");
Condition0%0/2
params()->{'d'} || ''
l!l
00
MC/DC0%0/1
params()->{'d'} || ''
params()->{'d'}
Truth table0%0/2
A
A= params()->{'d'}
Aresult
11
00
1326 0 ▶ my $page = uri_escape(params->{'p'} || 0);
Condition0%0/2
params()->{'p'} || 0
l!l
00
MC/DC0%0/1
params()->{'p'} || 0
params()->{'p'}
Truth table0%0/2
A
A= params()->{'p'}
Aresult
11
00
1327 0 ▶ $page = 0 unless $page =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $page =~ /^\d+$/ 0 0 0
1328  
1329 0 my $offset = $page_size * $page;
1330 0 my $limit = $page_size;
1331  
1332 my $url = _external_url($args->{dancer_prefix}, $args->{prefix})
1333 0 . "?o=$o&d=$d&q=$qt&searchfield=$sf&searchtype=$st";
1334 0 $html .= "<p>";
1335 0 $html .= "<table class=\"$paginate_table_class\"><tr>";
1336  
1337 0 ▶ if ($page > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($page > 0) { } 0 0 0
1338 0 $html
1339 .= sprintf(
1340 "<td><a href=\"%s&p=%d\">&larr;&nbsp;prev.&nbsp;page</a></td>",
1341 $url, $page - 1)
1342 } else {
1343 0 $html .= "<td>&larr;&nbsp;prev.&nbsp;page&nbsp</td>";
1344 }
1345 0 $html .= sprintf(
1346 "<td>Showing page %d (records %d to %d)",
1347 $page + 1,
1348 $offset + 1,
1349 $offset + 1 + $limit
1350 );
1351 0 $html .= "</td>";
1352 0 $html .= sprintf("<td><a href=\"%s&p=%d\">next&nbsp;page&nbsp;&rarr;</a>",
1353 $url, $page + 1);
1354 0 $html .= "</td></tr></table>";
1355  
1356 0 $query .= " LIMIT $limit OFFSET $offset ";
1357 }
1358  
1359 14 debug("Running query: $query");
1360 14 my $sth = $dbh->prepare($query);
1361 14 ▶ $sth->execute(@binds)
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@binds) or die "Failed to query for records in $table_name - " . $dbh->errstr 0 14 14
1362 or die "Failed to query for records in $table_name - "
1363 . $dbh->errstr;
1364  
1365 14 ▶ if ($args->{downloadable} && params->{format}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"downloadable"} and params()->{"format"}) 0 14 14
Condition33%1/3
$args->{"downloadable"} and params()->{"format"}
!ll&&!rl&&r
1400
MC/DC0%0/2
$args->{"downloadable"} and params()->{"format"}
$args->{"downloadable"} params()->{"format"}
Truth table33%1/3
A and B
A= $args->{"downloadable"}B= params()->{"format"}
ABresult
0X0
100
111
1366  
1367 ##Return results as a downloaded file, instead of generating the HTML table.
1368 0 return _return_downloadable_query($args, $sth, params->{format});
1369 }
1370  
1371 14 my @custom_callbacks = ();
1372 14 ▶ for my $custom_col_spec (@{ $args->{custom_columns} || [] } ) {
Branch: 1 branch
BranchTrueFalseTotal
$args->{"custom_columns"} or [] 3 11 14
1373 push @custom_callbacks, {
1374 column=>$custom_col_spec->{name},
1375 11 ▶ transform=> ($custom_col_spec->{transform} or sub { return shift;}),
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$custom_col_spec->{'transform'} || sub { return shift(); }
l!l&&r!l&&!r
1100
MC/DC0%0/2
$custom_col_spec->{'transform'} || sub { return shift(); }
$custom_col_spec->{'transform'} sub { return shift(); }
Truth table33%1/3
A || B
A= $custom_col_spec->{'transform'}B= sub { return shift(); }
ABresult
1X1
011
000
1376 };
1377 }
1378  
1379  
1380 my $table = HTML::Table::FromDatabase->new(
1381 -sth => $sth,
1382 -border => 1,
1383 -callbacks => [
1384 {
1385 column => 'actions',
1386 transform => sub {
1387 16 ▶ my $id = shift;
Subroutine __ANON__: called CC=5 SCAR=19.3
1388 16 my $action_links;
1389 16 ▶ if ($args->{editable} && _has_permission('edit', $args)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"editable"} and _has_permission("edit", $args)) 16 0 16
Condition33%1/3
$args->{"editable"} and _has_permission("edit", $args)
!ll&&!rl&&r
0016
MC/DC0%0/2
$args->{"editable"} and _has_permission("edit", $args)
$args->{"editable"} _has_permission("edit", $args)
Truth table33%1/3
A and B
A= $args->{"editable"}B= _has_permission("edit", $args)
ABresult
0X0
100
111
1390 my $edit_url
1391 = _external_url(
1392 $args->{dancer_prefix}, $args->{prefix},
1393 16 "/edit/$id"
1394 );
1395 16 $action_links
1396 .= qq[<a href="$edit_url" class="edit_link">Edit</a>];
1397 16 ▶ if ($args->{deletable} && _has_permission('edit', $args)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"deletable"} and _has_permission("edit", $args)) 0 16 16
Condition33%1/3
$args->{"deletable"} and _has_permission("edit", $args)
!ll&&!rl&&r
1600
MC/DC0%0/2
$args->{"deletable"} and _has_permission("edit", $args)
$args->{"deletable"} _has_permission("edit", $args)
Truth table33%1/3
A and B
A= $args->{"deletable"}B= _has_permission("edit", $args)
ABresult
0X0
100
111
1398 my $del_url =_external_url(
1399 $args->{dancer_prefix}, $args->{prefix},
1400 0 "/delete/$id"
1401 );
1402 0 $action_links
1403 .= qq[ / <a href="$del_url" class="delete_link"]
1404 . qq[ onclick="delrec('$id'); return false;">]
1405 . qq[Delete</a>];
1406 }
1407 }
1408 16 return $action_links;
1409 },
1410 },
1411 14 @custom_callbacks,
1412 ],
1413 -rename_headers => \%columns_sort_options,
1414 -html => 'escape',
1415 -class => $table_class,
1416 );
1417  
1418 # apply custom columns' column_classes as specified. Can this be done via HTML::Table::FromDatabase->new() above?
1419 14 my @all_column_names = ( (map { $_->{COLUMN_NAME} } @$columns), (map { $_->{name} } @{$args->{custom_columns}}) );
1420 14 ▶ for my $custom_col_spec (@{ $args->{custom_columns} || [] } ) {
Branch: 1 branch
BranchTrueFalseTotal
$args->{"custom_columns"} or [] 0 14 14
1421 11 ▶ if (my $column_class = $custom_col_spec->{column_class}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $column_class = $custom_col_spec->{"column_class"}) 11 0 11
1422 11 ▶ my $first_index = first_index { $_ eq $custom_col_spec->{name} } uniq @all_column_names;
Subroutine __ANON__: called CC=1 SCAR=0.0
1423 11 ▶ die "Cannot find index of column '$custom_col_spec->{name}'" if ($first_index == -1);
Branch: 1 branch
BranchTrueFalseTotal
if $first_index == -1 0 11 11
1424 11 $table->setColClass( 1 + $first_index, $column_class );
1425 }
1426 }
1427  
1428 14 ▶ $html .= $table->getTable || '';
Condition100%2/2
$table->getTable || ''
l!l
131
MC/DC100%1/1
$table->getTable || ''
$table->getTable
Truth table100%2/2
A
A= $table->getTable
Aresult
11
00
1429  
1430 14 ▶ if ($args->{addable} && _has_permission('edit', $args)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"addable"} and _has_permission("edit", $args)) 1 13 14
Condition66%2/3
$args->{"addable"} and _has_permission("edit", $args)
!ll&&!rl&&r
1301
MC/DC50%1/2
$args->{"addable"} and _has_permission("edit", $args)
$args->{"addable"} _has_permission("edit", $args)
Truth table66%2/3
A and B
A= $args->{"addable"}B= _has_permission("edit", $args)
ABresult
0X0
100
111
1431 $html .= sprintf '<a href="%s">Add a new %s</a></p>',
1432 _external_url($args->{dancer_prefix}, $args->{prefix}, '/add'),
1433 1 $args->{record_title};
1434  
1435 # Append a little Javascript which asks for confirmation that they'd
1436 # like to delete the record, then makes a POST request via a hidden
1437 # form. This could be made AJAXy in future.
1438 my $del_action = _external_url(
1439 1 $args->{dancer_prefix}, $args->{prefix}, '/delete'
1440 );
1441 1 $html .= <<DELETEJS;
1442 <form name="deleteform" method="post" action="$del_action">
1443 <input name="record_id" type="hidden">
1444 </form>
1445 <script language="Javascript">
1446 function delrec(record_id) {
1447 if (confirm('Confirm you wish to delete this record?')) {
1448 document.deleteform.rowid.value = record_id;
1449 document.deleteform.submit();
1450 }
1451 }
1452 </script>
1453  
1454 DELETEJS
1455 }
1456  
1457 14 return _apply_template($html, $args->{'template'}, $args->{'record_title'});
1458 }
1459  
1460 sub _apply_template {
1461 19 ▶ my ($html, $template, $title) = @_;
Subroutine _apply_template: called CC=2 SCAR=7.6
1462  
1463 19 ▶ if ($template) {
Branch: 1 branch
BranchTrueFalseTotal
if ($template) { } 0 19 19
1464 0 return template $template, { simple_crud => $html, record_title => $title };
1465 } else {
1466 19 return engine('template')->apply_layout($html);
1467 }
1468 }
1469  
1470 sub _return_downloadable_query {
1471 0 ▶ my ($args, $sth, $format) = @_;
Subroutine _return_downloadable_query: not called CC=11 SCAR=48.8
1472  
1473 0 my $output;
1474  
1475 ## Generate an informative filename
1476 0 my $filename = $args->{db_table};
1477 0 ▶ if (params->{'o'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (params()->{"o"}) 0 0 0
1478 0 my $order = params->{'o'};
1479 0 $order =~ s/[^\w\.\-]+/_/g;
1480 0 $filename .= "__sorted_by_" . $order;
1481 }
1482 0 my $q = _defined_or_empty(params->{'q'});
1483 0 ▶ if (length($q)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $q) 0 0 0
1484 0 my $query = $q;
1485 0 $query =~ s/[^\w\.\-]+/_/g;
1486 0 $filename .= "__query_" . $query;
1487 }
1488 0 ▶ if (params->{'p'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (params()->{"p"}) 0 0 0
1489 0 my $page = params->{'p'};
1490 0 $page =~ s/[^0-9]+/_/g;
1491 0 $filename .= "__page_" . $page;
1492 }
1493  
1494 ## Generate data in the requested format
1495 0 ▶ if ($format eq "tabular") {
Branch: 4 branches
BranchTrueFalseTotal
if ($format eq 'tabular') { } 0 0 0
elsif ($format eq 'csv') { } 0 0 0
elsif ($format eq 'json') { } 0 0 0
elsif ($format eq 'xml') { } 0 0 0
1496 0 header('Content-Type' => 'text/tab-separated-values');
1497 0 header('Content-Disposition' =>
1498 "attachment; filename=\"$filename.txt\"");
1499 0 my $aref = $sth->{NAME};
1500 0 $output = join("\t", @$aref) . "\r\n";
1501 0 ▶ while ($aref = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($aref = $sth->fetchrow_arrayref) 0 0 0
1502 0 $output .= join("\t", @{$aref}) . "\r\n";
1503 }
1504 } elsif ($format eq "csv") {
1505 0 eval { require Text::CSV };
1506 return
1507 0 ▶ "Error: required module Text::CSV not installed. Can't generate CSV file."
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1508 if $@;
1509  
1510 0 header('Content-Type' => 'text/comma-separated-values');
1511 0 header('Content-Disposition' =>
1512 "attachment; filename=\"$filename.csv\"");
1513  
1514 0 my $csv = Text::CSV->new();
1515 0 my $aref = $sth->{NAME};
1516 0 $csv->combine(@{$aref});
1517 0 $output = $csv->string() . "\r\n";
1518 0 ▶ while ($aref = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($aref = $sth->fetchrow_arrayref) 0 0 0
1519 0 $csv->combine(@{$aref});
1520 0 $output .= $csv->string() . "\r\n";
1521 }
1522 } elsif ($format eq "json") {
1523 0 header('Content-Type' => 'text/json');
1524 0 header('Content-Disposition' =>
1525 "attachment; filename=\"$filename.json\"");
1526 0 $output = to_json($sth->fetchall_arrayref({}));
1527 } elsif ($format eq "xml") {
1528 0 header('Content-Type' => 'text/xml');
1529 0 header('Content-Disposition' =>
1530 "attachment; filename=\"$filename.xml\"");
1531 0 $output = to_xml($sth->fetchall_arrayref({}));
1532 } else {
1533 0 $output = "Error: unknown format $format";
1534 }
1535  
1536 0 return $output;
1537 }
1538  
1539 # Given a table name, return an arrayref of hashrefs describing each column in
1540 # the table.
1541 # Expect to see the following keys:
1542 # COLUMN_NAME
1543 # COLUMN_SIZE
1544 # NULLABLE
1545 # DATETIME ?
1546 # TYPE_NAME (e.g. INT, VARCHAR, ENUM)
1547 # MySQL-specific stuff includes:
1548 # mysql_type_name (e.g. "enum('One', 'Two', 'Three')"
1549 # mysql_is_pri_key
1550 # mysql_values (for an enum, ["One", "Two", "Three"]
1551 sub _find_columns {
1552 19 ▶ my ($dbh, $table_name) = @_;
Subroutine _find_columns: called CC=4 SCAR=14.0
1553 19 ▶ my $sth = $dbh->column_info(undef, undef, $table_name, undef)
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $dbh->column_info(undef, undef, $table_name, undef) or die "Failed to get column info for $table_name - " . $dbh->errstr 0 19 19
1554 or die "Failed to get column info for $table_name - " . $dbh->errstr;
1555 19 my @columns;
1556 19 ▶ while (my $col = $sth->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $col = $sth->fetchrow_hashref) 57 19 76
1557  
1558 # Push a copy of the hashref, as I think DBI re-uses them
1559 57 push @columns, {%$col};
1560 }
1561  
1562 19 ▶ die "no columns for table [$table_name]--are you sure this table exists in the database [$dbh->{Driver}->{Name}:$dbh->{Name}]?" unless @columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @columns 0 19 19
1563  
1564 # Return the columns, sorted by their position in the table:
1565 19 return [sort { $a->{ORDINAL_POSITION} <=> $b->{ORDINAL_POSITION} }
1566 @columns];
1567 }
1568  
1569 # Given parts of an URL, assemble them together, prepending the current prefix
1570 # setting if needed, and taking care to get slashes right.
1571 # e.g. for the following example:
1572 # prefix '/foo';
1573 # simple_crud( prefix => '/bar', ....);
1574 # calling: _construct_url($args{prefix}, '/baz')
1575 # would return: /foo/bar/baz
1576 sub _construct_url {
1577 54 ▶ my @url_parts = @_;
Subroutine _construct_url: called CC=1 SCAR=0.0
1578  
1579 # Just concatenate all parts together, then deal with multiple slashes.
1580 # This could be problematic if any URL was ever supposed to contain multiple
1581 # slashes, but that shouldn't be an issue here.
1582 54 my $url = '/' . join '/', @url_parts;
1583 54 $url =~ s{/{2,}}{/}g;
1584 54 return $url;
1585 }
1586  
1587 sub _external_url {
1588 37 ▶ if ( plugin_setting()->{use_old_url_scheme} ) {
Subroutine _external_url: called CC=2 SCAR=8.1
Branch: 1 branch
BranchTrueFalseTotal
if (plugin_setting()->{'use_old_url_scheme'}) { } 0 37 37
1589 0 return _construct_url(@_);
1590 }
1591 else {
1592 37 return uri_for(_construct_url(@_));
1593 }
1594 }
1595  
1596 # Given a mode ("view" or "edit", a handler coderef, and an args coderef, works
1597 # out if we need to wrap the handler coderef via
1598 # Dancer::Plugin::Auth::Extensible to ensure authorisation, and if so, does so.
1599 sub _ensure_auth {
1600 17 ▶ my ($mode, $handler, $args) = @_;
Subroutine _ensure_auth: called CC=8 SCAR=33.9
1601
1602 17 ▶ my $auth_settings = $args->{auth}{$mode} || $args->{auth} || {};
Condition40%2/5
$args->{'auth'}{$mode} || $args->{'auth'} || {}
l!l
170
$args->{"auth"}{$mode} or $args->{"auth"}
l!l&&r!l&&!r
0170
MC/DC0%0/2
$args->{'auth'}{$mode} || $args->{'auth'} || {}
$args->{"auth"}{$mode} $args->{"auth"}
Truth table33%1/3
A or B
A= $args->{"auth"}{$mode}B= $args->{"auth"}
ABresult
1X1
011
000
1603  
1604 17 ▶ if (keys %$auth_settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$auth_settings) { } 0 17 17
1605 0 ▶ Dancer::ModuleLoader->load('Dancer::Plugin::Auth::Extensible')
Branch: 1 branch
BranchTrueFalseTotal
"Dancer::ModuleLoader"->load("Dancer::Plugin::Auth::Extensible") or die "Can't use auth settings without Dancer::Plugin::Auth::Extensible!" 0 0 0
1606 or die "Can't use auth settings without"
1607 . " Dancer::Plugin::Auth::Extensible!";
1608 } else {
1609 # I think this can just be 'return;' given the way it is
1610 # used currently, but the other branch returns a $handler,
1611 # so this is more consistent
1612 17 return $handler;
1613 }
1614  
1615 0 ▶ if ($auth_settings->{require_login}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth_settings->{'require_login'}) { } 0 0 0
1616 0 return $handler =
1617 Dancer::Plugin::Auth::Extensible::require_login($handler);
1618 } else {
1619 0 for my $keyword (qw(require_role require_any_role require_all_roles)) {
1620 0 ▶ if (my $val = $auth_settings->{$keyword}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $val = $auth_settings->{$keyword}) 0 0 0
1621 0 return $handler = Dancer::Plugin::Auth::Extensible->can($keyword)->(
1622 $val, $handler
1623 );
1624 }
1625 }
1626 }
1627 }
1628  
1629 # Given an action (view/edit) and an args coderef, returns whether the user has
1630 # permission to perform that action (e.g. if require_login is set, checks the
1631 # user is logged in; if require_role is set, checks they have that role, etc)
1632 sub _has_permission {
1633 17 ▶ my ($mode, $args) = @_;
Subroutine _has_permission: called CC=8 SCAR=35.0
1634
1635 17 ▶ my $auth_settings = $args->{auth}{$mode} || $args->{auth} || {};
Condition40%2/5
$args->{'auth'}{$mode} || $args->{'auth'} || {}
l!l
170
$args->{"auth"}{$mode} or $args->{"auth"}
l!l&&r!l&&!r
0170
MC/DC0%0/2
$args->{'auth'}{$mode} || $args->{'auth'} || {}
$args->{"auth"}{$mode} $args->{"auth"}
Truth table33%1/3
A or B
A= $args->{"auth"}{$mode}B= $args->{"auth"}
ABresult
1X1
011
000
1636 17 ▶ if (keys %$auth_settings) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$auth_settings) { } 0 17 17
1637 0 ▶ Dancer::ModuleLoader->load('Dancer::Plugin::Auth::Extensible')
Branch: 1 branch
BranchTrueFalseTotal
"Dancer::ModuleLoader"->load("Dancer::Plugin::Auth::Extensible") or die "Can't use auth settings without Dancer::Plugin::Auth::Extensible!" 0 0 0
1638 or die "Can't use auth settings without"
1639 . " Dancer::Plugin::Auth::Extensible!";
1640 } else {
1641 # If no auth settings provided, they can do what they like
1642 17 return 1;
1643 }
1644  
1645 0 ▶ if ($auth_settings->{require_login}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth_settings->{"require_login"}) 0 0 0
1646 0 ▶ return Dancer::Plugin::Auth::Extensible::logged_in_user() ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
Dancer::Plugin::Auth::Extensible::logged_in_user() ? : 0 0 0
1647 }
1648  
1649 0 ▶ if (my $need_role = $auth_settings->{require_role}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $need_role = $auth_settings->{"require_role"}) 0 0 0
1650 0 return Dancer::Plugin::Auth::Extensible::user_has_role($need_role);
1651 }
1652  
1653 # TODO: handle require_any_role / require_all_roles here
1654 0 warn "TODO: handle require_any_role / requires_all_roles";
1655 0 return 0;
1656 }
1657  
1658 sub _defined_or_empty {
1659 14 ▶ my $v = shift;
Subroutine _defined_or_empty: called CC=2 SCAR=6.9
1660 14 ▶ return defined($v) ? $v : "";
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 4 10 14
1661 }
1662  
1663 # where_filter "if it's a coderef, call it and check it gave us a hashref to
1664 # use, otherwise expect it to be a hashref" logic as we need this in several
1665 # places. Returns a hashref, ready for us to add other stuff to in most cases
1666 # (e.g. usually we'd call this, then add $key_column => ... to it)
1667 sub _get_where_filter_from_args {
1668 21 ▶ my $args = shift;
Subroutine _get_where_filter_from_args: called CC=5 SCAR=29.4
1669 21 ▶ return unless $args->{where_filter};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"where_filter"} 21 0 21
1670  
1671 0 ▶ if (ref $args->{where_filter} eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args->{'where_filter'} eq 'HASH') { } 0 0 0
elsif (ref $args->{'where_filter'} eq 'CODE') { } 0 0 0
1672 0 return $args->{where_filter};
1673 } elsif (ref $args->{where_filter} eq 'CODE') {
1674 0 my $result = $args->{where_filter}->();
1675 0 ▶ if (ref $result eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq 'HASH') { } 0 0 0
1676 0 return $result;
1677 } else {
1678 # TODO: better error reporting, so we know which one caused
1679 # the problem
1680 0 die "where_filter coderef didn't return a hashref!";
1681 }
1682 } else {
1683 0 die "Invalid where_filter";
1684 }
1685 }
1686  
1687 sub _prettify_column_name {
1688 14 ▶ my $name = shift;
Subroutine _prettify_column_name: called CC=2 SCAR=6.9
1689 14 for ($name) {
1690 14 $_ = lc;
1691 14 s{_}{ }g;
1692 14 s{\b(\w)}{\u$1}g;
1693 }
1694 14 return $name;
1695 }
1696  
1697 =back
1698  
1699 =head1 DWIMmery
1700  
1701 This module tries to do what you'd expect it to do, so you can rock up your web
1702 app with as little code and effort as possible, whilst still giving you control
1703 to override its decisions wherever you need to.
1704  
1705 =head2 Field types
1706  
1707 CGI::FormBuilder is excellent at working out what kind of field to use by
1708 itself, but we give it a little help where needed. For instance, if a field
1709 looks like it's supposed to contain a password, we'll have it rendered as a
1710 password entry box, rather than a standard text box.
1711  
1712 If the column in the database is an ENUM, we'll limit the choices available for
1713 this field to the choices defined by the ENUM list. (Unless you've provided a
1714 set of acceptable values for this field using the C<acceptable_values> option to
1715 C<simple_crud>, in which case what you say goes.)
1716  
1717 =head1 Hooks
1718  
1719 Hooks are provided, which can be used in the normal Dancer way, using the
1720 C<hook> keyword.
1721  
1722 =head2 add_edit_row (deprecated, use add_edit_row_pre_save)
1723  
1724 You can use the same code from your add_edit_row hook in an add_edit_row_pre_save
1725 hook. The only modification is that the new hook passes the editable params
1726 as a key of the first argument (called C<params>), rather than as the first
1727 argument itself. So, if your hook had C<my $args = shift;>, it could just
1728 use C<< my $args = shift->{params}; >> and it should work the same way.
1729  
1730 =head2 add_edit_row_pre_save, add_edit_row_post_save
1731  
1732 These fire right before and after a row is added/edited; a hashref is
1733 passed with metadata such as the name of the table (in C<table_name>), the
1734 args from the original route setup (C<args>), the table's key column
1735 (C<key_column>), and the values of the editable params (C<params>).
1736  
1737 In the post-save hook, you are also sent C<success> (the return value of
1738 quick_insert or quick_update) telling you if the save was successful
1739 (which is a little redundant because your post-save hook won't be called unless
1740 the insert or update was successful). You'll also get
1741 C<dbh> giving you the instance of the handle used to save the entity
1742 (so you can access last_insert_id()), and C<verb> (currently either
1743 'create new' or 'update').
1744  
1745 For instance, if you were dealing with a users table, you could use the
1746 pre_save hook to hash the password before storing it - assuming for the sake
1747 of example that you have a C<hash_pw()> function to return a hashed password:
1748  
1749 hook add_edit_row_pre_save => sub {
1750 my $args = shift;
1751 if ($args->{table_name} eq 'user') {
1752 $args->{params}{password} = hash_pw($args->{params}{password});
1753 }
1754 };
1755  
1756 =head2 delete_row_pre_delete, delete_row_post_delete
1757  
1758 These fire right before and after a row is deleted. As with the
1759 add_edit_row_pre_save and add_edit_row_post_save hooks, these are
1760 passed a hashref with metadata such as the name of the table
1761 (in C<table_name>), the args from the original route setup (C<args>),
1762 the table's key column (C<key_column>), and the values of the
1763 editable params (C<params>). As with the post-save hook, delete_row_post_delete hook won't be
1764 called if we weren't able to delete the row.
1765  
1766 You could use these to clean up ancillary data associated with a
1767 database row when it was deleted, for example.
1768  
1769 =head1 AUTHOR
1770  
1771 David Precious, C<< <davidp@preshweb.co.uk> >>
1772  
1773 =head1 ACKNOWLEDGEMENTS
1774  
1775 Alberto Simões (ambs)
1776  
1777 WK
1778  
1779 Johnathan Barber
1780  
1781 saberworks
1782  
1783 jasonjayr
1784  
1785 Paul Johnson (pjcj)
1786  
1787 Rahul Kotamaraju
1788  
1789 Michael J South (msouth)
1790  
1791 Martijn Lievaart
1792  
1793 Josh Rabinowitz
1794  
1795 =head1 BUGS
1796  
1797 Please report any bugs or feature requests to C<bug-dancer-plugin-simplecrud at rt.cpan.org>, or through
1798 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Dancer-Plugin-SimpleCRUD>. I will be notified, and then you'll
1799 automatically be notified of progress on your bug as I make changes.
1800  
1801  
1802 =head1 CONTRIBUTING
1803  
1804 This module is developed on Github:
1805  
1806 http://github.com/bigpresh/Dancer-Plugin-SimpleCRUD
1807  
1808 Bug reports, ideas, suggestions, patches/pull requests all welcome.
1809  
1810 Even just a quick "Hey, this is great, thanks" or "This is no good to me
1811 because..." is greatly appreciated. It's always good to know if people are
1812 using your code, and what they think.
1813  
1814  
1815 =head1 SUPPORT
1816  
1817 You can find documentation for this module with the perldoc command.
1818  
1819 perldoc Dancer::Plugin::SimpleCRUD
1820  
1821 You may find help with this module on the main Dancer IRC channel or mailing
1822 list - see http://www.perldancer.org/
1823  
1824  
1825 You can also look for information at:
1826  
1827 =over 4
1828  
1829 =item * RT: CPAN's request tracker
1830  
1831 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Dancer-Plugin-SimpleCRUD>
1832  
1833 =item * AnnoCPAN: Annotated CPAN documentation
1834  
1835 L<http://annocpan.org/dist/Dancer-Plugin-SimpleCRUD>
1836  
1837 =item * CPAN Ratings
1838  
1839 L<http://cpanratings.perl.org/d/Dancer-Plugin-SimpleCRUD>
1840  
1841 =item * Search CPAN
1842  
1843 L<http://search.cpan.org/dist/Dancer-Plugin-SimpleCRUD/>
1844  
1845 =back
1846  
1847  
1848 =head1 LICENSE AND COPYRIGHT
1849  
1850 Copyright 2010-16 David Precious.
1851  
1852 This program is free software; you can redistribute it and/or modify it
1853 under the terms of either: the GNU General Public License as published
1854 by the Free Software Foundation; or the Artistic License.
1855  
1856 See http://dev.perl.org/licenses/ for more information.
1857  
1858  
1859 =cut
1860  
1861 3 1; # End of Dancer::Plugin::SimpleCRUD
↑ Summary