4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $me %dbdef_cache %virtual_fields_cache );
6 use subs qw(reload_dbdef);
8 use Carp qw(carp cluck croak confess);
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.23;
13 use FS::UID qw(dbh getotaker datasrc driver_name);
15 use FS::Msgcat qw(gettext);
18 use FS::part_virtual_field;
23 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
34 #ask FS::UID to run this stuff for us later
35 $FS::UID::callback{'FS::Record'} = sub {
37 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
38 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
39 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
44 FS::Record - Database record objects
49 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
51 $record = new FS::Record 'table', \%hash;
52 $record = new FS::Record 'table', { 'column' => 'value', ... };
54 $record = qsearchs FS::Record 'table', \%hash;
55 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
56 @records = qsearch FS::Record 'table', \%hash;
57 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
59 $table = $record->table;
60 $dbdef_table = $record->dbdef_table;
62 $value = $record->get('column');
63 $value = $record->getfield('column');
64 $value = $record->column;
66 $record->set( 'column' => 'value' );
67 $record->setfield( 'column' => 'value' );
68 $record->column('value');
70 %hash = $record->hash;
72 $hashref = $record->hashref;
74 $error = $record->insert;
76 $error = $record->delete;
78 $error = $new_record->replace($old_record);
80 # external use deprecated - handled by the database (at least for Pg, mysql)
81 $value = $record->unique('column');
83 $error = $record->ut_float('column');
84 $error = $record->ut_number('column');
85 $error = $record->ut_numbern('column');
86 $error = $record->ut_money('column');
87 $error = $record->ut_text('column');
88 $error = $record->ut_textn('column');
89 $error = $record->ut_alpha('column');
90 $error = $record->ut_alphan('column');
91 $error = $record->ut_phonen('column');
92 $error = $record->ut_anything('column');
93 $error = $record->ut_name('column');
95 $dbdef = reload_dbdef;
96 $dbdef = reload_dbdef "/non/standard/filename";
99 $quoted_value = _quote($value,'table','field');
102 $fields = hfields('table');
103 if ( $fields->{Field} ) { # etc.
105 @fields = fields 'table'; #as a subroutine
106 @fields = $record->fields; #as a method call
111 (Mostly) object-oriented interface to database records. Records are currently
112 implemented on top of DBI. FS::Record is intended as a base class for
113 table-specific classes to inherit from, i.e. FS::cust_main.
119 =item new [ TABLE, ] HASHREF
121 Creates a new record. It doesn't store it in the database, though. See
122 L<"insert"> for that.
124 Note that the object stores this hash reference, not a distinct copy of the
125 hash it points to. You can ask the object for a copy with the I<hash>
128 TABLE can only be omitted when a dervived class overrides the table method.
134 my $class = ref($proto) || $proto;
136 bless ($self, $class);
138 unless ( defined ( $self->table ) ) {
139 $self->{'Table'} = shift;
140 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
143 $self->{'Hash'} = shift;
145 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
146 $self->{'Hash'}{$field}='';
149 $self->_rebless if $self->can('_rebless');
151 $self->{'modified'} = 0;
153 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
160 my $class = ref($proto) || $proto;
162 bless ($self, $class);
164 $self->{'Table'} = shift unless defined ( $self->table );
166 my $hashref = $self->{'Hash'} = shift;
168 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
169 my $obj = $cache->cache->{$hashref->{$cache->key}};
170 $obj->_cache($hashref, $cache) if $obj->can('_cache');
173 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
180 my $class = ref($proto) || $proto;
182 bless ($self, $class);
183 if ( defined $self->table ) {
184 cluck "create constructor is deprecated, use new!";
187 croak "FS::Record::create called (not from a subclass)!";
191 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
193 Searches the database for all records matching (at least) the key/value pairs
194 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
195 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
198 ###oops, argh, FS::Record::new only lets us create database fields.
199 #Normal behaviour if SELECT is not specified is `*', as in
200 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
201 #feature where you can specify SELECT - remember, the objects returned,
202 #although blessed into the appropriate `FS::TABLE' package, will only have the
203 #fields you specify. This might have unwanted results if you then go calling
204 #regular FS::TABLE methods
210 my($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
211 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
213 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
218 my $table = $cache ? $cache->table : $stable;
219 my $dbdef_table = $dbdef->table($table)
220 or die "No schema for table $table found - ".
221 "do you need to create it or run dbdef-create?";
222 my $pkey = $dbdef_table->primary_key;
224 my @real_fields = grep exists($record->{$_}), real_fields($table);
226 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
227 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
229 cluck "warning: FS::$table not loaded; virtual fields not searchable";
230 @virtual_fields = ();
233 my $statement = "SELECT $select FROM $stable";
234 $statement .= " $addl_from" if $addl_from;
235 if ( @real_fields or @virtual_fields ) {
236 $statement .= ' WHERE '. join(' AND ',
241 if ( ref($record->{$_}) ) {
242 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
243 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
244 if ( uc($op) eq 'ILIKE' ) {
246 $record->{$_}{'value'} = lc($record->{$_}{'value'});
247 $column = "LOWER($_)";
249 $record->{$_} = $record->{$_}{'value'}
252 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
254 if ( driver_name eq 'Pg' ) {
255 my $type = $dbdef->table($table)->column($column)->type;
256 if ( $type =~ /(int|serial)/i ) {
257 qq-( $column IS NULL )-;
259 qq-( $column IS NULL OR $column = '' )-;
262 qq-( $column IS NULL OR $column = "" )-;
264 } elsif ( $op eq '!=' ) {
265 if ( driver_name eq 'Pg' ) {
266 my $type = $dbdef->table($table)->column($column)->type;
267 if ( $type =~ /(int|serial)/i ) {
268 qq-( $column IS NOT NULL )-;
270 qq-( $column IS NOT NULL AND $column != '' )-;
273 qq-( $column IS NOT NULL AND $column != "" )-;
276 if ( driver_name eq 'Pg' ) {
277 qq-( $column $op '' )-;
279 qq-( $column $op "" )-;
289 if ( ref($record->{$_}) ) {
290 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
291 if ( uc($op) eq 'ILIKE' ) {
293 $record->{$_}{'value'} = lc($record->{$_}{'value'});
294 $column = "LOWER($_)";
296 $record->{$_} = $record->{$_}{'value'};
299 # ... EXISTS ( SELECT name, value FROM part_virtual_field
301 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
302 # WHERE recnum = svc_acct.svcnum
303 # AND (name, value) = ('egad', 'brain') )
305 my $value = $record->{$_};
309 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
310 "( SELECT part_virtual_field.name, virtual_field.value ".
311 "FROM part_virtual_field JOIN virtual_field ".
312 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
313 "WHERE virtual_field.recnum = ${table}.${pkey} ".
314 "AND part_virtual_field.name = '${column}'".
316 " AND virtual_field.value ${op} '${value}'"
320 } @virtual_fields ) );
324 $statement .= " $extra_sql" if defined($extra_sql);
326 warn "[debug]$me $statement\n" if $DEBUG > 1;
327 my $sth = $dbh->prepare($statement)
328 or croak "$dbh->errstr doing $statement";
333 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
335 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
336 && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
338 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
340 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
344 # $sth->execute( map $record->{$_},
345 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
346 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
348 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
350 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
351 @virtual_fields = "FS::$table"->virtual_fields;
353 cluck "warning: FS::$table not loaded; virtual fields not returned either";
354 @virtual_fields = ();
358 tie %result, "Tie::IxHash";
359 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
361 %result = map { $_->{$pkey}, $_ } @stuff;
363 @result{@stuff} = @stuff;
368 if ( keys(%result) and @virtual_fields ) {
370 "SELECT virtual_field.recnum, part_virtual_field.name, ".
371 "virtual_field.value ".
372 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
373 "WHERE part_virtual_field.dbtable = '$table' AND ".
374 "virtual_field.recnum IN (".
375 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
376 join(q!', '!, @virtual_fields) . "')";
377 warn "[debug]$me $statement\n" if $DEBUG > 1;
378 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
379 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
381 foreach (@{ $sth->fetchall_arrayref({}) }) {
382 my $recnum = $_->{recnum};
383 my $name = $_->{name};
384 my $value = $_->{value};
385 if (exists($result{$recnum})) {
386 $result{$recnum}->{$name} = $value;
391 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
392 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
393 #derivied class didn't override new method, so this optimization is safe
396 new_or_cached( "FS::$table", { %{$_} }, $cache )
400 new( "FS::$table", { %{$_} } )
404 warn "untested code (class FS::$table uses custom new method)";
406 eval 'FS::'. $table. '->new( { %{$_} } )';
410 # Check for encrypted fields and decrypt them.
411 if ($conf->exists('encryption') && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
412 foreach my $record (@return) {
413 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
414 # Set it directly... This may cause a problem in the future...
415 $record->setfield($field, $record->decrypt($record->getfield($field)));
420 cluck "warning: FS::$table not loaded; returning FS::Record objects";
422 FS::Record->new( $table, { %{$_} } );
428 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
430 Experimental JOINed search method. Using this method, you can execute a
431 single SELECT spanning multiple tables, and cache the results for subsequent
432 method calls. Interface will almost definately change in an incompatible
440 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
441 my $cache = FS::SearchCache->new( $ptable, $pkey );
444 grep { !$saw{$_->getfield($pkey)}++ }
445 qsearch($table, $record, $select, $extra_sql, $cache )
449 =item qsearchs TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
451 Same as qsearch, except that if more than one record matches, it B<carp>s but
452 returns the first. If this happens, you either made a logic error in asking
453 for a single item, or your data is corrupted.
457 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
459 my(@result) = qsearch(@_);
460 cluck "warning: Multiple records in scalar search ($table)"
461 if scalar(@result) > 1;
462 #should warn more vehemently if the search was on a primary key?
463 scalar(@result) ? ($result[0]) : ();
474 Returns the table name.
479 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
486 Returns the DBIx::DBSchema::Table object for the table.
492 my($table)=$self->table;
493 $dbdef->table($table);
496 =item get, getfield COLUMN
498 Returns the value of the column/field/key COLUMN.
503 my($self,$field) = @_;
504 # to avoid "Use of unitialized value" errors
505 if ( defined ( $self->{Hash}->{$field} ) ) {
506 $self->{Hash}->{$field};
516 =item set, setfield COLUMN, VALUE
518 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
523 my($self,$field,$value) = @_;
524 $self->{'modified'} = 1;
525 $self->{'Hash'}->{$field} = $value;
532 =item AUTLOADED METHODS
534 $record->column is a synonym for $record->get('column');
536 $record->column('value') is a synonym for $record->set('column','value');
543 my($field)=$AUTOLOAD;
545 if ( defined($value) ) {
546 confess "errant AUTOLOAD $field for $self (arg $value)"
547 unless ref($self) && $self->can('setfield');
548 $self->setfield($field,$value);
550 confess "errant AUTOLOAD $field for $self (no args)"
551 unless ref($self) && $self->can('getfield');
552 $self->getfield($field);
558 # my $field = $AUTOLOAD;
560 # if ( defined($_[1]) ) {
561 # $_[0]->setfield($field, $_[1]);
563 # $_[0]->getfield($field);
569 Returns a list of the column/value pairs, usually for assigning to a new hash.
571 To make a distinct duplicate of an FS::Record object, you can do:
573 $new = new FS::Record ( $old->table, { $old->hash } );
579 confess $self. ' -> hash: Hash attribute is undefined'
580 unless defined($self->{'Hash'});
581 %{ $self->{'Hash'} };
586 Returns a reference to the column/value hash. This may be deprecated in the
587 future; if there's a reason you can't just use the autoloaded or get/set
599 Returns true if any of this object's values have been modified with set (or via
600 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
612 Inserts this record to the database. If there is an error, returns the error,
613 otherwise returns false.
621 my $error = $self->check;
622 return $error if $error;
624 #single-field unique keys are given a value if false
625 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
626 foreach ( $self->dbdef_table->unique->singles ) {
627 $self->unique($_) unless $self->getfield($_);
630 #and also the primary key, if the database isn't going to
631 my $primary_key = $self->dbdef_table->primary_key;
633 if ( $primary_key ) {
634 my $col = $self->dbdef_table->column($primary_key);
637 uc($col->type) eq 'SERIAL'
638 || ( driver_name eq 'Pg'
639 && defined($col->default)
640 && $col->default =~ /^nextval\(/i
642 || ( driver_name eq 'mysql'
643 && defined($col->local)
644 && $col->local =~ /AUTO_INCREMENT/i
646 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
649 my $table = $self->table;
652 # Encrypt before the database
653 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . 'encrypted_fields')) {
654 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
655 $self->{'saved'} = $self->getfield($field);
656 $self->setfield($field, $self->enrypt($self->getfield($field)));
661 #false laziness w/delete
663 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
666 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
669 my $statement = "INSERT INTO $table ( ".
670 join( ', ', @real_fields ).
672 join( ', ', @values ).
675 warn "[debug]$me $statement\n" if $DEBUG > 1;
676 my $sth = dbh->prepare($statement) or return dbh->errstr;
678 local $SIG{HUP} = 'IGNORE';
679 local $SIG{INT} = 'IGNORE';
680 local $SIG{QUIT} = 'IGNORE';
681 local $SIG{TERM} = 'IGNORE';
682 local $SIG{TSTP} = 'IGNORE';
683 local $SIG{PIPE} = 'IGNORE';
685 $sth->execute or return $sth->errstr;
688 if ( $db_seq ) { # get inserted id from the database, if applicable
689 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
690 if ( driver_name eq 'Pg' ) {
692 my $oid = $sth->{'pg_oid_status'};
693 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
694 my $i_sth = dbh->prepare($i_sql) or do {
695 dbh->rollback if $FS::UID::AutoCommit;
698 $i_sth->execute($oid) or do {
699 dbh->rollback if $FS::UID::AutoCommit;
700 return $i_sth->errstr;
702 $insertid = $i_sth->fetchrow_arrayref->[0];
704 } elsif ( driver_name eq 'mysql' ) {
706 $insertid = dbh->{'mysql_insertid'};
707 # work around mysql_insertid being null some of the time, ala RT :/
708 unless ( $insertid ) {
709 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
710 "using SELECT LAST_INSERT_ID();";
711 my $i_sql = "SELECT LAST_INSERT_ID()";
712 my $i_sth = dbh->prepare($i_sql) or do {
713 dbh->rollback if $FS::UID::AutoCommit;
716 $i_sth->execute or do {
717 dbh->rollback if $FS::UID::AutoCommit;
718 return $i_sth->errstr;
720 $insertid = $i_sth->fetchrow_arrayref->[0];
724 dbh->rollback if $FS::UID::AutoCommit;
725 return "don't know how to retreive inserted ids from ". driver_name.
726 ", try using counterfiles (maybe run dbdef-create?)";
728 $self->setfield($primary_key, $insertid);
732 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
733 $self->virtual_fields;
734 if (@virtual_fields) {
735 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
737 my $vfieldpart = $self->vfieldpart_hashref;
739 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
742 my $v_sth = dbh->prepare($v_statement) or do {
743 dbh->rollback if $FS::UID::AutoCommit;
747 foreach (keys(%v_values)) {
748 $v_sth->execute($self->getfield($primary_key),
752 dbh->rollback if $FS::UID::AutoCommit;
753 return $v_sth->errstr;
760 if ( defined $dbdef->table('h_'. $table) ) {
761 my $h_statement = $self->_h_statement('insert');
762 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
763 $h_sth = dbh->prepare($h_statement) or do {
764 dbh->rollback if $FS::UID::AutoCommit;
770 $h_sth->execute or return $h_sth->errstr if $h_sth;
772 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
774 # Now that it has been saved, reset the encrypted fields so that $new
776 foreach my $field (keys %{$saved}) {
777 $self->setfield($field, $saved->{$field});
785 Depriciated (use insert instead).
790 cluck "warning: FS::Record::add deprecated!";
791 insert @_; #call method in this scope
796 Delete this record from the database. If there is an error, returns the error,
797 otherwise returns false.
804 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
806 $self->getfield($_) eq ''
807 #? "( $_ IS NULL OR $_ = \"\" )"
808 ? ( driver_name eq 'Pg'
810 : "( $_ IS NULL OR $_ = \"\" )"
812 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
813 } ( $self->dbdef_table->primary_key )
814 ? ( $self->dbdef_table->primary_key)
815 : real_fields($self->table)
817 warn "[debug]$me $statement\n" if $DEBUG > 1;
818 my $sth = dbh->prepare($statement) or return dbh->errstr;
821 if ( defined $dbdef->table('h_'. $self->table) ) {
822 my $h_statement = $self->_h_statement('delete');
823 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
824 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
829 my $primary_key = $self->dbdef_table->primary_key;
832 my $vfp = $self->vfieldpart_hashref;
833 foreach($self->virtual_fields) {
834 next if $self->getfield($_) eq '';
835 unless(@del_vfields) {
836 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
837 $v_sth = dbh->prepare($st) or return dbh->errstr;
839 push @del_vfields, $_;
842 local $SIG{HUP} = 'IGNORE';
843 local $SIG{INT} = 'IGNORE';
844 local $SIG{QUIT} = 'IGNORE';
845 local $SIG{TERM} = 'IGNORE';
846 local $SIG{TSTP} = 'IGNORE';
847 local $SIG{PIPE} = 'IGNORE';
849 my $rc = $sth->execute or return $sth->errstr;
850 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
851 $h_sth->execute or return $h_sth->errstr if $h_sth;
852 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
853 or return $v_sth->errstr
854 foreach (@del_vfields);
856 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
858 #no need to needlessly destoy the data either (causes problems actually)
859 #undef $self; #no need to keep object!
866 Depriciated (use delete instead).
871 cluck "warning: FS::Record::del deprecated!";
872 &delete(@_); #call method in this scope
875 =item replace OLD_RECORD
877 Replace the OLD_RECORD with this one in the database. If there is an error,
878 returns the error, otherwise returns false.
888 if (!defined($old)) {
889 warn "[debug]$me replace called with no arguments; autoloading old record\n"
891 my $primary_key = $new->dbdef_table->primary_key;
892 if ( $primary_key ) {
893 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
894 or croak "can't find ". $new->table. ".$primary_key ".
895 $new->$primary_key();
897 croak $new->table. " has no primary key; pass old record as argument";
901 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
903 return "Records not in same table!" unless $new->table eq $old->table;
905 my $primary_key = $old->dbdef_table->primary_key;
906 return "Can't change $primary_key"
908 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
910 my $error = $new->check;
911 return $error if $error;
913 # Encrypt for replace
914 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
915 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
916 $saved->{$field} = $new->getfield($field);
917 $new->setfield($field, $new->encrypt($new->getfield($field)));
921 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
922 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
923 ? ($_, $new->getfield($_)) : () } $old->fields;
925 unless ( keys(%diff) ) {
926 carp "[warning]$me $new -> replace $old: records identical";
930 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
932 "$_ = ". _quote($new->getfield($_),$old->table,$_)
933 } real_fields($old->table)
938 if ( $old->getfield($_) eq '' ) {
940 #false laziness w/qsearch
941 if ( driver_name eq 'Pg' ) {
942 my $type = $old->dbdef_table->column($_)->type;
943 if ( $type =~ /(int|serial)/i ) {
946 qq-( $_ IS NULL OR $_ = '' )-;
949 qq-( $_ IS NULL OR $_ = "" )-;
953 "$_ = ". _quote($old->getfield($_),$old->table,$_);
956 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
959 warn "[debug]$me $statement\n" if $DEBUG > 1;
960 my $sth = dbh->prepare($statement) or return dbh->errstr;
963 if ( defined $dbdef->table('h_'. $old->table) ) {
964 my $h_old_statement = $old->_h_statement('replace_old');
965 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
966 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
972 if ( defined $dbdef->table('h_'. $new->table) ) {
973 my $h_new_statement = $new->_h_statement('replace_new');
974 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
975 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
980 # For virtual fields we have three cases with different SQL
981 # statements: add, replace, delete
985 my (@add_vfields, @rep_vfields, @del_vfields);
986 my $vfp = $old->vfieldpart_hashref;
987 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
988 if($diff{$_} eq '') {
990 unless(@del_vfields) {
991 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
992 "AND vfieldpart = ?";
993 warn "[debug]$me $st\n" if $DEBUG > 2;
994 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
996 push @del_vfields, $_;
997 } elsif($old->getfield($_) eq '') {
999 unless(@add_vfields) {
1000 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1002 warn "[debug]$me $st\n" if $DEBUG > 2;
1003 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1005 push @add_vfields, $_;
1008 unless(@rep_vfields) {
1009 my $st = "UPDATE virtual_field SET value = ? ".
1010 "WHERE recnum = ? AND vfieldpart = ?";
1011 warn "[debug]$me $st\n" if $DEBUG > 2;
1012 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1014 push @rep_vfields, $_;
1018 local $SIG{HUP} = 'IGNORE';
1019 local $SIG{INT} = 'IGNORE';
1020 local $SIG{QUIT} = 'IGNORE';
1021 local $SIG{TERM} = 'IGNORE';
1022 local $SIG{TSTP} = 'IGNORE';
1023 local $SIG{PIPE} = 'IGNORE';
1025 my $rc = $sth->execute or return $sth->errstr;
1026 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1027 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1028 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1030 $v_del_sth->execute($old->getfield($primary_key),
1032 or return $v_del_sth->errstr
1033 foreach(@del_vfields);
1035 $v_add_sth->execute($new->getfield($_),
1036 $old->getfield($primary_key),
1038 or return $v_add_sth->errstr
1039 foreach(@add_vfields);
1041 $v_rep_sth->execute($new->getfield($_),
1042 $old->getfield($primary_key),
1044 or return $v_rep_sth->errstr
1045 foreach(@rep_vfields);
1047 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1049 # Now that it has been saved, reset the encrypted fields so that $new
1050 # can still be used.
1051 foreach my $field (keys %{$saved}) {
1052 $new->setfield($field, $saved->{$field});
1061 Depriciated (use replace instead).
1066 cluck "warning: FS::Record::rep deprecated!";
1067 replace @_; #call method in this scope
1072 Checks virtual fields (using check_blocks). Subclasses should still provide
1073 a check method to validate real fields, foreign keys, etc., and call this
1074 method via $self->SUPER::check.
1076 (FIXME: Should this method try to make sure that it I<is> being called from
1077 a subclass's check method, to keep the current semantics as far as possible?)
1082 #confess "FS::Record::check not implemented; supply one in subclass!";
1085 foreach my $field ($self->virtual_fields) {
1086 for ($self->getfield($field)) {
1087 # See notes on check_block in FS::part_virtual_field.
1088 eval $self->pvf($field)->check_block;
1090 #this is bad, probably want to follow the stack backtrace up and see
1092 my $err = "Fatal error checking $field for $self";
1094 return "$err (see log for backtrace): $@";
1097 $self->setfield($field, $_);
1104 my( $self, $action ) = @_;
1107 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1108 real_fields($self->table);
1110 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1112 "INSERT INTO h_". $self->table. " ( ".
1113 join(', ', qw(history_date history_user history_action), @fields ).
1115 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
1122 B<Warning>: External use is B<deprecated>.
1124 Replaces COLUMN in record with a unique number, using counters in the
1125 filesystem. Used by the B<insert> method on single-field unique columns
1126 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1127 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1129 Returns the new value.
1134 my($self,$field) = @_;
1135 my($table)=$self->table;
1137 croak "Unique called on field $field, but it is ",
1138 $self->getfield($field),
1140 if $self->getfield($field);
1142 #warn "table $table is tainted" if is_tainted($table);
1143 #warn "field $field is tainted" if is_tainted($field);
1145 my($counter) = new File::CounterFile "$table.$field",0;
1147 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1149 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1152 my $index = $counter->inc;
1153 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1155 $index =~ /^(\d*)$/;
1158 $self->setfield($field,$index);
1162 =item ut_float COLUMN
1164 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1165 null. If there is an error, returns the error, otherwise returns false.
1170 my($self,$field)=@_ ;
1171 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1172 $self->getfield($field) =~ /^(\d+)$/ ||
1173 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1174 $self->getfield($field) =~ /^(\d+e\d+)$/)
1175 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1176 $self->setfield($field,$1);
1180 =item ut_snumber COLUMN
1182 Check/untaint signed numeric data (whole numbers). May not be null. If there
1183 is an error, returns the error, otherwise returns false.
1188 my($self, $field) = @_;
1189 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1190 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1191 $self->setfield($field, "$1$2");
1195 =item ut_number COLUMN
1197 Check/untaint simple numeric data (whole numbers). May not be null. If there
1198 is an error, returns the error, otherwise returns false.
1203 my($self,$field)=@_;
1204 $self->getfield($field) =~ /^(\d+)$/
1205 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1206 $self->setfield($field,$1);
1210 =item ut_numbern COLUMN
1212 Check/untaint simple numeric data (whole numbers). May be null. If there is
1213 an error, returns the error, otherwise returns false.
1218 my($self,$field)=@_;
1219 $self->getfield($field) =~ /^(\d*)$/
1220 or return "Illegal (numeric) $field: ". $self->getfield($field);
1221 $self->setfield($field,$1);
1225 =item ut_money COLUMN
1227 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1228 is an error, returns the error, otherwise returns false.
1233 my($self,$field)=@_;
1234 $self->setfield($field, 0) if $self->getfield($field) eq '';
1235 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1236 or return "Illegal (money) $field: ". $self->getfield($field);
1237 #$self->setfield($field, "$1$2$3" || 0);
1238 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1242 =item ut_text COLUMN
1244 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1245 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1246 May not be null. If there is an error, returns the error, otherwise returns
1252 my($self,$field)=@_;
1253 #warn "msgcat ". \&msgcat. "\n";
1254 #warn "notexist ". \¬exist. "\n";
1255 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1256 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1257 or return gettext('illegal_or_empty_text'). " $field: ".
1258 $self->getfield($field);
1259 $self->setfield($field,$1);
1263 =item ut_textn COLUMN
1265 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1266 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1267 May be null. If there is an error, returns the error, otherwise returns false.
1272 my($self,$field)=@_;
1273 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1274 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1275 $self->setfield($field,$1);
1279 =item ut_alpha COLUMN
1281 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1282 an error, returns the error, otherwise returns false.
1287 my($self,$field)=@_;
1288 $self->getfield($field) =~ /^(\w+)$/
1289 or return "Illegal or empty (alphanumeric) $field: ".
1290 $self->getfield($field);
1291 $self->setfield($field,$1);
1295 =item ut_alpha COLUMN
1297 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1298 error, returns the error, otherwise returns false.
1303 my($self,$field)=@_;
1304 $self->getfield($field) =~ /^(\w*)$/
1305 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1306 $self->setfield($field,$1);
1310 =item ut_phonen COLUMN [ COUNTRY ]
1312 Check/untaint phone numbers. May be null. If there is an error, returns
1313 the error, otherwise returns false.
1315 Takes an optional two-letter ISO country code; without it or with unsupported
1316 countries, ut_phonen simply calls ut_alphan.
1321 my( $self, $field, $country ) = @_;
1322 return $self->ut_alphan($field) unless defined $country;
1323 my $phonen = $self->getfield($field);
1324 if ( $phonen eq '' ) {
1325 $self->setfield($field,'');
1326 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1328 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1329 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1330 $phonen = "$1-$2-$3";
1331 $phonen .= " x$4" if $4;
1332 $self->setfield($field,$phonen);
1334 warn "warning: don't know how to check phone numbers for country $country";
1335 return $self->ut_textn($field);
1342 Check/untaint ip addresses. IPv4 only for now.
1347 my( $self, $field ) = @_;
1348 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1349 or return "Illegal (IP address) $field: ". $self->getfield($field);
1350 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1351 $self->setfield($field, "$1.$2.$3.$4");
1357 Check/untaint ip addresses. IPv4 only for now. May be null.
1362 my( $self, $field ) = @_;
1363 if ( $self->getfield($field) =~ /^()$/ ) {
1364 $self->setfield($field,'');
1367 $self->ut_ip($field);
1371 =item ut_domain COLUMN
1373 Check/untaint host and domain names.
1378 my( $self, $field ) = @_;
1379 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1380 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1381 or return "Illegal (domain) $field: ". $self->getfield($field);
1382 $self->setfield($field,$1);
1386 =item ut_name COLUMN
1388 Check/untaint proper names; allows alphanumerics, spaces and the following
1389 punctuation: , . - '
1396 my( $self, $field ) = @_;
1397 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1398 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1399 $self->setfield($field,$1);
1405 Check/untaint zip codes.
1410 my( $self, $field, $country ) = @_;
1411 if ( $country eq 'US' ) {
1412 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1413 or return gettext('illegal_zip'). " $field for country $country: ".
1414 $self->getfield($field);
1415 $self->setfield($field,$1);
1417 if ( $self->getfield($field) =~ /^\s*$/ ) {
1418 $self->setfield($field,'');
1420 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1421 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1422 $self->setfield($field,$1);
1428 =item ut_country COLUMN
1430 Check/untaint country codes. Country names are changed to codes, if possible -
1431 see L<Locale::Country>.
1436 my( $self, $field ) = @_;
1437 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1438 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1439 && country2code($1) ) {
1440 $self->setfield($field,uc(country2code($1)));
1443 $self->getfield($field) =~ /^(\w\w)$/
1444 or return "Illegal (country) $field: ". $self->getfield($field);
1445 $self->setfield($field,uc($1));
1449 =item ut_anything COLUMN
1451 Untaints arbitrary data. Be careful.
1456 my( $self, $field ) = @_;
1457 $self->getfield($field) =~ /^(.*)$/s
1458 or return "Illegal $field: ". $self->getfield($field);
1459 $self->setfield($field,$1);
1463 =item ut_enum COLUMN CHOICES_ARRAYREF
1465 Check/untaint a column, supplying all possible choices, like the "enum" type.
1470 my( $self, $field, $choices ) = @_;
1471 foreach my $choice ( @$choices ) {
1472 if ( $self->getfield($field) eq $choice ) {
1473 $self->setfield($choice);
1477 return "Illegal (enum) field $field: ". $self->getfield($field);
1480 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1482 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1483 on the column first.
1487 sub ut_foreign_key {
1488 my( $self, $field, $table, $foreign ) = @_;
1489 qsearchs($table, { $foreign => $self->getfield($field) })
1490 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1491 " in $table.$foreign";
1495 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1497 Like ut_foreign_key, except the null value is also allowed.
1501 sub ut_foreign_keyn {
1502 my( $self, $field, $table, $foreign ) = @_;
1503 $self->getfield($field)
1504 ? $self->ut_foreign_key($field, $table, $foreign)
1509 =item virtual_fields [ TABLE ]
1511 Returns a list of virtual fields defined for the table. This should not
1512 be exported, and should only be called as an instance or class method.
1516 sub virtual_fields {
1519 $table = $self->table or confess "virtual_fields called on non-table";
1521 confess "Unknown table $table" unless $dbdef->table($table);
1523 return () unless $self->dbdef->table('part_virtual_field');
1525 unless ( $virtual_fields_cache{$table} ) {
1526 my $query = 'SELECT name from part_virtual_field ' .
1527 "WHERE dbtable = '$table'";
1529 my $result = $dbh->selectcol_arrayref($query);
1530 confess $dbh->errstr if $dbh->err;
1531 $virtual_fields_cache{$table} = $result;
1534 @{$virtual_fields_cache{$table}};
1539 =item fields [ TABLE ]
1541 This is a wrapper for real_fields and virtual_fields. Code that called
1542 fields before should probably continue to call fields.
1547 my $something = shift;
1549 if($something->isa('FS::Record')) {
1550 $table = $something->table;
1552 $table = $something;
1553 $something = "FS::$table";
1555 return (real_fields($table), $something->virtual_fields());
1560 =item pvf FIELD_NAME
1562 Returns the FS::part_virtual_field object corresponding to a field in the
1563 record (specified by FIELD_NAME).
1568 my ($self, $name) = (shift, shift);
1570 if(grep /^$name$/, $self->virtual_fields) {
1571 return qsearchs('part_virtual_field', { dbtable => $self->table,
1581 =item real_fields [ TABLE ]
1583 Returns a list of the real columns in the specified table. Called only by
1584 fields() and other subroutines elsewhere in FS::Record.
1591 my($table_obj) = $dbdef->table($table);
1592 confess "Unknown table $table" unless $table_obj;
1593 $table_obj->columns;
1596 =item reload_dbdef([FILENAME])
1598 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1599 non-default filename. This command is executed at startup unless
1600 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1605 my $file = shift || $dbdef_file;
1607 unless ( exists $dbdef_cache{$file} ) {
1608 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1609 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1610 or die "can't load database schema from $file";
1612 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1614 $dbdef = $dbdef_cache{$file};
1619 Returns the current database definition. See L<DBIx::DBSchema>.
1623 sub dbdef { $dbdef; }
1625 =item _quote VALUE, TABLE, COLUMN
1627 This is an internal function used to construct SQL statements. It returns
1628 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1629 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1634 my($value, $table, $column) = @_;
1635 my $column_obj = $dbdef->table($table)->column($column);
1636 my $column_type = $column_obj->type;
1637 my $nullable = $column_obj->null;
1639 warn " $table.$column: $value ($column_type".
1640 ( $nullable ? ' NULL' : ' NOT NULL' ).
1641 ")\n" if $DEBUG > 2;
1643 if ( $value eq '' && $column_type =~ /^int/ ) {
1647 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1651 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1652 ! $column_type =~ /(char|binary|text)$/i ) {
1659 =item vfieldpart_hashref TABLE
1661 Returns a hashref of virtual field names and vfieldparts applicable to the given
1666 sub vfieldpart_hashref {
1668 my $table = $self->table;
1670 return {} unless $self->dbdef->table('part_virtual_field');
1673 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1674 "dbtable = '$table'";
1675 my $sth = $dbh->prepare($statement);
1676 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1677 return { map { $_->{name}, $_->{vfieldpart} }
1678 @{$sth->fetchall_arrayref({})} };
1685 This is deprecated. Don't use it.
1687 It returns a hash-type list with the fields of this record's table set true.
1692 carp "warning: hfields is deprecated";
1695 foreach (fields($table)) {
1704 "$_: ". $self->getfield($_). "|"
1705 } (fields($self->table)) );
1709 my ($self, $value) = @_;
1712 if ($conf->exists('encryption')) {
1713 if ($self->is_encrypted($value)) {
1714 # Return the original value if it isn't plaintext.
1715 $encrypted = $value;
1718 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1719 # RSA doesn't like the empty string so let's pack it up
1720 # The database doesn't like the RSA data so uuencode it
1721 my $length = length($value)+1;
1722 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1724 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1732 my ($self, $value) = @_;
1733 # Possible Bug - Some work may be required here....
1735 if (length($value) > 80) {
1743 my ($self,$value) = @_;
1744 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1745 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1747 if (ref($rsa_decrypt) =~ /::RSA/) {
1748 my $encrypted = unpack ("u*", $value);
1749 $decrypted = unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1757 #Initialize the Module
1758 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1760 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1761 $rsa_module = $conf->config('encryptionmodule');
1765 eval ("require $rsa_module"); # No need to import the namespace
1768 # Initialize Encryption
1769 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1770 my $public_key = join("\n",$conf->config('encryptionpublickey'));
1771 $rsa_encrypt = $rsa_module->new_public_key($public_key);
1774 # Intitalize Decryption
1775 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1776 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1777 $rsa_decrypt = $rsa_module->new_private_key($private_key);
1781 sub DESTROY { return; }
1785 # #use Carp qw(cluck);
1786 # #cluck "DESTROYING $self";
1787 # warn "DESTROYING $self";
1791 # return ! eval { join('',@_), kill 0; 1; };
1798 This module should probably be renamed, since much of the functionality is
1799 of general use. It is not completely unlike Adapter::DBI (see below).
1801 Exported qsearch and qsearchs should be deprecated in favor of method calls
1802 (against an FS::Record object like the old search and searchs that qsearch
1803 and qsearchs were on top of.)
1805 The whole fields / hfields mess should be removed.
1807 The various WHERE clauses should be subroutined.
1809 table string should be deprecated in favor of DBIx::DBSchema::Table.
1811 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1812 true maps to the database (and WHERE clauses) would also help.
1814 The ut_ methods should ask the dbdef for a default length.
1816 ut_sqltype (like ut_varchar) should all be defined
1818 A fallback check method should be provided which uses the dbdef.
1820 The ut_money method assumes money has two decimal digits.
1822 The Pg money kludge in the new method only strips `$'.
1824 The ut_phonen method only checks US-style phone numbers.
1826 The _quote function should probably use ut_float instead of a regex.
1828 All the subroutines probably should be methods, here or elsewhere.
1830 Probably should borrow/use some dbdef methods where appropriate (like sub
1833 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1834 or allow it to be set. Working around it is ugly any way around - DBI should
1835 be fixed. (only affects RDBMS which return uppercase column names)
1837 ut_zip should take an optional country like ut_phone.
1841 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1843 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.