File Coverage

blib/lib/Rose/DB.pm
Criterion Covered Total %
statement 469 1189 39.4
branch 188 584 32.1
condition 112 332 33.7
subroutine 81 210 38.5
pod 69 158 43.6
total 919 2473 37.1


line stmt bran cond sub pod time code
1             package Rose::DB;
2              
3 16     16   3801105 use strict;
  16         70  
  16         681  
4              
5 16     16   29484 use DBI;
  16         412106  
  16         1506  
6 16     16   175 use Carp();
  16         38  
  16         283  
7 16     16   19020 use Clone::PP();
  16         16400  
  16         549  
8 16     16   10058 use Bit::Vector::Overload;
  16         260274  
  16         1244  
9 16     16   10990 use SQL::ReservedWords();
  16         338179  
  16         799  
10              
11 16     16   9869 use Time::Clock;
  16         86202  
  16         750  
12 16     16   8910 use Rose::DateTime::Util();
  16         9778096  
  16         677  
13              
14 16     16   11196 use Rose::DB::Cache;
  16         192  
  16         697  
15 16     16   10490 use Rose::DB::Registry;
  16         79  
  16         711  
16 16     16   134 use Rose::DB::Registry::Entry;
  16         55  
  16         492  
17 16     16   9299 use Rose::DB::Constants qw(IN_TRANSACTION);
  16         69  
  16         1489  
18              
19 16     16   104 use Rose::Object;
  16         31  
  16         1646  
20             our @ISA = qw(Rose::Object);
21              
22             our $Error;
23              
24             our $VERSION = '0.786';
25              
26             our $Debug = 0;
27              
28             #
29             # Class data
30             #
31              
32             use Rose::Class::MakeMethods::Generic
33             (
34 16         255 inheritable_scalar =>
35             [
36             'default_domain',
37             'default_type',
38             'registry',
39             'max_array_characters',
40             'max_interval_characters',
41             '_db_cache',
42             'db_cache_class',
43             'parent_class',
44             ],
45              
46             inheritable_boolean =>
47             [
48             'default_keyword_function_calls',
49             ]
50 16     16   95 );
  16         31  
51              
52             use Rose::Class::MakeMethods::Generic
53             (
54 16         315 inheritable_hash =>
55             [
56             driver_classes => { interface => 'get_set_all' },
57             _driver_class => { interface => 'get_set', hash_key => 'driver_classes' },
58             delete_driver_class => { interface => 'delete', hash_key => 'driver_classes' },
59              
60             default_connect_options => { interface => 'get_set_all', },
61             default_connect_option => { interface => 'get_set', hash_key => 'default_connect_options' },
62             delete_connect_option => { interface => 'delete', hash_key => 'default_connect_options' },
63             ],
64 16     16   11606 );
  16         34  
65              
66             __PACKAGE__->db_cache_class('Rose::DB::Cache');
67             __PACKAGE__->default_domain('default');
68             __PACKAGE__->default_type('default');
69              
70             __PACKAGE__->max_array_characters(255); # Used for array type emulation
71             __PACKAGE__->max_interval_characters(255); # Used for interval type emulation
72              
73             __PACKAGE__->default_keyword_function_calls(
74             defined $ENV{'ROSE_DB_KEYWORD_FUNCTION_CALLS'} ? $ENV{'ROSE_DB_KEYWORD_FUNCTION_CALLS'} : 0);
75              
76             __PACKAGE__->driver_classes
77             (
78             mysql => 'Rose::DB::MySQL',
79             mariadb => 'Rose::DB::MariaDB',
80             pg => 'Rose::DB::Pg',
81             informix => 'Rose::DB::Informix',
82             oracle => 'Rose::DB::Oracle',
83             sqlite => 'Rose::DB::SQLite',
84             generic => 'Rose::DB::Generic',
85             );
86              
87             __PACKAGE__->default_connect_options
88             (
89             AutoCommit => 1,
90             RaiseError => 1,
91             PrintError => 1,
92             ChopBlanks => 1,
93             Warn => 0,
94             );
95              
96 16     16   11752 BEGIN { __PACKAGE__->registry(Rose::DB::Registry->new(parent => __PACKAGE__)) }
97              
98             my %Class_Loaded;
99              
100             # Load on demand instead
101             # LOAD_SUBCLASSES:
102             # {
103             # my %seen;
104             #
105             # my $map = __PACKAGE__->driver_classes;
106             #
107             # foreach my $class (values %$map)
108             # {
109             # eval qq(require $class) unless($seen{$class}++);
110             # die "Could not load $class - $@" if($@);
111             # }
112             # }
113              
114             #
115             # Object data
116             #
117              
118             use Rose::Object::MakeMethods::Generic
119             (
120 16         417 'scalar' =>
121             [
122             qw(dbi_driver username _dbh_refcount id)
123             ],
124              
125             'boolean' =>
126             [
127             'auto_create' => { default => 1 },
128             'european_dates' => { default => 0 },
129             ],
130              
131             'scalar --get_set_init' =>
132             [
133             'domain',
134             'type',
135             'date_handler',
136             'server_time_zone',
137             'keyword_function_calls',
138             ],
139              
140             'array' =>
141             [
142             'post_connect_sql',
143             'pre_disconnect_sql',
144             ],
145              
146             'hash' =>
147             [
148             connect_options => { interface => 'get_set_init' },
149             ]
150 16     16   2650 );
  16         219  
151              
152             #
153             # Class methods
154             #
155              
156             sub register_db
157             {
158 224     224 1 610904 my $class = shift;
159              
160             # Smuggle parent/caller in with an otherwise nonsensical arrayref arg
161 224         745 my $entry = $class->registry->add_entry([ $class ], @_);
162              
163 224 50       1217 if($entry)
164             {
165 224         581 my $driver = $entry->driver;
166              
167 224 50       610 Carp::confess "No driver found for registry entry $entry"
168             unless(defined $driver);
169              
170 224         746 $class->setup_dynamic_class_for_driver($driver);
171             }
172              
173 224         3383 return $entry;
174             }
175              
176             our %Rebless;
177              
178             sub setup_dynamic_class_for_driver
179             {
180 306     306 0 778 my($class, $driver) = @_;
181              
182 306   33     1118 my $driver_class = $class->driver_class($driver) ||
183             $class->driver_class('generic') || Carp::croak
184             "No driver class found for drivers '$driver' or 'generic'";
185              
186 306 100       6817 unless($Rebless{$class,$driver_class})
187             {
188 16     16   34658 no strict 'refs';
  16         74  
  16         3055  
189 184 100 100     649 unless($Class_Loaded{$driver_class} || @{"${driver_class}::ISA"})
  164         1556  
190             {
191 82         162 my $error;
192              
193             TRY:
194             {
195 82         125 local $@;
  82         140  
196 82         7982 eval "require $driver_class";
197 82         527 $error = $@;
198             }
199              
200 82 50       333 Carp::croak "Could not load driver class '$driver_class' - $error" if($error);
201             }
202              
203 184         605 $Class_Loaded{$driver_class}++;
204              
205             # Make a new driver class based on the current class
206 184         484 my $new_class = $class . '::__RoseDBPrivate__::' . $driver_class;
207              
208 16     16   166 no strict 'refs';
  16         41  
  16         33860  
209 184         347 @{"${new_class}::ISA"} = ($driver_class, $class);
  184         5790  
210 184         553 *{"${new_class}::STORABLE_thaw"} = \&STORABLE_thaw;
  184         1191  
211 184         384 *{"${new_class}::STORABLE_freeze"} = \&STORABLE_freeze;
  184         880  
212              
213 184         1914 $new_class->parent_class($class);
214              
215             # Cache result
216 184         2415 $Rebless{$class,$driver_class} = $new_class;
217             }
218              
219 306         871 return $Rebless{$class,$driver_class};
220             }
221              
222 0     0 1 0 sub unregister_db { shift->registry->delete_entry(@_) }
223              
224 0     0 0 0 sub default_implicit_schema { undef }
225 0     0 0 0 sub registration_schema { undef }
226              
227 19     19 1 2459 sub use_private_registry { $_[0]->registry(Rose::DB::Registry->new(parent => $_[0])) }
228              
229             sub modify_db
230             {
231 4     4 1 18287 my($class, %args) = @_;
232              
233 4   33     25 my $domain = delete $args{'domain'} || $class->default_domain ||
234             Carp::croak "Missing domain";
235              
236 4   33     16 my $type = delete $args{'type'} || $class->default_type ||
237             Carp::croak "Missing type";
238              
239 4 50       21 my $entry = $class->registry->entry(domain => $domain, type => $type) or
240             Carp::croak "No db defined for domain '$domain' and type '$type'";
241              
242 4         47 while(my($key, $val) = each(%args))
243             {
244 8         57 $entry->$key($val);
245             }
246              
247 4         26 return $entry;
248             }
249              
250             sub db_exists
251             {
252 14     14 1 9990 my($class) = shift;
253              
254 14 100       84 my %args = (@_ == 1) ? (type => $_[0]) : @_;
255              
256 14   33     68 my $domain = $args{'domain'} || $class->default_domain ||
257             Carp::croak "Missing domain";
258              
259 14   33     190 my $type = $args{'type'} || $class->default_type ||
260             Carp::croak "Missing type";
261              
262 14         43 return $class->registry->entry_exists(domain => $domain, type => $type);
263             }
264              
265             sub alias_db
266             {
267 2     2 1 28 my($class, %args) = @_;
268              
269 2 50       10 my $source = $args{'source'} or Carp::croak "Missing source";
270              
271 2 50       8 my $src_domain = $source->{'domain'} or Carp::croak "Missing source domain";
272 2 50       12 my $src_type = $source->{'type'} or Carp::croak "Missing source type";
273              
274 2 50       8 my $alias = $args{'alias'} or Carp::croak "Missing alias";
275              
276 2 50       7 my $alias_domain = $alias->{'domain'} or Carp::croak "Missing source domain";
277 2 50       5 my $alias_type = $alias->{'type'} or Carp::croak "Missing source type";
278              
279 2         10 my $registry = $class->registry;
280              
281 2 50       40 my $entry = $registry->entry(domain => $src_domain, type => $src_type) or
282             Carp::croak "No db defined for domain '$src_domain' and type '$src_type'";
283              
284 2         22 $registry->add_entry(domain => $alias_domain,
285             type => $alias_type,
286             entry => $entry);
287             }
288              
289 0     0 1 0 sub unregister_domain { shift->registry->delete_domain(@_) }
290              
291             sub driver_class
292             {
293 546     546 1 7512 my($class, $driver) = (shift, lc shift);
294              
295 546 100       1328 if(@_)
296             {
297 82         326 $class->_driver_class($driver, @_);
298 82         2702 $class->setup_dynamic_class_for_driver($driver);
299             }
300              
301 546         1606 return $class->_driver_class($driver);
302             }
303              
304             sub db_cache
305             {
306 0     0 1 0 my($class) = shift;
307              
308 0 0       0 if(@_)
309             {
310 0         0 return $class->_db_cache(@_);
311             }
312              
313 0 0       0 if(my $cache = $class->_db_cache)
314             {
315 0         0 return $cache;
316             }
317              
318 0         0 my $cache_class = $class->db_cache_class;
319              
320 0         0 my $error;
321              
322             TRY:
323             {
324 0         0 local $@;
  0         0  
325 0         0 eval "use $cache_class";
326 0         0 $error = $@;
327             }
328              
329 0 0       0 die "Could not load db cache class '$cache_class' - $error" if($error);
330              
331 0         0 return $class->_db_cache($cache_class->new);
332             }
333              
334             sub use_cache_during_apache_startup
335             {
336 0     0 1 0 shift->db_cache->use_cache_during_apache_startup(@_);
337             }
338              
339             sub prepare_cache_for_apache_fork
340             {
341 0     0 1 0 shift->db_cache->prepare_for_apache_fork(@_);
342             }
343              
344             sub new_or_cached
345             {
346 0     0 1 0 my($class) = shift;
347              
348 0 0       0 @_ = (type => $_[0]) if(@_ == 1);
349              
350 0         0 my %args = @_;
351              
352 0 0       0 $args{'domain'} = $class->default_domain unless(exists $args{'domain'});
353 0 0       0 $args{'type'} = $class->default_type unless(exists $args{'type'});
354              
355             #$Debug && warn "New or cached db type: $args{'type'}, domain: $args{'domain'}\n";
356              
357 0         0 my $cache = $class->db_cache;
358              
359 0 0       0 if(my $db = $cache->get_db(%args))
360             {
361 0 0       0 $Debug && warn "$$ $class Returning cached db (", $db->domain, ', ', $db->type,
362             ") $db from ", $cache, "\n";
363 0         0 return $db;
364             }
365              
366 0 0       0 if($Debug)
367             {
368 0         0 my $db = $class->new(@_);
369             $Debug && warn "$$ $class Setting cached db $db (",
370 0 0       0 join(', ', map { $args{$_} } qw(domain type)),
  0         0  
371             ") in ", $cache, "\n";
372              
373             # The set_db() call may refuse to set, so call get_db() to properly
374             # register clean-up handlers, etc., but fall back to the db returned
375             # by set_db() in the case where the db was never cached.
376 0         0 $db = $cache->set_db($class->new(@_));
377 0   0     0 return $cache->get_db(%args) || $db;
378             }
379             else
380             {
381             # The set_db() call may refuse to set, so call get_db() to properly
382             # register clean-up handlers, etc., but fall back to the db returned
383             # by set_db() in the case where the db was never cached.
384 0         0 my $db = $cache->set_db($class->new(@_));
385 0   0     0 return $cache->get_db(%args) || $db;
386             }
387             }
388              
389 0     0 0 0 sub clear_db_cache { shift->db_cache->clear(@_) }
390              
391             #
392             # Object methods
393             #
394              
395             sub new
396             {
397 86     86 1 2094759 my($class) = shift;
398              
399 86 100       500 @_ = (type => $_[0]) if(@_ == 1);
400              
401 86         336 my %args = @_;
402              
403 86   33     428 my $allow_empty = $args{'driver'} && !($args{'type'} || $args{'domain'});
404              
405             my $domain =
406 86 100       613 exists $args{'domain'} ? delete $args{'domain'} : $class->default_domain;
407              
408             my $type =
409 86 100       1572 exists $args{'type'} ? delete $args{'type'} : $class->default_type;
410              
411 86         315 my $db_info;
412              
413             # I'm being bad here for speed purposes, digging into private hashes instead
414             # of using object methods. I'll fix it when the first person emails me to
415             # complain that I'm breaking their Rose::DB or Rose::DB::Registry[::Entry]
416             # subclass by doing this. Call it "demand-paged programming" :)
417 86         321 my $registry = $class->registry->hash;
418              
419 86 100 100     2613 if(exists $registry->{$domain} && exists $registry->{$domain}{$type})
    50          
420             {
421 68         222 $db_info = $registry->{$domain}{$type}
422             }
423             elsif(!$allow_empty)
424             {
425 18         3409 Carp::croak "No database information found for domain '$domain' and ",
426             "type '$type' and no driver type specified in call to ",
427             "$class->new(...)";
428             }
429              
430 68   33     337 my $driver = $db_info->{'driver'} || $args{'driver'};
431              
432 68 50       232 Carp::croak "No driver found for domain '$domain' and type '$type'"
433             unless(defined $driver);
434              
435 68   33     263 my $driver_class = $class->driver_class($driver) ||
436             $class->driver_class('generic') || Carp::croak
437             "No driver class found for drivers '$driver' or 'generic'";
438              
439 68 50       1528 unless($Class_Loaded{$driver_class})
440             {
441 0         0 $class->load_driver_class($driver_class);
442             }
443              
444 68         129 my $self;
445              
446             REBLESS: # Do slightly evil re-blessing magic
447             {
448             # Check cache
449 68 50       117 if(my $new_class = $Rebless{$class,$driver_class})
  68         400  
450             {
451 68         503 $self = bless {}, $new_class;
452             }
453             else
454             {
455             # Make a new driver class based on the current class
456 0         0 my $new_class = $class . '::__RoseDBPrivate__::' . $driver_class;
457              
458 16     16   252 no strict 'refs';
  16         86  
  16         6671  
459 0         0 @{"${new_class}::ISA"} = ($driver_class, $class);
  0         0  
460              
461 0         0 $self = bless {}, $new_class;
462              
463 0         0 $new_class->parent_class($class);
464              
465             # Cache result
466 0         0 $Rebless{$class,$driver_class} = ref $self;
467             }
468             }
469              
470 68         836 $self->class($class);
471              
472 68         345 $self->{'id'} = "$domain\0$type";
473 68         165 $self->{'type'} = $type;
474 68         158 $self->{'domain'} = $domain;
475              
476 68         697 $self->init(@_);
477              
478 68         1375 $self->init_db_info;
479              
480 68         460 return $self;
481             }
482              
483             sub class
484             {
485 140     140 0 296 my($self) = shift;
486 140 100       1022 return $self->{'_origin_class'} = shift if(@_);
487 72   33     363 return $self->{'_origin_class'} || ref $self;
488             }
489              
490 6     6 0 138 sub init_keyword_function_calls { ref($_[0])->default_keyword_function_calls }
491              
492             # sub init
493             # {
494             # my($self) = shift;
495             # $self->SUPER::init(@_);
496             # $self->init_db_info;
497             # }
498              
499             sub load_driver_class
500             {
501 80     80 0 168 my($class, $arg) = @_;
502              
503 80   33     201 my $driver_class = $class->driver_class($arg) || $arg;
504              
505 16     16   126 no strict 'refs';
  16         31  
  16         59592  
506 80 100       1094 unless(defined ${"${driver_class}::VERSION"})
  80         480  
507             {
508 16         623 my $error;
509              
510             TRY:
511             {
512 16         166 local $@;
  16         36  
513 16         1392 eval "require $driver_class";
514 16         129 $error = $@;
515             }
516              
517 16 50       88 Carp::croak "Could not load driver class '$driver_class' - $error" if($error);
518             }
519              
520 80         344 $Class_Loaded{$driver_class}++;
521             }
522              
523 0     0 0 0 sub driver_class_is_loaded { $Class_Loaded{$_[1]} }
524              
525             sub load_driver_classes
526             {
527 16     16 0 17506 my($class) = shift;
528              
529 16         181 my $map = $class->driver_classes;
530              
531 16 50       323 foreach my $arg (@_ ? @_ : keys %$map)
532             {
533 80         203 $class->load_driver_class($arg);
534             }
535              
536 16         85 return;
537             }
538              
539             sub database
540             {
541 75     75 1 241 my($self) = shift;
542              
543 75 100       238 if(@_)
544             {
545 73 100       228 $self->{'dsn'} = undef if($self->{'dsn'});
546 73         325 return $self->{'database'} = shift;
547             }
548              
549 2         10 return $self->{'database'};
550             }
551              
552             sub schema
553             {
554 0     0 1 0 my($self) = shift;
555              
556 0 0       0 if(@_)
557             {
558 0 0       0 $self->{'dsn'} = undef if($self->{'dsn'});
559 0         0 return $self->{'schema'} = shift;
560             }
561              
562 0         0 return $self->{'schema'};
563             }
564              
565             sub catalog
566             {
567 0     0 1 0 my($self) = shift;
568              
569 0 0       0 if(@_)
570             {
571 0 0       0 $self->{'dsn'} = undef if($self->{'dsn'});
572 0         0 return $self->{'catalog'} = shift;
573             }
574              
575 0         0 return $self->{'catalog'};
576             }
577              
578             sub service
579             {
580 0     0 0 0 my($self) = shift;
581              
582 0 0       0 if(@_)
583             {
584 0 0       0 $self->{'dsn'} = undef if($self->{'dsn'});
585 0         0 return $self->{'service'} = shift;
586             }
587              
588 0         0 return $self->{'service'};
589             }
590              
591             sub host
592             {
593 62     62 1 139 my($self) = shift;
594              
595 62 50       209 if(@_)
596             {
597 62 50       168 $self->{'dsn'} = undef if($self->{'dsn'});
598 62         293 return $self->{'host'} = shift;
599             }
600              
601 0         0 return $self->{'host'};
602             }
603              
604             sub port
605             {
606 9     9 1 24 my($self) = shift;
607              
608 9 50       18 if(@_)
609             {
610 9 50       19 $self->{'dsn'} = undef if($self->{'dsn'});
611 9         23 return $self->{'port'} = shift;
612             }
613              
614 0         0 return $self->{'port'};
615             }
616              
617             sub database_version
618             {
619 0     0 0 0 my($self) = shift;
620 0 0       0 return $self->{'database_version'} if(defined $self->{'database_version'});
621 0         0 return $self->{'database_version'} = $self->dbh->get_info(18); # SQL_DBMS_VER
622             }
623              
624             # Use a closure to keep the password from appearing when the
625             # object is dumped using Data::Dumper
626             sub password
627             {
628 95     95 1 184 my($self) = shift;
629              
630 95 100       259 if(@_)
631             {
632 54         231 my $password = shift;
633 54     31   353 $self->{'password_closure'} = sub { $password };
  31         304  
634 54         258 return $password;
635             }
636              
637 41 100       233 return $self->{'password_closure'} ? $self->{'password_closure'}->() : undef;
638             }
639              
640             # These have to "cheat" to get the right values by going through
641             # the real origin class because they may be called after the
642             # re-blessing magic takes place.
643 0     0 0 0 sub init_domain { shift->{'_origin_class'}->default_domain }
644 0     0 0 0 sub init_type { shift->{'_origin_class'}->default_type }
645              
646 2     2 0 67 sub init_date_handler { Rose::DateTime::Format::Generic->new }
647 0     0 0 0 sub init_server_time_zone { 'floating' }
648              
649             sub init_db_info
650             {
651 72     72 1 285 my($self, %args) = @_;
652              
653 72 100       267 return 1 if($self->{'dsn'});
654              
655 70         159 my $class = ref $self;
656              
657 70         439 my $domain = $self->domain;
658 70         570 my $type = $self->type;
659              
660 70         392 my $db_info;
661              
662             # I'm being bad here for speed purposes, digging into private hashes instead
663             # of using object methods. I'll fix it when the first person emails me to
664             # complain that I'm breaking their Rose::DB or Rose::DB::Registry[::Entry]
665             # subclass by doing this. Call it "demand-paged programming" :)
666 70         509 my $registry = $self->class->registry->hash;
667              
668 70 50 33     1734 if(exists $registry->{$domain} && exists $registry->{$domain}{$type})
669             {
670 70         173 $db_info = $registry->{$domain}{$type}
671             }
672             else
673             {
674 0 0       0 return 1 if($self->{'driver'});
675 0         0 Carp::croak "No database information found for domain '$domain' and type '$type'";
676             }
677              
678 70 50 33     462 unless($args{'refresh'} || ($self->{'connect_options_for'}{$domain} &&
      66        
679             $self->{'connect_options_for'}{$domain}{$type}))
680             {
681 66 100       276 if(my $custom_options = $db_info->{'connect_options'})
682             {
683 28         189 my $options = $self->connect_options;
684 28         3011 @$options{keys %$custom_options} = values %$custom_options;
685             }
686              
687 66         352 $self->{'connect_options_for'} = { $domain => { $type => 1 } };
688             }
689              
690 70         531 $self->driver($db_info->{'driver'});
691              
692 70         390 while(my($field, $value) = each(%$db_info))
693             {
694 573 100 66     3420 if($field ne 'connect_options' && defined $value && !defined $self->{$field})
      100        
695             {
696 317         2455 $self->$field($value);
697             }
698             }
699              
700 70         265 return 1;
701             }
702              
703             sub init_connect_options
704             {
705 57     57 0 839 my($class) = ref $_[0];
706 57         396 return Clone::PP::clone(scalar $class->default_connect_options);
707             }
708              
709             sub connect_option
710             {
711 50     50 1 114 my($self, $param) = (shift, shift);
712              
713 50         224 my $options = $self->connect_options;
714              
715 50 100       3225 return $options->{$param} = shift if(@_);
716 25         88 return $options->{$param};
717             }
718              
719             sub dsn
720             {
721 51     51 1 26485 my($self) = shift;
722              
723 51 100       162 unless(@_)
724             {
725 45   66     604 return $self->{'dsn'} || $self->build_dsn(%$self);
726             }
727              
728 6 50       21 if(my $dsn = shift)
729             {
730 6         16 foreach my $method (qw(database host port))
731             {
732 18         71 $self->$method(undef);
733             }
734              
735 6         24 $self->init($self->parse_dsn($dsn));
736 4         22 return $self->{'dsn'} = $dsn;
737             }
738             else
739             {
740 0         0 $self->{'dsn'} = undef;
741 0         0 return $self->build_dsn(%$self);
742             }
743             }
744              
745             my %DSN_Attr_Method =
746             (
747             db => 'database',
748             dbname => 'database',
749             user => 'username',
750             hostname => 'host',
751             hostaddr => 'host',
752             sid => 'database',
753             service => 'service_name',
754             );
755              
756 16     16 0 75 sub dsn_attribute_to_db_method { $DSN_Attr_Method{$_[1]} }
757              
758             sub parse_dsn
759             {
760 6     6 0 13 my($self, $dsn) = @_;
761              
762 6         10 my($scheme, $driver, $attr_string, $attr_hash, $driver_dsn);
763              
764             # x DBI->parse_dsn('dbi:mysql:database=test;host=localhost')
765             # 0 'dbi'
766             # 1 'mysql'
767             # 2 undef
768             # 3 undef
769             # 4 'database=test;host=localhost'
770              
771 6 50       71 if(DBI->can('parse_dsn'))
772             {
773 6         23 ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) =
774             DBI->parse_dsn($dsn);
775             }
776             else
777             {
778 0         0 ($scheme, $driver, $attr_string, $driver_dsn) =
779             ($dsn =~ /^((?i)dbi) : (\w+) : (?: \( ([^)]+) \) : )? (.*)/x);
780             }
781              
782 6         175 my %init =
783             (
784             dbi_driver => $driver,
785             driver => $driver,
786             );
787              
788 6         43 while($driver_dsn =~ /\G(\w+)=([^;]+)(?:;|$)?/g)
789             {
790 16         39 my($name, $value) = ($1, $2);
791              
792 16 100       38 if(my $method = $self->dsn_attribute_to_db_method($name))
    50          
793             {
794 4         22 $init{$method} = $value;
795             }
796             elsif($self->can($name))
797             {
798 12         48 $init{$name} = $value;
799             }
800             }
801              
802 6 50       16 unless($init{'database'})
803             {
804 0         0 $init{'database'} = $driver_dsn;
805             }
806              
807 6         96 return %init;
808             }
809              
810             sub database_from_dsn
811             {
812 0     0 0 0 my($self_or_class, $dsn) = @_;
813 0         0 my %attrs = $self_or_class->parse_dsn($dsn);
814 0         0 return $attrs{'database'};
815             }
816              
817             sub dbh
818             {
819 41     41 1 117 my($self) = shift;
820              
821 41 50       151 unless(@_)
822             {
823 41 50       168 if(my $dbh = $self->{'dbh'})
824             {
825             # If this db connection wasn't created in another process or thread, return it
826 0 0 0     0 if((!$INC{'threads.pm'} || $dbh->{'private_tid'} == threads->tid) &&
      0        
827             $dbh->{'private_pid'} == $$)
828             {
829 0         0 return $dbh;
830             }
831              
832             # This $dbh wasn't created here, so disable destroy actions,
833             # undef it, and create a new one by falling through to the
834             # init_dbh() call below.
835 0         0 $dbh->{'InactiveDestroy'} = 1;
836 0         0 $self->{'dbh'} = undef;
837             }
838              
839 41         295 return $self->init_dbh;
840             }
841              
842 0 0       0 unless(defined($_[0]))
843             {
844 0         0 return $self->{'dbh'} = undef;
845             }
846              
847 0         0 $self->driver($_[0]->{'Driver'}{'Name'});
848              
849 0         0 $self->{'_dbh_refcount'}++;
850 0         0 return $self->{'dbh'} = $_[0];
851             }
852              
853             sub driver
854             {
855 76 50   76 1 281 if(@_ > 1)
856             {
857 76         269 my $driver = lc $_[1];
858              
859 76 100 66     485 if(defined $driver && defined $_[0]->{'driver'} && $_[0]->{'driver'} ne $driver)
      100        
860             {
861 2         525 Carp::croak "Attempt to change driver from '$_[0]->{'driver'}' to ",
862             "'$driver' detected. The driver cannot be changed after ",
863             "object creation.";
864             }
865              
866 74         301 return $_[0]->{'driver'} = $driver;
867             }
868              
869 0         0 return $_[0]->{'driver'};
870             }
871              
872             sub retain_dbh
873             {
874 41     41 1 302 my($self) = shift;
875 41 0       294 my $dbh = $self->dbh or return undef;
876             #$Debug && warn "$self->{'_dbh_refcount'} -> ", ($self->{'_dbh_refcount'} + 1), " $dbh\n";
877 0         0 $self->{'_dbh_refcount'}++;
878 0         0 return $dbh;
879             }
880              
881             sub release_dbh
882             {
883 68     68 1 200 my($self, %args) = @_;
884              
885 68 50       1673 my $dbh = $self->{'dbh'} or return 0;
886              
887 0 0       0 if($args{'force'})
888             {
889 0         0 $self->{'_dbh_refcount'} = 0;
890              
891             # Account for possible Apache::DBI magic
892 0 0       0 if(UNIVERSAL::isa($dbh, 'Apache::DBI::db'))
893             {
894 0         0 return $dbh->DBI::db::disconnect; # bypass Apache::DBI
895             }
896             else
897             {
898 0         0 return $dbh->disconnect;
899             }
900             }
901              
902             #$Debug && warn "$self->{'_dbh_refcount'} -> ", ($self->{'_dbh_refcount'} - 1), " $dbh\n";
903 0         0 $self->{'_dbh_refcount'}--;
904              
905 0 0 0     0 unless($self->{'_dbh_refcount'} || $self->{'_dbh_has_foreign_owner'})
906             {
907 0 0       0 if(my $sqls = $self->pre_disconnect_sql)
908             {
909 0         0 my $error;
910              
911             TRY:
912             {
913 0         0 local $@;
  0         0  
914              
915             eval
916 0         0 {
917 0         0 foreach my $sql (@$sqls)
918             {
919 0 0       0 $dbh->do($sql) or die "$sql - " . $dbh->errstr;
920 0         0 return undef;
921             }
922             };
923              
924 0         0 $error = $@;
925             }
926              
927 0 0       0 if($error)
928             {
929 0         0 $self->error("Could not do pre-disconnect SQL: $error");
930 0         0 return undef;
931             }
932             }
933              
934             #$Debug && warn "DISCONNECT $dbh ", join(':', (caller(3))[0,2]), "\n";
935 0         0 return $dbh->disconnect;
936             }
937             #else { $Debug && warn "DISCONNECT NOOP $dbh ", join(':', (caller(2))[0,2]), "\n"; }
938              
939 0         0 return 1;
940             }
941              
942             sub dbh_attribute
943             {
944 0     0 0 0 my($self, $name) = (shift, shift);
945              
946 0 0       0 if(@_)
947             {
948 0 0       0 if(my $dbh = $self->{'dbh'})
949             {
950 0         0 return $self->{'dbh'}{$name} = $self->{'__dbh_attributes'}{$name} = shift;
951             }
952             else
953             {
954 0         0 return $self->{'__dbh_attributes'}{$name} = shift;
955             }
956             }
957              
958 0 0       0 if(my $dbh = $self->{'dbh'})
959             {
960 0         0 return $self->{'dbh'}{$name};
961             }
962             else
963             {
964 0         0 return $self->{'__dbh_attributes'}{$name};
965             }
966             }
967              
968             sub dbh_attribute_boolean
969             {
970 0     0 0 0 my($self, $name) = (shift, shift);
971 0 0       0 return $self->dbh_attribute($name, (@_ ? ($_[0] ? 1 : 0) : ()));
    0          
972             }
973              
974 2     2 1 13 sub has_dbh { defined shift->{'dbh'} }
975              
976             sub dbi_connect
977             {
978 41     41 1 102 shift;
979              
980 41 50       131 if($Debug)
981             {
982 0         0 require Data::Dumper;
983 0         0 local $Data::Dumper::Terse = 1;
984 0         0 local $Data::Dumper::Indent = 1;
985 0         0 local $Data::Dumper::Maxdepth = 1;
986 0         0 local $Data::Dumper::Quotekeys = 0;
987 0         0 local $Data::Dumper::Sortkeys = 1;
988 0   0     0 my $options = Data::Dumper::Dumper($_[3] || {});
989 0         0 $options =~ s/\n\s*/ /g;
990 0         0 warn "DBI->connect('$_[0]', '$_[1]', ..., $options)\n";
991             }
992              
993 41         404 DBI->connect(@_);
994             }
995              
996 16     16   234 use constant DID_PCSQL_KEY => 'private_rose_db_did_post_connect_sql';
  16         91  
  16         19803  
997              
998             sub init_dbh
999             {
1000 41     41 0 161 my($self) = shift;
1001              
1002 41         237 my $options = $self->connect_options;
1003              
1004 41         2756 $options->{'private_pid'} = $$;
1005 41 50       211 $options->{'private_tid'} = threads->tid if($INC{'threads.pm'});
1006              
1007 41         438 my $dsn = $self->dsn;
1008              
1009 41         201 $self->{'error'} = undef;
1010 41         258 $self->{'database_version'} = undef;
1011 41         137 $self->{'_dbh_refcount'} = 0;
1012 41         103 $self->{'_dbh_has_foreign_owner'} = undef;
1013              
1014 41         275 my $dbh = $self->dbi_connect($dsn, $self->username, $self->password, $options);
1015              
1016 0 0       0 unless($dbh)
1017             {
1018 0         0 $self->error("Could not connect to database: $DBI::errstr");
1019 0         0 return undef;
1020             }
1021              
1022 0 0       0 if($dbh->{'private_rose_db_inited'})
1023             {
1024             # Someone else owns this dbh
1025 0         0 $self->{'_dbh_has_foreign_owner'} = 1;
1026             }
1027             else # Only initialize if this is really a new connection
1028             {
1029 0         0 $dbh->{'private_rose_db_inited'} = 1;
1030              
1031 0 0       0 if($self->{'__dbh_attributes'})
1032             {
1033 0         0 foreach my $attr (keys %{$self->{'__dbh_attributes'}})
  0         0  
1034             {
1035 0         0 my $val = $self->dbh_attribute($attr);
1036 0 0       0 next unless(defined $val);
1037 0         0 $dbh->{$attr} = $val;
1038             }
1039             }
1040              
1041 0 0 0     0 if((my $sqls = $self->post_connect_sql) && !$dbh->{DID_PCSQL_KEY()})
1042             {
1043 0         0 my $error;
1044              
1045             TRY:
1046             {
1047 0         0 local $@;
  0         0  
1048              
1049             eval
1050 0         0 {
1051 0         0 foreach my $sql (@$sqls)
1052             {
1053             #$Debug && warn "$dbh DO: $sql\n";
1054 0 0       0 $dbh->do($sql) or die "$sql - " . $dbh->errstr;
1055             }
1056             };
1057              
1058 0         0 $error = $@;
1059             }
1060              
1061 0 0       0 if($error)
1062             {
1063 0         0 $self->error("Could not do post-connect SQL: $error");
1064 0         0 $dbh->disconnect;
1065 0         0 return undef;
1066             }
1067              
1068 0         0 $dbh->{DID_PCSQL_KEY()} = 1;
1069             }
1070             }
1071              
1072 0         0 $self->{'_dbh_refcount'} = 1;
1073              
1074 0         0 return $self->{'dbh'} = $dbh;
1075             }
1076              
1077 25     25 1 350 sub print_error { shift->_dbh_and_connect_option('PrintError', @_) }
1078 0     0 1 0 sub raise_error { shift->_dbh_and_connect_option('RaiseError', @_) }
1079 0     0 1 0 sub autocommit { shift->_dbh_and_connect_option('AutoCommit', @_) }
1080 0     0 1 0 sub handle_error { shift->_dbh_and_connect_option('HandleError', @_) }
1081              
1082             sub _dbh_and_connect_option
1083             {
1084 25     25   74 my($self, $param) = (shift, shift);
1085              
1086 25 50       81 if(@_)
1087             {
1088 25 50       130 my $val = $_[0] ? 1 : 0;
1089 25         176 $self->connect_option($param => $val);
1090              
1091 25 50       110 $self->{'dbh'}{$param} = $val if($self->{'dbh'});
1092             }
1093              
1094 25 50       167 return $self->{'dbh'} ? $self->{'dbh'}{$param} :
1095             $self->connect_option($param);
1096             }
1097              
1098             sub connect
1099             {
1100 0     0 1 0 my($self) = shift;
1101              
1102 0 0       0 $self->dbh or return 0;
1103 0         0 return 1;
1104             }
1105              
1106             sub disconnect
1107             {
1108 68     68 1 174 my($self) = shift;
1109              
1110 68 50       382 $self->release_dbh(@_) or return undef;
1111              
1112 0         0 $self->{'dbh'} = undef;
1113             }
1114              
1115             sub begin_work
1116             {
1117 0     0 1 0 my($self) = shift;
1118              
1119 0 0       0 my $dbh = $self->dbh or return undef;
1120              
1121 0 0       0 if($dbh->{'AutoCommit'})
1122             {
1123 0         0 my $ret;
1124              
1125             #$Debug && warn "BEGIN TRX\n";
1126              
1127             my $error;
1128              
1129             TRY:
1130             {
1131 0         0 local $@;
  0         0  
1132              
1133             eval
1134 0         0 {
1135 0         0 local $dbh->{'RaiseError'} = 1;
1136              
1137             # XXX: Detect DBD::mysql bug (in some versions before 4.012) that
1138             # XXX: fails to set Active back to 1 when mysql_auto_reconnect
1139             # XXX: is in use.
1140 0 0       0 unless($dbh->{'Active'})
1141             {
1142 0 0 0     0 if($dbh->{'Driver'}{'Name'} eq 'mysql' && $dbh->{'Driver'}{'Version'} < 4.012)
1143             {
1144 0         0 die 'Database handle does not have Active set to a true value. DBD::mysql ',
1145             'versions before 4.012 may fail to set Active back to 1 when the ',
1146             'mysql_auto_reconnect is set. Try upgrading to DBD::mysql 4.012 or later';
1147             }
1148             else
1149             {
1150 0         0 die "Cannot start transaction on inactive database handle ($dbh)";
1151             }
1152             }
1153              
1154 0         0 $ret = $dbh->begin_work
1155             };
1156              
1157 0         0 $error = $@;
1158             }
1159              
1160 0 0       0 if($error)
1161             {
1162 16     16   166 no warnings 'uninitialized';
  16         34  
  16         6601  
1163 0         0 $self->error("begin_work() - $error " . $dbh->errstr);
1164 0         0 return undef;
1165             }
1166              
1167 0 0       0 unless($ret)
1168             {
1169 0         0 $self->error('begin_work() failed - ' . $dbh->errstr);
1170 0         0 return undef;
1171             }
1172              
1173 0         0 return 1;
1174             }
1175              
1176 0         0 return IN_TRANSACTION;
1177             }
1178              
1179             sub in_transaction
1180             {
1181 0 0   0 1 0 my $dbh = shift->{'dbh'} or return undef;
1182 0 0       0 return ($dbh->{'AutoCommit'}) ? 0 : 1;
1183             }
1184              
1185             sub commit
1186             {
1187 0     0 1 0 my($self) = shift;
1188              
1189 0 0 0     0 my $is_active = (defined $self->{'dbh'} && $self->{'dbh'}{'Active'}) ? 1 : 0;
1190              
1191 0 0       0 unless(defined $self->{'dbh'})
1192             {
1193 0         0 $self->error("Could not commit transaction: database handle is undefined");
1194 0         0 return 0;
1195             }
1196              
1197 0 0       0 my $dbh = $self->dbh or return undef;
1198              
1199 0 0       0 unless($dbh->{'AutoCommit'})
1200             {
1201 0         0 my $ret;
1202              
1203             #$Debug && warn "COMMIT TRX\n";
1204              
1205             my $error;
1206              
1207             TRY:
1208             {
1209 0         0 local $@;
  0         0  
1210              
1211             eval
1212 0         0 {
1213 0         0 local $dbh->{'RaiseError'} = 1;
1214 0         0 $ret = $dbh->commit;
1215             };
1216              
1217 0         0 $error = $@;
1218             }
1219              
1220 0 0       0 if($error)
1221             {
1222 16     16   150 no warnings 'uninitialized';
  16         37  
  16         7852  
1223 0         0 $self->error("commit() $error - " . $dbh->errstr);
1224              
1225 0 0       0 unless($is_active)
1226             {
1227 0 0 0     0 if($dbh->{'Driver'}{'Name'} eq 'mysql' && $dbh->{'Driver'}{'Version'} < 4.012)
1228             {
1229 0         0 $self->error($self->error . '; Also, the database handle did not ' .
1230             'have Active set to a true value. DBD::mysql versions before 4.012 ' .
1231             'may fail to set Active back to 1 when the mysql_auto_reconnect is ' .
1232             'set. Try upgrading to DBD::mysql 4.012 or later');
1233             }
1234              
1235 0         0 return 0;
1236             }
1237              
1238 0         0 return undef;
1239             }
1240              
1241 0 0       0 unless($ret)
1242             {
1243 0   0     0 $self->error('Could not commit transaction: ' .
1244             ($dbh->errstr || $DBI::errstr ||
1245             'Possibly a referential integrity violation. ' .
1246             'Check the database error log for more information.'));
1247 0         0 return undef;
1248             }
1249              
1250 0         0 return 1;
1251             }
1252              
1253 0         0 return -1;
1254             }
1255              
1256             sub rollback
1257             {
1258 0     0 1 0 my($self) = shift;
1259              
1260 0 0 0     0 my $is_active = (defined $self->{'dbh'} && $self->{'dbh'}{'Active'}) ? 1 : 0;
1261              
1262 0 0       0 unless(defined $self->{'dbh'})
1263             {
1264 0         0 $self->error("Could not roll back transaction: database handle is undefined");
1265 0         0 return 0;
1266             }
1267              
1268 0 0       0 my $dbh = $self->dbh or return undef;
1269              
1270 0         0 my $ac = $dbh->{'AutoCommit'};
1271              
1272 0 0       0 return 1 if($ac);
1273              
1274 0         0 my $ret;
1275              
1276             #$Debug && warn "ROLLBACK TRX\n";
1277              
1278             my $error;
1279              
1280             TRY:
1281             {
1282 0         0 local $@;
  0         0  
1283              
1284             eval
1285 0         0 {
1286 0         0 local $dbh->{'RaiseError'} = 1;
1287 0         0 $ret = $dbh->rollback;
1288             };
1289              
1290 0         0 $error = $@;
1291             }
1292              
1293 0 0       0 if($error)
1294             {
1295 16     16   149 no warnings 'uninitialized';
  16         62  
  16         14461  
1296 0         0 $self->error("rollback() - $error " . $dbh->errstr);
1297              
1298 0 0       0 unless($is_active)
1299             {
1300 0 0 0     0 if($dbh->{'Driver'}{'Name'} eq 'mysql' && $dbh->{'Driver'}{'Version'} < 4.012)
1301             {
1302 0         0 $self->error($self->error . '; Also, the database handle did not ' .
1303             'have Active set to a true value. DBD::mysql versions before 4.012 ' .
1304             'may fail to set Active back to 1 when the mysql_auto_reconnect is ' .
1305             'set. Try upgrading to DBD::mysql 4.012 or later');
1306             }
1307              
1308 0         0 return 0;
1309             }
1310              
1311 0         0 return undef;
1312             }
1313              
1314 0 0 0     0 unless($ret || $ac)
1315             {
1316 0         0 $self->error('rollback() failed - ' . $dbh->errstr);
1317 0         0 return undef;
1318             }
1319              
1320             # DBI does this for me...
1321             #$dbh->{'AutoCommit'} = 1;
1322              
1323 0         0 return 1;
1324             }
1325              
1326             sub do_transaction
1327             {
1328 0     0 1 0 my($self, $code) = (shift, shift);
1329              
1330 0 0       0 my $dbh = $self->dbh or return undef;
1331              
1332 0         0 my $error;
1333              
1334             TRY:
1335             {
1336 0         0 local $@;
  0         0  
1337              
1338             eval
1339 0         0 {
1340 0 0       0 $self->begin_work or die $self->error;
1341 0         0 $code->(@_);
1342 0 0       0 $self->commit or die $self->error;
1343             };
1344              
1345 0         0 $error = $@;
1346             }
1347              
1348 0 0       0 if($error)
1349             {
1350 0 0       0 $error = ref $error ? $error : "do_transaction() failed - $error";
1351              
1352 0 0       0 if($self->rollback)
1353             {
1354 0         0 $self->error($error);
1355             }
1356             else
1357             {
1358 0         0 $self->error("$error. rollback() also failed - " . $self->error)
1359             }
1360              
1361 0         0 return undef;
1362             }
1363              
1364 0         0 return 1;
1365             }
1366              
1367             sub auto_quote_table_name
1368             {
1369 0     0 0 0 my($self, $name) = @_;
1370              
1371 0 0 0     0 if($name =~ /\W/ || $self->is_reserved_word($name))
1372             {
1373 0         0 return $self->quote_table_name($name, @_);
1374             }
1375              
1376 0         0 return $name;
1377             }
1378              
1379             sub auto_quote_column_name
1380             {
1381 0     0 0 0 my($self, $name) = @_;
1382              
1383 0 0 0     0 if($name =~ /\W/ || $self->is_reserved_word($name))
1384             {
1385 0         0 return $self->quote_column_name($name, @_);
1386             }
1387              
1388 0         0 return $name;
1389             }
1390              
1391             sub quote_column_name
1392             {
1393 0     0 1 0 my $name = $_[1];
1394 0         0 $name =~ s/"/""/g;
1395 0         0 return qq("$name");
1396             }
1397              
1398             sub quote_table_name
1399             {
1400 0     0 0 0 my $name = $_[1];
1401 0         0 $name =~ s/"/""/g;
1402 0         0 return qq("$name");
1403             }
1404              
1405             sub unquote_column_name
1406             {
1407 0     0 0 0 my($self_or_class, $name) = @_;
1408              
1409 16     16   144 no warnings 'uninitialized';
  16         36  
  16         6026  
1410              
1411             # handle quoted strings with quotes doubled inside them
1412 0 0       0 if($name =~ /^(['"`])(.+)\1$/)
1413             {
1414 0         0 my $q = $1;
1415 0         0 $name = $2;
1416 0         0 $name =~ s/$q$q/$q/g;
1417             }
1418              
1419 0         0 return $name;
1420             }
1421              
1422             *unquote_table_name = \&unquote_column_name;
1423              
1424             #sub is_reserved_word { 0 }
1425              
1426             *is_reserved_word = \&SQL::ReservedWords::is_reserved;
1427              
1428             BEGIN
1429             {
1430             sub quote_identifier_dbi
1431             {
1432 0     0 0 0 my($self) = shift;
1433 0 0       0 my $dbh = $self->dbh or die $self->error;
1434 0         0 return $dbh->quote_identifier(@_);
1435             }
1436              
1437             sub quote_identifier_fallback
1438             {
1439 0     0 0 0 my($self, $catalog, $schema, $table) = @_;
1440 0         0 return join('.', map { qq("$_") } grep { defined } ($schema, $table));
  0         0  
  0         0  
1441             }
1442              
1443 16 50   16   243 if($DBI::VERSION >= 1.21)
1444             {
1445 16         7622 *quote_identifier = \&quote_identifier_dbi;
1446             }
1447             else
1448             {
1449 0         0 *quote_identifier = \&quote_identifier_fallback;
1450             }
1451             }
1452              
1453             *quote_identifier_for_sequence = \&quote_identifier;
1454              
1455             sub quote_column_with_table
1456             {
1457 0     0 0 0 my($self, $column, $table) = @_;
1458              
1459 0 0       0 return $table ?
1460             $self->quote_table_name($table) . '.' .
1461             $self->quote_column_name($column) :
1462             $self->quote_column_name($column);
1463             }
1464              
1465             sub auto_quote_column_with_table
1466             {
1467 0     0 0 0 my($self, $column, $table) = @_;
1468              
1469 0 0       0 return $table ?
1470             $self->auto_quote_table_name($table) . '.' .
1471             $self->auto_quote_column_name($column) :
1472             $self->auto_quote_column_name($column);
1473             }
1474              
1475             sub has_primary_key
1476             {
1477 0     0 1 0 my($self) = shift;
1478 0         0 my $columns = $self->primary_key_column_names(@_);
1479 0 0 0     0 return (ref $columns && @$columns) ? 1 : 0;
1480             }
1481              
1482             sub primary_key_column_names
1483             {
1484 0     0 1 0 my($self) = shift;
1485              
1486 0 0       0 my %args = @_ == 1 ? (table => @_) : @_;
1487              
1488 0 0       0 my $table = $args{'table'} or Carp::croak "Missing table name parameter";
1489 0   0     0 my $catalog = $args{'catalog'} || $self->catalog;
1490 0   0     0 my $schema = $args{'schema'} || $self->schema;
1491              
1492 0 0       0 $schema = $self->default_implicit_schema unless(defined $schema);
1493              
1494 0 0       0 $table = lc $table if($self->likes_lowercase_table_names);
1495              
1496 0 0 0     0 $schema = lc $schema
1497             if(defined $schema && $self->likes_lowercase_schema_names);
1498              
1499 0 0 0     0 $catalog = lc $catalog
1500             if(defined $catalog && $self->likes_lowercase_catalog_names);
1501              
1502 0         0 my $table_unquoted = $self->unquote_table_name($table);
1503              
1504 0         0 my $columns;
1505              
1506             my $error;
1507              
1508             TRY:
1509             {
1510 0         0 local $@;
  0         0  
1511              
1512             eval
1513 0         0 {
1514 0         0 $columns =
1515             $self->_get_primary_key_column_names($catalog, $schema, $table_unquoted);
1516             };
1517              
1518 0         0 $error = $@;
1519             }
1520              
1521 0 0 0     0 if($error || !$columns)
1522             {
1523 16     16   141 no warnings 'uninitialized'; # undef strings okay
  16         50  
  16         3992  
1524 0 0       0 $error = 'no primary key columns found' unless(defined $error);
1525 0         0 Carp::croak "Could not get primary key columns for catalog '" .
1526             $catalog . "' schema '" . $schema . "' table '" .
1527             $table_unquoted . "' - " . $error;
1528             }
1529              
1530 0 0       0 return wantarray ? @$columns : $columns;
1531             }
1532              
1533             sub _get_primary_key_column_names
1534             {
1535 0     0   0 my($self, $catalog, $schema, $table) = @_;
1536              
1537 0 0       0 my $dbh = $self->dbh or die $self->error;
1538              
1539 0         0 local $dbh->{'FetchHashKeyName'} = 'NAME';
1540              
1541 0         0 my $sth = $dbh->primary_key_info($catalog, $schema, $table);
1542              
1543 0 0       0 unless(defined $sth)
1544             {
1545 16     16   123 no warnings 'uninitialized'; # undef strings okay
  16         77  
  16         2043  
1546 0         0 $self->error("No primary key information found for catalog '", $catalog,
1547             "' schema '", $schema, "' table '", $table, "'");
1548 0         0 return [];
1549             }
1550              
1551 0         0 my @columns;
1552              
1553 0         0 my $supports_catalog = $self->supports_catalog;
1554              
1555 0         0 PK: while(my $pk_info = $sth->fetchrow_hashref)
1556             {
1557             CHECK_TABLE: # Make sure this column is from the right table
1558             {
1559 16     16   131 no warnings; # Allow undef coercion to empty string
  16         44  
  16         19992  
  0         0  
1560              
1561             $pk_info->{'TABLE_NAME'} =
1562 0         0 $self->unquote_table_name($pk_info->{'TABLE_NAME'});
1563              
1564             next PK unless((!$supports_catalog || $pk_info->{'TABLE_CAT'} eq $catalog) &&
1565             $pk_info->{'TABLE_SCHEM'} eq $schema &&
1566 0 0 0     0 $pk_info->{'TABLE_NAME'} eq $table);
      0        
      0        
1567             }
1568              
1569 0 0       0 unless(defined $pk_info->{'COLUMN_NAME'})
1570             {
1571 0         0 Carp::croak "Could not extract column name from DBI primary_key_info()";
1572             }
1573              
1574 0         0 push(@columns, $self->unquote_column_name($pk_info->{'COLUMN_NAME'}));
1575             }
1576              
1577 0         0 return \@columns;
1578             }
1579              
1580             #
1581             # These methods could/should be overridden in driver-specific subclasses
1582             #
1583              
1584 0     0 1 0 sub insertid_param { undef }
1585 0     0 0 0 sub null_date { '0000-00-00' }
1586 0     0 0 0 sub null_datetime { '0000-00-00 00:00:00' }
1587 0     0 0 0 sub null_timestamp { '00000000000000' }
1588 0     0 0 0 sub min_timestamp { '00000000000000' }
1589 0     0 0 0 sub max_timestamp { '00000000000000' }
1590              
1591 0     0 1 0 sub last_insertid_from_sth { $_[1]->{$_[0]->insertid_param} }
1592 0   0 0 0 0 sub generate_primary_key_values { (undef) x ($_[1] || 1) }
1593 0   0 0 0 0 sub generate_primary_key_placeholders { (undef) x ($_[1] || 1) }
1594              
1595 0     0 0 0 sub max_column_name_length { 255 }
1596 0     0 0 0 sub max_column_alias_length { 255 }
1597              
1598             # Boolean formatting and parsing
1599              
1600 0 0   0 1 0 sub format_boolean { $_[1] ? 1 : 0 }
1601              
1602             sub parse_boolean
1603             {
1604 0     0 1 0 my($self, $value) = @_;
1605              
1606 0 0 0     0 return $value if($self->validate_boolean_keyword($_[1]) ||
      0        
1607             ($self->keyword_function_calls && $_[1] =~ /^\w+\(.*\)$/));
1608 0 0       0 return 1 if($value =~ /^(?:t(?:rue)?|y(?:es)?|1)$/i);
1609 0 0       0 return 0 if($value =~ /^(?:f(?:alse)?|no?|0)$/i);
1610              
1611 0         0 $self->error("Invalid boolean value: '$value'");
1612 0         0 return undef;
1613             }
1614              
1615             # Date formatting
1616              
1617             sub format_date
1618             {
1619 0     0 1 0 my($self, $date) = @_;
1620 0 0 0     0 return $date
      0        
1621             if($self->validate_date_keyword($date) ||
1622             ($self->keyword_function_calls && $date =~ /^\w+\(.*\)$/));
1623 0         0 return $self->date_handler->format_date($date);
1624             }
1625              
1626             sub format_datetime
1627             {
1628 0     0 1 0 my($self, $date) = @_;
1629 0 0 0     0 return $date if($self->validate_datetime_keyword($date) ||
      0        
1630             ($self->keyword_function_calls && $date =~ /^\w+\(.*\)$/));
1631 0         0 return $self->date_handler->format_datetime($date);
1632             }
1633              
1634 16     16   155 use constant HHMMSS_PRECISION => 6;
  16         36  
  16         1330  
1635 16     16   103 use constant HHMM_PRECISION => 4;
  16         33  
  16         100563  
1636              
1637             sub format_time
1638             {
1639 24     24 1 24572 my($self, $time, $precision) = @_;
1640 24 50 33     78 return $time if($self->validate_time_keyword($time) ||
      33        
1641             ($self->keyword_function_calls && $time =~ /^\w+\(.*\)$/));
1642              
1643 24 50       226 if(defined $precision)
1644             {
1645 0 0       0 if($precision > HHMMSS_PRECISION)
    0          
    0          
1646             {
1647 0         0 my $scale = $precision - HHMMSS_PRECISION;
1648 0         0 return $time->format("%H:%M:%S%${scale}n");
1649             }
1650             elsif($precision == HHMMSS_PRECISION)
1651             {
1652 0         0 return $time->format("%H:%M:%S");
1653             }
1654             elsif($precision == HHMM_PRECISION)
1655             {
1656 0         0 return $time->format("%H:%M");
1657             }
1658             }
1659              
1660             # Punt
1661 24         96 return $time->as_string;
1662             }
1663              
1664             sub format_timestamp
1665             {
1666 0     0 1 0 my($self, $date) = @_;
1667 0 0 0     0 return $date if($self->validate_timestamp_keyword($date) ||
      0        
1668             ($self->keyword_function_calls && $date =~ /^\w+\(.*\)$/));
1669 0         0 return $self->date_handler->format_timestamp($date);
1670             }
1671              
1672             sub format_timestamp_with_time_zone
1673             {
1674 0     0 1 0 my($self, $date) = @_;
1675 0 0 0     0 return $date if($self->validate_timestamp_keyword($date) ||
      0        
1676             ($self->keyword_function_calls && $date =~ /^\w+\(.*\)$/));
1677 0         0 return $self->date_handler->format_timestamp_with_time_zone($date);
1678             }
1679              
1680             # Date parsing
1681              
1682             sub parse_date
1683             {
1684 0     0 1 0 my($self, $value) = @_;
1685              
1686 0 0 0     0 if(UNIVERSAL::isa($value, 'DateTime') || $self->validate_date_keyword($value))
1687             {
1688 0         0 return $value;
1689             }
1690              
1691 0         0 my($dt, $error);
1692              
1693             TRY:
1694             {
1695 0         0 local $@;
  0         0  
1696 0         0 eval { $dt = $self->date_handler->parse_date($value) };
  0         0  
1697 0         0 $error = $@;
1698             }
1699              
1700 0 0       0 if($error)
1701             {
1702 0         0 $self->error("Could not parse date '$value' - $error");
1703 0         0 return undef;
1704             }
1705              
1706 0         0 return $dt;
1707             }
1708              
1709             sub parse_datetime
1710             {
1711 0     0 1 0 my($self, $value) = @_;
1712              
1713 0 0 0     0 if(UNIVERSAL::isa($value, 'DateTime') ||
1714             $self->validate_datetime_keyword($value))
1715             {
1716 0         0 return $value;
1717             }
1718              
1719 0         0 my($dt, $error);
1720              
1721             TRY:
1722             {
1723 0         0 local $@;
  0         0  
1724 0         0 eval { $dt = $self->date_handler->parse_datetime($value) };
  0         0  
1725 0         0 $error = $@;
1726             }
1727              
1728 0 0       0 if($error)
1729             {
1730 0         0 $self->error("Could not parse datetime '$value' - $error");
1731 0         0 return undef;
1732             }
1733              
1734 0         0 return $dt;
1735             }
1736              
1737             sub parse_timestamp
1738             {
1739 0     0 1 0 my($self, $value) = @_;
1740              
1741 0 0 0     0 if(UNIVERSAL::isa($value, 'DateTime') ||
1742             $self->validate_timestamp_keyword($value))
1743             {
1744 0         0 return $value;
1745             }
1746              
1747 0         0 my($dt, $error);
1748              
1749             TRY:
1750             {
1751 0         0 local $@;
  0         0  
1752 0         0 eval { $dt = $self->date_handler->parse_timestamp($value) };
  0         0  
1753 0         0 $error = $@;
1754             }
1755              
1756 0 0       0 if($error)
1757             {
1758 0         0 $self->error("Could not parse timestamp '$value' - $error");
1759 0         0 return undef;
1760             }
1761              
1762 0         0 return $dt;
1763             }
1764              
1765             sub parse_timestamp_with_time_zone
1766             {
1767 0     0 1 0 my($self, $value) = @_;
1768              
1769 0 0 0     0 if(UNIVERSAL::isa($value, 'DateTime') ||
1770             $self->validate_timestamp_keyword($value))
1771             {
1772 0         0 return $value;
1773             }
1774              
1775 0         0 my($dt, $error);
1776              
1777             TRY:
1778             {
1779 0         0 local $@;
  0         0  
1780 0         0 eval { $dt = $self->date_handler->parse_timestamp_with_time_zone($value) };
  0         0  
1781 0         0 $error = $@;
1782             }
1783              
1784 0 0       0 if($error)
1785             {
1786 0         0 $self->error("Could not parse timestamp with time zone '$value' - $error");
1787 0         0 return undef;
1788             }
1789              
1790 0         0 return $dt;
1791             }
1792              
1793             sub parse_time
1794             {
1795 30     30 1 24787 my($self, $value) = @_;
1796              
1797 30 50 33     396 if(!defined $value || UNIVERSAL::isa($value, 'Time::Clock') ||
      33        
      33        
      33        
1798             $self->validate_time_keyword($value) ||
1799             ($self->keyword_function_calls && $value =~ /^\w+\(.*\)$/))
1800             {
1801 0         0 return $value;
1802             }
1803              
1804 30         320 my($time, $error);
1805              
1806             TRY:
1807             {
1808 30         45 local $@;
  30         43  
1809 30         62 eval { $time = Time::Clock->new->parse($value) };
  30         118  
1810 30         4435 $error = $@;
1811             }
1812              
1813 30 100       94 if($error)
1814             {
1815 6         12 my $second_error;
1816              
1817             TRY:
1818             {
1819 6         13 local $@;
  6         10  
1820              
1821             eval
1822 6         14 {
1823 6         51 my $dt = $self->date_handler->parse_time($value);
1824             # Using parse()/strftime() is faster than using the
1825             # Time::Clock constructor and the DateTime accessors.
1826 0         0 $time = Time::Clock->new->parse($dt->strftime('%H:%M:%S.%N'));
1827             };
1828              
1829 6         233 $second_error = $@;
1830             }
1831              
1832 6 50       20 if($second_error)
1833             {
1834 6         52 $self->error("Could not parse time '$value' - Time::Clock::parse() failed " .
1835             "($error) and $second_error");
1836 6         47 return undef;
1837             }
1838             }
1839              
1840 24         204 return $time;
1841             }
1842              
1843             sub parse_bitfield
1844             {
1845 0     0 1 0 my($self, $val, $size) = @_;
1846              
1847 0 0       0 return undef unless(defined $val);
1848              
1849 0 0       0 if(ref $val)
1850             {
1851 0 0 0     0 if($size && $val->Size != $size)
1852             {
1853 0         0 return Bit::Vector->new_Bin($size, $val->to_Bin);
1854             }
1855              
1856 0         0 return $val;
1857             }
1858              
1859 0 0 0     0 if($val =~ /^[10]+$/)
    0 0        
    0          
    0          
1860             {
1861 0   0     0 return Bit::Vector->new_Bin($size || length $val, $val);
1862             }
1863             elsif($val =~ /^\d*[2-9]\d*$/)
1864             {
1865 0   0     0 return Bit::Vector->new_Dec($size || (length($val) * 4), $val);
1866             }
1867             elsif($val =~ s/^0x// || $val =~ s/^X'(.*)'$/$1/ || $val =~ /^[0-9a-f]+$/i)
1868             {
1869 0   0     0 return Bit::Vector->new_Hex($size || (length($val) * 4), $val);
1870             }
1871             elsif($val =~ s/^B'([10]+)'$/$1/i)
1872             {
1873 0   0     0 return Bit::Vector->new_Bin($size || length $val, $val);
1874             }
1875             else
1876             {
1877 0         0 $self->error("Could not parse bitfield value '$val'");
1878 0         0 return undef;
1879             #return Bit::Vector->new_Bin($size || length($val), $val);
1880             }
1881             }
1882              
1883             sub format_bitfield
1884             {
1885 0     0 1 0 my($self, $vec, $size) = @_;
1886              
1887 0 0       0 if($size)
1888             {
1889 0         0 $vec = Bit::Vector->new_Bin($size, $vec->to_Bin);
1890 0         0 return sprintf('%0*b', $size, hex($vec->to_Hex));
1891             }
1892              
1893 0         0 return sprintf('%b', hex($vec->to_Hex));
1894             }
1895              
1896 0     0 0 0 sub select_bitfield_column_sql { shift->auto_quote_column_with_table(@_) }
1897              
1898             sub parse_array
1899             {
1900 0     0 0 0 my($self) = shift;
1901              
1902 0 0       0 return $_[0] if(ref $_[0]);
1903 0 0       0 return [ @_ ] if(@_ > 1);
1904              
1905 0         0 my $val = $_[0];
1906              
1907 0 0       0 return undef unless(defined $val);
1908              
1909 0         0 $val =~ s/^ (?:\[.+\]=)? \{ (.*) \} $/$1/sx;
1910              
1911 0         0 my @array;
1912              
1913 0         0 while($val =~ s/(?:"((?:[^"\\]+|\\.)*)"|([^",]+))(?:,|$)//)
1914             {
1915 0 0       0 my($item) = map { $_ eq 'NULL' ? undef : $_ } (defined $1 ? $1 : $2);
  0 0       0  
1916 0 0       0 $item =~ s{\\(.)}{$1}g if(defined $item);
1917 0         0 push(@array, $item);
1918             }
1919              
1920 0         0 return \@array;
1921             }
1922              
1923             sub format_array
1924             {
1925 0     0 0 0 my($self) = shift;
1926              
1927 0 0 0     0 return undef unless(ref $_[0] || defined $_[0]);
1928              
1929 0 0       0 my @array = (ref $_[0]) ? @{$_[0]} : @_;
  0         0  
1930              
1931             my $str = '{' . join(',', map
1932             {
1933 0 0       0 if(!defined $_)
  0 0       0  
1934             {
1935 0         0 'NULL'
1936             }
1937             elsif(/^[-+]?\d+(?:\.\d*)?$/)
1938             {
1939 0         0 $_
1940             }
1941             else
1942             {
1943 0         0 s/\\/\\\\/g;
1944 0         0 s/"/\\"/g;
1945 0         0 qq("$_")
1946             }
1947             } @array) . '}';
1948              
1949 0 0       0 if(length($str) > $self->max_array_characters)
1950             {
1951 0         0 Carp::croak "Array string is longer than ", ref($self),
1952             "->max_array_characters (", $self->max_array_characters,
1953             ") characters long: $str";
1954             }
1955              
1956 0         0 return $str;
1957             }
1958              
1959             my $Interval_Regex = qr{
1960             (?:\@\s*)?
1961             (?:
1962             (?: (?: \s* ([+-]?) (\d+) : ([0-5]?\d)? (?:: ([0-5]?\d (?:\.\d+)? )? )?)) # (sign)hhh:mm:ss
1963             |
1964             (?: \s* ( [+-]? \d+ (?:\.\d+(?=\s+s))? ) \s+ # quantity
1965             (?: # unit
1966             (?:\b(dec) (?:ades?\b | s?\b)?\b) # decades
1967             | (?:\b(d) (?:ays?\b)?\b) # days
1968             | (?:\b(y) (?:ears?\b)?\b) # years
1969             | (?:\b(h) (?:ours?\b)?\b) # hours
1970             | (?:\b(mon) (?:s\b | ths?\b)?\b) # months
1971             | (?:\b(mil) (?:s\b | lenniums?\b)?\b) # millenniums
1972             | (?:\b(m) (?:inutes?\b | ins?\b)?\b) # minutes
1973             | (?:\b(s) (?:ec(?:s | onds?)?)?\b) # seconds
1974             | (?:\b(w) (?:eeks?\b)?\b) # weeks
1975             | (?:\b(c) (?:ent(?:s | ury | uries)?\b)?\b) # centuries
1976             )
1977             )
1978             )
1979             (?: \s+ (ago) \b)? # direction
1980             | (.+)
1981             }ix;
1982              
1983             sub parse_interval
1984             {
1985 76     76 1 56345 my($self, $value, $end_of_month_mode) = @_;
1986              
1987 76 100 33     926 if(!defined $value || UNIVERSAL::isa($value, 'DateTime::Duration') ||
      33        
      100        
      66        
1988             $self->validate_interval_keyword($value) ||
1989             ($self->keyword_function_calls && $value =~ /^\w+\(.*\)$/))
1990             {
1991 2         43 return $value;
1992             }
1993              
1994 74         947 for($value)
1995             {
1996 74         156 s/\A //;
1997 74         135 s/ \z//;
1998 74         699 s/\s+/ /g;
1999             }
2000              
2001 74         216 my(%units, $is_ago, $sign, $error, $dt_duration);
2002              
2003 74         0 my $value_pos;
2004              
2005 74   66     965 while(!$error && $value =~ /$Interval_Regex/go)
2006             {
2007 218         407 $value_pos = pos($value);
2008              
2009 218 100       588 $is_ago = 1 if($16);
2010              
2011 218 100 100     2045 if($2 || $3 || $4)
    100 66        
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
    100          
2012             {
2013 22 100 100     120 if($sign || defined $units{'hours'} || defined $units{'minutes'} ||
      66        
      100        
2014             defined $units{'seconds'})
2015             {
2016 10         15 $error = 1;
2017 10         22 last;
2018             }
2019              
2020 12 100 66     48 $sign = ($1 && $1 eq '-') ? -1 : 1;
2021              
2022 12         28 my $secs = $4;
2023              
2024 12 50 33     28 if(defined $secs && $secs != int($secs))
2025             {
2026 0         0 my $fsecs = substr($secs, index($secs, '.') + 1);
2027 0         0 $secs = int($secs);
2028              
2029 0         0 my $len = length $fsecs;
2030              
2031 0 0       0 if($len < 9)
    0          
2032             {
2033 0         0 $fsecs .= ('0' x (9 - length $fsecs));
2034             }
2035             elsif($len > 9)
2036             {
2037 0         0 $fsecs = substr($fsecs, 0, 9);
2038             }
2039              
2040 0         0 $units{'nanoseconds'} = $sign * $fsecs;
2041             }
2042              
2043 12   100     56 $units{'hours'} = $sign * ($2 || 0);
2044 12   100     57 $units{'minutes'} = $sign * ($3 || 0);
2045 12   50     143 $units{'seconds'} = $sign * ($secs || 0);
2046             }
2047             elsif($6)
2048             {
2049 10 50       27 if($units{'decades'}) { $error = 1; last }
  0         0  
  0         0  
2050 10         125 $units{'decades'} = $5;
2051             }
2052             elsif(defined $7)
2053             {
2054 28 100       70 if($units{'days'}) { $error = 1; last }
  2         6  
  2         7  
2055 26         213 $units{'days'} = $5;
2056             }
2057             elsif(defined $8)
2058             {
2059 20 50       60 if($units{'years'}) { $error = 1; last }
  0         0  
  0         0  
2060 20         233 $units{'years'} = $5;
2061             }
2062             elsif(defined $9)
2063             {
2064 18 50       48 if($units{'hours'}) { $error = 1; last }
  0         0  
  0         0  
2065 18         211 $units{'hours'} = $5;
2066             }
2067             elsif(defined $10)
2068             {
2069 14 50       43 if($units{'months'}) { $error = 1; last }
  0         0  
  0         0  
2070 14         136 $units{'months'} = $5;
2071             }
2072             elsif(defined $11)
2073             {
2074 14 50       50 if($units{'millenniums'}) { $error = 1; last }
  0         0  
  0         0  
2075 14         185 $units{'millenniums'} = $5;
2076             }
2077             elsif(defined $12)
2078             {
2079 22 50       56 if($units{'minutes'}) { $error = 1; last }
  0         0  
  0         0  
2080 22         239 $units{'minutes'} = $5;
2081             }
2082             elsif(defined $13)
2083             {
2084 26 50       69 if($units{'seconds'}) { $error = 1; last }
  0         0  
  0         0  
2085              
2086 26         77 my $secs = $5;
2087              
2088 26         107 $units{'seconds'} = int($secs);
2089              
2090 26 100       176 if($units{'seconds'} != $secs)
2091             {
2092 2         11 my $fsecs = substr($secs, index($secs, '.') + 1);
2093              
2094 2         7 my $len = length $fsecs;
2095              
2096 2 50       11 if($len < 9)
    0          
2097             {
2098 2         10 $fsecs .= ('0' x (9 - length $fsecs));
2099             }
2100             elsif($len > 9)
2101             {
2102 0         0 $fsecs = substr($fsecs, 0, 9);
2103             }
2104              
2105 2         15 $units{'nanoseconds'} = $fsecs;
2106             }
2107             }
2108             elsif(defined $14)
2109             {
2110 10 50       31 if($units{'weeks'}) { $error = 1; last }
  0         0  
  0         0  
2111 10         99 $units{'weeks'} = $5;
2112             }
2113             elsif(defined $15)
2114             {
2115 10 50       29 if($units{'centuries'}) { $error = 1; last }
  0         0  
  0         0  
2116 10         110 $units{'centuries'} = $5;
2117             }
2118             elsif(defined $17)
2119             {
2120 22         43 $error = 1;
2121 22         48 last;
2122             }
2123             }
2124              
2125 74 100       157 if($error)
2126             {
2127 34         203 $self->error("Could not parse interval '$value' - found overlaping time units");
2128 34         174 return undef;
2129             }
2130              
2131 40 50       88 if($value_pos != length($value))
2132             {
2133 0         0 $self->error("Could not parse interval '$value' - could not interpret all tokens");
2134 0         0 return undef;
2135             }
2136              
2137 40 100       86 if(defined $units{'millenniums'})
2138             {
2139 14         49 $units{'years'} += 1000 * $units{'millenniums'};
2140 14         38 delete $units{'millenniums'};
2141             }
2142              
2143 40 100       111 if(defined $units{'centuries'})
2144             {
2145 10         20 $units{'years'} += 100 * $units{'centuries'};
2146 10         22 delete $units{'centuries'};
2147             }
2148              
2149 40 100       111 if(defined $units{'decades'})
2150             {
2151 10         18 $units{'years'} += 10 * $units{'decades'};
2152 10         13 delete $units{'decades'};
2153             }
2154              
2155 40 100 100     157 if($units{'hours'} || $units{'minutes'} || $units{'seconds'})
      100        
2156             {
2157             my $seconds = ($units{'hours'} || 0) * 60 * 60 +
2158             ($units{'minutes'} || 0) * 60 +
2159 24   100     212 ($units{'seconds'} || 0);
      100        
      100        
2160 24         64 $units{'hours'} = int($seconds / 3600);
2161 24         43 $seconds -= $units{'hours'} * 3600;
2162 24         42 $units{'minutes'} = int($seconds / 60);
2163 24         46 $units{'seconds'} = $seconds - $units{'minutes'} * 60;
2164             }
2165              
2166 40 50       81 $units{'end_of_month'} = $end_of_month_mode if(defined $end_of_month_mode);
2167              
2168 40 100       294 $dt_duration = $is_ago ?
2169             DateTime::Duration->new(%units)->inverse :
2170             DateTime::Duration->new(%units);
2171              
2172             # XXX: Ugly hack workaround for DateTime::Duration bug (RT 53985)
2173 40 50 66     6664 if($is_ago && defined $end_of_month_mode &&
      33        
2174             $dt_duration->end_of_month_mode ne $end_of_month_mode)
2175             {
2176 0         0 $dt_duration->{'end_of_month'} = $end_of_month_mode;
2177             }
2178              
2179 40         221 return $dt_duration;
2180             }
2181              
2182             sub format_interval
2183             {
2184 74     74 1 2691 my($self, $dur) = @_;
2185              
2186 74 50 66     238 if(!defined $dur || $self->validate_interval_keyword($dur) ||
      66        
      66        
2187             ($self->keyword_function_calls && $dur =~ /^\w+\(.*\)$/))
2188             {
2189 34         196 return $dur;
2190             }
2191              
2192 40         551 my $output = '';
2193              
2194 40         79 my(%deltas, %unit, $neg);
2195              
2196 40         144 @deltas{qw/years mons days h m s/} =
2197             $dur->in_units(qw/years months days hours minutes seconds/);
2198              
2199 40         2508 foreach (qw/years mons days/)
2200             {
2201 120         227 $unit{$_} = $_;
2202 120 100       339 $unit{$_} =~ s/s\z// if $deltas{$_} == 1;
2203             }
2204              
2205 40 100       126 $output .= "$deltas{'years'} $unit{'years'} " if($deltas{'years'});
2206 40 100       90 $neg = 1 if($deltas{'years'} < 0);
2207              
2208 40 50 66     115 $output .= '+' if ($neg && $deltas{'mons'} > 0);
2209 40 100       111 $output .= "$deltas{'mons'} $unit{'mons'} " if($deltas{'mons'});
2210             $neg = $deltas{'mons'} < 0 ? 1 :
2211 40 100       122 $deltas{'mons'} ? 0 :
    100          
2212             $neg;
2213              
2214 40 100 100     121 $output .= '+' if($neg && $deltas{'days'} > 0);
2215 40 100       105 $output .= "$deltas{'days'} $unit{'days'} " if($deltas{'days'});
2216              
2217 40 100 100     179 if($deltas{'h'} || $deltas{'m'} || $deltas{'s'} || $dur->nanoseconds)
      100        
      100        
2218             {
2219             $neg = $deltas{'days'} < 0 ? 1 :
2220 26 100       160 $deltas{'days'} ? 0 :
    100          
2221             $neg;
2222              
2223 26 100 66     124 if($neg && (($deltas{'h'} > 0) || (!$deltas{'h'} && $deltas{'m'} > 0) ||
      100        
2224             (!$deltas{'h'} && !$deltas{'m'} && $deltas{'s'} > 0)))
2225             {
2226 4         37 $output .= '+';
2227             }
2228              
2229 26         73 my $nsec = $dur->nanoseconds;
2230              
2231 26 100 66     962 $output .= '-' if(!$deltas{'h'} && ($deltas{'m'} < 0 || $deltas{'s'} < 0));
      66        
2232 26         70 @deltas{qw/m s/} = (abs($deltas{'m'}), abs($deltas{'s'}));
2233 52         266 $deltas{'hms'} = join(':', map { sprintf('%.2d', $deltas{$_}) } (qw/h m/)) .
2234             ($nsec ? sprintf(':%02d.%09d', $deltas{'s'}, $nsec) :
2235 26 100       41 sprintf(':%02d', $deltas{'s'}));
2236              
2237 26 50       90 $output .= "$deltas{'hms'}" if($deltas{'hms'});
2238             }
2239              
2240 40         762 $output =~ s/ \z//;
2241              
2242 40 100       161 if(length($output) > $self->max_interval_characters)
2243             {
2244 2         77 Carp::croak "Interval string is longer than ", ref($self),
2245             "->max_interval_characters (", $self->max_interval_characters,
2246             ") characters long: $output";
2247             }
2248              
2249 38         2036 return $output;
2250             }
2251              
2252 0     0 0 0 sub build_dsn { 'override in subclass' }
2253              
2254 0     0 0 0 sub validate_integer_keyword { 0 }
2255 0     0 0 0 sub validate_float_keyword { 0 }
2256 0     0 0 0 sub validate_numeric_keyword { 0 }
2257 0     0 0 0 sub validate_decimal_keyword { 0 }
2258 0     0 0 0 sub validate_double_precision_keyword { 0 }
2259 0     0 0 0 sub validate_bigint_keyword { 0 }
2260 0     0 1 0 sub validate_date_keyword { 0 }
2261 0     0 1 0 sub validate_datetime_keyword { 0 }
2262 54     54 1 384 sub validate_time_keyword { 0 }
2263 0     0 1 0 sub validate_timestamp_keyword { 0 }
2264 116     116 1 736 sub validate_interval_keyword { 0 }
2265 0     0 0 0 sub validate_set_keyword { 0 }
2266 0     0 0 0 sub validate_array_keyword { 0 }
2267 0     0 0 0 sub validate_bitfield_keyword { 0 }
2268              
2269             sub validate_boolean_keyword
2270             {
2271 16     16   204 no warnings 'uninitialized';
  16         52  
  16         2691  
2272 0     0 1 0 $_[1] =~ /^(?:TRUE|FALSE)$/;
2273             }
2274              
2275             sub should_inline_keyword
2276             {
2277 16     16   147 no warnings 'uninitialized';
  16         40  
  16         6624  
2278 0 0   0 0 0 ($_[1] =~ /^\w+\(.*\)$/) ? 1 : 0;
2279             }
2280              
2281             BEGIN
2282             {
2283 16     16   99 *should_inline_integer_keyword = \&should_inline_keyword;
2284 16         65 *should_inline_float_keyword = \&should_inline_keyword;
2285 16         52 *should_inline_decimal_keyword = \&should_inline_keyword;
2286 16         37 *should_inline_numeric_keyword = \&should_inline_keyword;
2287 16         38 *should_inline_double_precision_keyword = \&should_inline_keyword;
2288 16         34 *should_inline_bigint_keyword = \&should_inline_keyword;
2289 16         46 *should_inline_date_keyword = \&should_inline_keyword;
2290 16         34 *should_inline_datetime_keyword = \&should_inline_keyword;
2291 16         38 *should_inline_time_keyword = \&should_inline_keyword;
2292 16         36 *should_inline_timestamp_keyword = \&should_inline_keyword;
2293 16         32 *should_inline_interval_keyword = \&should_inline_keyword;
2294 16         60 *should_inline_set_keyword = \&should_inline_keyword;
2295 16         34 *should_inline_array_keyword = \&should_inline_keyword;
2296 16         31 *should_inline_boolean_keyword = \&should_inline_keyword;
2297 16         44748 *should_inline_bitfield_value = \&should_inline_keyword;
2298             }
2299              
2300             sub next_value_in_sequence
2301             {
2302 0     0 0 0 my($self, $seq) = @_;
2303 0         0 $self->error("Don't know how to select next value in sequence '$seq' " .
2304             "for database driver " . $self->driver);
2305 0         0 return undef;
2306             }
2307              
2308             sub current_value_in_sequence
2309             {
2310 0     0 0 0 my($self, $seq) = @_;
2311 0         0 $self->error("Don't know how to select current value in sequence '$seq' " .
2312             "for database driver " . $self->driver);
2313 0         0 return undef;
2314             }
2315              
2316             sub sequence_exists
2317             {
2318 0     0 0 0 my($self, $seq) = @_;
2319 0         0 $self->error("Don't know how to tell if sequence '$seq' exists " .
2320             "for database driver " . $self->driver);
2321 0         0 return undef;
2322             }
2323              
2324 0     0 0 0 sub auto_sequence_name { undef }
2325              
2326 0     0 0 0 sub supports_multi_column_count_distinct { 1 }
2327 0     0 0 0 sub supports_nested_joins { 1 }
2328 0     0 0 0 sub supports_limit_with_offset { 1 }
2329 0     0 0 0 sub supports_arbitrary_defaults_on_insert { 0 }
2330 0     0 0 0 sub supports_select_from_subselect { 0 }
2331 0     0 0 0 sub format_select_from_subselect { "(\n$_[1]\n )" }
2332              
2333 0     0 0 0 sub likes_redundant_join_conditions { 0 }
2334 0     0 0 0 sub likes_lowercase_table_names { 0 }
2335 0     0 0 0 sub likes_uppercase_table_names { 0 }
2336 0     0 0 0 sub likes_lowercase_schema_names { 0 }
2337 0     0 0 0 sub likes_uppercase_schema_names { 0 }
2338 0     0 0 0 sub likes_lowercase_catalog_names { 0 }
2339 0     0 0 0 sub likes_uppercase_catalog_names { 0 }
2340 0     0 0 0 sub likes_lowercase_sequence_names { 0 }
2341 0     0 0 0 sub likes_uppercase_sequence_names { 0 }
2342 0     0 0 0 sub likes_implicit_joins { 0 }
2343              
2344 0     0 0 0 sub supports_schema { 0 }
2345 0     0 0 0 sub supports_catalog { 0 }
2346              
2347 0     0 0 0 sub use_auto_sequence_name { 0 }
2348              
2349             sub format_limit_with_offset
2350             {
2351 0     0 0 0 my($self, $limit, $offset, $args) = @_;
2352              
2353 0         0 delete $args->{'limit'};
2354 0         0 delete $args->{'offset'};
2355              
2356 0 0       0 if(defined $offset)
2357             {
2358 0         0 $args->{'limit_suffix'} = "LIMIT $limit OFFSET $offset";
2359             }
2360             else
2361             {
2362 0         0 $args->{'limit_suffix'} = "LIMIT $limit";
2363             }
2364             }
2365              
2366             sub format_table_with_alias
2367             {
2368             #my($self, $table, $alias, $hints) = @_;
2369 0     0 0 0 return "$_[1] $_[2]";
2370             }
2371              
2372             sub format_select_start_sql
2373             {
2374 0     0 0 0 my($self, $hints) = @_;
2375 0 0       0 return 'SELECT' unless($hints);
2376 0 0       0 return 'SELECT ' . ($hints->{'comment'} ? "/* $hints->{'comment'} */" : '');
2377             }
2378              
2379 0     0 0 0 sub format_select_lock { '' }
2380              
2381             sub column_sql_from_lock_on_value
2382             {
2383 0     0 0 0 my($self, $object_or_class, $name, $tables) = @_;
2384              
2385 0         0 my %map;
2386              
2387 0 0       0 if($tables)
2388             {
2389 0         0 my $tn = 1;
2390              
2391 0         0 foreach my $table (@$tables)
2392             {
2393 0         0 (my $table_key = $table) =~ s/^(["']?)[^.]+\1\.//;
2394 0         0 $map{$table_key} = 't' . $tn++;
2395             }
2396             }
2397              
2398 0         0 my $table;
2399 0         0 my $chase_meta = $object_or_class->meta;
2400              
2401             # Chase down multi-level keys: e.g., products.vendor.name
2402 0         0 while($name =~ /\G([^.]+)(\.|$)/g)
2403             {
2404 0         0 my($sub_name, $more) = ($1, $2);
2405              
2406 0   0     0 my $key = $chase_meta->foreign_key($sub_name) ||
2407             $chase_meta->relationship($sub_name);
2408              
2409 0 0       0 if($key)
2410             {
2411 0 0       0 $chase_meta = $key->can('foreign_class') ?
2412             $key->foreign_class->meta : $key->class->meta;
2413              
2414 0         0 $table = $chase_meta->table;
2415             }
2416             else
2417             {
2418 0 0       0 if($more)
2419             {
2420 0         0 Carp::confess 'Invalid lock => { on => ... } argument: ',
2421             "no foreign key or relationship named '$sub_name' ",
2422             'found in ', $chase_meta->class;
2423             }
2424             else
2425             {
2426 0         0 my $column = $sub_name;
2427              
2428 0 0       0 if($table)
2429             {
2430 0 0       0 $table = $map{$table} if(defined $map{$table});
2431 0         0 return $self->auto_quote_column_with_table($column, $table);
2432             }
2433             else
2434             {
2435 0         0 return $self->auto_quote_column_name($column);
2436             }
2437             }
2438             }
2439             }
2440              
2441 0         0 Carp::confess "Invalid lock => { on => ... } argument: $name";
2442             }
2443              
2444             sub table_sql_from_lock_on_value
2445             {
2446 0     0 0 0 my($self, $object_or_class, $name, $tables) = @_;
2447              
2448 0         0 my %map;
2449              
2450 0 0       0 if($tables)
2451             {
2452 0         0 my $tn = 1;
2453              
2454 0         0 foreach my $table (@$tables)
2455             {
2456 0         0 (my $table_key = $table) =~ s/^(["']?)[^.]+\1\.//;
2457 0         0 $map{$table_key} = 't' . $tn++;
2458             }
2459             }
2460              
2461 0         0 my $table;
2462 0         0 my $chase_meta = $object_or_class->meta;
2463              
2464             # Chase down multi-level keys: e.g., products.vendor.location
2465 0         0 while($name =~ /\G([^.]+)(\.|$)/g)
2466             {
2467 0         0 my($sub_name, $more) = ($1, $2);
2468              
2469 0   0     0 my $key = $chase_meta->foreign_key($sub_name) ||
2470             $chase_meta->relationship($sub_name);
2471              
2472 0 0 0     0 if($key || !$more)
2473             {
2474 0 0       0 if($key)
2475             {
2476 0 0       0 $chase_meta = $key->can('foreign_class') ?
2477             $key->foreign_class->meta : $key->class->meta;
2478              
2479 0         0 $table = $chase_meta->table;
2480             }
2481             else
2482             {
2483 0         0 $table = $sub_name;
2484             }
2485              
2486 0 0       0 next if($more);
2487              
2488 0 0       0 $table = $map{$table} if(defined $map{$table});
2489 0         0 return $self->auto_quote_table_name($table);
2490             }
2491             else
2492             {
2493 0         0 Carp::confess 'Invalid lock => { on => ... } argument: ',
2494             "no foreign key or relationship named '$sub_name' ",
2495             'found in ', $chase_meta->class;
2496             }
2497             }
2498              
2499 0         0 Carp::confess "Invalid lock => { on => ... } argument: $name";
2500             }
2501              
2502 0     0 0 0 sub supports_on_duplicate_key_update { 0 }
2503              
2504             #
2505             # DBI introspection
2506             #
2507              
2508             sub refine_dbi_column_info
2509             {
2510 0     0 0 0 my($self, $col_info) = @_;
2511              
2512             # Parse odd default value syntaxes
2513             $col_info->{'COLUMN_DEF'} =
2514 0         0 $self->parse_dbi_column_info_default($col_info->{'COLUMN_DEF'}, $col_info);
2515              
2516             # Make sure the data type name is lowercase
2517 0         0 $col_info->{'TYPE_NAME'} = lc $col_info->{'TYPE_NAME'};
2518              
2519             # Unquote column name
2520 0         0 $col_info->{'COLUMN_NAME'} = $self->unquote_column_name($col_info->{'COLUMN_NAME'});
2521              
2522 0         0 return;
2523             }
2524              
2525             sub refine_dbi_foreign_key_info
2526             {
2527 0     0 0 0 my($self, $fk_info) = @_;
2528              
2529             # Unquote names
2530 0         0 foreach my $name (qw(NAME COLUMN_NAME DATA_TYPE TABLE_NAME TABLE_CAT TABLE_SCHEM))
2531             {
2532 0         0 foreach my $prefix (qw(FK_ UK_))
2533             {
2534 0         0 my $param = $prefix . $name;
2535             $fk_info->{$param} = $self->unquote_column_name($fk_info->{$param})
2536 0 0       0 if(exists $fk_info->{$param});
2537             }
2538             }
2539              
2540 0         0 return;
2541             }
2542              
2543 0     0 0 0 sub parse_dbi_column_info_default { $_[1] }
2544              
2545             sub list_tables
2546             {
2547 0     0 1 0 my($self, %args) = @_;
2548              
2549 0 0       0 my $types = $args{'include_views'} ? "'TABLE','VIEW'" : 'TABLE';
2550              
2551 0         0 my(@tables, $error);
2552              
2553             TRY:
2554             {
2555 0         0 local $@;
  0         0  
2556              
2557             eval
2558 0         0 {
2559 0 0       0 my $dbh = $self->dbh or die $self->error;
2560              
2561 0         0 local $dbh->{'RaiseError'} = 1;
2562 0         0 local $dbh->{'FetchHashKeyName'} = 'NAME';
2563              
2564 0         0 my $sth = $dbh->table_info($self->catalog, $self->schema, '%', $types);
2565              
2566 0         0 $sth->execute;
2567              
2568 0         0 while(my $table_info = $sth->fetchrow_hashref)
2569             {
2570 0         0 push(@tables, $table_info->{'TABLE_NAME'})
2571             }
2572             };
2573              
2574 0         0 $error = $@;
2575             }
2576              
2577 0 0       0 if($error)
2578             {
2579 0         0 Carp::croak "Could not list tables from ", $self->dsn, " - $error";
2580             }
2581              
2582 0 0       0 return wantarray ? @tables : \@tables;
2583             }
2584              
2585             #
2586             # Setup overrides
2587             #
2588              
2589             # - Rose::DB development init file - Perl code
2590             # - Rose::DB fixup rc file - YAML format
2591              
2592             sub auto_load_fixups
2593             {
2594 0     0 1 0 my($class) = shift;
2595              
2596             # Load a file full of fix-ups for the data sources (usually just passwords)
2597             # from a "well-known" (or at least "well-specified") location.
2598 0         0 my $fixup_file = $ENV{'ROSEDBRC'};
2599 0 0 0     0 $fixup_file = '/etc/rosedbrc' unless(defined $fixup_file && -e $fixup_file);
2600              
2601 0 0       0 if(-e $fixup_file)
2602             {
2603 0 0       0 if(-r $fixup_file)
2604             {
2605 0         0 $class->load_yaml_fixup_file($fixup_file);
2606             }
2607             else
2608             {
2609 0         0 warn "Cannot read Rose::DB fixup file '$fixup_file'";
2610             }
2611             }
2612              
2613             # Load a file or package full of arbitrary Perl used to alter the data
2614             # source registry. This is intended for use in development only.
2615 0         0 my $rosedb_devinit = $ENV{'ROSEDB_DEVINIT'};
2616              
2617 0         0 my $error;
2618              
2619 0 0       0 if(defined $rosedb_devinit)
2620             {
2621 0 0       0 if(-e $rosedb_devinit)
2622             {
2623             TRY:
2624             {
2625 0         0 local $@;
  0         0  
2626 0         0 do $rosedb_devinit;
2627 0         0 $error = $@;
2628             }
2629             }
2630             else
2631             {
2632             TRY:
2633             {
2634 0         0 local $@;
  0         0  
2635 0         0 eval qq(require $rosedb_devinit);
2636 0         0 $error = $@;
2637             }
2638              
2639 0 0       0 if($rosedb_devinit->can('fixup'))
2640             {
2641 0         0 $rosedb_devinit->fixup($class);
2642             }
2643             }
2644             }
2645              
2646 0 0 0     0 if($error || !defined $rosedb_devinit)
2647             {
2648 0         0 my $username;
2649              
2650             # The getpwuid() function is often(?) unimplemented in perl on Windows
2651             TRY:
2652             {
2653 0         0 local $@;
  0         0  
2654 0         0 eval { $username = lc getpwuid($<) };
  0         0  
2655 0         0 $error = $@;
2656             }
2657              
2658 0 0       0 unless($error)
2659             {
2660 0         0 $rosedb_devinit = "Rose::DB::Devel::Init::$username";
2661              
2662             TRY:
2663             {
2664 0         0 local $@;
  0         0  
2665 0         0 eval qq(require $rosedb_devinit);
2666 0         0 $error = $@;
2667             }
2668              
2669 0 0       0 if($error)
2670             {
2671             TRY:
2672             {
2673 0         0 local $@;
  0         0  
2674 0         0 eval { do $rosedb_devinit };
  0         0  
2675 0         0 $error = $@;
2676             }
2677             }
2678             else
2679             {
2680 0 0       0 if($rosedb_devinit->can('fixup'))
2681             {
2682 0         0 $rosedb_devinit->fixup($class);
2683             }
2684             }
2685             }
2686             }
2687             }
2688              
2689             # YAML syntax example:
2690             #
2691             # ---
2692             # production:
2693             # g3db:
2694             # password: mysecret
2695             # ---
2696             # mqa:
2697             # g3db:
2698             # password: myothersecret
2699              
2700             our $YAML_Class;
2701              
2702             sub load_yaml_fixup_file
2703             {
2704 0     0 0 0 my($class, $file) = @_;
2705              
2706 0         0 my $registry = $class->registry;
2707              
2708 0 0       0 unless($YAML_Class)
2709             {
2710 0         0 my $error;
2711              
2712             TRY:
2713             {
2714 0         0 local $@;
  0         0  
2715 0         0 eval { require YAML::Syck };
  0         0  
2716 0         0 $error = $@;
2717             }
2718              
2719 0 0       0 if($error)
2720             {
2721 0         0 require YAML;
2722             #warn "# Using YAML\n";
2723 0         0 $YAML_Class = 'YAML';
2724             }
2725             else
2726             {
2727             #warn "# Using YAML::Syck\n";
2728 0         0 $YAML_Class = 'YAML::Syck';
2729             }
2730             }
2731              
2732 0 0       0 $Debug && warn "$class - Loading fixups from $file...\n";
2733 16     16   169 no strict 'refs';
  16         35  
  16         11685  
2734 0         0 my @data = &{"${YAML_Class}::LoadFile"}($file);
  0         0  
2735              
2736 0         0 foreach my $data (@data)
2737             {
2738 0         0 foreach my $domain (sort keys %$data)
2739             {
2740 0         0 foreach my $type (sort keys %{$data->{$domain}})
  0         0  
2741             {
2742 0         0 my $entry = $registry->entry(domain => $domain, type => $type);
2743              
2744 0 0       0 unless($entry)
2745             {
2746 0         0 warn "No $class data source found for domain '$domain' ",
2747             "and type '$type'";
2748 0         0 next;
2749             }
2750              
2751 0         0 while(my($method, $value) = each(%{$data->{$domain}{$type}}))
  0         0  
2752             {
2753             #$Debug && warn "$class - $domain:$type - $method = $value\n";
2754 0         0 $entry->$method($value);
2755             }
2756             }
2757             }
2758             }
2759             }
2760              
2761             #
2762             # Storable hooks
2763             #
2764              
2765             sub STORABLE_freeze
2766             {
2767 0     0 0 0 my($self, $cloning) = @_;
2768              
2769 0 0       0 return if($cloning);
2770              
2771             # Ditch the DBI $dbh and pull the password out of its closure
2772 0         0 my $db = { %$self };
2773 0         0 $db->{'dbh'} = undef;
2774 0         0 $db->{'password'} = $self->password;
2775 0         0 $db->{'password_closure'} = undef;
2776              
2777 0         0 require Storable;
2778 0         0 return Storable::freeze($db);
2779             }
2780              
2781             sub STORABLE_thaw
2782             {
2783 0     0 0 0 my($self, $cloning, $serialized) = @_;
2784              
2785 0         0 %$self = %{ Storable::thaw($serialized) };
  0         0  
2786              
2787             # Put the password back in a closure
2788 0         0 my $password = delete $self->{'password'};
2789 0 0   0   0 $self->{'password_closure'} = sub { $password } if(defined $password);
  0         0  
2790             }
2791              
2792             #
2793             # This is both a class and an object method
2794             #
2795              
2796             sub error
2797             {
2798 54     54 1 1698 my($self_or_class) = shift;
2799              
2800 54 100       136 if(ref $self_or_class) # Object method
2801             {
2802 48 100       129 if(@_)
2803             {
2804 44         161 return $self_or_class->{'error'} = $Error = shift;
2805             }
2806 4         24 return $self_or_class->{'error'};
2807             }
2808              
2809             # Class method
2810 6 100       17 return $Error = shift if(@_);
2811 4         21 return $Error;
2812             }
2813              
2814             sub DESTROY
2815             {
2816 68     68   85287 $_[0]->disconnect;
2817             }
2818              
2819             BEGIN
2820 0         0 {
2821             package Rose::DateTime::Format::Generic;
2822              
2823 16     16   157 use Rose::Object;
  16         36  
  16         1125  
2824 16     16   17003 our @ISA = qw(Rose::Object);
2825              
2826             use Rose::Object::MakeMethods::Generic
2827             (
2828 16         156 scalar => 'server_tz',
2829             boolean => 'european',
2830 16     16   135 );
  16         85  
2831              
2832 0     0     sub format_date { shift; Rose::DateTime::Util::format_date($_[0], '%Y-%m-%d') }
  0            
2833 0     0     sub format_datetime { shift; Rose::DateTime::Util::format_date($_[0], '%Y-%m-%d %T') }
  0            
2834 0     0     sub format_timestamp { shift; Rose::DateTime::Util::format_date($_[0], '%Y-%m-%d %H:%M:%S.%N') }
  0            
2835 0     0     sub format_timestamp_with_time_zone { shift->format_timestamp(@_) }
2836              
2837 0     0     sub parse_date { shift; Rose::DateTime::Util::parse_date($_[0], $_[0]->server_tz) }
  0            
2838 0     0     sub parse_datetime { shift; Rose::DateTime::Util::parse_date($_[0], $_[0]->server_tz) }
  0            
2839 0     0     sub parse_timestamp { shift; Rose::DateTime::Util::parse_date($_[0], $_[0]->server_tz) }
  0            
2840 0     0     sub parse_timestamp_with_time_zone { shift->parse_timestamp(@_) }
2841             }
2842              
2843             1;
2844              
2845             __END__
2846              
2847             =encoding utf8
2848              
2849             =head1 NAME
2850              
2851             Rose::DB - A DBI wrapper and abstraction layer.
2852              
2853             =head1 SYNOPSIS
2854              
2855             package My::DB;
2856              
2857             use Rose::DB;
2858             our @ISA = qw(Rose::DB);
2859              
2860             My::DB->register_db(
2861             domain => 'development',
2862             type => 'main',
2863             driver => 'Pg',
2864             database => 'dev_db',
2865             host => 'localhost',
2866             username => 'devuser',
2867             password => 'mysecret',
2868             server_time_zone => 'UTC',
2869             );
2870              
2871             My::DB->register_db(
2872             domain => 'production',
2873             type => 'main',
2874             driver => 'Pg',
2875             database => 'big_db',
2876             host => 'dbserver.acme.com',
2877             username => 'dbadmin',
2878             password => 'prodsecret',
2879             server_time_zone => 'UTC',
2880             );
2881              
2882             My::DB->default_domain('development');
2883             My::DB->default_type('main');
2884             ...
2885              
2886             $db = My::DB->new;
2887              
2888             my $dbh = $db->dbh or die $db->error;
2889              
2890             $db->begin_work or die $db->error;
2891             $dbh->do(...) or die $db->error;
2892             $db->commit or die $db->error;
2893              
2894             $db->do_transaction(sub
2895             {
2896             $dbh->do(...);
2897             $sth = $dbh->prepare(...);
2898             $sth->execute(...);
2899             while($sth->fetch) { ... }
2900             $dbh->do(...);
2901             })
2902             or die $db->error;
2903              
2904             $dt = $db->parse_timestamp('2001-03-05 12:34:56.123');
2905             $val = $db->format_timestamp($dt);
2906              
2907             $dt = $db->parse_datetime('2001-03-05 12:34:56');
2908             $val = $db->format_datetime($dt);
2909              
2910             $dt = $db->parse_date('2001-03-05');
2911             $val = $db->format_date($dt);
2912              
2913             $bit = $db->parse_bitfield('0x0AF', 32);
2914             $val = $db->format_bitfield($bit);
2915              
2916             ...
2917              
2918             =head1 DESCRIPTION
2919              
2920             L<Rose::DB> is a wrapper and abstraction layer for L<DBI>-related functionality. A L<Rose::DB> object "has a" L<DBI> object; it is not a subclass of L<DBI>.
2921              
2922             Please see the L<tutorial|Rose::DB::Tutorial> (perldoc Rose::DB::Tutorial) for an example usage scenario that reflects "best practices" for this module.
2923              
2924             B<Tip:> Are you looking for an object-relational mapper (ORM)? If so, please see the L<Rose::DB::Object> module. L<Rose::DB::Object> is an ORM that uses this module to manage its database connections. L<Rose::DB> alone is simply a data source abstraction layer; it is not an ORM.
2925              
2926             =head1 DATABASE SUPPORT
2927              
2928             L<Rose::DB> currently supports the following L<DBI> database drivers:
2929              
2930             DBD::Pg (PostgreSQL)
2931             DBD::mysql (MySQL)
2932             DBD::MariaDB (MariaDB)
2933             DBD::SQLite (SQLite)
2934             DBD::Informix (Informix)
2935             DBD::Oracle (Oracle)
2936              
2937             L<Rose::DB> will attempt to service an unsupported database using a L<generic|Rose::DB::Generic> implementation that may or may not work. Support for more drivers may be added in the future. Patches are welcome.
2938              
2939             All database-specific behavior is contained and documented in the subclasses of L<Rose::DB>. L<Rose::DB>'s constructor method (L<new()|/new>) returns a database-specific subclass of L<Rose::DB>, chosen based on the L<driver|/driver> value of the selected L<data source|"Data Source Abstraction">. The default mapping of databases to L<Rose::DB> subclasses is:
2940              
2941             DBD::Pg -> Rose::DB::Pg
2942             DBD::mysql -> Rose::DB::MySQL
2943             DBD::MariaDB -> Rose::DB::MariaDB
2944             DBD::SQLite -> Rose::DB::SQLite
2945             DBD::Informix -> Rose::DB::Informix
2946             DBD::Oracle -> Rose::DB::Oracle
2947              
2948             This mapping can be changed using the L<driver_class|/driver_class> class method.
2949              
2950             The L<Rose::DB> object method documentation found here defines the purpose of each method, as well as the default behavior of the method if it is not overridden by a subclass. You must read the subclass documentation to learn about behaviors that are specific to each type of database.
2951              
2952             Subclasses may also add methods that do not exist in the parent class, of course. This is yet another reason to read the documentation for the subclass that corresponds to your data source's database software.
2953              
2954             =head1 FEATURES
2955              
2956             The basic features of L<Rose::DB> are as follows.
2957              
2958             =head2 Data Source Abstraction
2959              
2960             Instead of dealing with "databases" that exist on "hosts" or are located via some vendor-specific addressing scheme, L<Rose::DB> deals with "logical" data sources. Each logical data source is currently backed by a single "physical" database (basically a single L<DBI> connection).
2961              
2962             Multiplexing, fail-over, and other more complex relationships between logical data sources and physical databases are not part of L<Rose::DB>. Some basic types of fail-over may be added to L<Rose::DB> in the future, but right now the mapping is strictly one-to-one. (I'm also currently inclined to encourage multiplexing functionality to exist in a layer above L<Rose::DB>, rather than within it or in a subclass of it.)
2963              
2964             The driver type of the data source determines the functionality of all methods that do vendor-specific things (e.g., L<column value parsing and formatting|"Vendor-Specific Column Value Parsing and Formatting">).
2965              
2966             L<Rose::DB> identifies data sources using a two-level namespace made of a "domain" and a "type". Both are arbitrary strings. If left unspecified, the default domain and default type (accessible via L<Rose::DB>'s L<default_domain|/default_domain> and L<default_type|/default_type> class methods) are assumed.
2967              
2968             There are many ways to use the two-level namespace, but the most common is to use the domain to represent the current environment (e.g., "development", "staging", "production") and then use the type to identify the logical data source within that environment (e.g., "report", "main", "archive")
2969              
2970             A typical deployment scenario will set the default domain using the L<default_domain|/default_domain> class method as part of the configure/install process. Within application code, L<Rose::DB> objects can be constructed by specifying type alone:
2971              
2972             $main_db = Rose::DB->new(type => 'main');
2973             $archive_db = Rose::DB->new(type => 'archive');
2974              
2975             If there is only one database type, then all L<Rose::DB> objects can be instantiated with a bare constructor call like this:
2976              
2977             $db = Rose::DB->new;
2978              
2979             Again, remember that this is just one of many possible uses of domain and type. Arbitrarily complex scenarios can be created by nesting namespaces within one or both parameters (much like how Perl uses "::" to create a multi-level namespace from single strings).
2980              
2981             The important point is the abstraction of data sources so they can be identified and referred to using a vocabulary that is entirely independent of the actual DSN (data source names) used by L<DBI> behind the scenes.
2982              
2983             =head2 Database Handle Life-Cycle Management
2984              
2985             When a L<Rose::DB> object is destroyed while it contains an active L<DBI> database handle, the handle is explicitly disconnected before destruction. L<Rose::DB> supports a simple retain/release reference-counting system which allows a database handle to out-live its parent L<Rose::DB> object.
2986              
2987             In the simplest case, L<Rose::DB> could be used for its data source abstractions features alone. For example, transiently creating a L<Rose::DB> and then retaining its L<DBI> database handle before it is destroyed:
2988              
2989             $main_dbh = Rose::DB->new(type => 'main')->retain_dbh
2990             or die Rose::DB->error;
2991              
2992             $aux_dbh = Rose::DB->new(type => 'aux')->retain_dbh
2993             or die Rose::DB->error;
2994              
2995             If the database handle was simply extracted via the L<dbh|/dbh> method instead of retained with L<retain_dbh|/retain_dbh>, it would be disconnected by the time the statement completed.
2996              
2997             # WRONG: $dbh will be disconnected immediately after the assignment!
2998             $dbh = Rose::DB->new(type => 'main')->dbh or die Rose::DB->error;
2999              
3000             =head2 Vendor-Specific Column Value Parsing and Formatting
3001              
3002             Certain semantically identical column types are handled differently in different databases. Date and time columns are good examples. Although many databases store month, day, year, hours, minutes, and seconds using a "datetime" column type, there will likely be significant differences in how each of those databases expects to receive such values, and how they're returned.
3003              
3004             L<Rose::DB> is responsible for converting the wide range of vendor-specific column values for a particular column type into a single form that is convenient for use within Perl code. L<Rose::DB> also handles the opposite task, taking input from the Perl side and converting it into the appropriate format for a specific database. Not all column types that exist in the supported databases are handled by L<Rose::DB>, but support will expand in the future.
3005              
3006             Many column types are specific to a single database and do not exist elsewhere. When it is reasonable to do so, vendor-specific column types may be "emulated" by L<Rose::DB> for the benefit of other databases. For example, an ARRAY value may be stored as a specially formatted string in a VARCHAR field in a database that does not have a native ARRAY column type.
3007              
3008             L<Rose::DB> does B<NOT> attempt to present a unified column type system, however. If a column type does not exist in a particular kind of database, there should be no expectation that L<Rose::DB> will be able to parse and format that value type on behalf of that database.
3009              
3010             =head2 High-Level Transaction Support
3011              
3012             Transactions may be started, committed, and rolled back in a variety of ways using the L<DBI> database handle directly. L<Rose::DB> provides wrappers to do the same things, but with different error handling and return values. There's also a method (L<do_transaction|/do_transaction>) that will execute arbitrary code within a single transaction, automatically handling rollback on failure and commit on success.
3013              
3014             =head1 SUBCLASSING
3015              
3016             Subclassing is B<strongly encouraged> and generally works as expected. (See the L<tutorial|Rose::DB::Tutorial> for a complete example.) There is, however, the question of how class data is shared with subclasses. Here's how it works for the various pieces of class data.
3017              
3018             =over
3019              
3020             =item B<alias_db>, B<modify_db>, B<register_db>, B<unregister_db>, B<unregister_domain>
3021              
3022             By default, all subclasses share the same data source "registry" with L<Rose::DB>. To provide a private registry for your subclass (the recommended approach), see the example in the documentation for the L<registry|/registry> method below.
3023              
3024             =item B<default_domain>, B<default_type>
3025              
3026             If called with no arguments, and if the attribute was never set for this
3027             class, then a left-most, breadth-first search of the parent classes is
3028             initiated. The value returned is taken from first parent class
3029             encountered that has ever had this attribute set.
3030              
3031             (These attributes use the L<inheritable_scalar|Rose::Class::MakeMethods::Generic/inheritable_scalar> method type as defined in L<Rose::Class::MakeMethods::Generic>.)
3032              
3033             =item B<driver_class, default_connect_options>
3034              
3035             These hashes of attributes are inherited by subclasses using a one-time, shallow copy from a superclass. Any subclass that accesses or manipulates the hash in any way will immediately get its own private copy of the hash I<as it exists in the superclass at the time of the access or manipulation>.
3036              
3037             The superclass from which the hash is copied is the closest ("least super") class that has ever accessed or manipulated this hash. The copy is a "shallow" copy, duplicating only the keys and values. Reference values are not recursively copied.
3038              
3039             Setting to hash to undef (using the 'reset' interface) will cause it to be re-copied from a superclass the next time it is accessed.
3040              
3041             (These attributes use the L<inheritable_hash|Rose::Class::MakeMethods::Generic/inheritable_hash> method type as defined in L<Rose::Class::MakeMethods::Generic>.)
3042              
3043             =back
3044              
3045             =head1 SERIALIZATION
3046              
3047             A L<Rose::DB> object may contain a L<DBI> database handle, and L<DBI> database handles usually don't survive the serialize process intact. L<Rose::DB> objects also hide database passwords inside closures, which also don't serialize well. In order for a L<Rose::DB> object to survive serialization, custom hooks are required.
3048              
3049             L<Rose::DB> has hooks for the L<Storable> serialization module, but there is an important caveat. Since L<Rose::DB> objects are blessed into a dynamically generated class (derived from the L<driver class|/driver_class>), you must load your L<Rose::DB>-derived class with all its registered data sources before you can successfully L<thaw|Storable/thaw> a L<frozen|Storable/freeze> L<Rose::DB>-derived object. Here's an example.
3050              
3051             Imagine that this is your L<Rose::DB>-derived class:
3052              
3053             package My::DB;
3054              
3055             use Rose::DB;
3056             our @ISA = qw(Rose::DB);
3057              
3058             My::DB->register_db(
3059             domain => 'dev',
3060             type => 'main',
3061             driver => 'Pg',
3062             ...
3063             );
3064              
3065             My::DB->register_db(
3066             domain => 'prod',
3067             type => 'main',
3068             driver => 'Pg',
3069             ...
3070             );
3071              
3072             My::DB->default_domain('dev');
3073             My::DB->default_type('main');
3074              
3075             In one program, a C<My::DB> object is L<frozen|Storable/freeze> using L<Storable>:
3076              
3077             # my_freeze_script.pl
3078              
3079             use My::DB;
3080             use Storable qw(nstore);
3081              
3082             # Create My::DB object
3083             $db = My::DB->new(domain => 'dev', type => 'main');
3084              
3085             # Do work...
3086             $db->dbh->db('CREATE TABLE some_table (...)');
3087             ...
3088              
3089             # Serialize $db and store it in frozen_data_file
3090             nstore($db, 'frozen_data_file');
3091              
3092             Now another program wants to L<thaw|Storable/thaw> out that C<My::DB> object and use it. To do so, it must be sure to load the L<My::DB> module (which registers all its data sources when loaded) I<before> attempting to deserialize the C<My::DB> object serialized by C<my_freeze_script.pl>.
3093              
3094             # my_thaw_script.pl
3095              
3096             # IMPORTANT: load db modules with all data sources registered before
3097             # attempting to deserialize objects of this class.
3098             use My::DB;
3099              
3100             use Storable qw(retrieve);
3101              
3102             # Retrieve frozen My::DB object from frozen_data_file
3103             $db = retrieve('frozen_data_file');
3104              
3105             # Do work...
3106             $db->dbh->db('DROP TABLE some_table');
3107             ...
3108              
3109             Note that this rule about loading a L<Rose::DB>-derived class with all its data sources registered prior to deserializing such an object only applies if the serialization was done in a different process. If you L<freeze|Storable/freeze> and L<thaw|Storable/thaw> within the same process, you don't have to worry about it.
3110              
3111             =head1 ENVIRONMENT
3112              
3113             There are two ways to alter the initial L<Rose::DB> data source registry.
3114              
3115             =over 4
3116              
3117             =item * The ROSEDB_DEVINIT file or module, which can add, modify, or remove data sources and alter the default L<domain|Rose::DB/domain> and L<type|Rose::DB/type>.
3118              
3119             =item * The ROSEDBRC file, which can modify existing data sources.
3120              
3121             =back
3122              
3123             =head2 ROSEDB_DEVINIT
3124              
3125             The C<ROSEDB_DEVINIT> file or module is used during development, usually to set up data sources for a particular developer's database or project. If the C<ROSEDB_DEVINIT> environment variable is set, it should be the name of a Perl module or file. If it is a Perl module and that module has a C<fixup()> subroutine, it will be called as a class method after the module is loaded.
3126              
3127             If the C<ROSEDB_DEVINIT> environment variable is not set, or if the specified file does not exist or has errors, then it defaults to the package name C<Rose::DB::Devel::Init::username>, where "username" is the account name of the current user.
3128              
3129             B<Note:> if the L<getpwuid()|perlfunc/getpwuid> function is unavailable (as is often the case on Windows versions of perl) then this default does not apply and the loading of the module named C<Rose::DB::Devel::Init::username> is not attempted.
3130              
3131             The C<ROSEDB_DEVINIT> file or module may contain arbitrary Perl code which will be loaded and evaluated in the context of L<Rose::DB>. Example:
3132              
3133             Rose::DB->default_domain('development');
3134              
3135             Rose::DB->modify_db(domain => 'development',
3136             type => 'main_db',
3137             database => 'main',
3138             username => 'jdoe',
3139             password => 'mysecret');
3140              
3141             1;
3142              
3143             Remember to end the file with a true value.
3144              
3145             The C<ROSEDB_DEVINIT> file or module must be read explicitly by calling the L<auto_load_fixups|/auto_load_fixups> class method.
3146              
3147             =head2 ROSEDBRC
3148              
3149             The C<ROSEDBRC> file contains configuration "fix-up" information. This file is most often used to dynamically set passwords that are too sensitive to be included directly in the source code of a L<Rose::DB>-derived class.
3150              
3151             The path to the fix-up file is determined by the C<ROSEDBRC> environment variable. If this variable is not set, or if the file it points to does not exist, then it defaults to C</etc/rosedbrc>.
3152              
3153             This file should be in YAML format. To read this file, you must have either L<YAML::Syck> or some reasonably modern version of L<YAML> installed (0.66 or later recommended). L<YAML::Syck> will be preferred if both are installed.
3154              
3155             The C<ROSEDBRC> file's contents have the following structure:
3156              
3157             ---
3158             somedomain:
3159             sometype:
3160             somemethod: somevalue
3161             ---
3162             otherdomain:
3163             othertype:
3164             othermethod: othervalue
3165              
3166             Each entry modifies an existing registered data source. Any valid L<registry entry|Rose::DB::Registry::Entry> object method can be used (in place of "somemethod" and "othermethod" in the YAML example above).
3167              
3168             This file must be read explicitly by calling the L<auto_load_fixups|/auto_load_fixups> class method I<after> setting up all your data sources. Example:
3169              
3170             package My::DB;
3171              
3172             use Rose::DB;
3173             our @ISA = qw(Rose::DB);
3174              
3175             __PACKAGE__->use_private_registry;
3176              
3177             # Register all data sources
3178             __PACKAGE__->register_db(
3179             domain => 'development',
3180             type => 'main',
3181             driver => 'Pg',
3182             database => 'dev_db',
3183             host => 'localhost',
3184             username => 'devuser',
3185             password => 'mysecret',
3186             );
3187              
3188             ...
3189              
3190             # Load fix-up files, if any
3191             __PACKAGE__->auto_load_fixups;
3192              
3193             =head1 CLASS METHODS
3194              
3195             =over 4
3196              
3197             =item B<alias_db PARAMS>
3198              
3199             Make one data source an alias for another by pointing them both to the same registry entry. PARAMS are name/value pairs that must include domain and type values for both the source and alias parameters. Example:
3200              
3201             Rose::DB->alias_db(source => { domain => 'dev', type => 'main' },
3202             alias => { domain => 'dev', type => 'aux' });
3203              
3204             This makes the "dev/aux" data source point to the same registry entry as the "dev/main" data source. Modifications to either registry entry (via L<modify_db|/modify_db>) will be reflected in both.
3205              
3206             =item B<auto_load_fixups>
3207              
3208             Attempt to load both the YAML-based L<ROSEDBRC|/ROSEDBRC> and Perl-based L<ROSEDB_DEVINIT|/ROSEDB_DEVINIT> fix-up files, if any exist, in that order. The L<ROSEDBRC|/ROSEDBRC> file will modify the data source L<registry|/registry> of the calling class. See the L<ENVIRONMENT|/ENVIRONMENT> section above for more information.
3209              
3210             =item B<db_cache [CACHE]>
3211              
3212             Get or set the L<Rose::DB::Cache>-derived object used to cache L<Rose::DB> objects on behalf of this class. If no such object exists, a new cache object of L<db_cache_class|/db_cache_class> class will be created, stored, and returned.
3213              
3214             =item B<db_cache_class [CLASS]>
3215              
3216             Get or set the name of the L<Rose::DB::Cache>-derived class used to cache L<Rose::DB> objects on behalf of this class. The default value is L<Rose::DB::Cache>.
3217              
3218             =item B<db_exists PARAMS>
3219              
3220             Returns true of the data source specified by PARAMS is registered, false otherwise. PARAMS are name/value pairs for C<domain> and C<type>. If they are omitted, they default to L<default_domain|/default_domain> and L<default_type|/default_type>, respectively. If default values do not exist, a fatal error will occur. If a single value is passed instead of name/value pairs, it is taken as the value of the C<type> parameter.
3221              
3222             =item B<default_connect_options [HASHREF | PAIRS]>
3223              
3224             Get or set the default L<DBI> connect options hash. If a reference to a hash is passed, it replaces the default connect options hash. If a series of name/value pairs are passed, they are added to the default connect options hash.
3225              
3226             The default set of default connect options is:
3227              
3228             AutoCommit => 1,
3229             RaiseError => 1,
3230             PrintError => 1,
3231             ChopBlanks => 1,
3232             Warn => 0,
3233              
3234             See the L<connect_options|/connect_options> object method for more information on how the default connect options are used.
3235              
3236             =item B<default_domain [DOMAIN]>
3237              
3238             Get or set the default data source domain. See the L<"Data Source Abstraction"> section for more information on data source domains.
3239              
3240             =item B<default_type [TYPE]>
3241              
3242             Get or set the default data source type. See the L<"Data Source Abstraction"> section for more information on data source types.
3243              
3244             =item B<driver_class DRIVER [, CLASS]>
3245              
3246             Get or set the subclass used for DRIVER. The DRIVER argument is automatically converted to lowercase. (Driver names are effectively case-insensitive.)
3247              
3248             $class = Rose::DB->driver_class('Pg'); # get
3249             Rose::DB->driver_class('pg' => 'MyDB::Pg'); # set
3250              
3251             The default mapping of driver names to class names is as follows:
3252              
3253             mysql -> Rose::DB::MySQL
3254             mariadb -> Rose::DB::MariaDB
3255             pg -> Rose::DB::Pg
3256             informix -> Rose::DB::Informix
3257             sqlite -> Rose::DB::SQLite
3258             oracle -> Rose::DB::Oracle
3259             generic -> Rose::DB::Generic
3260              
3261             The class mapped to the special driver name "generic" will be used for any driver name that does not have an entry in the map.
3262              
3263             See the documentation for the L<new|/new> method for more information on how the driver influences the class of objects returned by the constructor.
3264              
3265             =item B<default_keyword_function_calls [BOOL]>
3266              
3267             Get or set a boolean default value for the L<keyword_function_calls|/keyword_function_calls> object attribute. Defaults to the value of the C<ROSE_DB_KEYWORD_FUNCTION_CALLS> environment variable, it set to a defined value, or false otherwise.
3268              
3269             =item B<modify_db PARAMS>
3270              
3271             Modify a data source, setting the attributes specified in PARAMS, where
3272             PARAMS are name/value pairs. Any L<Rose::DB> object method that sets a L<data source configuration value|"Data Source Configuration"> is a valid parameter name.
3273              
3274             # Set new username for data source identified by domain and type
3275             Rose::DB->modify_db(domain => 'test',
3276             type => 'main',
3277             username => 'tester');
3278              
3279             PARAMS should include values for both the C<type> and C<domain> parameters since these two attributes are used to identify the data source. If they are omitted, they default to L<default_domain|/default_domain> and L<default_type|/default_type>, respectively. If default values do not exist, a fatal error will occur. If there is no data source defined for the specified C<type> and C<domain>, a fatal error will occur.
3280              
3281             =item B<prepare_cache_for_apache_fork>
3282              
3283             This is a convenience method that is equivalent to the following call:
3284              
3285             Rose::DB->db_cache->prepare_for_apache_fork()
3286              
3287             Any arguments passed to this method are passed on to the call to the L<db_cache|/db_cache>'s L<prepare_for_apache_fork|Rose::DB::Cache/prepare_for_apache_fork> method.
3288              
3289             Please read the L<Rose::DB::Cache> documentation, particularly the documentation for the L<use_cache_during_apache_startup|Rose::DB::Cache/use_cache_during_apache_startup> method for more information.
3290              
3291             =item B<register_db PARAMS>
3292              
3293             Registers a new data source with the attributes specified in PARAMS, where
3294             PARAMS are name/value pairs. Any L<Rose::DB> object method that sets a L<data source configuration value|"Data Source Configuration"> is a valid parameter name.
3295              
3296             PARAMS B<must> include a value for the C<driver> parameter. If the C<type> or C<domain> parameters are omitted or undefined, they default to the return values of the L<default_type|/default_type> and L<default_domain|/default_domain> class methods, respectively.
3297              
3298             The C<type> and C<domain> are used to identify the data source. If either one is missing, a fatal error will occur. See the L<"Data Source Abstraction"> section for more information on data source types and domains.
3299              
3300             The C<driver> is used to determine which class objects will be blessed into by the L<Rose::DB> constructor, L<new|/new>. The driver name is automatically converted to lowercase. If it is missing, a fatal error will occur.
3301              
3302             In most deployment scenarios, L<register_db|/register_db> is called early in the compilation process to ensure that the registered data sources are available when the "real" code runs.
3303              
3304             Database registration can be included directly in your L<Rose::DB> subclass. This is the recommended approach. Example:
3305              
3306             package My::DB;
3307              
3308             use Rose::DB;
3309             our @ISA = qw(Rose::DB);
3310              
3311             # Use a private registry for this class
3312             __PACKAGE__->use_private_registry;
3313              
3314             # Register data sources
3315             My::DB->register_db(
3316             domain => 'development',
3317             type => 'main',
3318             driver => 'Pg',
3319             database => 'dev_db',
3320             host => 'localhost',
3321             username => 'devuser',
3322             password => 'mysecret',
3323             );
3324              
3325             My::DB->register_db(
3326             domain => 'production',
3327             type => 'main',
3328             driver => 'Pg',
3329             database => 'big_db',
3330             host => 'dbserver.acme.com',
3331             username => 'dbadmin',
3332             password => 'prodsecret',
3333             );
3334             ...
3335              
3336             Another possible approach is to consolidate data source registration in a single module which is then C<use>ed early on in the code path. For example, imagine a mod_perl web server environment:
3337              
3338             # File: MyCorp/DataSources.pm
3339             package MyCorp::DataSources;
3340              
3341             My::DB->register_db(
3342             domain => 'development',
3343             type => 'main',
3344             driver => 'Pg',
3345             database => 'dev_db',
3346             host => 'localhost',
3347             username => 'devuser',
3348             password => 'mysecret',
3349             );
3350              
3351             My::DB->register_db(
3352             domain => 'production',
3353             type => 'main',
3354             driver => 'Pg',
3355             database => 'big_db',
3356             host => 'dbserver.acme.com',
3357             username => 'dbadmin',
3358             password => 'prodsecret',
3359             );
3360             ...
3361              
3362             # File: /usr/local/apache/conf/startup.pl
3363              
3364             use My::DB; # your Rose::DB subclass
3365             use MyCorp::DataSources; # register all data sources
3366             ...
3367              
3368             Data source registration can happen at any time, of course, but it is most useful when all application code can simply assume that all the data sources are already registered. Doing the registration as early as possible (e.g., directly in your L<Rose::DB> subclass, or in a C<startup.pl> file that is loaded from an apache/mod_perl web server's C<httpd.conf> file) is the best way to create such an environment.
3369              
3370             Note that the data source registry serves as an I<initial> source of information for L<Rose::DB> objects. Once an object is instantiated, it is independent of the registry. Changes to an object are not reflected in the registry, and changes to the registry are not reflected in existing objects.
3371              
3372             =item B<registry [REGISTRY]>
3373              
3374             Get or set the L<Rose::DB::Registry>-derived object that manages and stores the data source registry. It defaults to an "empty" L<Rose::DB::Registry> object. Remember that setting a new registry will replace the existing registry and all the data sources registered in it.
3375              
3376             Note that L<Rose::DB> subclasses will inherit the base class's L<Rose::DB::Registry> object and will therefore inherit all existing registry entries and share the same registry namespace as the base class. This may or may not be what you want.
3377              
3378             In most cases, it's wise to give your subclass its own private registry if it inherits directly from L<Rose::DB>. To do that, just set a new registry object in your subclass. Example:
3379              
3380             package My::DB;
3381              
3382             use Rose::DB;
3383             our @ISA = qw(Rose::DB);
3384              
3385             # Create a private registry for this class:
3386             #
3387             # either explicitly:
3388             # use Rose::DB::Registry;
3389             # __PACKAGE__->registry(Rose::DB::Registry->new);
3390             #
3391             # or use the convenience method:
3392             __PACKAGE__->use_private_registry;
3393             ...
3394              
3395             Further subclasses of C<My::DB> may then inherit its registry object, if desired, or may create their own private registries in the manner shown above.
3396              
3397             =item B<unregister_db PARAMS>
3398              
3399             Unregisters the data source having the C<type> and C<domain> specified in PARAMS, where PARAMS are name/value pairs. Returns true if the data source was unregistered successfully, false if it did not exist in the first place. Example:
3400              
3401             Rose::DB->unregister_db(type => 'main', domain => 'test');
3402              
3403             PARAMS B<must> include values for both the C<type> and C<domain> parameters since these two attributes are used to identify the data source. If either one is missing, a fatal error will occur.
3404              
3405             Unregistering a data source removes all knowledge of it. This may be harmful to any existing L<Rose::DB> objects that are associated with that data source.
3406              
3407             =item B<unregister_domain DOMAIN>
3408              
3409             Unregisters an entire domain. Returns true if the domain was unregistered successfully, false if it did not exist in the first place. Example:
3410              
3411             Rose::DB->unregister_domain('test');
3412              
3413             Unregistering a domain removes all knowledge of all of the data sources that existed under it. This may be harmful to any existing L<Rose::DB> objects that are associated with any of those data sources.
3414              
3415             =item B<use_cache_during_apache_startup [BOOL]>
3416              
3417             This is a convenience method that is equivalent to the following call:
3418              
3419             Rose::DB->db_cache->use_cache_during_apache_startup(...)
3420              
3421             The boolean argument passed to this method is passed on to the call to the L<db_cache|/db_cache>'s L<use_cache_during_apache_startup|Rose::DB::Cache/use_cache_during_apache_startup> method.
3422              
3423             Please read the L<Rose::DB::Cache>'s L<use_cache_during_apache_startup|Rose::DB::Cache/use_cache_during_apache_startup> documentation for more information.
3424              
3425             =item B<use_private_registry>
3426              
3427             This method is used to give a class its own private L<registry|/registry>. In other words, this:
3428              
3429             __PACKAGE__->use_private_registry;
3430              
3431             is roughly equivalent to this:
3432              
3433             use Rose::DB::Registry;
3434             __PACKAGE__->registry(Rose::DB::Registry->new);
3435              
3436             =back
3437              
3438             =head1 CONSTRUCTORS
3439              
3440             =over 4
3441              
3442             =item B<new PARAMS>
3443              
3444             Constructs a new object based on PARAMS, where PARAMS are
3445             name/value pairs. Any object method is a valid parameter name. Example:
3446              
3447             $db = Rose::DB->new(type => 'main', domain => 'qa');
3448              
3449             If a single argument is passed to L<new|/new>, it is used as the C<type> value:
3450              
3451             $db = Rose::DB->new(type => 'aux');
3452             $db = Rose::DB->new('aux'); # same thing
3453              
3454             Each L<Rose::DB> object is associated with a particular data source, defined by the L<type|/type> and L<domain|/domain> values. If these are not part of PARAMS, then the default values are used. If you do not want to use the default values for the L<type|/type> and L<domain|/domain> attributes, you should specify them in the constructor PARAMS.
3455              
3456             The default L<type|/type> and L<domain|/domain> can be set using the L<default_type|/default_type> and L<default_domain|/default_domain> class methods. See the L<"Data Source Abstraction"> section for more information on data sources.
3457              
3458             Object attributes are set based on the L<registry|/registry> entry specified by the C<type> and C<domain> parameters. This registry entry must exist or a fatal error will occur (with one exception; see below). Any additional PARAMS will override the values taken from the registry entry.
3459              
3460             If C<type> and C<domain> parameters are not passed, but a C<driver> parameter is passed, then a new "empty" object will be returned. Examples:
3461              
3462             # This is ok, even if no registered data sources exist
3463             $db = Rose::DB->new(driver => 'sqlite');
3464              
3465             The object returned by L<new|/new> will be derived from a database-specific driver class, chosen based on the L<driver|/driver> value of the selected data source. If there is no registered data source for the specified L<type|/type> and L<domain|/domain>, a fatal error will occur.
3466              
3467             The default driver-to-class mapping is as follows:
3468              
3469             pg -> Rose::DB::Pg
3470             mysql -> Rose::DB::MySQL
3471             mariadb -> Rose::DB::MariaDB
3472             informix -> Rose::DB::Informix
3473             oracle -> Rose::DB::Oracle
3474             sqlite -> Rose::DB::SQLite
3475              
3476             You can change this mapping with the L<driver_class|/driver_class> class method.
3477              
3478             =item B<new_or_cached PARAMS>
3479              
3480             Constructs or returns a L<Rose::DB> object based on PARAMS, where PARAMS are any name/value pairs that can be passed to the L<new|/new> method. If the L<db_cache|/db_cache>'s L<get_db|Rose::DB::Cache/get_db> method returns an existing L<Rose::DB> object that matches PARAMS, then it is returned. Otherwise, a L<new|/new> L<Rose::DB> object is created, L<stored|Rose::DB::Cache/set_db> in the L<db_cache|/db_cache>, then returned.
3481              
3482             See the L<Rose::DB::Cache> documentation to learn about the cache API and the default implementation.
3483              
3484             =back
3485              
3486             =head1 OBJECT METHODS
3487              
3488             =over 4
3489              
3490             =item B<begin_work>
3491              
3492             Attempt to start a transaction by calling the L<begin_work|DBI/begin_work> method on the L<DBI> database handle.
3493              
3494             If necessary, the database handle will be constructed and connected to the current data source. If this fails, undef is returned. If there is no registered data source for the current C<type> and C<domain>, a fatal error will occur.
3495              
3496             If the "AutoCommit" database handle attribute is false, the handle is assumed to already be in a transaction and L<Rose::DB::Constants::IN_TRANSACTION|Rose::DB::Constants> (-1) is returned. If the call to L<DBI>'s L<begin_work|DBI/begin_work> method succeeds, 1 is returned. If it fails, undef is returned.
3497              
3498             =item B<commit>
3499              
3500             Attempt to commit the current transaction by calling the L<commit|DBI/commit> method on the L<DBI> database handle. If the L<DBI> database handle does not exist or is not connected, 0 is returned.
3501              
3502             If the "AutoCommit" database handle attribute is true, the handle is assumed to not be in a transaction and L<Rose::DB::Constants::IN_TRANSACTION|Rose::DB::Constants> (-1) is returned. If the call to L<DBI>'s L<commit|DBI/commit> method succeeds, 1 is returned. If it fails, undef is returned.
3503              
3504             =item B<connect>
3505              
3506             Constructs and connects the L<DBI> database handle for the current data source, calling L<dbi_connect|/dbi_connect> to create a new L<DBI> database handle if none exists. If there is no registered data source for the current L<type|/type> and L<domain|/domain>, a fatal error will occur.
3507              
3508             If any L<post_connect_sql|/post_connect_sql> statement failed to execute, the database handle is disconnected and then discarded.
3509              
3510             If the database handle returned by L<dbi_connect|/dbi_connect> was originally connected by another L<Rose::DB>-derived object (e.g., if a subclass's custom implementation of L<dbi_connect|/dbi_connect> calls L<DBI>'s L<connect_cached|DBI/connect_cached> method) then the L<post_connect_sql|/post_connect_sql> statements will not be run, nor will any custom L<DBI> attributes be applied (e.g., L<Rose::DB::MySQL>'s L<mysql_enable_utf8|Rose::DB::MySQL/mysql_enable_utf8> attribute).
3511              
3512             Returns true if the database handle was connected successfully and all L<post_connect_sql|/post_connect_sql> statements (if any) were run successfully, false otherwise.
3513              
3514             =item B<connect_option NAME [, VALUE]>
3515              
3516             Get or set a single connection option. Example:
3517              
3518             $val = $db->connect_option('RaiseError'); # get
3519             $db->connect_option(AutoCommit => 1); # set
3520              
3521             Connection options are name/value pairs that are passed in a hash reference as the fourth argument to the call to L<DBI-E<gt>connect()|DBI/connect>. See the L<DBI> documentation for descriptions of the various options.
3522              
3523             =item B<connect_options [HASHREF | PAIRS]>
3524              
3525             Get or set the L<DBI> connect options hash. If a reference to a hash is passed, it replaces the connect options hash. If a series of name/value pairs are passed, they are added to the connect options hash.
3526              
3527             Returns a reference to the connect options has in scalar context, or a list of name/value pairs in list context.
3528              
3529             =item B<dbh [DBH]>
3530              
3531             Get or set the L<DBI> database handle connected to the current data source. If the database handle does not exist or was created in another process or thread, this method will discard the old database handle (if any) and L<dbi_connect|/dbi_connect> will be called to create a new one.
3532              
3533             Returns undef if the database handle could not be constructed and connected. If there is no registered data source for the current C<type> and C<domain>, a fatal error will occur.
3534              
3535             Note: when setting this attribute, you I<must> pass in a L<DBI> database handle that has the same L<driver|/driver> as the object. For example, if the L<driver|/driver> is C<mysql> then the L<DBI> database handle must be connected to a MySQL database. Passing in a mismatched database handle will cause a fatal error.
3536              
3537             =item B<dbi_connect [ARGS]>
3538              
3539             This method calls L<DBI-E<gt>connect(...)|DBI/connect>, passing all ARGS and returning all values. This method has no affect on the internal state of the object. Use the L<connect|/connect> method to create and store a new L<database handle|/dbh> in the object.
3540              
3541             Override this method in your L<Rose::DB> subclass if you want to use a different method (e.g. L<DBI-E<gt>connect_cached()|DBI/connect_cached>) to create database handles.
3542              
3543             =item B<disconnect>
3544              
3545             Decrements the reference count for the database handle and disconnects it if the reference count is zero and if the database handle was originally connected by this object. (This may not be the case if, say, a subclass's custom implementation of L<dbi_connect|/dbi_connect> calls L<DBI>'s L<connect_cached|DBI/connect_cached> method.) Regardless of the reference count, it sets the L<dbh|/dbh> attribute to undef.
3546              
3547             Returns true if all L<pre_disconnect_sql|/pre_disconnect_sql> statements (if any) were run successfully and the database handle was disconnected successfully (or if it was simply set to undef), false otherwise.
3548              
3549             The database handle will not be disconnected if any L<pre_disconnect_sql|/pre_disconnect_sql> statement fails to execute, and the L<pre_disconnect_sql|/pre_disconnect_sql> is not run unless the handle is going to be disconnected.
3550              
3551             =item B<do_transaction CODE [, ARGS]>
3552              
3553             Execute arbitrary code within a single transaction, rolling back if any of the code fails, committing if it succeeds. CODE should be a code reference. It will be called with any arguments passed to L<do_transaction|/do_transaction> after the code reference. Example:
3554              
3555             # Transfer $100 from account id 5 to account id 9
3556             $db->do_transaction(sub
3557             {
3558             my($amt, $id1, $id2) = @_;
3559              
3560             my $dbh = $db->dbh or die $db->error;
3561              
3562             # Transfer $amt from account id $id1 to account id $id2
3563             $dbh->do("UPDATE acct SET bal = bal - $amt WHERE id = $id1");
3564             $dbh->do("UPDATE acct SET bal = bal + $amt WHERE id = $id2");
3565             },
3566             100, 5, 9) or warn "Transfer failed: ", $db->error;
3567              
3568             If the CODE block threw an exception or the transaction could not be started and committed successfully, then undef is returned and the exception thrown is available in the L<error|/error> attribute. Otherwise, a true value is returned.
3569              
3570             =item B<error [MSG]>
3571              
3572             Get or set the error message associated with the last failure. If a method fails, check this attribute to get the reason for the failure in the form of a text message.
3573              
3574             =item B<has_dbh>
3575              
3576             Returns true if the object has a L<DBI> database handle (L<dbh|/dbh>), false if it does not.
3577              
3578             =item B<has_primary_key [ TABLE | PARAMS ]>
3579              
3580             Returns true if the specified table has a primary key (as determined by the L<primary_key_column_names|/primary_key_column_names> method), false otherwise.
3581              
3582             The arguments are the same as those for the L<primary_key_column_names|/primary_key_column_names> method: either a table name or name/value pairs specifying C<table>, C<catalog>, and C<schema>. The C<catalog> and C<schema> parameters are optional and default to the return values of the L<catalog|/catalog> and L<schema|/schema> methods, respectively. See the documentation for the L<primary_key_column_names|/primary_key_column_names> for more information.
3583              
3584             =item B<in_transaction>
3585              
3586             Return true if the L<dbh|/dbh> is currently in the middle of a transaction, false (but defined) if it is not. If no L<dbh|/dbh> exists, then undef is returned.
3587              
3588             =item B<init_db_info>
3589              
3590             Initialize data source configuration information based on the current values of the L<type|/type> and L<domain|/domain> attributes by pulling data from the corresponding registry entry. If there is no registered data source for the current L<type|/type> and L<domain|/domain>, a fatal error will occur. L<init_db_info|/init_db_info> is called as part of the L<new|/new> and L<connect|/connect> methods.
3591              
3592             =item B<insertid_param>
3593              
3594             Returns the name of the L<DBI> statement handle attribute that contains the auto-generated unique key created during the last insert operation. Returns undef if the current data source does not support this attribute.
3595              
3596             =item B<keyword_function_calls [BOOL]>
3597              
3598             Get or set a boolean value that indicates whether or not any string that looks like a function call (matches C</^\w+\(.*\)$/>) will be treated as a "keyword" by the various L<format_*|/"Vendor-Specific Column Value Parsing and Formatting"> methods. Defaults to the value returned by the L<default_keyword_function_calls|/default_keyword_function_calls> class method.
3599              
3600             =item B<last_insertid_from_sth STH>
3601              
3602             Given a L<DBI> statement handle, returns the value of the auto-generated unique key created during the last insert operation. This value may be undefined if this feature is not supported by the current data source.
3603              
3604             =item B<list_tables>
3605              
3606             Returns a list (in list context) or reference to an array (in scalar context) of tables in the database. The current L<catalog|/catalog> and L<schema|/schema> are honored.
3607              
3608             =item B<quote_column_name NAME>
3609              
3610             Returns the column name NAME appropriately quoted for use in an SQL statement. (Note that "appropriate" quoting may mean no quoting at all.)
3611              
3612             =item B<release_dbh>
3613              
3614             Decrements the reference count for the L<DBI> database handle, if it exists. Returns 0 if the database handle does not exist.
3615              
3616             If the reference count drops to zero, the database handle is disconnected. Keep in mind that the L<Rose::DB> object itself will increment the reference count when the database handle is connected, and decrement it when L<disconnect|/disconnect> is called.
3617              
3618             Returns true if the reference count is not 0 or if all L<pre_disconnect_sql|/pre_disconnect_sql> statements (if any) were run successfully and the database handle was disconnected successfully, false otherwise.
3619              
3620             The database handle will not be disconnected if any L<pre_disconnect_sql|/pre_disconnect_sql> statement fails to execute, and the L<pre_disconnect_sql|/pre_disconnect_sql> is not run unless the handle is going to be disconnected.
3621              
3622             See the L<"Database Handle Life-Cycle Management"> section for more information on the retain/release system.
3623              
3624             =item B<retain_dbh>
3625              
3626             Returns the connected L<DBI> database handle after incrementing the reference count. If the database handle does not exist or is not already connected, this method will do everything necessary to do so.
3627              
3628             Returns undef if the database handle could not be constructed and connected. If there is no registered data source for the current L<type|/type> and L<domain|/domain>, a fatal error will occur.
3629              
3630             See the L<"Database Handle Life-Cycle Management"> section for more information on the retain/release system.
3631              
3632             =item B<rollback>
3633              
3634             Roll back the current transaction by calling the L<rollback|DBI/rollback> method on the L<DBI> database handle. If the L<DBI> database handle does not exist or is not connected, 0 is returned.
3635              
3636             If the call to L<DBI>'s L<rollback|DBI/rollback> method succeeds or if auto-commit is enabled, 1 is returned. If it fails, undef is returned.
3637              
3638             =back
3639              
3640             =head2 Data Source Configuration
3641              
3642             Not all databases will use all of these values. Values that are not supported are simply ignored.
3643              
3644             =over 4
3645              
3646             =item B<autocommit [VALUE]>
3647              
3648             Get or set the value of the "AutoCommit" connect option and L<DBI> handle attribute. If a VALUE is passed, it will be set in both the connect options hash and the current database handle, if any. Returns the value of the "AutoCommit" attribute of the database handle if it exists, or the connect option otherwise.
3649              
3650             This method should not be mixed with the L<connect_options|/connect_options> method in calls to L<register_db|/register_db> or L<modify_db|/modify_db> since L<connect_options|/connect_options> will overwrite I<all> the connect options with its argument, and neither L<register_db|/register_db> nor L<modify_db|/modify_db> guarantee the order that its parameters will be evaluated.
3651              
3652             =item B<catalog [CATALOG]>
3653              
3654             Get or set the database catalog name. This setting is only relevant to databases that support the concept of catalogs.
3655              
3656             =item B<connect_options [HASHREF | PAIRS]>
3657              
3658             Get or set the options passed in a hash reference as the fourth argument to the call to L<DBI-E<gt>connect()|DBI/connect>. See the L<DBI> documentation for descriptions of the various options.
3659              
3660             If a reference to a hash is passed, it replaces the connect options hash. If a series of name/value pairs are passed, they are added to the connect options hash.
3661              
3662             Returns a reference to the hash of options in scalar context, or a list of name/value pairs in list context.
3663              
3664             When L<init_db_info|/init_db_info> is called for the first time on an object (either in isolation or as part of the L<connect|/connect> process), the connect options are merged with the L<default_connect_options|/default_connect_options>. The defaults are overridden in the case of a conflict. Example:
3665              
3666             Rose::DB->register_db(
3667             domain => 'development',
3668             type => 'main',
3669             driver => 'Pg',
3670             database => 'dev_db',
3671             host => 'localhost',
3672             username => 'devuser',
3673             password => 'mysecret',
3674             connect_options =>
3675             {
3676             RaiseError => 0,
3677             AutoCommit => 0,
3678             }
3679             );
3680              
3681             # Rose::DB->default_connect_options are:
3682             #
3683             # AutoCommit => 1,
3684             # ChopBlanks => 1,
3685             # PrintError => 1,
3686             # RaiseError => 1,
3687             # Warn => 0,
3688              
3689             # The object's connect options are merged with default options
3690             # since new() will trigger the first call to init_db_info()
3691             # for this object
3692             $db = Rose::DB->new(domain => 'development', type => 'main');
3693              
3694             # $db->connect_options are:
3695             #
3696             # AutoCommit => 0,
3697             # ChopBlanks => 1,
3698             # PrintError => 1,
3699             # RaiseError => 0,
3700             # Warn => 0,
3701              
3702             $db->connect_options(TraceLevel => 2); # Add an option
3703              
3704             # $db->connect_options are now:
3705             #
3706             # AutoCommit => 0,
3707             # ChopBlanks => 1,
3708             # PrintError => 1,
3709             # RaiseError => 0,
3710             # TraceLevel => 2,
3711             # Warn => 0,
3712              
3713             # The object's connect options are NOT re-merged with the default
3714             # connect options since this will trigger the second call to
3715             # init_db_info(), not the first
3716             $db->connect or die $db->error;
3717              
3718             # $db->connect_options are still:
3719             #
3720             # AutoCommit => 0,
3721             # ChopBlanks => 1,
3722             # PrintError => 1,
3723             # RaiseError => 0,
3724             # TraceLevel => 2,
3725             # Warn => 0,
3726              
3727             =item B<database [NAME]>
3728              
3729             Get or set the database name used in the construction of the DSN used in the L<DBI> L<connect|DBI/connect> call.
3730              
3731             =item B<domain [DOMAIN]>
3732              
3733             Get or set the data source domain. See the L<"Data Source Abstraction"> section for more information on data source domains.
3734              
3735             =item B<driver [DRIVER]>
3736              
3737             Get or set the driver name. The driver name can only be set during object construction (i.e., as an argument to L<new|/new>) since it determines the object class. After the object is constructed, setting the driver to anything other than the same value it already has will cause a fatal error.
3738              
3739             Even in the call to L<new|/new>, setting the driver name explicitly is not recommended. Instead, specify the driver when calling L<register_db|/register_db> for each data source and allow the L<driver|/driver> to be set automatically based on the L<domain|/domain> and L<type|/type>.
3740              
3741             The driver names for the L<currently supported database types|"DATABASE SUPPORT"> are:
3742              
3743             pg
3744             mysql
3745             mariadb
3746             informix
3747             oracle
3748             sqlite
3749              
3750             Driver names should only use lowercase letters.
3751              
3752             =item B<dsn [DSN]>
3753              
3754             Get or set the L<DBI> DSN (Data Source Name) passed to the call to L<DBI>'s L<connect|DBI/connect> method.
3755              
3756             An attempt is made to parse the new DSN. Any parts successfully extracted are assigned to the corresponding L<Rose::DB> attributes (e.g., L<host|/host>, L<port|/port>, L<database|/database>). If no value could be extracted for an attribute, it is set to undef.
3757              
3758             If the DSN is never set explicitly, it is built automatically based on the relevant object attributes.
3759              
3760             If the DSN is set explicitly, but any of L<host|/host>, L<port|/port>, L<database|/database>, L<schema|/schema>, or L<catalog|/catalog> are also provided, either in an object constructor or when the data source is registered, the explicit DSN may be ignored as a new DSN is constructed based on these attributes.
3761              
3762             =item B<handle_error [VALUE]>
3763              
3764             Get or set the value of the "HandleError" connect option and L<DBI> handle attribute. If a VALUE is passed, it will be set in both the connect options hash and the current database handle, if any. Returns the value of the "HandleError" attribute of the database handle if it exists, or the connect option otherwise.
3765              
3766             This method should not be mixed with the L<connect_options|/connect_options> method in calls to L<register_db|/register_db> or L<modify_db|/modify_db> since L<connect_options|/connect_options> will overwrite I<all> the connect options with its argument, and neither L<register_db|/register_db> nor L<modify_db|/modify_db> guarantee the order that its parameters will be evaluated.
3767              
3768             =item B<host [NAME]>
3769              
3770             Get or set the database server host name used in the construction of the DSN which is passed in the L<DBI> L<connect|DBI/connect> call.
3771              
3772             =item B<password [PASS]>
3773              
3774             Get or set the password that will be passed to the L<DBI> L<connect|DBI/connect> call.
3775              
3776             =item B<port [NUM]>
3777              
3778             Get or set the database server port number used in the construction of the DSN which is passed in the L<DBI> L<connect|DBI/connect> call.
3779              
3780             =item B<pre_disconnect_sql [STATEMENTS]>
3781              
3782             Get or set the SQL statements that will be run immediately before disconnecting from the database. STATEMENTS should be a list or reference to an array of SQL statements. Returns a reference to the array of SQL statements in scalar context, or a list of SQL statements in list context.
3783              
3784             The SQL statements are run in the order that they are supplied in STATEMENTS. If any L<pre_disconnect_sql|/pre_disconnect_sql> statement fails when executed, the subsequent statements are ignored.
3785              
3786             =item B<post_connect_sql [STATEMENTS]>
3787              
3788             Get or set the SQL statements that will be run immediately after connecting to the database. STATEMENTS should be a list or reference to an array of SQL statements. Returns a reference to the array of SQL statements in scalar context, or a list of SQL statements in list context.
3789              
3790             The SQL statements are run in the order that they are supplied in STATEMENTS. If any L<post_connect_sql|/post_connect_sql> statement fails when executed, the subsequent statements are ignored.
3791              
3792             =item B<primary_key_column_names [ TABLE | PARAMS ]>
3793              
3794             Returns a list (in list context) or reference to an array (in scalar context) of the names of the columns that make up the primary key for the specified table. If the table has no primary key, an empty list (in list context) or reference to an empty array (in scalar context) will be returned.
3795              
3796             The table may be specified in two ways. If one argument is passed, it is taken as the name of the table. Otherwise, name/value pairs are expected. Valid parameter names are:
3797              
3798             =over 4
3799              
3800             =item C<catalog>
3801              
3802             The name of the catalog that contains the table. This parameter is optional and defaults to the return value of the L<catalog|/catalog> method.
3803              
3804             =item C<schema>
3805              
3806             The name of the schema that contains the table. This parameter is optional and defaults to the return value of the L<schema|/schema> method.
3807              
3808             =item C<table>
3809              
3810             The name of the table. This parameter is required.
3811              
3812             =back
3813              
3814             Case-sensitivity of names is determined by the underlying database. If your database is case-sensitive, then you must pass names to this method with the expected case.
3815              
3816             =item B<print_error [VALUE]>
3817              
3818             Get or set the value of the "PrintError" connect option and L<DBI> handle attribute. If a VALUE is passed, it will be set in both the connect options hash and the current database handle, if any. Returns the value of the "PrintError" attribute of the database handle if it exists, or the connect option otherwise.
3819              
3820             This method should not be mixed with the L<connect_options|/connect_options> method in calls to L<register_db|/register_db> or L<modify_db|/modify_db> since L<connect_options|/connect_options> will overwrite I<all> the connect options with its argument, and neither L<register_db|/register_db> nor L<modify_db|/modify_db> guarantee the order that its parameters will be evaluated.
3821              
3822             =item B<raise_error [VALUE]>
3823              
3824             Get or set the value of the "RaiseError" connect option and L<DBI> handle attribute. If a VALUE is passed, it will be set in both the connect options hash and the current database handle, if any. Returns the value of the "RaiseError" attribute of the database handle if it exists, or the connect option otherwise.
3825              
3826             This method should not be mixed with the L<connect_options|/connect_options> method in calls to L<register_db|/register_db> or L<modify_db|/modify_db> since L<connect_options|/connect_options> will overwrite I<all> the connect options with its argument, and neither L<register_db|/register_db> nor L<modify_db|/modify_db> guarantee the order that its parameters will be evaluated.
3827              
3828             =item B<schema [SCHEMA]>
3829              
3830             Get or set the database schema name. This setting is only useful to databases that support the concept of schemas (e.g., PostgreSQL).
3831              
3832             =item B<server_time_zone [TZ]>
3833              
3834             Get or set the time zone used by the database server software. TZ should be a time zone name that is understood by L<DateTime::TimeZone>. The default value is "floating".
3835              
3836             See the L<DateTime::TimeZone> documentation for acceptable values of TZ.
3837              
3838             =item B<type [TYPE]>
3839              
3840             Get or set the data source type. See the L<"Data Source Abstraction"> section for more information on data source types.
3841              
3842             =item B<username [NAME]>
3843              
3844             Get or set the username that will be passed to the L<DBI> L<connect|DBI/connect> call.
3845              
3846             =back
3847              
3848             =head2 Value Parsing and Formatting
3849              
3850             =over 4
3851              
3852             =item B<format_bitfield BITS [, SIZE]>
3853              
3854             Converts the L<Bit::Vector> object BITS into the appropriate format for the "bitfield" data type of the current data source. If a SIZE argument is provided, the bit field will be padded with the appropriate number of zeros until it is SIZE bits long. If the data source does not have a native "bit" or "bitfield" data type, a character data type may be used to store the string of 1s and 0s returned by the default implementation.
3855              
3856             =item B<format_boolean VALUE>
3857              
3858             Converts VALUE into the appropriate format for the "boolean" data type of the current data source. VALUE is simply evaluated in Perl's scalar context to determine if it's true or false.
3859              
3860             =item B<format_date DATETIME>
3861              
3862             Converts the L<DateTime> object DATETIME into the appropriate format for the "date" (month, day, year) data type of the current data source.
3863              
3864             =item B<format_datetime DATETIME>
3865              
3866             Converts the L<DateTime> object DATETIME into the appropriate format for the "datetime" (month, day, year, hour, minute, second) data type of the current data source.
3867              
3868             =item B<format_interval DURATION>
3869              
3870             Converts the L<DateTime::Duration> object DURATION into the appropriate format for the interval (years, months, days, hours, minutes, seconds) data type of the current data source. If DURATION is undefined, a L<DateTime::Duration> object, a valid interval keyword (according to L<validate_interval_keyword|/validate_interval_keyword>), or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified.
3871              
3872             =item B<format_time TIMECLOCK>
3873              
3874             Converts the L<Time::Clock> object TIMECLOCK into the appropriate format for the time (hour, minute, second, fractional seconds) data type of the current data source. Fractional seconds are optional, and the useful precision may vary depending on the data source.
3875              
3876             =item B<format_timestamp DATETIME>
3877              
3878             Converts the L<DateTime> object DATETIME into the appropriate format for the timestamp (month, day, year, hour, minute, second, fractional seconds) data type of the current data source. Fractional seconds are optional, and the useful precision may vary depending on the data source.
3879              
3880             =item B<format_timestamp_with_time_zone DATETIME>
3881              
3882             Converts the L<DateTime> object DATETIME into the appropriate format for the timestamp with time zone (month, day, year, hour, minute, second, fractional seconds, time zone) data type of the current data source. Fractional seconds are optional, and the useful precision may vary depending on the data source.
3883              
3884             =item B<parse_bitfield BITS [, SIZE]>
3885              
3886             Parse BITS and return a corresponding L<Bit::Vector> object. If SIZE is not passed, then it defaults to the number of bits in the parsed bit string.
3887              
3888             If BITS is a string of "1"s and "0"s or matches C</^B'[10]+'$/>, then the "1"s and "0"s are parsed as a binary string.
3889              
3890             If BITS is a string of numbers, at least one of which is in the range 2-9, it is assumed to be a decimal (base 10) number and is converted to a bitfield as such.
3891              
3892             If BITS matches any of these regular expressions:
3893              
3894             /^0x/
3895             /^X'.*'$/
3896             /^[0-9a-f]+$/
3897              
3898             it is assumed to be a hexadecimal number and is converted to a bitfield as such.
3899              
3900             Otherwise, undef is returned.
3901              
3902             =item B<parse_boolean STRING>
3903              
3904             Parse STRING and return a boolean value of 1 or 0. STRING should be formatted according to the data source's native "boolean" data type. The default implementation accepts 't', 'true', 'y', 'yes', and '1' values for true, and 'f', 'false', 'n', 'no', and '0' values for false.
3905              
3906             If STRING is a valid boolean keyword (according to L<validate_boolean_keyword|/validate_boolean_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "boolean" value.
3907              
3908             =item B<parse_date STRING>
3909              
3910             Parse STRING and return a L<DateTime> object. STRING should be formatted according to the data source's native "date" (month, day, year) data type.
3911              
3912             If STRING is a valid date keyword (according to L<validate_date_keyword|/validate_date_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "date" value.
3913              
3914             =item B<parse_datetime STRING>
3915              
3916             Parse STRING and return a L<DateTime> object. STRING should be formatted according to the data source's native "datetime" (month, day, year, hour, minute, second) data type.
3917              
3918             If STRING is a valid datetime keyword (according to L<validate_datetime_keyword|/validate_datetime_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "datetime" value.
3919              
3920             =item B<parse_interval STRING [, MODE]>
3921              
3922             Parse STRING and return a L<DateTime::Duration> object. STRING should be formatted according to the data source's native "interval" (years, months, days, hours, minutes, seconds) data type.
3923              
3924             If STRING is a L<DateTime::Duration> object, a valid interval keyword (according to L<validate_interval_keyword|/validate_interval_keyword>), or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Otherwise, undef is returned if STRING could not be parsed as a valid "interval" value.
3925              
3926             This optional MODE argument determines how math is done on duration objects. If defined, the C<end_of_month> setting for each L<DateTime::Duration> object created by this column will have its mode set to MODE. Otherwise, the C<end_of_month> parameter will not be passed to the L<DateTime::Duration> constructor.
3927              
3928             Valid modes are C<wrap>, C<limit>, and C<preserve>. See the documentation for L<DateTime::Duration> for a full explanation.
3929              
3930             =item B<parse_time STRING>
3931              
3932             Parse STRING and return a L<Time::Clock> object. STRING should be formatted according to the data source's native "time" (hour, minute, second, fractional seconds) data type.
3933              
3934             If STRING is a valid time keyword (according to L<validate_time_keyword|/validate_time_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "time" value.
3935              
3936             =item B<parse_timestamp STRING>
3937              
3938             Parse STRING and return a L<DateTime> object. STRING should be formatted according to the data source's native "timestamp" (month, day, year, hour, minute, second, fractional seconds) data type. Fractional seconds are optional, and the acceptable precision may vary depending on the data source.
3939              
3940             If STRING is a valid timestamp keyword (according to L<validate_timestamp_keyword|/validate_timestamp_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "timestamp" value.
3941              
3942             =item B<parse_timestamp_with_time_zone STRING>
3943              
3944             Parse STRING and return a L<DateTime> object. STRING should be formatted according to the data source's native "timestamp with time zone" (month, day, year, hour, minute, second, fractional seconds, time zone) data type. Fractional seconds are optional, and the acceptable precision may vary depending on the data source.
3945              
3946             If STRING is a valid timestamp keyword (according to L<validate_timestamp_keyword|/validate_timestamp_keyword>) or if it looks like a function call (matches C</^\w+\(.*\)$/>) and L<keyword_function_calls|/keyword_function_calls> is true, then it is returned unmodified. Returns undef if STRING could not be parsed as a valid "timestamp with time zone" value.
3947              
3948             =item B<validate_boolean_keyword STRING>
3949              
3950             Returns true if STRING is a valid keyword for the "boolean" data type of the current data source, false otherwise. The default implementation accepts the values "TRUE" and "FALSE".
3951              
3952             =item B<validate_date_keyword STRING>
3953              
3954             Returns true if STRING is a valid keyword for the "date" (month, day, year) data type of the current data source, false otherwise. The default implementation always returns false.
3955              
3956             =item B<validate_datetime_keyword STRING>
3957              
3958             Returns true if STRING is a valid keyword for the "datetime" (month, day, year, hour, minute, second) data type of the current data source, false otherwise. The default implementation always returns false.
3959              
3960             =item B<validate_interval_keyword STRING>
3961              
3962             Returns true if STRING is a valid keyword for the "interval" (years, months, days, hours, minutes, seconds) data type of the current data source, false otherwise. The default implementation always returns false.
3963              
3964             =item B<validate_time_keyword STRING>
3965              
3966             Returns true if STRING is a valid keyword for the "time" (hour, minute, second, fractional seconds) data type of the current data source, false otherwise. The default implementation always returns false.
3967              
3968             =item B<validate_timestamp_keyword STRING>
3969              
3970             Returns true if STRING is a valid keyword for the "timestamp" (month, day, year, hour, minute, second, fractional seconds) data type of the current data source, false otherwise. The default implementation always returns false.
3971              
3972             =back
3973              
3974             =head1 DEVELOPMENT POLICY
3975              
3976             The L<Rose development policy|Rose/"DEVELOPMENT POLICY"> applies to this, and all C<Rose::*> modules. Please install L<Rose> from CPAN and then run "C<perldoc Rose>" for more information.
3977              
3978             =head1 SUPPORT
3979              
3980             Any L<Rose::DB> questions or problems can be posted to the L<Rose::DB::Object> mailing list. (If the volume ever gets high enough, I'll create a separate list for L<Rose::DB>, but it isn't an issue right now.) To subscribe to the list or view the archives, go here:
3981              
3982             L<http://groups.google.com/group/rose-db-object>
3983              
3984             Although the mailing list is the preferred support mechanism, you can also email the author (see below) or file bugs using the CPAN bug tracking system:
3985              
3986             L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Rose-DB>
3987              
3988             There's also a wiki and other resources linked from the Rose project home page:
3989              
3990             L<http://rosecode.org>
3991              
3992             =head1 CONTRIBUTORS
3993              
3994             Kostas Chatzikokolakis, Peter Karman, Brian Duggan, Lucian Dragus, Ask Bjørn Hansen, Sergey Leschenko, Ron Savage, Ferry Hendrikx
3995              
3996             =head1 AUTHOR
3997              
3998             John C. Siracusa (siracusa@gmail.com)
3999              
4000             =head1 LICENSE
4001              
4002             Copyright (c) 2010 by John C. Siracusa. All rights reserved. This program is
4003             free software; you can redistribute it and/or modify it under the same terms
4004             as Perl itself.