blib/lib/DBIx/VersionedSubs.pm

filter: Statementstmt 78.9% 90 / 114 Branchbran 55.2% 21 / 38 Conditioncond 42.8% 3 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 77.2% 17 / 22 Podpod 100% 14 / 14 totaltotal 72.8% 145 / 199 CC 24 SCAR 17.1
CC
24
Cov
72%
update_code
13.7
redefine_sub
12.0
startup
6.0
CRAP 5.5
« eg/lib/My/App.pm ↑ Summary blib/lib/DBIx/VersionedSubs/AutoLoad.pm »
1 #!/usr/bin/perl -w
2 package DBIx::VersionedSubs;
3 16 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 16 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 16 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 16 ▶use base 'Class::Data::Inheritable';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =head1 NAME
9  
10 DBIx::VersionedSubs - all your code are belong into the DB
11  
12 =head1 SYNOPSIS
13  
14 package My::App;
15 use strict;
16 use base 'DBIx::VersionedSubs';
17  
18 package main;
19 use strict;
20  
21 My::App->startup($dsn);
22 while (my $request = Some::Server->get_request) {
23 My::App->update_code; # update code from the DB
24 My::App->handle_request($request);
25 }
26  
27 And C<handle_request> might look like the following in the DB:
28  
29 sub handle_request {
30 my ($request) = @_;
31 my %args = split /[=;]/, $request;
32 my $method = delete $args{method};
33 no strict 'refs';
34 &{$method}( %args );
35 }
36  
37 See C<eg/> for a sample HTTP implementation of a framework based
38 on this concept.
39  
40 =head1 ABSTRACT
41  
42 This module implements a minimal driver to load
43 your application code from a database into a namespace
44 and to update that code whenever the database changes.
45  
46 =head1 TABLES USED
47  
48 This module uses two tables in the database, C<code_live> and C<code_history>.
49 The C<code_live> table stores the current version of the code and is used to
50 initialize the namespace. The C<code_history> table stores all modifications
51 to the C<code_live> table, that is, insertions, deletions and modifications
52 of rows in it. It is used to determine if the code has changed and what
53 changes to apply to the namespace to bring it up to par with the
54 database version.
55  
56 The two tables are presumed to have a layout like the following:
57  
58 create table code_live (
59 name varchar(256) not null primary key,
60 code varchar(65536) not null
61 );
62  
63 create table code_history (
64 version integer primary key not null,
65 timestamp varchar(15) not null,
66 name varchar(256) not null,
67 action varchar(1) not null, -- IUD, redundant with old_* and new_*
68 old_code varchar(65536) not null,
69 new_code varchar(65536) not null
70 );
71  
72 Additional columns are ignored by this code. It is likely prudent
73 to create an index on C<code_history.version> as that will be used
74 for (descending) ordering of rows.
75  
76 =cut
77  
78 __PACKAGE__->mk_classdata($_)
79 16 for qw(dbh code_version code_live code_history code_source verbose);
80  
81 16 ▶use vars qw'%default_values $VERSION';
Subroutine BEGIN: called CC=1 SCAR=0.0
82  
83 16 $VERSION = '0.09';
84  
85 16 %default_values = (
86 dbh => undef,
87 code_source => {},
88 code_live => 'code_live',
89 code_history => 'code_history',
90 code_version => 0,
91 verbose => 0,
92 );
93  
94 =head1 CLASS METHODS
95  
96 =head2 C<< Package->setup >>
97  
98 Sets up the class data defaults:
99  
100 code_source => {}
101 code_live => 'code_live',
102 code_history => 'code_history',
103 code_version => 0,
104 verbose => 0,
105  
106 C<code_source> contains the Perl source code for all loaded functions.
107 C<code_live> and C<code_history> are the names of the two tables
108 in which the live code and the history of changes to the live code
109 are stored. C<code_version> is the version of the code when it
110 was last loaded from the database.
111  
112 The C<verbose> setting determines if progress gets output to
113 C<STDERR>.
114 Likely, this package variable will get dropped in favour of
115 a method to output (or discard) the progress.
116  
117 =cut
118  
119 15 ▶sub setup {
Subroutine setup: called CC=4 SCAR=13.9
Pod documented
120 15 my $package = shift;
121 15 ▶ warn "Setting up $package defaults"
Branch: 1 branch
BranchTrueFalseTotal
if $package->verbose 0 15 15
122 if $package->verbose;
123 15 my %defaults = (%default_values,@_);
124 15 for my $def (keys %defaults) {
125 91 ▶ if (! defined $package->$def) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $package->$def) 90 1 91
126 90 $package->$def($defaults{$def});
127 };
128 }
129 15 $package;
130 };
131  
132 =head2 C<< Package->connect DSN,User,Pass,Options >>
133  
134 Connects to the database with the credentials given.
135  
136 If called in void context, stores the DBI handle in the
137 C<dbh> accessor, otherwise returns the DBI handle.
138  
139 If you already have an existing database handle, just
140 set the C<dbh> accessor with it instead.
141  
142 =cut
143  
144 12 ▶sub connect {
Subroutine connect: called CC=3 SCAR=14.2
Pod documented
145 12 my ($package,$dsn,$user,$pass,$options) = @_;
146 12 ▶ if (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 0 12 12
147 0 ▶ DBI->connect($dsn,$user,$pass,$options)
Branch: 1 branch
BranchTrueFalseTotal
"DBI"->connect($dsn, $user, $pass, $options) or die "Couldn't connect to $dsn/$user/$pass/$options" 0 0 0
148 or die "Couldn't connect to $dsn/$user/$pass/$options";
149 } else {
150 12 $package->dbh(DBI->connect($dsn,$user,$pass,$options));
151 }
152 };
153  
154 =head2 C<< Package->create_sub NAME, CODE >>
155  
156 Creates a subroutine in the Package namespace.
157  
158 If you want a code block to be run automatically
159 when loaded from the database, you can name it C<BEGIN>.
160 The loader code basically uses
161  
162 package $package;
163 *{"$package\::$name"} = eval "sub { $code }"
164  
165 so you cannot stuff attributes and other whatnot
166 into the name of your subroutine, not that you should.
167  
168 One name is special cased - C<BEGIN> will be immediately
169 executed instead of installed. This is most likely what you expect.
170 As the code elements are loaded by C<init_code> in alphabetical
171 order on the name, your C<Aardvark> and C<AUTOLOAD> subroutines
172 will still be loaded before your C<BEGIN> block runs.
173  
174 The C<BEGIN> block will be called with the package name in C<@_>.
175  
176 Also, names like C<main::foo> or C<Other::Package::foo> are possible
177 but get stuffed below C<$package>. The practice doesn't get saner there.
178  
179 =cut
180  
181 18 ▶sub create_sub {
Subroutine create_sub: called CC=4 SCAR=13.9
Pod documented
182 18 my ($package,$name,$code) = @_;
183 18 ▶ my $package_name = ref $package || $package;
Condition33%1/3
ref $package || $package
l!l&&r!l&&!r
0180
MC/DC0%0/2
ref $package || $package
ref $package $package
Truth table33%1/3
A || B
A= ref $packageB= $package
ABresult
1X1
011
000
184  
185 18 my $ref = $package->eval_sub($package_name,$name,$code);
186 18 ▶ if ($ref) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref) 14 4 18
187 14 ▶ if ($name eq 'BEGIN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq 'BEGIN') { } 3 11 14
188 3 $ref->($package);
189 return undef
190 3 } else {
191 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
192 16 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
193 11 *{"$package\::$name"} = $ref;
194 11 $package->code_source->{$name} = $code;
195 #warn "Set $package\::$name to " . $package->code_source->{$name};
196 11 return $ref
197 };
198 };
199 }
200  
201 =head2 C<< Package->eval_sub PACKAGE, NAME, CODE >>
202  
203 Helper method to take a piece of code and to return
204 a code reference with the correct file/line information.
205  
206 Raises a warning if code doesn't compile. Returns
207 the reference to the code or C<undef> if there was an error.
208  
209 =cut
210  
211 20 ▶sub eval_sub {
Subroutine eval_sub: called CC=2 SCAR=6.9
Pod documented
212 20 my ($self,$package,$name,$code) = @_;
213 20 my $perl_code = <<CODE;
214 package $package;
215 #line $package/$name#1
216 sub {$code}
217 CODE
218  
219 20 ▶ my $ref = eval $perl_code;
Subroutine __ANON__: called CC=1 SCAR=0.0
220 20 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) { } 4 16 20
221 4 warn $perl_code . "\n$package\::$name>> $err";
222 return undef
223 4 } else {
224 16 return $ref
225 };
226 };
227  
228 =head2 C<< Package->destroy_sub $name >>
229  
230 Destroy the subroutine named C<$name>. For the default
231 implementation, this replaces the subroutine with a
232 dummy subroutine that C<croak>s.
233  
234 =cut
235  
236 0 ▶sub destroy_sub {
Subroutine destroy_sub: not called CC=1 SCAR=6.9
Pod documented
237 0 my ($package,$name) = @_;
238 0 $package->create_sub($name,<<ERROR_SUB);
239 use Carp qw(croak);
240 croak "Undefined subroutine '$name' called"
241 ERROR_SUB
242 0 delete $package->code_source->{$name};
243 };
244  
245 =head2 C<< Package->live_code_version >>
246  
247 Returns the version number of the live code
248 in the database.
249  
250 This is done with a C< SELECT max(version) FROM ... > query,
251 so this might scale badly on MySQL which (I hear) is bad
252 with queries even against indexed tables. If this becomes
253 a problem, changing the layout to a single-row table which
254 stores the live version number is the best approach.
255  
256 =cut
257  
258 17 ▶sub live_code_version {
Subroutine live_code_version: called CC=2 SCAR=6.9
Pod documented
259 17 my ($package) = @_;
260 17 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL', $package->code_history);
261 SELECT max(version) FROM %s
262 SQL
263 17 $sth->execute();
264 17 my ($result) = $sth->fetchall_arrayref();
265 17 ▶ $result->[0]->[0] || 0
Branch: 1 branch
BranchTrueFalseTotal
$result->[0][0] or 0 6 11 17
266 }
267  
268 =head2 C<< Package->init_code >>
269  
270 Adds / overwrites subroutines/methods in the Package namespace
271 from the database.
272  
273 =cut
274  
275 9 ▶sub init_code {
Subroutine init_code: called CC=2 SCAR=6.9
Pod documented
276 9 my ($package) = @_;
277 9 my $table = $package->code_live;
278 #warn "Loading code for $package from $table";
279 9 my $sql = sprintf <<'SQL', $table;
280 SELECT name,code FROM %s
281 ORDER BY name
282 SQL
283  
284 9 my $sth = $package->dbh->prepare_cached($sql);
285 9 $sth->execute();
286 9 ▶ while (my ($name,$code) = $sth->fetchrow()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sth->fetchrow) 16 9 25
287 16 $package->create_sub($name,$code);
288 }
289  
290 9 $package->code_version($package->live_code_version);
291 };
292  
293 =head2 C<< Package->update_code >>
294  
295 Updates the namespace from the database by loading
296 all changes.
297  
298 Note that if you have/use closures or iterators,
299 these will behave weird if you redefine a subroutine
300 that was previously closed over.
301  
302 =cut
303  
304 1 ▶sub update_code {
Subroutine update_code: called CC=10 SCAR=26.2
Pod documented
305 1 my ($package) = @_;
306 1 ▶ my $version = $package->code_version || 0;
Condition50%1/2
$package->code_version || 0
l!l
01
MC/DC0%0/1
$package->code_version || 0
$package->code_version
Truth table50%1/2
A
A= $package->code_version
Aresult
11
00
307 #warn "Checking against $version";
308 1 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL', $package->code_history);
309 SELECT distinct name,action,new_code,version FROM %s
310 WHERE version > ?
311 ORDER BY version DESC
312 SQL
313  
314 1 $sth->execute($version);
315  
316 1 my %seen;
317  
318 1 ▶ my $current_version = $version || 0;
Condition50%1/2
$version || 0
l!l
01
MC/DC0%0/1
$version || 0
$version
Truth table50%1/2
A
A= $version
Aresult
11
00
319 1 ▶ while (my ($name,$action,$code,$new_version) = $sth->fetchrow()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = $sth->fetchrow) 1 1 2
320 1 ▶ next if $seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ 0 1 1
321
322 1 ▶ warn "Reloading $name"
Branch: 1 branch
BranchTrueFalseTotal
if $package->verbose 0 1 1
323 if $package->verbose;
324 1 ▶ $current_version = $current_version < $new_version
Branch: 1 branch
BranchTrueFalseTotal
$current_version < $new_version ? : 1 0 1
325 ? $new_version
326 : $current_version;
327  
328 1 ▶ if ($action eq 'I') {
Branch: 3 branches
BranchTrueFalseTotal
if ($action eq 'I') { } 0 1 1
elsif ($action eq 'U') { } 1 0 1
elsif ($action eq 'D') { } 0 0 0
329 0 $package->create_sub($name,$code);
330 } elsif ($action eq 'U') {
331 1 $package->create_sub($name,$code);
332 } elsif ($action eq 'D') {
333 0 $package->destroy_sub($name);
334 };
335 }
336 1 $package->code_version($current_version);
337 };
338  
339 =head2 C<< Package->add_code_history Name,Old,New,Action >>
340  
341 Inserts a new row in the code history table.
342  
343 This
344 would be done with triggers on a real database,
345 but my development target includes MySQL 3 and 4.
346  
347 =cut
348  
349 2 ▶sub add_code_history {
Subroutine add_code_history: called CC=1 SCAR=0.0
Pod documented
350 2 my ($package,$name,$old_code,$new_code,$action) = @_;
351 2 my $ts = strftime('%Y%m%d-%H%M%S',gmtime());
352 2 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL',$package->code_history);
353 INSERT INTO %s (name,old_code,new_code,action,timestamp) VALUES (?,?,?,?,?)
354 SQL
355 2 $sth->execute($name,$old_code,$new_code,$action,$ts);
356 }
357  
358 =head2 C<< Package->update_sub name,code >>
359  
360 Updates the code for the subroutine C<Package::$name>
361 with the code given.
362  
363 Note that the update only happens in the database, so the change
364 will only take place on the next roundtrip / code refresh.
365  
366 This cannot override subroutines that don't exist in the database.
367  
368 =cut
369  
370 2 ▶sub update_sub {
Subroutine update_sub: called CC=1 SCAR=0.0
Pod documented
371 2 my ($package,$name,$new_code) = @_;
372 2 $package->add_code_history($name,$package->code_source->{$name},$new_code,'U');
373 2 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL',$package->code_live);
374 UPDATE %s SET code=?
375 WHERE name=?
376 SQL
377 2 $sth->execute($new_code,$name);
378 };
379  
380  
381 =head2 C<< Package->insert_sub name,code >>
382  
383 Inserts the code for the subroutine C<Package::$name>.
384  
385 Note that the insert only happens in the database, so the change
386 will only take place on the next roundtrip / code refresh.
387  
388 This can also be used to override methods / subroutines that
389 are defined elsewhere in the Package:: namespace.
390  
391 =cut
392  
393 0 ▶sub insert_sub {
Subroutine insert_sub: not called CC=1 SCAR=6.9
Pod documented
394 0 my ($package,$name,$new_code) = @_;
395 0 $package->add_code_history($name,'',$new_code,'I');
396 0 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL',$package->code_live);
397 INSERT INTO %s (name,code) VALUES (?,?)
398 SQL
399 0 $sth->execute($name,$new_code);
400 };
401  
402 =head2 C<< Package->redefine_sub name,code >>
403  
404 Inserts or updates the code for the subroutine C<Package::$name>.
405  
406 Note that the change only happens in the database, so the change
407 will only take place on the next roundtrip / code refresh.
408  
409 This can be used to override methods / subroutines that
410 are defined in the database, elsewhere in the Package::
411 namespace or not at all.
412  
413 =cut
414  
415 0 ▶sub redefine_sub {
Subroutine redefine_sub: not called CC=3 SCAR=24.8
Pod documented
416 0 my ($package,$name,$new_code) = @_;
417
418 0 ▶ if (! eval { $package->update_sub($name,$new_code) }) {
Branch: 1 branch
BranchTrueFalseTotal
if (not eval { do { $package->update_sub($name, $new_code) } }) 0 0 0
419 0 ▶ warn "Inserting $name"
Branch: 1 branch
BranchTrueFalseTotal
if $package->verbose 0 0 0
420 if $package->verbose;
421 0 $package->insert_sub($name,$new_code)
422 }
423 };
424  
425 =head2 C<< Package->delete_sub name,code >>
426  
427 Deletes the code for the subroutine C<Package::$name>.
428  
429 Note that the update only happens in the database, so the change
430 will only take place on the next roundtrip / code refresh.
431  
432 If you delete the row of a subroutine that overrides a subroutine
433 declared elsewhere (for example in Perl code), the non-database Perl code
434 will not become
435 visible to the Perl interpreter until the next call to
436 C<< Package->init_code >>,
437 that is, likely until the next process restart. This will lead to very
438 weird behaviour, so don't do that.
439  
440 =cut
441  
442 0 ▶sub delete_sub {
Subroutine delete_sub: not called CC=1 SCAR=6.9
Pod documented
443 0 my ($package,$name,$new_code) = @_;
444 0 $package->add_code_history($name,$package->code_source->{$name},'','D');
445 0 my $sth = $package->dbh->prepare_cached(sprintf <<'SQL',$package->code_live);
446 -- here's a small race condition
447 -- - delete trumps insert/update
448 DELETE FROM %s WHERE name = ?
449 SQL
450 0 $sth->execute($name);
451 };
452  
453 =head2 C<< Package->startup(DBIargs) >>
454  
455 Shorthand method to initialize a package
456 from a database connection.
457  
458 If C<< Package->dbh >> already returns a true
459 value, no new connection is made.
460  
461 This method is equivalent to:
462  
463 if (! Package->dbh) {
464 Package->connect(@_);
465 };
466 Package->setup;
467 Package->init_code;
468  
469 =cut
470  
471 0 ▶sub startup {
Subroutine startup: not called CC=2 SCAR=17.9
Pod documented
472 0 my $package = shift;
473 0 ▶ if (! $package->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($package->dbh) 0 0 0
474 0 $package->connect(@_);
475 };
476 0 $package->setup;
477 0 $package->init_code;
478 }
479  
480 =head1 BEST PRACTICES
481  
482 The most bare-bones hosting package looks like the following (see also
483 C<eg/lib/My/App.pm> in the distribution):
484  
485 package My::App;
486 use strict;
487 use base 'DBIx::VersionedSubs';
488  
489 Global variables are best declared within the C<BEGIN> block. You will find
490 typos or use of undeclared variables reported to C<STDERR> as the
491 subroutines get compiled.
492  
493 =head1 TODO
494  
495 =over 4
496  
497 =item * Implement closures (marked via a bare block)
498  
499 =item * Find a saner way instead of C<< ->setup >> and C<%default_values>
500 for configuring the initial class values while still preventing hashref
501 usage across packages. The "classic" approach of using Class::Data::Inheritable
502 means that there is the risk of sharing the C<code_source> reference across
503 namespaces which is wrong. Maybe the accessor should simply be smart
504 and depend on the namespace it was called with instead of a stock accessor
505  
506 =item * Discuss whether it's sane
507 to store all your code with your data in the database.
508 It works well for L<http://perlmonks.org/> and the
509 Everything Engine.
510  
511 =back
512  
513 =head1 AUTHOR
514  
515 Max Maischein, E<lt>corion@cpan.orgE<gt>
516  
517 =head1 CREDITS
518  
519 Tye McQueen for suggesting the module name
520  
521 =head1 SEE ALSO
522  
523 The Everything Engine, L<http://everydevel.everything2.com/>
524  
525 =head1 LICENSE
526  
527 This module is licensed under the same terms as Perl itself.
528  
529 =head1 ALTERNATIVE NAMES
530  
531 DBIx::Seven::Days, Nothing::Driver, Corion's::Code::From::Outer::Space
532  
533 =cut
534  
535 16 1;
« eg/lib/My/App.pm ↑ Summary blib/lib/DBIx/VersionedSubs/AutoLoad.pm »