4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $me %dbdef_cache %virtual_fields_cache $nowarn_identical );
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.25;
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);
28 $nowarn_identical = 0;
36 #ask FS::UID to run this stuff for us later
37 $FS::UID::callback{'FS::Record'} = sub {
39 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
40 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
41 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
46 FS::Record - Database record objects
51 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
53 $record = new FS::Record 'table', \%hash;
54 $record = new FS::Record 'table', { 'column' => 'value', ... };
56 $record = qsearchs FS::Record 'table', \%hash;
57 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
58 @records = qsearch FS::Record 'table', \%hash;
59 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
61 $table = $record->table;
62 $dbdef_table = $record->dbdef_table;
64 $value = $record->get('column');
65 $value = $record->getfield('column');
66 $value = $record->column;
68 $record->set( 'column' => 'value' );
69 $record->setfield( 'column' => 'value' );
70 $record->column('value');
72 %hash = $record->hash;
74 $hashref = $record->hashref;
76 $error = $record->insert;
78 $error = $record->delete;
80 $error = $new_record->replace($old_record);
82 # external use deprecated - handled by the database (at least for Pg, mysql)
83 $value = $record->unique('column');
85 $error = $record->ut_float('column');
86 $error = $record->ut_number('column');
87 $error = $record->ut_numbern('column');
88 $error = $record->ut_money('column');
89 $error = $record->ut_text('column');
90 $error = $record->ut_textn('column');
91 $error = $record->ut_alpha('column');
92 $error = $record->ut_alphan('column');
93 $error = $record->ut_phonen('column');
94 $error = $record->ut_anything('column');
95 $error = $record->ut_name('column');
97 $dbdef = reload_dbdef;
98 $dbdef = reload_dbdef "/non/standard/filename";
101 $quoted_value = _quote($value,'table','field');
104 $fields = hfields('table');
105 if ( $fields->{Field} ) { # etc.
107 @fields = fields 'table'; #as a subroutine
108 @fields = $record->fields; #as a method call
113 (Mostly) object-oriented interface to database records. Records are currently
114 implemented on top of DBI. FS::Record is intended as a base class for
115 table-specific classes to inherit from, i.e. FS::cust_main.
121 =item new [ TABLE, ] HASHREF
123 Creates a new record. It doesn't store it in the database, though. See
124 L<"insert"> for that.
126 Note that the object stores this hash reference, not a distinct copy of the
127 hash it points to. You can ask the object for a copy with the I<hash>
130 TABLE can only be omitted when a dervived class overrides the table method.
136 my $class = ref($proto) || $proto;
138 bless ($self, $class);
140 unless ( defined ( $self->table ) ) {
141 $self->{'Table'} = shift;
142 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
145 $self->{'Hash'} = shift;
147 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
148 $self->{'Hash'}{$field}='';
151 $self->_rebless if $self->can('_rebless');
153 $self->{'modified'} = 0;
155 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
162 my $class = ref($proto) || $proto;
164 bless ($self, $class);
166 $self->{'Table'} = shift unless defined ( $self->table );
168 my $hashref = $self->{'Hash'} = shift;
170 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
171 my $obj = $cache->cache->{$hashref->{$cache->key}};
172 $obj->_cache($hashref, $cache) if $obj->can('_cache');
175 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
182 my $class = ref($proto) || $proto;
184 bless ($self, $class);
185 if ( defined $self->table ) {
186 cluck "create constructor is deprecated, use new!";
189 croak "FS::Record::create called (not from a subclass)!";
193 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
195 Searches the database for all records matching (at least) the key/value pairs
196 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
197 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
200 ###oops, argh, FS::Record::new only lets us create database fields.
201 #Normal behaviour if SELECT is not specified is `*', as in
202 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
203 #feature where you can specify SELECT - remember, the objects returned,
204 #although blessed into the appropriate `FS::TABLE' package, will only have the
205 #fields you specify. This might have unwanted results if you then go calling
206 #regular FS::TABLE methods
212 my($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
213 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
215 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
220 my $table = $cache ? $cache->table : $stable;
221 my $dbdef_table = $dbdef->table($table)
222 or die "No schema for table $table found - ".
223 "do you need to create it or run dbdef-create?";
224 my $pkey = $dbdef_table->primary_key;
226 my @real_fields = grep exists($record->{$_}), real_fields($table);
228 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
229 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
231 cluck "warning: FS::$table not loaded; virtual fields not searchable";
232 @virtual_fields = ();
235 my $statement = "SELECT $select FROM $stable";
236 $statement .= " $addl_from" if $addl_from;
237 if ( @real_fields or @virtual_fields ) {
238 $statement .= ' WHERE '. join(' AND ',
243 if ( ref($record->{$_}) ) {
244 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
245 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
246 if ( uc($op) eq 'ILIKE' ) {
248 $record->{$_}{'value'} = lc($record->{$_}{'value'});
249 $column = "LOWER($_)";
251 $record->{$_} = $record->{$_}{'value'}
254 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
256 if ( driver_name eq 'Pg' ) {
257 my $type = $dbdef->table($table)->column($column)->type;
258 if ( $type =~ /(int|serial)/i ) {
259 qq-( $column IS NULL )-;
261 qq-( $column IS NULL OR $column = '' )-;
264 qq-( $column IS NULL OR $column = "" )-;
266 } elsif ( $op eq '!=' ) {
267 if ( driver_name eq 'Pg' ) {
268 my $type = $dbdef->table($table)->column($column)->type;
269 if ( $type =~ /(int|serial)/i ) {
270 qq-( $column IS NOT NULL )-;
272 qq-( $column IS NOT NULL AND $column != '' )-;
275 qq-( $column IS NOT NULL AND $column != "" )-;
278 if ( driver_name eq 'Pg' ) {
279 qq-( $column $op '' )-;
281 qq-( $column $op "" )-;
291 if ( ref($record->{$_}) ) {
292 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
293 if ( uc($op) eq 'ILIKE' ) {
295 $record->{$_}{'value'} = lc($record->{$_}{'value'});
296 $column = "LOWER($_)";
298 $record->{$_} = $record->{$_}{'value'};
301 # ... EXISTS ( SELECT name, value FROM part_virtual_field
303 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
304 # WHERE recnum = svc_acct.svcnum
305 # AND (name, value) = ('egad', 'brain') )
307 my $value = $record->{$_};
311 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
312 "( SELECT part_virtual_field.name, virtual_field.value ".
313 "FROM part_virtual_field JOIN virtual_field ".
314 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
315 "WHERE virtual_field.recnum = ${table}.${pkey} ".
316 "AND part_virtual_field.name = '${column}'".
318 " AND virtual_field.value ${op} '${value}'"
322 } @virtual_fields ) );
326 $statement .= " $extra_sql" if defined($extra_sql);
328 warn "[debug]$me $statement\n" if $DEBUG > 1;
329 my $sth = $dbh->prepare($statement)
330 or croak "$dbh->errstr doing $statement";
335 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
337 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
338 && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
340 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
342 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
346 # $sth->execute( map $record->{$_},
347 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
348 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
350 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
352 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
353 @virtual_fields = "FS::$table"->virtual_fields;
355 cluck "warning: FS::$table not loaded; virtual fields not returned either";
356 @virtual_fields = ();
360 tie %result, "Tie::IxHash";
361 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
363 %result = map { $_->{$pkey}, $_ } @stuff;
365 @result{@stuff} = @stuff;
370 if ( keys(%result) and @virtual_fields ) {
372 "SELECT virtual_field.recnum, part_virtual_field.name, ".
373 "virtual_field.value ".
374 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
375 "WHERE part_virtual_field.dbtable = '$table' AND ".
376 "virtual_field.recnum IN (".
377 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
378 join(q!', '!, @virtual_fields) . "')";
379 warn "[debug]$me $statement\n" if $DEBUG > 1;
380 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
381 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
383 foreach (@{ $sth->fetchall_arrayref({}) }) {
384 my $recnum = $_->{recnum};
385 my $name = $_->{name};
386 my $value = $_->{value};
387 if (exists($result{$recnum})) {
388 $result{$recnum}->{$name} = $value;
393 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
394 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
395 #derivied class didn't override new method, so this optimization is safe
398 new_or_cached( "FS::$table", { %{$_} }, $cache )
402 new( "FS::$table", { %{$_} } )
406 warn "untested code (class FS::$table uses custom new method)";
408 eval 'FS::'. $table. '->new( { %{$_} } )';
412 # Check for encrypted fields and decrypt them.
413 if ($conf->exists('encryption') && eval 'defined(@FS::'. $table . '::encrypted_fields)') {
414 foreach my $record (@return) {
415 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
416 # Set it directly... This may cause a problem in the future...
417 $record->setfield($field, $record->decrypt($record->getfield($field)));
422 cluck "warning: FS::$table not loaded; returning FS::Record objects";
424 FS::Record->new( $table, { %{$_} } );
430 =item by_key PRIMARY_KEY_VALUE
432 This is a class method that returns the record with the given primary key
433 value. This method is only useful in FS::Record subclasses. For example:
435 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
439 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
444 my ($class, $pkey_value) = @_;
446 my $table = $class->table
447 or croak "No table for $class found";
449 my $dbdef_table = $dbdef->table($table)
450 or die "No schema for table $table found - ".
451 "do you need to create it or run dbdef-create?";
452 my $pkey = $dbdef_table->primary_key
453 or die "No primary key for table $table";
455 return qsearchs($table, { $pkey => $pkey_value });
458 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
460 Experimental JOINed search method. Using this method, you can execute a
461 single SELECT spanning multiple tables, and cache the results for subsequent
462 method calls. Interface will almost definately change in an incompatible
470 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
471 my $cache = FS::SearchCache->new( $ptable, $pkey );
474 grep { !$saw{$_->getfield($pkey)}++ }
475 qsearch($table, $record, $select, $extra_sql, $cache )
479 =item qsearchs TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
481 Same as qsearch, except that if more than one record matches, it B<carp>s but
482 returns the first. If this happens, you either made a logic error in asking
483 for a single item, or your data is corrupted.
487 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
489 my(@result) = qsearch(@_);
490 cluck "warning: Multiple records in scalar search ($table)"
491 if scalar(@result) > 1;
492 #should warn more vehemently if the search was on a primary key?
493 scalar(@result) ? ($result[0]) : ();
504 Returns the table name.
509 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
516 Returns the DBIx::DBSchema::Table object for the table.
522 my($table)=$self->table;
523 $dbdef->table($table);
526 =item get, getfield COLUMN
528 Returns the value of the column/field/key COLUMN.
533 my($self,$field) = @_;
534 # to avoid "Use of unitialized value" errors
535 if ( defined ( $self->{Hash}->{$field} ) ) {
536 $self->{Hash}->{$field};
546 =item set, setfield COLUMN, VALUE
548 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
553 my($self,$field,$value) = @_;
554 $self->{'modified'} = 1;
555 $self->{'Hash'}->{$field} = $value;
562 =item AUTLOADED METHODS
564 $record->column is a synonym for $record->get('column');
566 $record->column('value') is a synonym for $record->set('column','value');
573 my($field)=$AUTOLOAD;
575 if ( defined($value) ) {
576 confess "errant AUTOLOAD $field for $self (arg $value)"
577 unless ref($self) && $self->can('setfield');
578 $self->setfield($field,$value);
580 confess "errant AUTOLOAD $field for $self (no args)"
581 unless ref($self) && $self->can('getfield');
582 $self->getfield($field);
588 # my $field = $AUTOLOAD;
590 # if ( defined($_[1]) ) {
591 # $_[0]->setfield($field, $_[1]);
593 # $_[0]->getfield($field);
599 Returns a list of the column/value pairs, usually for assigning to a new hash.
601 To make a distinct duplicate of an FS::Record object, you can do:
603 $new = new FS::Record ( $old->table, { $old->hash } );
609 confess $self. ' -> hash: Hash attribute is undefined'
610 unless defined($self->{'Hash'});
611 %{ $self->{'Hash'} };
616 Returns a reference to the column/value hash. This may be deprecated in the
617 future; if there's a reason you can't just use the autoloaded or get/set
629 Returns true if any of this object's values have been modified with set (or via
630 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
642 Inserts this record to the database. If there is an error, returns the error,
643 otherwise returns false.
651 my $error = $self->check;
652 return $error if $error;
654 #single-field unique keys are given a value if false
655 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
656 foreach ( $self->dbdef_table->unique->singles ) {
657 $self->unique($_) unless $self->getfield($_);
660 #and also the primary key, if the database isn't going to
661 my $primary_key = $self->dbdef_table->primary_key;
663 if ( $primary_key ) {
664 my $col = $self->dbdef_table->column($primary_key);
667 uc($col->type) eq 'SERIAL'
668 || ( driver_name eq 'Pg'
669 && defined($col->default)
670 && $col->default =~ /^nextval\(/i
672 || ( driver_name eq 'mysql'
673 && defined($col->local)
674 && $col->local =~ /AUTO_INCREMENT/i
676 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
679 my $table = $self->table;
682 # Encrypt before the database
683 if ($conf->exists('encryption') && defined(eval '@FS::'. $table . 'encrypted_fields')) {
684 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
685 $self->{'saved'} = $self->getfield($field);
686 $self->setfield($field, $self->enrypt($self->getfield($field)));
691 #false laziness w/delete
693 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
696 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
699 my $statement = "INSERT INTO $table ( ".
700 join( ', ', @real_fields ).
702 join( ', ', @values ).
705 warn "[debug]$me $statement\n" if $DEBUG > 1;
706 my $sth = dbh->prepare($statement) or return dbh->errstr;
708 local $SIG{HUP} = 'IGNORE';
709 local $SIG{INT} = 'IGNORE';
710 local $SIG{QUIT} = 'IGNORE';
711 local $SIG{TERM} = 'IGNORE';
712 local $SIG{TSTP} = 'IGNORE';
713 local $SIG{PIPE} = 'IGNORE';
715 $sth->execute or return $sth->errstr;
718 if ( $db_seq ) { # get inserted id from the database, if applicable
719 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
720 if ( driver_name eq 'Pg' ) {
722 my $oid = $sth->{'pg_oid_status'};
723 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
724 my $i_sth = dbh->prepare($i_sql) or do {
725 dbh->rollback if $FS::UID::AutoCommit;
728 $i_sth->execute($oid) or do {
729 dbh->rollback if $FS::UID::AutoCommit;
730 return $i_sth->errstr;
732 $insertid = $i_sth->fetchrow_arrayref->[0];
734 } elsif ( driver_name eq 'mysql' ) {
736 $insertid = dbh->{'mysql_insertid'};
737 # work around mysql_insertid being null some of the time, ala RT :/
738 unless ( $insertid ) {
739 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
740 "using SELECT LAST_INSERT_ID();";
741 my $i_sql = "SELECT LAST_INSERT_ID()";
742 my $i_sth = dbh->prepare($i_sql) or do {
743 dbh->rollback if $FS::UID::AutoCommit;
746 $i_sth->execute or do {
747 dbh->rollback if $FS::UID::AutoCommit;
748 return $i_sth->errstr;
750 $insertid = $i_sth->fetchrow_arrayref->[0];
754 dbh->rollback if $FS::UID::AutoCommit;
755 return "don't know how to retreive inserted ids from ". driver_name.
756 ", try using counterfiles (maybe run dbdef-create?)";
758 $self->setfield($primary_key, $insertid);
762 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
763 $self->virtual_fields;
764 if (@virtual_fields) {
765 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
767 my $vfieldpart = $self->vfieldpart_hashref;
769 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
772 my $v_sth = dbh->prepare($v_statement) or do {
773 dbh->rollback if $FS::UID::AutoCommit;
777 foreach (keys(%v_values)) {
778 $v_sth->execute($self->getfield($primary_key),
782 dbh->rollback if $FS::UID::AutoCommit;
783 return $v_sth->errstr;
790 if ( defined $dbdef->table('h_'. $table) ) {
791 my $h_statement = $self->_h_statement('insert');
792 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
793 $h_sth = dbh->prepare($h_statement) or do {
794 dbh->rollback if $FS::UID::AutoCommit;
800 $h_sth->execute or return $h_sth->errstr if $h_sth;
802 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
804 # Now that it has been saved, reset the encrypted fields so that $new
806 foreach my $field (keys %{$saved}) {
807 $self->setfield($field, $saved->{$field});
815 Depriciated (use insert instead).
820 cluck "warning: FS::Record::add deprecated!";
821 insert @_; #call method in this scope
826 Delete this record from the database. If there is an error, returns the error,
827 otherwise returns false.
834 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
836 $self->getfield($_) eq ''
837 #? "( $_ IS NULL OR $_ = \"\" )"
838 ? ( driver_name eq 'Pg'
840 : "( $_ IS NULL OR $_ = \"\" )"
842 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
843 } ( $self->dbdef_table->primary_key )
844 ? ( $self->dbdef_table->primary_key)
845 : real_fields($self->table)
847 warn "[debug]$me $statement\n" if $DEBUG > 1;
848 my $sth = dbh->prepare($statement) or return dbh->errstr;
851 if ( defined $dbdef->table('h_'. $self->table) ) {
852 my $h_statement = $self->_h_statement('delete');
853 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
854 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
859 my $primary_key = $self->dbdef_table->primary_key;
862 my $vfp = $self->vfieldpart_hashref;
863 foreach($self->virtual_fields) {
864 next if $self->getfield($_) eq '';
865 unless(@del_vfields) {
866 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
867 $v_sth = dbh->prepare($st) or return dbh->errstr;
869 push @del_vfields, $_;
872 local $SIG{HUP} = 'IGNORE';
873 local $SIG{INT} = 'IGNORE';
874 local $SIG{QUIT} = 'IGNORE';
875 local $SIG{TERM} = 'IGNORE';
876 local $SIG{TSTP} = 'IGNORE';
877 local $SIG{PIPE} = 'IGNORE';
879 my $rc = $sth->execute or return $sth->errstr;
880 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
881 $h_sth->execute or return $h_sth->errstr if $h_sth;
882 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
883 or return $v_sth->errstr
884 foreach (@del_vfields);
886 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
888 #no need to needlessly destoy the data either (causes problems actually)
889 #undef $self; #no need to keep object!
896 Depriciated (use delete instead).
901 cluck "warning: FS::Record::del deprecated!";
902 &delete(@_); #call method in this scope
905 =item replace OLD_RECORD
907 Replace the OLD_RECORD with this one in the database. If there is an error,
908 returns the error, otherwise returns false.
916 if (!defined($old)) {
917 warn "[debug]$me replace called with no arguments; autoloading old record\n"
919 my $primary_key = $new->dbdef_table->primary_key;
920 if ( $primary_key ) {
921 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
922 or croak "can't find ". $new->table. ".$primary_key ".
923 $new->$primary_key();
925 croak $new->table. " has no primary key; pass old record as argument";
929 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
931 return "Records not in same table!" unless $new->table eq $old->table;
933 my $primary_key = $old->dbdef_table->primary_key;
934 return "Can't change primary key $primary_key ".
935 'from '. $old->getfield($primary_key).
936 ' to ' . $new->getfield($primary_key)
938 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
940 my $error = $new->check;
941 return $error if $error;
943 # Encrypt for replace
945 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . 'encrypted_fields')) {
946 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
947 $saved->{$field} = $new->getfield($field);
948 $new->setfield($field, $new->encrypt($new->getfield($field)));
952 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
953 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
954 ? ($_, $new->getfield($_)) : () } $old->fields;
956 unless ( keys(%diff) ) {
957 carp "[warning]$me $new -> replace $old: records identical"
958 unless $nowarn_identical;
962 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
964 "$_ = ". _quote($new->getfield($_),$old->table,$_)
965 } real_fields($old->table)
970 if ( $old->getfield($_) eq '' ) {
972 #false laziness w/qsearch
973 if ( driver_name eq 'Pg' ) {
974 my $type = $old->dbdef_table->column($_)->type;
975 if ( $type =~ /(int|serial)/i ) {
978 qq-( $_ IS NULL OR $_ = '' )-;
981 qq-( $_ IS NULL OR $_ = "" )-;
985 "$_ = ". _quote($old->getfield($_),$old->table,$_);
988 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
991 warn "[debug]$me $statement\n" if $DEBUG > 1;
992 my $sth = dbh->prepare($statement) or return dbh->errstr;
995 if ( defined $dbdef->table('h_'. $old->table) ) {
996 my $h_old_statement = $old->_h_statement('replace_old');
997 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
998 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1004 if ( defined $dbdef->table('h_'. $new->table) ) {
1005 my $h_new_statement = $new->_h_statement('replace_new');
1006 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1007 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1012 # For virtual fields we have three cases with different SQL
1013 # statements: add, replace, delete
1017 my (@add_vfields, @rep_vfields, @del_vfields);
1018 my $vfp = $old->vfieldpart_hashref;
1019 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1020 if($diff{$_} eq '') {
1022 unless(@del_vfields) {
1023 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1024 "AND vfieldpart = ?";
1025 warn "[debug]$me $st\n" if $DEBUG > 2;
1026 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1028 push @del_vfields, $_;
1029 } elsif($old->getfield($_) eq '') {
1031 unless(@add_vfields) {
1032 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1034 warn "[debug]$me $st\n" if $DEBUG > 2;
1035 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1037 push @add_vfields, $_;
1040 unless(@rep_vfields) {
1041 my $st = "UPDATE virtual_field SET value = ? ".
1042 "WHERE recnum = ? AND vfieldpart = ?";
1043 warn "[debug]$me $st\n" if $DEBUG > 2;
1044 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1046 push @rep_vfields, $_;
1050 local $SIG{HUP} = 'IGNORE';
1051 local $SIG{INT} = 'IGNORE';
1052 local $SIG{QUIT} = 'IGNORE';
1053 local $SIG{TERM} = 'IGNORE';
1054 local $SIG{TSTP} = 'IGNORE';
1055 local $SIG{PIPE} = 'IGNORE';
1057 my $rc = $sth->execute or return $sth->errstr;
1058 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1059 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1060 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1062 $v_del_sth->execute($old->getfield($primary_key),
1064 or return $v_del_sth->errstr
1065 foreach(@del_vfields);
1067 $v_add_sth->execute($new->getfield($_),
1068 $old->getfield($primary_key),
1070 or return $v_add_sth->errstr
1071 foreach(@add_vfields);
1073 $v_rep_sth->execute($new->getfield($_),
1074 $old->getfield($primary_key),
1076 or return $v_rep_sth->errstr
1077 foreach(@rep_vfields);
1079 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1081 # Now that it has been saved, reset the encrypted fields so that $new
1082 # can still be used.
1083 foreach my $field (keys %{$saved}) {
1084 $new->setfield($field, $saved->{$field});
1093 Depriciated (use replace instead).
1098 cluck "warning: FS::Record::rep deprecated!";
1099 replace @_; #call method in this scope
1104 Checks virtual fields (using check_blocks). Subclasses should still provide
1105 a check method to validate real fields, foreign keys, etc., and call this
1106 method via $self->SUPER::check.
1108 (FIXME: Should this method try to make sure that it I<is> being called from
1109 a subclass's check method, to keep the current semantics as far as possible?)
1114 #confess "FS::Record::check not implemented; supply one in subclass!";
1117 foreach my $field ($self->virtual_fields) {
1118 for ($self->getfield($field)) {
1119 # See notes on check_block in FS::part_virtual_field.
1120 eval $self->pvf($field)->check_block;
1122 #this is bad, probably want to follow the stack backtrace up and see
1124 my $err = "Fatal error checking $field for $self";
1126 return "$err (see log for backtrace): $@";
1129 $self->setfield($field, $_);
1136 my( $self, $action, $time ) = @_;
1141 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1142 real_fields($self->table);
1144 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1146 "INSERT INTO h_". $self->table. " ( ".
1147 join(', ', qw(history_date history_user history_action), @fields ).
1149 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1156 B<Warning>: External use is B<deprecated>.
1158 Replaces COLUMN in record with a unique number, using counters in the
1159 filesystem. Used by the B<insert> method on single-field unique columns
1160 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1161 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1163 Returns the new value.
1168 my($self,$field) = @_;
1169 my($table)=$self->table;
1171 croak "Unique called on field $field, but it is ",
1172 $self->getfield($field),
1174 if $self->getfield($field);
1176 #warn "table $table is tainted" if is_tainted($table);
1177 #warn "field $field is tainted" if is_tainted($field);
1179 my($counter) = new File::CounterFile "$table.$field",0;
1181 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1183 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1186 my $index = $counter->inc;
1187 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1189 $index =~ /^(\d*)$/;
1192 $self->setfield($field,$index);
1196 =item ut_float COLUMN
1198 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1199 null. If there is an error, returns the error, otherwise returns false.
1204 my($self,$field)=@_ ;
1205 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1206 $self->getfield($field) =~ /^(\d+)$/ ||
1207 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1208 $self->getfield($field) =~ /^(\d+e\d+)$/)
1209 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1210 $self->setfield($field,$1);
1214 =item ut_snumber COLUMN
1216 Check/untaint signed numeric data (whole numbers). May not be null. If there
1217 is an error, returns the error, otherwise returns false.
1222 my($self, $field) = @_;
1223 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1224 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1225 $self->setfield($field, "$1$2");
1229 =item ut_number COLUMN
1231 Check/untaint simple numeric data (whole numbers). May not be null. If there
1232 is an error, returns the error, otherwise returns false.
1237 my($self,$field)=@_;
1238 $self->getfield($field) =~ /^(\d+)$/
1239 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1240 $self->setfield($field,$1);
1244 =item ut_numbern COLUMN
1246 Check/untaint simple numeric data (whole numbers). May be null. If there is
1247 an error, returns the error, otherwise returns false.
1252 my($self,$field)=@_;
1253 $self->getfield($field) =~ /^(\d*)$/
1254 or return "Illegal (numeric) $field: ". $self->getfield($field);
1255 $self->setfield($field,$1);
1259 =item ut_money COLUMN
1261 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1262 is an error, returns the error, otherwise returns false.
1267 my($self,$field)=@_;
1268 $self->setfield($field, 0) if $self->getfield($field) eq '';
1269 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1270 or return "Illegal (money) $field: ". $self->getfield($field);
1271 #$self->setfield($field, "$1$2$3" || 0);
1272 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1276 =item ut_text COLUMN
1278 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1279 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1280 May not be null. If there is an error, returns the error, otherwise returns
1286 my($self,$field)=@_;
1287 #warn "msgcat ". \&msgcat. "\n";
1288 #warn "notexist ". \¬exist. "\n";
1289 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1290 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1291 or return gettext('illegal_or_empty_text'). " $field: ".
1292 $self->getfield($field);
1293 $self->setfield($field,$1);
1297 =item ut_textn COLUMN
1299 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1300 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1301 May be null. If there is an error, returns the error, otherwise returns false.
1306 my($self,$field)=@_;
1307 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1308 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1309 $self->setfield($field,$1);
1313 =item ut_alpha COLUMN
1315 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1316 an error, returns the error, otherwise returns false.
1321 my($self,$field)=@_;
1322 $self->getfield($field) =~ /^(\w+)$/
1323 or return "Illegal or empty (alphanumeric) $field: ".
1324 $self->getfield($field);
1325 $self->setfield($field,$1);
1329 =item ut_alpha COLUMN
1331 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1332 error, returns the error, otherwise returns false.
1337 my($self,$field)=@_;
1338 $self->getfield($field) =~ /^(\w*)$/
1339 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1340 $self->setfield($field,$1);
1344 =item ut_phonen COLUMN [ COUNTRY ]
1346 Check/untaint phone numbers. May be null. If there is an error, returns
1347 the error, otherwise returns false.
1349 Takes an optional two-letter ISO country code; without it or with unsupported
1350 countries, ut_phonen simply calls ut_alphan.
1355 my( $self, $field, $country ) = @_;
1356 return $self->ut_alphan($field) unless defined $country;
1357 my $phonen = $self->getfield($field);
1358 if ( $phonen eq '' ) {
1359 $self->setfield($field,'');
1360 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1362 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1363 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1364 $phonen = "$1-$2-$3";
1365 $phonen .= " x$4" if $4;
1366 $self->setfield($field,$phonen);
1368 warn "warning: don't know how to check phone numbers for country $country";
1369 return $self->ut_textn($field);
1376 Check/untaint ip addresses. IPv4 only for now.
1381 my( $self, $field ) = @_;
1382 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1383 or return "Illegal (IP address) $field: ". $self->getfield($field);
1384 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1385 $self->setfield($field, "$1.$2.$3.$4");
1391 Check/untaint ip addresses. IPv4 only for now. May be null.
1396 my( $self, $field ) = @_;
1397 if ( $self->getfield($field) =~ /^()$/ ) {
1398 $self->setfield($field,'');
1401 $self->ut_ip($field);
1405 =item ut_domain COLUMN
1407 Check/untaint host and domain names.
1412 my( $self, $field ) = @_;
1413 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1414 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1415 or return "Illegal (domain) $field: ". $self->getfield($field);
1416 $self->setfield($field,$1);
1420 =item ut_name COLUMN
1422 Check/untaint proper names; allows alphanumerics, spaces and the following
1423 punctuation: , . - '
1430 my( $self, $field ) = @_;
1431 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1432 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1433 $self->setfield($field,$1);
1439 Check/untaint zip codes.
1444 my( $self, $field, $country ) = @_;
1445 if ( $country eq 'US' ) {
1446 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1447 or return gettext('illegal_zip'). " $field for country $country: ".
1448 $self->getfield($field);
1449 $self->setfield($field,$1);
1451 if ( $self->getfield($field) =~ /^\s*$/ ) {
1452 $self->setfield($field,'');
1454 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1455 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1456 $self->setfield($field,$1);
1462 =item ut_country COLUMN
1464 Check/untaint country codes. Country names are changed to codes, if possible -
1465 see L<Locale::Country>.
1470 my( $self, $field ) = @_;
1471 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1472 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1473 && country2code($1) ) {
1474 $self->setfield($field,uc(country2code($1)));
1477 $self->getfield($field) =~ /^(\w\w)$/
1478 or return "Illegal (country) $field: ". $self->getfield($field);
1479 $self->setfield($field,uc($1));
1483 =item ut_anything COLUMN
1485 Untaints arbitrary data. Be careful.
1490 my( $self, $field ) = @_;
1491 $self->getfield($field) =~ /^(.*)$/s
1492 or return "Illegal $field: ". $self->getfield($field);
1493 $self->setfield($field,$1);
1497 =item ut_enum COLUMN CHOICES_ARRAYREF
1499 Check/untaint a column, supplying all possible choices, like the "enum" type.
1504 my( $self, $field, $choices ) = @_;
1505 foreach my $choice ( @$choices ) {
1506 if ( $self->getfield($field) eq $choice ) {
1507 $self->setfield($choice);
1511 return "Illegal (enum) field $field: ". $self->getfield($field);
1514 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1516 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1517 on the column first.
1521 sub ut_foreign_key {
1522 my( $self, $field, $table, $foreign ) = @_;
1523 qsearchs($table, { $foreign => $self->getfield($field) })
1524 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1525 " in $table.$foreign";
1529 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1531 Like ut_foreign_key, except the null value is also allowed.
1535 sub ut_foreign_keyn {
1536 my( $self, $field, $table, $foreign ) = @_;
1537 $self->getfield($field)
1538 ? $self->ut_foreign_key($field, $table, $foreign)
1543 =item virtual_fields [ TABLE ]
1545 Returns a list of virtual fields defined for the table. This should not
1546 be exported, and should only be called as an instance or class method.
1550 sub virtual_fields {
1553 $table = $self->table or confess "virtual_fields called on non-table";
1555 confess "Unknown table $table" unless $dbdef->table($table);
1557 return () unless $self->dbdef->table('part_virtual_field');
1559 unless ( $virtual_fields_cache{$table} ) {
1560 my $query = 'SELECT name from part_virtual_field ' .
1561 "WHERE dbtable = '$table'";
1563 my $result = $dbh->selectcol_arrayref($query);
1564 confess $dbh->errstr if $dbh->err;
1565 $virtual_fields_cache{$table} = $result;
1568 @{$virtual_fields_cache{$table}};
1573 =item fields [ TABLE ]
1575 This is a wrapper for real_fields and virtual_fields. Code that called
1576 fields before should probably continue to call fields.
1581 my $something = shift;
1583 if($something->isa('FS::Record')) {
1584 $table = $something->table;
1586 $table = $something;
1587 $something = "FS::$table";
1589 return (real_fields($table), $something->virtual_fields());
1594 =item pvf FIELD_NAME
1596 Returns the FS::part_virtual_field object corresponding to a field in the
1597 record (specified by FIELD_NAME).
1602 my ($self, $name) = (shift, shift);
1604 if(grep /^$name$/, $self->virtual_fields) {
1605 return qsearchs('part_virtual_field', { dbtable => $self->table,
1615 =item real_fields [ TABLE ]
1617 Returns a list of the real columns in the specified table. Called only by
1618 fields() and other subroutines elsewhere in FS::Record.
1625 my($table_obj) = $dbdef->table($table);
1626 confess "Unknown table $table" unless $table_obj;
1627 $table_obj->columns;
1630 =item reload_dbdef([FILENAME])
1632 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1633 non-default filename. This command is executed at startup unless
1634 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1639 my $file = shift || $dbdef_file;
1641 unless ( exists $dbdef_cache{$file} ) {
1642 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1643 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1644 or die "can't load database schema from $file";
1646 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1648 $dbdef = $dbdef_cache{$file};
1653 Returns the current database definition. See L<DBIx::DBSchema>.
1657 sub dbdef { $dbdef; }
1659 =item _quote VALUE, TABLE, COLUMN
1661 This is an internal function used to construct SQL statements. It returns
1662 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1663 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1668 my($value, $table, $column) = @_;
1669 my $column_obj = $dbdef->table($table)->column($column);
1670 my $column_type = $column_obj->type;
1671 my $nullable = $column_obj->null;
1673 warn " $table.$column: $value ($column_type".
1674 ( $nullable ? ' NULL' : ' NOT NULL' ).
1675 ")\n" if $DEBUG > 2;
1677 if ( $value eq '' && $column_type =~ /^int/ ) {
1681 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1685 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1686 ! $column_type =~ /(char|binary|text)$/i ) {
1693 =item vfieldpart_hashref TABLE
1695 Returns a hashref of virtual field names and vfieldparts applicable to the given
1700 sub vfieldpart_hashref {
1702 my $table = $self->table;
1704 return {} unless $self->dbdef->table('part_virtual_field');
1707 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1708 "dbtable = '$table'";
1709 my $sth = $dbh->prepare($statement);
1710 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1711 return { map { $_->{name}, $_->{vfieldpart} }
1712 @{$sth->fetchall_arrayref({})} };
1719 This is deprecated. Don't use it.
1721 It returns a hash-type list with the fields of this record's table set true.
1726 carp "warning: hfields is deprecated";
1729 foreach (fields($table)) {
1738 "$_: ". $self->getfield($_). "|"
1739 } (fields($self->table)) );
1743 my ($self, $value) = @_;
1746 if ($conf->exists('encryption')) {
1747 if ($self->is_encrypted($value)) {
1748 # Return the original value if it isn't plaintext.
1749 $encrypted = $value;
1752 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
1753 # RSA doesn't like the empty string so let's pack it up
1754 # The database doesn't like the RSA data so uuencode it
1755 my $length = length($value)+1;
1756 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
1758 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
1766 my ($self, $value) = @_;
1767 # Possible Bug - Some work may be required here....
1769 if (length($value) > 80) {
1777 my ($self,$value) = @_;
1778 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
1779 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
1781 if (ref($rsa_decrypt) =~ /::RSA/) {
1782 my $encrypted = unpack ("u*", $value);
1783 $decrypted = unpack("Z*", $rsa_decrypt->decrypt($encrypted));
1791 #Initialize the Module
1792 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
1794 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
1795 $rsa_module = $conf->config('encryptionmodule');
1799 eval ("require $rsa_module"); # No need to import the namespace
1802 # Initialize Encryption
1803 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
1804 my $public_key = join("\n",$conf->config('encryptionpublickey'));
1805 $rsa_encrypt = $rsa_module->new_public_key($public_key);
1808 # Intitalize Decryption
1809 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
1810 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
1811 $rsa_decrypt = $rsa_module->new_private_key($private_key);
1815 sub DESTROY { return; }
1819 # #use Carp qw(cluck);
1820 # #cluck "DESTROYING $self";
1821 # warn "DESTROYING $self";
1825 # return ! eval { join('',@_), kill 0; 1; };
1832 This module should probably be renamed, since much of the functionality is
1833 of general use. It is not completely unlike Adapter::DBI (see below).
1835 Exported qsearch and qsearchs should be deprecated in favor of method calls
1836 (against an FS::Record object like the old search and searchs that qsearch
1837 and qsearchs were on top of.)
1839 The whole fields / hfields mess should be removed.
1841 The various WHERE clauses should be subroutined.
1843 table string should be deprecated in favor of DBIx::DBSchema::Table.
1845 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1846 true maps to the database (and WHERE clauses) would also help.
1848 The ut_ methods should ask the dbdef for a default length.
1850 ut_sqltype (like ut_varchar) should all be defined
1852 A fallback check method should be provided which uses the dbdef.
1854 The ut_money method assumes money has two decimal digits.
1856 The Pg money kludge in the new method only strips `$'.
1858 The ut_phonen method only checks US-style phone numbers.
1860 The _quote function should probably use ut_float instead of a regex.
1862 All the subroutines probably should be methods, here or elsewhere.
1864 Probably should borrow/use some dbdef methods where appropriate (like sub
1867 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1868 or allow it to be set. Working around it is ugly any way around - DBI should
1869 be fixed. (only affects RDBMS which return uppercase column names)
1871 ut_zip should take an optional country like ut_phone.
1875 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1877 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.