blib/lib/DBIx/TNDBO.pm untested

filter: Statementstmt 0.0% 0 / 407 Branchbran 0.0% 0 / 132 Conditioncond 0.0% 0 / 22 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 637 CC 63 SCAR 40.7
CC
63
Cov
0%
import
210.0
_read_schema
132.0
get
72.0
CRAP 58.7
1 package DBIx::TNDBO;
2  
3 $VERSION = 0.02;
4  
5 use strict;
6 use warnings;
7 {
8 use Carp;
9 use Readonly;
10 use DBI;
11 use SQL::Abstract;
12 use Storable;
13 use File::Spec;
14 use Filter::Simple;
15 }
16  
17 $Carp::Internal{ (__PACKAGE__) }++;
18  
19 my ( $Class_Base, $Debug, %Dbh_For, $Schema_Hr, $Schema_Cache_Filename );
20  
21 sub new {
22 my ( $database, $table, $where_hr, $option_hr ) = @_;
23  
24 printf "%s::%s::new(%s)\n", $Class_Base, ucfirst $table,
25 _dumper($where_hr)
26 if $Debug;
27  
28 my $record_hr;
29  
30 my $dbh = _get_dbh( $database, $table );
31  
32 if ($where_hr) {
33  
34 my ( $sql, $param_ar ) = _build_sql( "$database.$table", $where_hr );
35  
36 my $sth = $dbh->prepare($sql);
37  
38 croak $DBI::errstr
39 if $DBI::errstr;
40  
41 $sth->execute( @{$param_ar} );
42  
43 return
44 if !$sth->rows();
45  
46 if ( $sth->rows() > 1 ) {
47 carp 'matched ', $sth->rows(), ' for: ', _dumper($where_hr);
48 return;
49 }
50  
51 $record_hr = $sth->fetchrow_hashref();
52 }
53 else {
54  
55 $record_hr = {};
56 }
57  
58 my %config = (
59 dbh => $Dbh_For{$database},
60 table => "$database.$table",
61 schema => $Schema_Hr->{"$database.$table"},
62 );
63 return DBIx::TNDBO::rec->_new( $record_hr, \%config );
64 }
65  
66 sub list {
67 my ( $database, $table, $where_hr, $option_hr ) = @_;
68  
69 printf "%s::%s::list(%s)\n", $Class_Base, ucfirst $table,
70 _dumper($where_hr)
71 if $Debug;
72  
73 my ( $sql, $param_ar ) = _build_sql( "$database.$table", $where_hr );
74  
75 my $dbh = _get_dbh( $database, $table );
76  
77 my $sth = $dbh->prepare($sql);
78  
79 croak $DBI::errstr
80 if $DBI::errstr;
81  
82 $sth->execute( @{$param_ar} );
83  
84 my %config = (
85 dbh => $Dbh_For{$database},
86 table => "$database.$table",
87 schema => $Schema_Hr->{"$database.$table"},
88 );
89 my @records = map { DBIx::TNDBO::rec->_new( $_, \%config ) }
90 @{ $sth->fetchall_arrayref( {} ) };
91  
92 return @records
93 if wantarray;
94  
95 return \@records;
96 }
97  
98 sub iterator {
99 my ( $database, $table, $where_hr, $option_hr ) = @_;
100  
101 printf "%s::%s::iterator(%s)\n", $Class_Base, ucfirst $table,
102 _dumper($where_hr)
103 if $Debug;
104  
105 my ( $sql, $param_ar ) = _build_sql( "$database.$table", $where_hr );
106  
107 my $dbh = _get_dbh( $database, $table );
108  
109 my $sth = $dbh->prepare($sql);
110  
111 $sth->execute( @{$param_ar} );
112  
113 my %config = (
114 dbh => $Dbh_For{$database},
115 table => "$database.$table",
116 schema => $Schema_Hr->{"$database.$table"},
117 );
118 return DBIx::TNDBO::iter->_new( $sth, \%config );
119 }
120  
121 sub count {
122 my ( $database, $table, $where_hr, $option_hr ) = @_;
123  
124 printf "%s::%s::list(%s)\n", $Class_Base, ucfirst $table,
125 _dumper($where_hr)
126 if $Debug;
127  
128 my ( $sql, $param_ar )
129 = _build_sql( "$database.$table", $where_hr, 'count' );
130  
131 my $dbh = _get_dbh( $database, $table );
132  
133 my $sth = $dbh->prepare($sql);
134  
135 croak $DBI::errstr
136 if $DBI::errstr;
137  
138 $sth->execute( @{$param_ar} );
139  
140 my ($n) = $sth->fetchrow();
141  
142 $sth->finish();
143  
144 return $n;
145 }
146  
147 # Called by Perl on use
148  
149 sub import {
150 my ( $class, @databases ) = @_;
151  
152 SYMBOL:
153 for my $symbol ( keys %:: ) {
154  
155 next SYMBOL
156 if $symbol !~ m{ :: \z}xms;
157  
158 next SYMBOL
159 if !defined $::{$symbol}->{ISA};
160  
161 if ( grep { $_ eq __PACKAGE__ } @{ $::{$symbol}->{ISA} } ) {
162  
163 $Class_Base = substr $symbol, 0, -2;
164 last SYMBOL;
165 }
166 }
167  
168 die 'unable to determine the class using ', __PACKAGE__, ' as its base'
169 if !$Class_Base;
170  
171 {
172 no strict 'refs';
173 *{ __PACKAGE__ . '::credentials' }
174 = *{ $Class_Base . '::credentials' };
175 }
176  
177 croak sprintf 'You must define %s::credentials( $dbname ) ', $Class_Base
178 if !defined &credentials;
179  
180 my $creds_key;
181  
182 NAME:
183 for my $dbname (@databases) {
184  
185 if ( $dbname =~ m{\A : ( \w+ ) \z}xms ) {
186  
187 $creds_key = $1;
188 last NAME;
189 }
190 }
191  
192 if ($creds_key) {
193  
194 @databases = grep { $_ ne ":$creds_key" } @databases;
195  
196 my $cred_hr = credentials();
197  
198 if ( ref $cred_hr->{$creds_key} eq 'ARRAY' ) {
199  
200 push @databases, @{ $cred_hr->{$creds_key} };
201 }
202 elsif ( ref $cred_hr->{$creds_key} eq 'HASH' ) {
203  
204 push @databases, keys %{ $cred_hr->{$creds_key} };
205 }
206 elsif ( $cred_hr->{$creds_key} ) {
207  
208 push @databases, $cred_hr->{$creds_key};
209 }
210 }
211  
212 return
213 if !@databases;
214  
215 if ( !$Schema_Hr ) {
216  
217 $Schema_Hr = _read_schema( \@databases );
218 }
219  
220 my @tables = keys %{ $Schema_Hr };
221  
222 for my $database_table (@tables) {
223  
224 my ( $database, $table ) = split /[.]/, $database_table;
225  
226 for my $method (qw( new list iterator count )) {
227  
228 my $class = sprintf '%s::%s', $Class_Base, ucfirst lc $table;
229 {
230 no strict 'refs';
231  
232 *{"${class}::${method}"} = sub {
233  
234 croak 'call constructors with arrow operator:',
235 sprintf ' %s->%s(...)', $class, $method
236 if $_[0] ne $class;
237  
238 shift @_;
239  
240 return *{$method}->( $database, $table, @_ );
241 };
242 }
243 }
244 }
245  
246 return;
247 }
248  
249 # Internal
250  
251 sub _read_schema {
252 my ($database_ar) = @_;
253  
254 if ( !$Schema_Cache_Filename ) {
255  
256 my $tmpdir = File::Spec->tmpdir();
257  
258 my ($sep) # TODO truly cross platform?
259 = grep { $_ ne 'x' }
260 reverse split //, File::Spec->catdir( 'x', 'x' );
261  
262 my $database_dsv = join '.', @{ $database_ar };
263  
264 $Schema_Cache_Filename = "${tmpdir}${sep}tndbo.$database_dsv.schema";
265 }
266  
267 return Storable::retrieve($Schema_Cache_Filename)
268 if stat $Schema_Cache_Filename;
269  
270 $Schema_Hr = {};
271  
272 for my $database ( @{$database_ar} ) {
273  
274 my $dbh = _get_dbh( $database );
275  
276 my $sth = $dbh->prepare('show tables');
277  
278 croak $DBI::errstr
279 if $DBI::errstr;
280  
281 $sth->execute();
282  
283 croak $DBI::errstr
284 if $DBI::errstr;
285  
286 croak "failed to find any tables in $database"
287 if !$sth || $sth->rows() == 0;
288  
289 while ( my ($table) = $sth->fetchrow() ) {
290  
291 my $sth = $dbh->prepare("desc $table");
292  
293 croak $DBI::errstr
294 if $DBI::errstr;
295  
296 $sth->execute();
297  
298 my @columns;
299  
300 while ( my $desc_hr = $sth->fetchrow_hashref() ) {
301  
302 # eliminate risk of case inconsistency issues
303 # i.e. Type => INT(10) vs. TYPE => Int(10)
304 # Extra => auto_increment vs. Extra => AUTO_INCREMENT
305 for my $name ( keys %{$desc_hr} ) {
306  
307 my $lc_name = lc $name;
308  
309 my $lc_prop
310 = $lc_name eq 'field' ? $desc_hr->{$name}
311 : defined $desc_hr->{$name} ? lc $desc_hr->{$name}
312 : "";
313  
314 $desc_hr->{$lc_name} = $lc_prop;
315  
316 if ( $name ne $lc_name ) {
317  
318 delete $desc_hr->{$name};
319 }
320 }
321  
322 push @columns, $desc_hr;
323 }
324  
325 $Schema_Hr->{"$database.$table"} = \@columns;
326 }
327 }
328  
329 croak sprintf 'failed to read schema from any of (%s)', join ',',
330 @{$database_ar}
331 if !%{$Schema_Hr};
332  
333 Storable::store( $Schema_Hr, $Schema_Cache_Filename );
334  
335 return $Schema_Hr;
336 }
337  
338 sub _build_sql {
339 my ( $from, $where_hr, $operation ) = @_;
340  
341 $operation ||= 'select';
342  
343 my $sql = SQL::Abstract->new();
344  
345 my @fields;
346  
347 if ( $operation eq 'count' ) {
348  
349 $operation = 'select';
350 @fields = qw/ count(*) /;
351 }
352 else {
353  
354 @fields = map { $_->{field} } @{ $Schema_Hr->{$from} };
355 }
356  
357 my ( $stmt, @bind ) = $sql->$operation( $from, \@fields, $where_hr );
358  
359 # TODO error condition handling
360  
361 return ( $stmt, \@bind );
362 }
363  
364 sub _get_dbh {
365 my ($database) = @_;
366  
367 my $dbh;
368  
369 if ( $database && exists $Dbh_For{$database} ) {
370  
371 $dbh = $Dbh_For{$database};
372 }
373  
374 if ( !$dbh || !$dbh->ping() ) {
375  
376 my ( $user, $pass, $driver, $host, $port );
377 {
378 my $cred_hr = credentials($database);
379  
380 my @keys = qw( user pass driver host port );
381  
382 my @creds = grep {$_} @{$cred_hr}{@keys};
383  
384 croak sprintf 'credentials() should include (%s)', join ',', @keys
385 if @creds != @keys;
386  
387 ( $user, $pass, $driver, $host, $port ) = @creds;
388 }
389  
390 my $dsn
391 = sprintf 'DBI:%s:database=%s;host=%s;port=%s',
392 $driver, $database, $host, $port;
393  
394 $dbh = DBI->connect( $dsn, $user, $pass );
395  
396 croak $DBI::errstr
397 if $DBI::errstr;
398  
399 $Dbh_For{$database} = $dbh;
400 }
401  
402 return $dbh;
403 }
404  
405 sub _dumper {
406 my ($ref) = @_;
407  
408 my $text;
409 {
410 require Data::Dumper;
411  
412 no warnings 'once';
413 local $Data::Dumper::Terse = 1;
414 local $Data::Dumper::Indent = 0;
415  
416 $text = Data::Dumper::Dumper($ref);
417 }
418  
419 $text =~ s{ ;? \s* \z}{}xms;
420  
421 return $text;
422 }
423  
424 # Secluded Iterator Package
425 {
426 package DBIx::TNDBO::iter;
427  
428 use strict;
429 use warnings;
430 {
431 use Carp;
432 }
433  
434 my $Index = 0;
435 my ( @Sths, @Configs, @Counts );
436  
437 sub _new {
438 my ( $class, $sth, $config_hr ) = @_;
439  
440 my $self = $Index++;
441 {
442 $Sths[$self] = $sth;
443 $Counts[$self] = $sth->rows();
444 $Configs[$self] = $config_hr;
445 }
446 return bless \$self, $class;
447 }
448  
449 sub has_next {
450 my ($self) = @_;
451 my $id = ${$self};
452 return $Counts[$id] > 0 ? 1 : 0;
453 }
454  
455 sub next {
456 my ($self) = @_;
457  
458 my $id = ${$self};
459  
460 return
461 if !$Counts[$id];
462  
463 $Counts[$id]--;
464  
465 my $record_hr = $Sths[$id]->fetchrow_hashref();
466  
467 return DBIx::TNDBO::rec->_new( $record_hr, $Configs[$id] );
468 }
469  
470 sub DESTROY {
471 my ($self) = @_;
472 my $id = ${$self};
473 if ( $Sths[$id] ) {
474 $Sths[$id]->finish();
475 }
476 return;
477 }
478  
479 1;
480 }
481  
482 # Secluded Record Package
483 {
484 package DBIx::TNDBO::rec;
485  
486 use strict;
487 use warnings;
488 use overload ( '""' => \&stringify );
489 {
490 use Carp;
491 }
492  
493 my $Index = 0;
494 my ( @Records, @Dbhs, @Schemas, @Tables, @Updates, @News );
495  
496 sub _new {
497 my ( $class, $record_hr, $config_hr ) = @_;
498  
499 my $self = $Index++;
500 {
501 $Records[$self] = $record_hr;
502 $Dbhs[$self] = $config_hr->{dbh};
503 $Schemas[$self] = $config_hr->{schema};
504 $Tables[$self] = $config_hr->{table};
505 $News[$self] = ( keys %{ $record_hr } == 0 ? 1 : 0 );
506 }
507 return bless \$self, $class;
508 }
509  
510 sub get {
511 my ($self) = shift @_;
512  
513 if ( @_ == 1 ) {
514  
515 if ( ref $_[0] eq 'HASH' ) {
516  
517 my $value_hr = shift @_;
518  
519 for my $column ( keys %{$value_hr} ) {
520  
521 $value_hr->{$column} = $self->get($column);
522 }
523  
524 return $value_hr;
525 }
526 elsif ( ref $_[0] eq 'ARRAY' ) {
527  
528 my $column_ar = shift @_;
529  
530 for my $i ( 0 .. $#{$column_ar} ) {
531  
532 $column_ar->[$i] = $self->get( $column_ar->[$i] );
533 }
534  
535 return @{$column_ar}
536 if wantarray;
537  
538 return $column_ar;
539 }
540 }
541  
542 my ( $column ) = @_;
543  
544 croak 'get method called without column name'
545 if !$column;
546  
547 my $id = ${$self};
548  
549 my ($desc_hr) = grep { $_->{field} eq $column } @{ $Schemas[$id] };
550  
551 croak "unrecognized column name: $column"
552 if !$desc_hr;
553  
554 my $value = $Records[$id]->{$column};
555 my $is_int = $desc_hr->{type} =~ m{\A int \W }xms;
556  
557 return int $value
558 if defined $value && $is_int;
559  
560 return $value;
561 }
562  
563 sub set {
564 my ($self) = shift @_;
565  
566 if ( @_ == 1 && ref $_[0] eq 'HASH' ) {
567  
568 my $value_rh = shift @_;
569  
570 while ( my ( $column, $value ) = each %{$value_rh} ) {
571  
572 $self->set( $column, $value );
573 }
574  
575 return $value_rh;
576 }
577  
578 my ( $column, $value ) = @_;
579  
580 my $id = ${$self};
581  
582 croak 'get method called without column name'
583 if !$column;
584  
585 my ($desc_hr) = grep { $_->{field} eq $column } @{ $Schemas[$id] };
586  
587 croak "unrecognized column name: $column"
588 if !$desc_hr;
589  
590 $value
591 = defined $value
592 ? $value
593 : $desc_hr->{default};
594  
595 $Updates[$id] ||= {};
596  
597 $Updates[$id]->{$column} = $value;
598  
599 return $value;
600 }
601  
602 sub delete {
603 my ($self) = @_;
604  
605 my $id = ${$self};
606  
607 my $sql = SQL::Abstract->new();
608  
609 my ( $stmt, @bind ) = $sql->delete( $Tables[$id], $Records[$id] );
610  
611 my $sth = $Dbhs[$id]->prepare($stmt);
612  
613 $sth->execute(@bind);
614  
615 croak $DBI::errstr
616 if $DBI::errstr;
617  
618 return 1;
619 }
620  
621 sub commit {
622 my ($self) = @_;
623  
624 my $id = ${$self};
625  
626 return 1
627 if !defined $Updates[$id];
628  
629 my $is_new = $News[$id];
630 my $table = $Tables[$id];
631 my $update_hr = $Updates[$id];
632  
633 my $sql = SQL::Abstract->new();
634  
635 my ( $stmt, @bind, $primary_key_value );
636  
637 if ($is_new) {
638  
639 ( $stmt, @bind ) = $sql->insert( $table, $update_hr );
640 }
641 else {
642  
643 ( $stmt, @bind ) = $sql->update( $table, $update_hr );
644  
645 my ($primary_key_name) = map { $_->{name} }
646 grep { $_->{key} eq 'pri' && $_->{extra} eq 'auto_increment' }
647 @{ $Schemas[$id] };
648  
649 if ($primary_key_name) {
650  
651 $primary_key_value = $Records[$id]->{$primary_key_name};
652 }
653 }
654  
655 my $sth = $Dbhs[$id]->prepare($stmt);
656  
657 $sth->execute(@bind);
658  
659 croak $DBI::errstr
660 if $DBI::errstr;
661  
662 if ( !defined $primary_key_value ) {
663  
664 $primary_key_value = $Dbhs[$id]->{mysql_insertid};
665 }
666  
667 return $primary_key_value;
668 }
669  
670 sub discard {
671 my ( $self ) = @_;
672  
673 my $id = ${$self};
674  
675 return 1
676 if !defined $Updates[$id];
677  
678 $Updates[$id] = {};
679  
680 return 1;
681 }
682  
683 sub stringify {
684 my ($self) = @_;
685  
686 my $id = ${$self};
687  
688 my %record = %{ $Records[$id] };
689  
690 if ( defined $Updates[$id] ) {
691  
692 my @fields = keys %{ $Updates[$id] };
693  
694 @record{@fields} = @{ $Updates[$id] }{@fields};
695 }
696  
697 return sprintf '%s->(%s)', $Tables[$id],
698 DBIx::TNDBO::_dumper( \%record );
699 }
700  
701 sub DESTROY {
702 my ( $self ) = @_;
703 }
704  
705 1;
706 }
707  
708 FILTER_ONLY code_no_comments => sub {
709 my $source = $_;
710  
711 my $eq = ' \s* = \s* ';
712 my $fc = ' \s* = \s* > \s* ';
713 my $dbo = ' _dbo-> ';
714 my $s = ' \s* [\$] ';
715 my $l = ' \s* [\@] ';
716 my $alpha = ' ( [A-Z][A-Za-z0-9]+ ) ';
717 my $paren = ' \(( .+? )\) ';
718  
719 my %xform_for = (
720  
721 # FROM: $word_dbo->get_data();
722 # TO: $word_dbo->get('data');
723 qr{ ( \w+ $dbo get )_( \w+ ) \( \s* \) }xms => sub {
724 return sprintf q{%1$s('%2$s')}, @_;
725 },
726  
727 # FROM: my $data = $word_dbo->get();
728 # TO: my $data = $word_dbo->get('data');
729 qr{ $s( \w+ ) $eq [\$] ( \w+ $dbo get )\( \s* \); }xms => sub {
730 return sprintf q{$%1$s = $%2$s('%1$s');}, @_;
731 },
732  
733 # FROM: data => $word_dbo->get(),
734 # TO: data => $word_dbo->get('data'),
735 qr{ ( \w+ ) $fc [\$] ( \w+ $dbo get )\( \s* \)([,\b\n]) }xms => sub {
736 return sprintf q{%1$s => $%2$s('%1$s')%3$s}, @_;
737 },
738  
739 # FROM: $word_dbo->set( $anagram );
740 # TO: $word_dbo->set( 'anagram', $anagram );
741 qr{ ( \w+ $dbo set )\( \s* [\$] ( \w+ ) \s* \) }xms => sub {
742 return sprintf q{%1$s( '%2$s', $%2$s )}, @_;
743 },
744  
745 # FROM: my $word_dbo = DB();
746 # TO: my $word_dbo = DB::Word->new();
747 qr{ my $s( \w+ )_dbo $eq $alpha $paren; }xms => sub {
748 return sprintf q{my $%1$s_dbo = %2$s::%3$s->new(%4$s);}, $_[0],
749 $_[1], ( ucfirst lc $_[0] ), ( $_[2] ? $_[2] : '' );
750 },
751  
752 # FROM: my @word_dbos = DB();
753 # TO: my @word_dbos = DB::Word->list();
754 qr{ my $l( \w+ )_dbos $eq $alpha $paren; }xms => sub {
755 return sprintf q{my @%1$s_dbos = %2$s::%3$s->list(%4$s);}, $_[0],
756 $_[1], ( ucfirst lc $_[0] ), ( $_[2] ? $_[2] : '' );
757 },
758  
759 # FROM: my $word_itr = DB();
760 # TO: my $word_itr = DB::Word->iterator();
761 qr{ my $s( \w+ )_itr $eq $alpha $paren; }xms => sub {
762 return sprintf q{my $%1$s_itr = %2$s::%3$s->iterator(%4$s);},
763 $_[0], $_[1], ( ucfirst lc $_[0] ), ( $_[2] ? $_[2] : '' );
764 },
765  
766 # FROM: my $word_count = DB();
767 # TO: my $word_count = DB::Word->count();
768 qr{ my $s( \w+ )_count $eq $alpha $paren; }xms => sub {
769 return sprintf q{my $%1$s_count = %2$s::%3$s->count(%4$s);},
770 $_[0], $_[1], ( ucfirst lc $_[0] ), ( $_[2] ? $_[2] : '' );
771 },
772 );
773 for my $regex ( keys %xform_for ) {
774  
775 my $xform_rc = $xform_for{$regex};
776  
777 $source =~ s{$regex}{ $xform_rc->( $1, $2, $3, $4 ) }xmseg;
778 }
779  
780 $_ = $source;
781  
782 return;
783 };
784  
785 1;