show a full stack backtrace if we wind up in the hash method with an empty Hash attri...
[freeside.git] / FS / FS / Record.pm
1 package FS::Record;
2
3 use strict;
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);
7 use Exporter;
8 use Carp qw(carp cluck croak confess);
9 use File::CounterFile;
10 use Locale::Country;
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.23;
13 use FS::UID qw(dbh getotaker datasrc driver_name);
14 use FS::SearchCache;
15 use FS::Msgcat qw(gettext);
16
17 use FS::part_virtual_field;
18
19 use Tie::IxHash;
20
21 @ISA = qw(Exporter);
22 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
23
24 $DEBUG = 0;
25 $me = '[FS::Record]';
26
27 #ask FS::UID to run this stuff for us later
28 $FS::UID::callback{'FS::Record'} = sub { 
29   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
30   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
31   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
32 };
33
34 =head1 NAME
35
36 FS::Record - Database record objects
37
38 =head1 SYNOPSIS
39
40     use FS::Record;
41     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
42
43     $record = new FS::Record 'table', \%hash;
44     $record = new FS::Record 'table', { 'column' => 'value', ... };
45
46     $record  = qsearchs FS::Record 'table', \%hash;
47     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
48     @records = qsearch  FS::Record 'table', \%hash; 
49     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
50
51     $table = $record->table;
52     $dbdef_table = $record->dbdef_table;
53
54     $value = $record->get('column');
55     $value = $record->getfield('column');
56     $value = $record->column;
57
58     $record->set( 'column' => 'value' );
59     $record->setfield( 'column' => 'value' );
60     $record->column('value');
61
62     %hash = $record->hash;
63
64     $hashref = $record->hashref;
65
66     $error = $record->insert;
67
68     $error = $record->delete;
69
70     $error = $new_record->replace($old_record);
71
72     # external use deprecated - handled by the database (at least for Pg, mysql)
73     $value = $record->unique('column');
74
75     $error = $record->ut_float('column');
76     $error = $record->ut_number('column');
77     $error = $record->ut_numbern('column');
78     $error = $record->ut_money('column');
79     $error = $record->ut_text('column');
80     $error = $record->ut_textn('column');
81     $error = $record->ut_alpha('column');
82     $error = $record->ut_alphan('column');
83     $error = $record->ut_phonen('column');
84     $error = $record->ut_anything('column');
85     $error = $record->ut_name('column');
86
87     $dbdef = reload_dbdef;
88     $dbdef = reload_dbdef "/non/standard/filename";
89     $dbdef = dbdef;
90
91     $quoted_value = _quote($value,'table','field');
92
93     #deprecated
94     $fields = hfields('table');
95     if ( $fields->{Field} ) { # etc.
96
97     @fields = fields 'table'; #as a subroutine
98     @fields = $record->fields; #as a method call
99
100
101 =head1 DESCRIPTION
102
103 (Mostly) object-oriented interface to database records.  Records are currently
104 implemented on top of DBI.  FS::Record is intended as a base class for
105 table-specific classes to inherit from, i.e. FS::cust_main.
106
107 =head1 CONSTRUCTORS
108
109 =over 4
110
111 =item new [ TABLE, ] HASHREF
112
113 Creates a new record.  It doesn't store it in the database, though.  See
114 L<"insert"> for that.
115
116 Note that the object stores this hash reference, not a distinct copy of the
117 hash it points to.  You can ask the object for a copy with the I<hash> 
118 method.
119
120 TABLE can only be omitted when a dervived class overrides the table method.
121
122 =cut
123
124 sub new { 
125   my $proto = shift;
126   my $class = ref($proto) || $proto;
127   my $self = {};
128   bless ($self, $class);
129
130   unless ( defined ( $self->table ) ) {
131     $self->{'Table'} = shift;
132     carp "warning: FS::Record::new called with table name ". $self->{'Table'};
133   }
134
135   my $hashref = $self->{'Hash'} = shift;
136
137   foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) { 
138     $hashref->{$field}='';
139   }
140
141   $self->_cache($hashref, shift) if $self->can('_cache') && @_;
142
143   $self;
144 }
145
146 sub new_or_cached {
147   my $proto = shift;
148   my $class = ref($proto) || $proto;
149   my $self = {};
150   bless ($self, $class);
151
152   $self->{'Table'} = shift unless defined ( $self->table );
153
154   my $hashref = $self->{'Hash'} = shift;
155   my $cache = shift;
156   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
157     my $obj = $cache->cache->{$hashref->{$cache->key}};
158     $obj->_cache($hashref, $cache) if $obj->can('_cache');
159     $obj;
160   } else {
161     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
162   }
163
164 }
165
166 sub create {
167   my $proto = shift;
168   my $class = ref($proto) || $proto;
169   my $self = {};
170   bless ($self, $class);
171   if ( defined $self->table ) {
172     cluck "create constructor is deprecated, use new!";
173     $self->new(@_);
174   } else {
175     croak "FS::Record::create called (not from a subclass)!";
176   }
177 }
178
179 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
180
181 Searches the database for all records matching (at least) the key/value pairs
182 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
183 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
184 objects.
185
186 ###oops, argh, FS::Record::new only lets us create database fields.
187 #Normal behaviour if SELECT is not specified is `*', as in
188 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
189 #feature where you can specify SELECT - remember, the objects returned,
190 #although blessed into the appropriate `FS::TABLE' package, will only have the
191 #fields you specify.  This might have unwanted results if you then go calling
192 #regular FS::TABLE methods
193 #on it.
194
195 =cut
196
197 sub qsearch {
198   my($stable, $record, $select, $extra_sql, $cache ) = @_;
199   #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
200   #for jsearch
201   $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
202   $stable = $1;
203   $select ||= '*';
204   my $dbh = dbh;
205
206   my $table = $cache ? $cache->table : $stable;
207   my $pkey = $dbdef->table($table)->primary_key;
208
209   my @real_fields = grep exists($record->{$_}), real_fields($table);
210   my @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
211
212   my $statement = "SELECT $select FROM $stable";
213   if ( @real_fields or @virtual_fields ) {
214     $statement .= ' WHERE '. join(' AND ',
215       ( map {
216
217       my $op = '=';
218       my $column = $_;
219       if ( ref($record->{$_}) ) {
220         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
221         #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
222         if ( uc($op) eq 'ILIKE' ) {
223           $op = 'LIKE';
224           $record->{$_}{'value'} = lc($record->{$_}{'value'});
225           $column = "LOWER($_)";
226         }
227         $record->{$_} = $record->{$_}{'value'}
228       }
229
230       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
231         if ( $op eq '=' ) {
232           if ( driver_name eq 'Pg' ) {
233             my $type = $dbdef->table($table)->column($column)->type;
234             if ( $type =~ /(int|serial)/i ) {
235               qq-( $column IS NULL )-;
236             } else {
237               qq-( $column IS NULL OR $column = '' )-;
238             }
239           } else {
240             qq-( $column IS NULL OR $column = "" )-;
241           }
242         } elsif ( $op eq '!=' ) {
243           if ( driver_name eq 'Pg' ) {
244             my $type = $dbdef->table($table)->column($column)->type;
245             if ( $type =~ /(int|serial)/i ) {
246               qq-( $column IS NOT NULL )-;
247             } else {
248               qq-( $column IS NOT NULL AND $column != '' )-;
249             }
250           } else {
251             qq-( $column IS NOT NULL AND $column != "" )-;
252           }
253         } else {
254           if ( driver_name eq 'Pg' ) {
255             qq-( $column $op '' )-;
256           } else {
257             qq-( $column $op "" )-;
258           }
259         }
260       } else {
261         "$column $op ?";
262       }
263     } @real_fields ), 
264     ( map {
265       my $op = '=';
266       my $column = $_;
267       if ( ref($record->{$_}) ) {
268         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
269         if ( uc($op) eq 'ILIKE' ) {
270           $op = 'LIKE';
271           $record->{$_}{'value'} = lc($record->{$_}{'value'});
272           $column = "LOWER($_)";
273         }
274         $record->{$_} = $record->{$_}{'value'};
275       }
276
277       # ... EXISTS ( SELECT name, value FROM part_virtual_field
278       #              JOIN virtual_field
279       #              ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
280       #              WHERE recnum = svc_acct.svcnum
281       #              AND (name, value) = ('egad', 'brain') )
282
283       my $value = $record->{$_};
284
285       my $subq;
286
287       $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
288       "( SELECT part_virtual_field.name, virtual_field.value ".
289       "FROM part_virtual_field JOIN virtual_field ".
290       "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
291       "WHERE virtual_field.recnum = ${table}.${pkey} ".
292       "AND part_virtual_field.name = '${column}'".
293       ($value ? 
294         " AND virtual_field.value ${op} '${value}'"
295       : "") . ")";
296       $subq;
297
298     } @virtual_fields ) );
299
300   }
301
302   $statement .= " $extra_sql" if defined($extra_sql);
303
304   warn "[debug]$me $statement\n" if $DEBUG > 1;
305   my $sth = $dbh->prepare($statement)
306     or croak "$dbh->errstr doing $statement";
307
308   my $bind = 1;
309
310   foreach my $field (
311     grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
312   ) {
313     if ( $record->{$field} =~ /^\d+(\.\d+)?$/
314          && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
315     ) {
316       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
317     } else {
318       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
319     }
320   }
321
322 #  $sth->execute( map $record->{$_},
323 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
324 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
325
326   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
327
328   my %result;
329   tie %result, "Tie::IxHash";
330   @virtual_fields = "FS::$table"->virtual_fields;
331
332   my @stuff = @{ $sth->fetchall_arrayref( {} ) };
333   if($pkey) {
334     %result = map { $_->{$pkey}, $_ } @stuff;
335   } else {
336     @result{@stuff} = @stuff;
337   }
338
339   $sth->finish;
340   if ( keys(%result) and @virtual_fields ) {
341     $statement =
342       "SELECT virtual_field.recnum, part_virtual_field.name, ".
343              "virtual_field.value ".
344       "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
345       "WHERE part_virtual_field.dbtable = '$table' AND ".
346       "virtual_field.recnum IN (".
347       join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
348       join(q!', '!, @virtual_fields) . "')";
349     warn "[debug]$me $statement\n" if $DEBUG > 1;
350     $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
351     $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
352
353     foreach (@{ $sth->fetchall_arrayref({}) }) {
354       my $recnum = $_->{recnum};
355       my $name = $_->{name};
356       my $value = $_->{value};
357       if (exists($result{$recnum})) {
358         $result{$recnum}->{$name} = $value;
359       }
360     }
361   }
362   
363   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
364     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
365       #derivied class didn't override new method, so this optimization is safe
366       if ( $cache ) {
367         map {
368           new_or_cached( "FS::$table", { %{$_} }, $cache )
369         } values(%result);
370       } else {
371         map {
372           new( "FS::$table", { %{$_} } )
373         } values(%result);
374       }
375     } else {
376       warn "untested code (class FS::$table uses custom new method)";
377       map {
378         eval 'FS::'. $table. '->new( { %{$_} } )';
379       } values(%result);
380     }
381   } else {
382     cluck "warning: FS::$table not loaded; returning FS::Record objects";
383     map {
384       FS::Record->new( $table, { %{$_} } );
385     } values(%result);
386   }
387
388 }
389
390 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
391
392 Experimental JOINed search method.  Using this method, you can execute a
393 single SELECT spanning multiple tables, and cache the results for subsequent
394 method calls.  Interface will almost definately change in an incompatible
395 fashion.
396
397 Arguments: 
398
399 =cut
400
401 sub jsearch {
402   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
403   my $cache = FS::SearchCache->new( $ptable, $pkey );
404   my %saw;
405   ( $cache,
406     grep { !$saw{$_->getfield($pkey)}++ }
407       qsearch($table, $record, $select, $extra_sql, $cache )
408   );
409 }
410
411 =item qsearchs TABLE, HASHREF
412
413 Same as qsearch, except that if more than one record matches, it B<carp>s but
414 returns the first.  If this happens, you either made a logic error in asking
415 for a single item, or your data is corrupted.
416
417 =cut
418
419 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
420   my $table = $_[0];
421   my(@result) = qsearch(@_);
422   carp "warning: Multiple records in scalar search ($table)"
423     if scalar(@result) > 1;
424   #should warn more vehemently if the search was on a primary key?
425   scalar(@result) ? ($result[0]) : ();
426 }
427
428 =back
429
430 =head1 METHODS
431
432 =over 4
433
434 =item table
435
436 Returns the table name.
437
438 =cut
439
440 sub table {
441 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
442   my $self = shift;
443   $self -> {'Table'};
444 }
445
446 =item dbdef_table
447
448 Returns the DBIx::DBSchema::Table object for the table.
449
450 =cut
451
452 sub dbdef_table {
453   my($self)=@_;
454   my($table)=$self->table;
455   $dbdef->table($table);
456 }
457
458 =item get, getfield COLUMN
459
460 Returns the value of the column/field/key COLUMN.
461
462 =cut
463
464 sub get {
465   my($self,$field) = @_;
466   # to avoid "Use of unitialized value" errors
467   if ( defined ( $self->{Hash}->{$field} ) ) {
468     $self->{Hash}->{$field};
469   } else { 
470     '';
471   }
472 }
473 sub getfield {
474   my $self = shift;
475   $self->get(@_);
476 }
477
478 =item set, setfield COLUMN, VALUE
479
480 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
481
482 =cut
483
484 sub set { 
485   my($self,$field,$value) = @_;
486   $self->{'Hash'}->{$field} = $value;
487 }
488 sub setfield {
489   my $self = shift;
490   $self->set(@_);
491 }
492
493 =item AUTLOADED METHODS
494
495 $record->column is a synonym for $record->get('column');
496
497 $record->column('value') is a synonym for $record->set('column','value');
498
499 =cut
500
501 # readable/safe
502 sub AUTOLOAD {
503   my($self,$value)=@_;
504   my($field)=$AUTOLOAD;
505   $field =~ s/.*://;
506   if ( defined($value) ) {
507     confess "errant AUTOLOAD $field for $self (arg $value)"
508       unless ref($self) && $self->can('setfield');
509     $self->setfield($field,$value);
510   } else {
511     confess "errant AUTOLOAD $field for $self (no args)"
512       unless ref($self) && $self->can('getfield');
513     $self->getfield($field);
514   }    
515 }
516
517 # efficient
518 #sub AUTOLOAD {
519 #  my $field = $AUTOLOAD;
520 #  $field =~ s/.*://;
521 #  if ( defined($_[1]) ) {
522 #    $_[0]->setfield($field, $_[1]);
523 #  } else {
524 #    $_[0]->getfield($field);
525 #  }    
526 #}
527
528 =item hash
529
530 Returns a list of the column/value pairs, usually for assigning to a new hash.
531
532 To make a distinct duplicate of an FS::Record object, you can do:
533
534     $new = new FS::Record ( $old->table, { $old->hash } );
535
536 =cut
537
538 sub hash {
539   my($self) = @_;
540   confess $self. ' -> hash: Hash attribute is undefined'
541     unless defined($self->{'Hash'});
542   %{ $self->{'Hash'} }; 
543 }
544
545 =item hashref
546
547 Returns a reference to the column/value hash.
548
549 =cut
550
551 sub hashref {
552   my($self) = @_;
553   $self->{'Hash'};
554 }
555
556 =item insert
557
558 Inserts this record to the database.  If there is an error, returns the error,
559 otherwise returns false.
560
561 =cut
562
563 sub insert {
564   my $self = shift;
565
566   my $error = $self->check;
567   return $error if $error;
568
569   #single-field unique keys are given a value if false
570   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
571   foreach ( $self->dbdef_table->unique->singles ) {
572     $self->unique($_) unless $self->getfield($_);
573   }
574
575   #and also the primary key, if the database isn't going to
576   my $primary_key = $self->dbdef_table->primary_key;
577   my $db_seq = 0;
578   if ( $primary_key ) {
579     my $col = $self->dbdef_table->column($primary_key);
580     
581     $db_seq =
582       uc($col->type) eq 'SERIAL'
583       || ( driver_name eq 'Pg'
584              && defined($col->default)
585              && $col->default =~ /^nextval\(/i
586          )
587       || ( driver_name eq 'mysql'
588              && defined($col->local)
589              && $col->local =~ /AUTO_INCREMENT/i
590          );
591     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
592   }
593
594   my $table = $self->table;
595   #false laziness w/delete
596   my @real_fields =
597     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
598     real_fields($table)
599   ;
600   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
601   #eslaf
602
603   my $statement = "INSERT INTO $table ( ".
604       join( ', ', @real_fields ).
605     ") VALUES (".
606       join( ', ', @values ).
607     ")"
608   ;
609   warn "[debug]$me $statement\n" if $DEBUG > 1;
610   my $sth = dbh->prepare($statement) or return dbh->errstr;
611
612   local $SIG{HUP} = 'IGNORE';
613   local $SIG{INT} = 'IGNORE';
614   local $SIG{QUIT} = 'IGNORE'; 
615   local $SIG{TERM} = 'IGNORE';
616   local $SIG{TSTP} = 'IGNORE';
617   local $SIG{PIPE} = 'IGNORE';
618
619   $sth->execute or return $sth->errstr;
620
621   my $insertid = '';
622   if ( $db_seq ) { # get inserted id from the database, if applicable
623     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
624     if ( driver_name eq 'Pg' ) {
625
626       my $oid = $sth->{'pg_oid_status'};
627       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
628       my $i_sth = dbh->prepare($i_sql) or do {
629         dbh->rollback if $FS::UID::AutoCommit;
630         return dbh->errstr;
631       };
632       $i_sth->execute($oid) or do {
633         dbh->rollback if $FS::UID::AutoCommit;
634         return $i_sth->errstr;
635       };
636       $insertid = $i_sth->fetchrow_arrayref->[0];
637
638     } elsif ( driver_name eq 'mysql' ) {
639
640       $insertid = dbh->{'mysql_insertid'};
641       # work around mysql_insertid being null some of the time, ala RT :/
642       unless ( $insertid ) {
643         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
644              "using SELECT LAST_INSERT_ID();";
645         my $i_sql = "SELECT LAST_INSERT_ID()";
646         my $i_sth = dbh->prepare($i_sql) or do {
647           dbh->rollback if $FS::UID::AutoCommit;
648           return dbh->errstr;
649         };
650         $i_sth->execute or do {
651           dbh->rollback if $FS::UID::AutoCommit;
652           return $i_sth->errstr;
653         };
654         $insertid = $i_sth->fetchrow_arrayref->[0];
655       }
656
657     } else {
658       dbh->rollback if $FS::UID::AutoCommit;
659       return "don't know how to retreive inserted ids from ". driver_name. 
660              ", try using counterfiles (maybe run dbdef-create?)";
661     }
662     $self->setfield($primary_key, $insertid);
663   }
664
665   my @virtual_fields = 
666       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
667           $self->virtual_fields;
668   if (@virtual_fields) {
669     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
670
671     my $vfieldpart = $self->vfieldpart_hashref;
672
673     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
674                     "VALUES (?, ?, ?)";
675
676     my $v_sth = dbh->prepare($v_statement) or do {
677       dbh->rollback if $FS::UID::AutoCommit;
678       return dbh->errstr;
679     };
680
681     foreach (keys(%v_values)) {
682       $v_sth->execute($self->getfield($primary_key),
683                       $vfieldpart->{$_},
684                       $v_values{$_})
685       or do {
686         dbh->rollback if $FS::UID::AutoCommit;
687         return $v_sth->errstr;
688       };
689     }
690   }
691
692
693   my $h_sth;
694   if ( defined $dbdef->table('h_'. $table) ) {
695     my $h_statement = $self->_h_statement('insert');
696     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
697     $h_sth = dbh->prepare($h_statement) or do {
698       dbh->rollback if $FS::UID::AutoCommit;
699       return dbh->errstr;
700     };
701   } else {
702     $h_sth = '';
703   }
704   $h_sth->execute or return $h_sth->errstr if $h_sth;
705
706   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
707
708   '';
709 }
710
711 =item add
712
713 Depriciated (use insert instead).
714
715 =cut
716
717 sub add {
718   cluck "warning: FS::Record::add deprecated!";
719   insert @_; #call method in this scope
720 }
721
722 =item delete
723
724 Delete this record from the database.  If there is an error, returns the error,
725 otherwise returns false.
726
727 =cut
728
729 sub delete {
730   my $self = shift;
731
732   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
733     map {
734       $self->getfield($_) eq ''
735         #? "( $_ IS NULL OR $_ = \"\" )"
736         ? ( driver_name eq 'Pg'
737               ? "$_ IS NULL"
738               : "( $_ IS NULL OR $_ = \"\" )"
739           )
740         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
741     } ( $self->dbdef_table->primary_key )
742           ? ( $self->dbdef_table->primary_key)
743           : real_fields($self->table)
744   );
745   warn "[debug]$me $statement\n" if $DEBUG > 1;
746   my $sth = dbh->prepare($statement) or return dbh->errstr;
747
748   my $h_sth;
749   if ( defined $dbdef->table('h_'. $self->table) ) {
750     my $h_statement = $self->_h_statement('delete');
751     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
752     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
753   } else {
754     $h_sth = '';
755   }
756
757   my $primary_key = $self->dbdef_table->primary_key;
758   my $v_sth;
759   my @del_vfields;
760   my $vfp = $self->vfieldpart_hashref;
761   foreach($self->virtual_fields) {
762     next if $self->getfield($_) eq '';
763     unless(@del_vfields) {
764       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
765       $v_sth = dbh->prepare($st) or return dbh->errstr;
766     }
767     push @del_vfields, $_;
768   }
769
770   local $SIG{HUP} = 'IGNORE';
771   local $SIG{INT} = 'IGNORE';
772   local $SIG{QUIT} = 'IGNORE'; 
773   local $SIG{TERM} = 'IGNORE';
774   local $SIG{TSTP} = 'IGNORE';
775   local $SIG{PIPE} = 'IGNORE';
776
777   my $rc = $sth->execute or return $sth->errstr;
778   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
779   $h_sth->execute or return $h_sth->errstr if $h_sth;
780   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
781     or return $v_sth->errstr 
782         foreach (@del_vfields);
783   
784   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
785
786   #no need to needlessly destoy the data either (causes problems actually)
787   #undef $self; #no need to keep object!
788
789   '';
790 }
791
792 =item del
793
794 Depriciated (use delete instead).
795
796 =cut
797
798 sub del {
799   cluck "warning: FS::Record::del deprecated!";
800   &delete(@_); #call method in this scope
801 }
802
803 =item replace OLD_RECORD
804
805 Replace the OLD_RECORD with this one in the database.  If there is an error,
806 returns the error, otherwise returns false.
807
808 =cut
809
810 sub replace {
811   my $new = shift;
812
813   my $old;
814   if ( @_ ) { 
815     $old = shift;
816   } else {
817     warn "[debug]$me replace called with no arguments; autoloading old record\n"
818      if $DEBUG;
819     my $primary_key = $new->dbdef_table->primary_key;
820     if ( $primary_key ) {
821       $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
822         or croak "can't find ". $new->table. ".$primary_key ".
823                  $new->$primary_key();
824     } else {
825       croak $new->table. " has no primary key; pass old record as argument";
826     }
827   }
828
829   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
830
831   return "Records not in same table!" unless $new->table eq $old->table;
832
833   my $primary_key = $old->dbdef_table->primary_key;
834   return "Can't change $primary_key"
835     if $primary_key
836        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
837
838   my $error = $new->check;
839   return $error if $error;
840
841   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
842   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
843                    ? ($_, $new->getfield($_)) : () } $old->fields;
844                    
845   unless ( keys(%diff) ) {
846     carp "[warning]$me $new -> replace $old: records identical";
847     return '';
848   }
849
850   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
851     map {
852       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
853     } real_fields($old->table)
854   ). ' WHERE '.
855     join(' AND ',
856       map {
857         $old->getfield($_) eq ''
858           #? "( $_ IS NULL OR $_ = \"\" )"
859           ? ( driver_name eq 'Pg'
860                 ? "( $_ IS NULL OR $_ = '' )"
861                 : "( $_ IS NULL OR $_ = \"\" )"
862             )
863           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
864       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
865     )
866   ;
867   warn "[debug]$me $statement\n" if $DEBUG > 1;
868   my $sth = dbh->prepare($statement) or return dbh->errstr;
869
870   my $h_old_sth;
871   if ( defined $dbdef->table('h_'. $old->table) ) {
872     my $h_old_statement = $old->_h_statement('replace_old');
873     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
874     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
875   } else {
876     $h_old_sth = '';
877   }
878
879   my $h_new_sth;
880   if ( defined $dbdef->table('h_'. $new->table) ) {
881     my $h_new_statement = $new->_h_statement('replace_new');
882     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
883     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
884   } else {
885     $h_new_sth = '';
886   }
887
888   # For virtual fields we have three cases with different SQL 
889   # statements: add, replace, delete
890   my $v_add_sth;
891   my $v_rep_sth;
892   my $v_del_sth;
893   my (@add_vfields, @rep_vfields, @del_vfields);
894   my $vfp = $old->vfieldpart_hashref;
895   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
896     if($diff{$_} eq '') {
897       # Delete
898       unless(@del_vfields) {
899         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
900                  "AND vfieldpart = ?";
901         warn "[debug]$me $st\n" if $DEBUG > 2;
902         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
903       }
904       push @del_vfields, $_;
905     } elsif($old->getfield($_) eq '') {
906       # Add
907       unless(@add_vfields) {
908         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
909                  "VALUES (?, ?, ?)";
910         warn "[debug]$me $st\n" if $DEBUG > 2;
911         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
912       }
913       push @add_vfields, $_;
914     } else {
915       # Replace
916       unless(@rep_vfields) {
917         my $st = "UPDATE virtual_field SET value = ? ".
918                  "WHERE recnum = ? AND vfieldpart = ?";
919         warn "[debug]$me $st\n" if $DEBUG > 2;
920         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
921       }
922       push @rep_vfields, $_;
923     }
924   }
925
926   local $SIG{HUP} = 'IGNORE';
927   local $SIG{INT} = 'IGNORE';
928   local $SIG{QUIT} = 'IGNORE'; 
929   local $SIG{TERM} = 'IGNORE';
930   local $SIG{TSTP} = 'IGNORE';
931   local $SIG{PIPE} = 'IGNORE';
932
933   my $rc = $sth->execute or return $sth->errstr;
934   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
935   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
936   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
937
938   $v_del_sth->execute($old->getfield($primary_key),
939                       $vfp->{$_})
940         or return $v_del_sth->errstr
941       foreach(@del_vfields);
942
943   $v_add_sth->execute($new->getfield($_),
944                       $old->getfield($primary_key),
945                       $vfp->{$_})
946         or return $v_add_sth->errstr
947       foreach(@add_vfields);
948
949   $v_rep_sth->execute($new->getfield($_),
950                       $old->getfield($primary_key),
951                       $vfp->{$_})
952         or return $v_rep_sth->errstr
953       foreach(@rep_vfields);
954
955   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
956
957   '';
958
959 }
960
961 =item rep
962
963 Depriciated (use replace instead).
964
965 =cut
966
967 sub rep {
968   cluck "warning: FS::Record::rep deprecated!";
969   replace @_; #call method in this scope
970 }
971
972 =item check
973
974 Checks virtual fields (using check_blocks).  Subclasses should still provide 
975 a check method to validate real fields, foreign keys, etc., and call this 
976 method via $self->SUPER::check.
977
978 (FIXME: Should this method try to make sure that it I<is> being called from 
979 a subclass's check method, to keep the current semantics as far as possible?)
980
981 =cut
982
983 sub check {
984   #confess "FS::Record::check not implemented; supply one in subclass!";
985   my $self = shift;
986
987   foreach my $field ($self->virtual_fields) {
988     for ($self->getfield($field)) {
989       # See notes on check_block in FS::part_virtual_field.
990       eval $self->pvf($field)->check_block;
991       if ( $@ ) {
992         #this is bad, probably want to follow the stack backtrace up and see
993         #wtf happened
994         my $err = "Fatal error checking $field for $self";
995         cluck "$err: $@";
996         return "$err (see log for backtrace): $@";
997
998       }
999       $self->setfield($field, $_);
1000     }
1001   }
1002   '';
1003 }
1004
1005 sub _h_statement {
1006   my( $self, $action ) = @_;
1007
1008   my @fields =
1009     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1010     real_fields($self->table);
1011   ;
1012   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1013
1014   "INSERT INTO h_". $self->table. " ( ".
1015       join(', ', qw(history_date history_user history_action), @fields ).
1016     ") VALUES (".
1017       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
1018     ")"
1019   ;
1020 }
1021
1022 =item unique COLUMN
1023
1024 B<Warning>: External use is B<deprecated>.  
1025
1026 Replaces COLUMN in record with a unique number, using counters in the
1027 filesystem.  Used by the B<insert> method on single-field unique columns
1028 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1029 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1030
1031 Returns the new value.
1032
1033 =cut
1034
1035 sub unique {
1036   my($self,$field) = @_;
1037   my($table)=$self->table;
1038
1039   croak "Unique called on field $field, but it is ",
1040         $self->getfield($field),
1041         ", not null!"
1042     if $self->getfield($field);
1043
1044   #warn "table $table is tainted" if is_tainted($table);
1045   #warn "field $field is tainted" if is_tainted($field);
1046
1047   my($counter) = new File::CounterFile "$table.$field",0;
1048 # hack for web demo
1049 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1050 #  my($user)=$1;
1051 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1052 # endhack
1053
1054   my $index = $counter->inc;
1055   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1056
1057   $index =~ /^(\d*)$/;
1058   $index=$1;
1059
1060   $self->setfield($field,$index);
1061
1062 }
1063
1064 =item ut_float COLUMN
1065
1066 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1067 null.  If there is an error, returns the error, otherwise returns false.
1068
1069 =cut
1070
1071 sub ut_float {
1072   my($self,$field)=@_ ;
1073   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1074    $self->getfield($field) =~ /^(\d+)$/ ||
1075    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1076    $self->getfield($field) =~ /^(\d+e\d+)$/)
1077     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1078   $self->setfield($field,$1);
1079   '';
1080 }
1081
1082 =item ut_snumber COLUMN
1083
1084 Check/untaint signed numeric data (whole numbers).  May not be null.  If there
1085 is an error, returns the error, otherwise returns false.
1086
1087 =cut
1088
1089 sub ut_snumber {
1090   my($self, $field) = @_;
1091   $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1092     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1093   $self->setfield($field, "$1$2");
1094   '';
1095 }
1096
1097 =item ut_number COLUMN
1098
1099 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1100 is an error, returns the error, otherwise returns false.
1101
1102 =cut
1103
1104 sub ut_number {
1105   my($self,$field)=@_;
1106   $self->getfield($field) =~ /^(\d+)$/
1107     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1108   $self->setfield($field,$1);
1109   '';
1110 }
1111
1112 =item ut_numbern COLUMN
1113
1114 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1115 an error, returns the error, otherwise returns false.
1116
1117 =cut
1118
1119 sub ut_numbern {
1120   my($self,$field)=@_;
1121   $self->getfield($field) =~ /^(\d*)$/
1122     or return "Illegal (numeric) $field: ". $self->getfield($field);
1123   $self->setfield($field,$1);
1124   '';
1125 }
1126
1127 =item ut_money COLUMN
1128
1129 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1130 is an error, returns the error, otherwise returns false.
1131
1132 =cut
1133
1134 sub ut_money {
1135   my($self,$field)=@_;
1136   $self->setfield($field, 0) if $self->getfield($field) eq '';
1137   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1138     or return "Illegal (money) $field: ". $self->getfield($field);
1139   #$self->setfield($field, "$1$2$3" || 0);
1140   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1141   '';
1142 }
1143
1144 =item ut_text COLUMN
1145
1146 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1147 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1148 May not be null.  If there is an error, returns the error, otherwise returns
1149 false.
1150
1151 =cut
1152
1153 sub ut_text {
1154   my($self,$field)=@_;
1155   #warn "msgcat ". \&msgcat. "\n";
1156   #warn "notexist ". \&notexist. "\n";
1157   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1158   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1159     or return gettext('illegal_or_empty_text'). " $field: ".
1160                $self->getfield($field);
1161   $self->setfield($field,$1);
1162   '';
1163 }
1164
1165 =item ut_textn COLUMN
1166
1167 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1168 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1169 May be null.  If there is an error, returns the error, otherwise returns false.
1170
1171 =cut
1172
1173 sub ut_textn {
1174   my($self,$field)=@_;
1175   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1176     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1177   $self->setfield($field,$1);
1178   '';
1179 }
1180
1181 =item ut_alpha COLUMN
1182
1183 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1184 an error, returns the error, otherwise returns false.
1185
1186 =cut
1187
1188 sub ut_alpha {
1189   my($self,$field)=@_;
1190   $self->getfield($field) =~ /^(\w+)$/
1191     or return "Illegal or empty (alphanumeric) $field: ".
1192               $self->getfield($field);
1193   $self->setfield($field,$1);
1194   '';
1195 }
1196
1197 =item ut_alpha COLUMN
1198
1199 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1200 error, returns the error, otherwise returns false.
1201
1202 =cut
1203
1204 sub ut_alphan {
1205   my($self,$field)=@_;
1206   $self->getfield($field) =~ /^(\w*)$/ 
1207     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1208   $self->setfield($field,$1);
1209   '';
1210 }
1211
1212 =item ut_phonen COLUMN [ COUNTRY ]
1213
1214 Check/untaint phone numbers.  May be null.  If there is an error, returns
1215 the error, otherwise returns false.
1216
1217 Takes an optional two-letter ISO country code; without it or with unsupported
1218 countries, ut_phonen simply calls ut_alphan.
1219
1220 =cut
1221
1222 sub ut_phonen {
1223   my( $self, $field, $country ) = @_;
1224   return $self->ut_alphan($field) unless defined $country;
1225   my $phonen = $self->getfield($field);
1226   if ( $phonen eq '' ) {
1227     $self->setfield($field,'');
1228   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1229     $phonen =~ s/\D//g;
1230     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1231       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1232     $phonen = "$1-$2-$3";
1233     $phonen .= " x$4" if $4;
1234     $self->setfield($field,$phonen);
1235   } else {
1236     warn "warning: don't know how to check phone numbers for country $country";
1237     return $self->ut_textn($field);
1238   }
1239   '';
1240 }
1241
1242 =item ut_ip COLUMN
1243
1244 Check/untaint ip addresses.  IPv4 only for now.
1245
1246 =cut
1247
1248 sub ut_ip {
1249   my( $self, $field ) = @_;
1250   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1251     or return "Illegal (IP address) $field: ". $self->getfield($field);
1252   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1253   $self->setfield($field, "$1.$2.$3.$4");
1254   '';
1255 }
1256
1257 =item ut_ipn COLUMN
1258
1259 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1260
1261 =cut
1262
1263 sub ut_ipn {
1264   my( $self, $field ) = @_;
1265   if ( $self->getfield($field) =~ /^()$/ ) {
1266     $self->setfield($field,'');
1267     '';
1268   } else {
1269     $self->ut_ip($field);
1270   }
1271 }
1272
1273 =item ut_domain COLUMN
1274
1275 Check/untaint host and domain names.
1276
1277 =cut
1278
1279 sub ut_domain {
1280   my( $self, $field ) = @_;
1281   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1282   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1283     or return "Illegal (domain) $field: ". $self->getfield($field);
1284   $self->setfield($field,$1);
1285   '';
1286 }
1287
1288 =item ut_name COLUMN
1289
1290 Check/untaint proper names; allows alphanumerics, spaces and the following
1291 punctuation: , . - '
1292
1293 May not be null.
1294
1295 =cut
1296
1297 sub ut_name {
1298   my( $self, $field ) = @_;
1299   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1300     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1301   $self->setfield($field,$1);
1302   '';
1303 }
1304
1305 =item ut_zip COLUMN
1306
1307 Check/untaint zip codes.
1308
1309 =cut
1310
1311 sub ut_zip {
1312   my( $self, $field, $country ) = @_;
1313   if ( $country eq 'US' ) {
1314     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1315       or return gettext('illegal_zip'). " $field for country $country: ".
1316                 $self->getfield($field);
1317     $self->setfield($field,$1);
1318   } else {
1319     if ( $self->getfield($field) =~ /^\s*$/ ) {
1320       $self->setfield($field,'');
1321     } else {
1322       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1323         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1324       $self->setfield($field,$1);
1325     }
1326   }
1327   '';
1328 }
1329
1330 =item ut_country COLUMN
1331
1332 Check/untaint country codes.  Country names are changed to codes, if possible -
1333 see L<Locale::Country>.
1334
1335 =cut
1336
1337 sub ut_country {
1338   my( $self, $field ) = @_;
1339   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1340     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1341          && country2code($1) ) {
1342       $self->setfield($field,uc(country2code($1)));
1343     }
1344   }
1345   $self->getfield($field) =~ /^(\w\w)$/
1346     or return "Illegal (country) $field: ". $self->getfield($field);
1347   $self->setfield($field,uc($1));
1348   '';
1349 }
1350
1351 =item ut_anything COLUMN
1352
1353 Untaints arbitrary data.  Be careful.
1354
1355 =cut
1356
1357 sub ut_anything {
1358   my( $self, $field ) = @_;
1359   $self->getfield($field) =~ /^(.*)$/s
1360     or return "Illegal $field: ". $self->getfield($field);
1361   $self->setfield($field,$1);
1362   '';
1363 }
1364
1365 =item ut_enum COLUMN CHOICES_ARRAYREF
1366
1367 Check/untaint a column, supplying all possible choices, like the "enum" type.
1368
1369 =cut
1370
1371 sub ut_enum {
1372   my( $self, $field, $choices ) = @_;
1373   foreach my $choice ( @$choices ) {
1374     if ( $self->getfield($field) eq $choice ) {
1375       $self->setfield($choice);
1376       return '';
1377     }
1378   }
1379   return "Illegal (enum) field $field: ". $self->getfield($field);
1380 }
1381
1382 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1383
1384 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1385 on the column first.
1386
1387 =cut
1388
1389 sub ut_foreign_key {
1390   my( $self, $field, $table, $foreign ) = @_;
1391   qsearchs($table, { $foreign => $self->getfield($field) })
1392     or return "Can't find $field ". $self->getfield($field).
1393               " in $table.$foreign";
1394   '';
1395 }
1396
1397 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1398
1399 Like ut_foreign_key, except the null value is also allowed.
1400
1401 =cut
1402
1403 sub ut_foreign_keyn {
1404   my( $self, $field, $table, $foreign ) = @_;
1405   $self->getfield($field)
1406     ? $self->ut_foreign_key($field, $table, $foreign)
1407     : '';
1408 }
1409
1410
1411 =item virtual_fields [ TABLE ]
1412
1413 Returns a list of virtual fields defined for the table.  This should not 
1414 be exported, and should only be called as an instance or class method.
1415
1416 =cut
1417
1418 sub virtual_fields {
1419   my $self = shift;
1420   my $table;
1421   $table = $self->table or confess "virtual_fields called on non-table";
1422
1423   confess "Unknown table $table" unless $dbdef->table($table);
1424
1425   return () unless $self->dbdef->table('part_virtual_field');
1426
1427   unless ( $virtual_fields_cache{$table} ) {
1428     my $query = 'SELECT name from part_virtual_field ' .
1429                 "WHERE dbtable = '$table'";
1430     my $dbh = dbh;
1431     my $result = $dbh->selectcol_arrayref($query);
1432     confess $dbh->errstr if $dbh->err;
1433     $virtual_fields_cache{$table} = $result;
1434   }
1435
1436   @{$virtual_fields_cache{$table}};
1437
1438 }
1439
1440
1441 =item fields [ TABLE ]
1442
1443 This is a wrapper for real_fields and virtual_fields.  Code that called
1444 fields before should probably continue to call fields.
1445
1446 =cut
1447
1448 sub fields {
1449   my $something = shift;
1450   my $table;
1451   if($something->isa('FS::Record')) {
1452     $table = $something->table;
1453   } else {
1454     $table = $something;
1455     $something = "FS::$table";
1456   }
1457   return (real_fields($table), $something->virtual_fields());
1458 }
1459
1460 =back
1461
1462 =item pvf FIELD_NAME
1463
1464 Returns the FS::part_virtual_field object corresponding to a field in the 
1465 record (specified by FIELD_NAME).
1466
1467 =cut
1468
1469 sub pvf {
1470   my ($self, $name) = (shift, shift);
1471
1472   if(grep /^$name$/, $self->virtual_fields) {
1473     return qsearchs('part_virtual_field', { dbtable => $self->table,
1474                                             name    => $name } );
1475   }
1476   ''
1477 }
1478
1479 =head1 SUBROUTINES
1480
1481 =over 4
1482
1483 =item real_fields [ TABLE ]
1484
1485 Returns a list of the real columns in the specified table.  Called only by 
1486 fields() and other subroutines elsewhere in FS::Record.
1487
1488 =cut
1489
1490 sub real_fields {
1491   my $table = shift;
1492
1493   my($table_obj) = $dbdef->table($table);
1494   confess "Unknown table $table" unless $table_obj;
1495   $table_obj->columns;
1496 }
1497
1498 =item reload_dbdef([FILENAME])
1499
1500 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1501 non-default filename.  This command is executed at startup unless
1502 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1503
1504 =cut
1505
1506 sub reload_dbdef {
1507   my $file = shift || $dbdef_file;
1508
1509   unless ( exists $dbdef_cache{$file} ) {
1510     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1511     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1512                             or die "can't load database schema from $file";
1513   } else {
1514     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1515   }
1516   $dbdef = $dbdef_cache{$file};
1517 }
1518
1519 =item dbdef
1520
1521 Returns the current database definition.  See L<DBIx::DBSchema>.
1522
1523 =cut
1524
1525 sub dbdef { $dbdef; }
1526
1527 =item _quote VALUE, TABLE, COLUMN
1528
1529 This is an internal function used to construct SQL statements.  It returns
1530 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1531 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1532
1533 =cut
1534
1535 sub _quote {
1536   my($value, $table, $column) = @_;
1537   my $column_obj = $dbdef->table($table)->column($column);
1538   my $column_type = $column_obj->type;
1539
1540   if ( $value eq '' && $column_type =~ /^int/ ) {
1541     if ( $column_obj->null ) {
1542       'NULL';
1543     } else {
1544       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1545             "using 0 instead";
1546       0;
1547     }
1548   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1549             ! $column_type =~ /(char|binary|text)$/i ) {
1550     $value;
1551   } else {
1552     dbh->quote($value);
1553   }
1554 }
1555
1556 =item vfieldpart_hashref TABLE
1557
1558 Returns a hashref of virtual field names and vfieldparts applicable to the given
1559 TABLE.
1560
1561 =cut
1562
1563 sub vfieldpart_hashref {
1564   my $self = shift;
1565   my $table = $self->table;
1566
1567   return {} unless $self->dbdef->table('part_virtual_field');
1568
1569   my $dbh = dbh;
1570   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1571                   "dbtable = '$table'";
1572   my $sth = $dbh->prepare($statement);
1573   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1574   return { map { $_->{name}, $_->{vfieldpart} } 
1575     @{$sth->fetchall_arrayref({})} };
1576
1577 }
1578
1579
1580 =item hfields TABLE
1581
1582 This is deprecated.  Don't use it.
1583
1584 It returns a hash-type list with the fields of this record's table set true.
1585
1586 =cut
1587
1588 sub hfields {
1589   carp "warning: hfields is deprecated";
1590   my($table)=@_;
1591   my(%hash);
1592   foreach (fields($table)) {
1593     $hash{$_}=1;
1594   }
1595   \%hash;
1596 }
1597
1598 sub _dump {
1599   my($self)=@_;
1600   join("\n", map {
1601     "$_: ". $self->getfield($_). "|"
1602   } (fields($self->table)) );
1603 }
1604
1605 sub DESTROY { return; }
1606
1607 #sub DESTROY {
1608 #  my $self = shift;
1609 #  #use Carp qw(cluck);
1610 #  #cluck "DESTROYING $self";
1611 #  warn "DESTROYING $self";
1612 #}
1613
1614 #sub is_tainted {
1615 #             return ! eval { join('',@_), kill 0; 1; };
1616 #         }
1617
1618 =back
1619
1620 =head1 BUGS
1621
1622 This module should probably be renamed, since much of the functionality is
1623 of general use.  It is not completely unlike Adapter::DBI (see below).
1624
1625 Exported qsearch and qsearchs should be deprecated in favor of method calls
1626 (against an FS::Record object like the old search and searchs that qsearch
1627 and qsearchs were on top of.)
1628
1629 The whole fields / hfields mess should be removed.
1630
1631 The various WHERE clauses should be subroutined.
1632
1633 table string should be deprecated in favor of DBIx::DBSchema::Table.
1634
1635 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1636 true maps to the database (and WHERE clauses) would also help.
1637
1638 The ut_ methods should ask the dbdef for a default length.
1639
1640 ut_sqltype (like ut_varchar) should all be defined
1641
1642 A fallback check method should be provided which uses the dbdef.
1643
1644 The ut_money method assumes money has two decimal digits.
1645
1646 The Pg money kludge in the new method only strips `$'.
1647
1648 The ut_phonen method only checks US-style phone numbers.
1649
1650 The _quote function should probably use ut_float instead of a regex.
1651
1652 All the subroutines probably should be methods, here or elsewhere.
1653
1654 Probably should borrow/use some dbdef methods where appropriate (like sub
1655 fields)
1656
1657 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1658 or allow it to be set.  Working around it is ugly any way around - DBI should
1659 be fixed.  (only affects RDBMS which return uppercase column names)
1660
1661 ut_zip should take an optional country like ut_phone.
1662
1663 =head1 SEE ALSO
1664
1665 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1666
1667 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1668
1669 =cut
1670
1671 1;
1672