recommend HTML::Mason
[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   %{ $self->{'Hash'} }; 
541 }
542
543 =item hashref
544
545 Returns a reference to the column/value hash.
546
547 =cut
548
549 sub hashref {
550   my($self) = @_;
551   $self->{'Hash'};
552 }
553
554 =item insert
555
556 Inserts this record to the database.  If there is an error, returns the error,
557 otherwise returns false.
558
559 =cut
560
561 sub insert {
562   my $self = shift;
563
564   my $error = $self->check;
565   return $error if $error;
566
567   #single-field unique keys are given a value if false
568   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
569   foreach ( $self->dbdef_table->unique->singles ) {
570     $self->unique($_) unless $self->getfield($_);
571   }
572
573   #and also the primary key, if the database isn't going to
574   my $primary_key = $self->dbdef_table->primary_key;
575   my $db_seq = 0;
576   if ( $primary_key ) {
577     my $col = $self->dbdef_table->column($primary_key);
578     
579     $db_seq =
580       uc($col->type) eq 'SERIAL'
581       || ( driver_name eq 'Pg'
582              && defined($col->default)
583              && $col->default =~ /^nextval\(/i
584          )
585       || ( driver_name eq 'mysql'
586              && defined($col->local)
587              && $col->local =~ /AUTO_INCREMENT/i
588          );
589     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
590   }
591
592   my $table = $self->table;
593   #false laziness w/delete
594   my @real_fields =
595     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
596     real_fields($table)
597   ;
598   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
599   #eslaf
600
601   my $statement = "INSERT INTO $table ( ".
602       join( ', ', @real_fields ).
603     ") VALUES (".
604       join( ', ', @values ).
605     ")"
606   ;
607   warn "[debug]$me $statement\n" if $DEBUG > 1;
608   my $sth = dbh->prepare($statement) or return dbh->errstr;
609
610   local $SIG{HUP} = 'IGNORE';
611   local $SIG{INT} = 'IGNORE';
612   local $SIG{QUIT} = 'IGNORE'; 
613   local $SIG{TERM} = 'IGNORE';
614   local $SIG{TSTP} = 'IGNORE';
615   local $SIG{PIPE} = 'IGNORE';
616
617   $sth->execute or return $sth->errstr;
618
619   my $insertid = '';
620   if ( $db_seq ) { # get inserted id from the database, if applicable
621     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
622     if ( driver_name eq 'Pg' ) {
623
624       my $oid = $sth->{'pg_oid_status'};
625       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
626       my $i_sth = dbh->prepare($i_sql) or do {
627         dbh->rollback if $FS::UID::AutoCommit;
628         return dbh->errstr;
629       };
630       $i_sth->execute($oid) or do {
631         dbh->rollback if $FS::UID::AutoCommit;
632         return $i_sth->errstr;
633       };
634       $insertid = $i_sth->fetchrow_arrayref->[0];
635
636     } elsif ( driver_name eq 'mysql' ) {
637
638       $insertid = dbh->{'mysql_insertid'};
639       # work around mysql_insertid being null some of the time, ala RT :/
640       unless ( $insertid ) {
641         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
642              "using SELECT LAST_INSERT_ID();";
643         my $i_sql = "SELECT LAST_INSERT_ID()";
644         my $i_sth = dbh->prepare($i_sql) or do {
645           dbh->rollback if $FS::UID::AutoCommit;
646           return dbh->errstr;
647         };
648         $i_sth->execute or do {
649           dbh->rollback if $FS::UID::AutoCommit;
650           return $i_sth->errstr;
651         };
652         $insertid = $i_sth->fetchrow_arrayref->[0];
653       }
654
655     } else {
656       dbh->rollback if $FS::UID::AutoCommit;
657       return "don't know how to retreive inserted ids from ". driver_name. 
658              ", try using counterfiles (maybe run dbdef-create?)";
659     }
660     $self->setfield($primary_key, $insertid);
661   }
662
663   my @virtual_fields = 
664       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
665           $self->virtual_fields;
666   if (@virtual_fields) {
667     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
668
669     my $vfieldpart = $self->vfieldpart_hashref;
670
671     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
672                     "VALUES (?, ?, ?)";
673
674     my $v_sth = dbh->prepare($v_statement) or do {
675       dbh->rollback if $FS::UID::AutoCommit;
676       return dbh->errstr;
677     };
678
679     foreach (keys(%v_values)) {
680       $v_sth->execute($self->getfield($primary_key),
681                       $vfieldpart->{$_},
682                       $v_values{$_})
683       or do {
684         dbh->rollback if $FS::UID::AutoCommit;
685         return $v_sth->errstr;
686       };
687     }
688   }
689
690
691   my $h_sth;
692   if ( defined $dbdef->table('h_'. $table) ) {
693     my $h_statement = $self->_h_statement('insert');
694     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
695     $h_sth = dbh->prepare($h_statement) or do {
696       dbh->rollback if $FS::UID::AutoCommit;
697       return dbh->errstr;
698     };
699   } else {
700     $h_sth = '';
701   }
702   $h_sth->execute or return $h_sth->errstr if $h_sth;
703
704   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
705
706   '';
707 }
708
709 =item add
710
711 Depriciated (use insert instead).
712
713 =cut
714
715 sub add {
716   cluck "warning: FS::Record::add deprecated!";
717   insert @_; #call method in this scope
718 }
719
720 =item delete
721
722 Delete this record from the database.  If there is an error, returns the error,
723 otherwise returns false.
724
725 =cut
726
727 sub delete {
728   my $self = shift;
729
730   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
731     map {
732       $self->getfield($_) eq ''
733         #? "( $_ IS NULL OR $_ = \"\" )"
734         ? ( driver_name eq 'Pg'
735               ? "$_ IS NULL"
736               : "( $_ IS NULL OR $_ = \"\" )"
737           )
738         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
739     } ( $self->dbdef_table->primary_key )
740           ? ( $self->dbdef_table->primary_key)
741           : real_fields($self->table)
742   );
743   warn "[debug]$me $statement\n" if $DEBUG > 1;
744   my $sth = dbh->prepare($statement) or return dbh->errstr;
745
746   my $h_sth;
747   if ( defined $dbdef->table('h_'. $self->table) ) {
748     my $h_statement = $self->_h_statement('delete');
749     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
750     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
751   } else {
752     $h_sth = '';
753   }
754
755   my $primary_key = $self->dbdef_table->primary_key;
756   my $v_sth;
757   my @del_vfields;
758   my $vfp = $self->vfieldpart_hashref;
759   foreach($self->virtual_fields) {
760     next if $self->getfield($_) eq '';
761     unless(@del_vfields) {
762       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
763       $v_sth = dbh->prepare($st) or return dbh->errstr;
764     }
765     push @del_vfields, $_;
766   }
767
768   local $SIG{HUP} = 'IGNORE';
769   local $SIG{INT} = 'IGNORE';
770   local $SIG{QUIT} = 'IGNORE'; 
771   local $SIG{TERM} = 'IGNORE';
772   local $SIG{TSTP} = 'IGNORE';
773   local $SIG{PIPE} = 'IGNORE';
774
775   my $rc = $sth->execute or return $sth->errstr;
776   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
777   $h_sth->execute or return $h_sth->errstr if $h_sth;
778   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
779     or return $v_sth->errstr 
780         foreach (@del_vfields);
781   
782   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
783
784   #no need to needlessly destoy the data either (causes problems actually)
785   #undef $self; #no need to keep object!
786
787   '';
788 }
789
790 =item del
791
792 Depriciated (use delete instead).
793
794 =cut
795
796 sub del {
797   cluck "warning: FS::Record::del deprecated!";
798   &delete(@_); #call method in this scope
799 }
800
801 =item replace OLD_RECORD
802
803 Replace the OLD_RECORD with this one in the database.  If there is an error,
804 returns the error, otherwise returns false.
805
806 =cut
807
808 sub replace {
809   my $new = shift;
810
811   my $old;
812   if ( @_ ) { 
813     $old = shift;
814   } else {
815     warn "[debug]$me replace called with no arguments; autoloading old record\n"
816      if $DEBUG;
817     my $primary_key = $new->dbdef_table->primary_key;
818     if ( $primary_key ) {
819       $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
820         or croak "can't find ". $new->table. ".$primary_key ".
821                  $new->$primary_key();
822     } else {
823       croak $new->table. " has no primary key; pass old record as argument";
824     }
825   }
826
827   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
828
829   return "Records not in same table!" unless $new->table eq $old->table;
830
831   my $primary_key = $old->dbdef_table->primary_key;
832   return "Can't change $primary_key"
833     if $primary_key
834        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
835
836   my $error = $new->check;
837   return $error if $error;
838
839   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
840   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
841                    ? ($_, $new->getfield($_)) : () } $old->fields;
842                    
843   unless ( keys(%diff) ) {
844     carp "[warning]$me $new -> replace $old: records identical";
845     return '';
846   }
847
848   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
849     map {
850       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
851     } real_fields($old->table)
852   ). ' WHERE '.
853     join(' AND ',
854       map {
855         $old->getfield($_) eq ''
856           #? "( $_ IS NULL OR $_ = \"\" )"
857           ? ( driver_name eq 'Pg'
858                 ? "( $_ IS NULL OR $_ = '' )"
859                 : "( $_ IS NULL OR $_ = \"\" )"
860             )
861           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
862       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
863     )
864   ;
865   warn "[debug]$me $statement\n" if $DEBUG > 1;
866   my $sth = dbh->prepare($statement) or return dbh->errstr;
867
868   my $h_old_sth;
869   if ( defined $dbdef->table('h_'. $old->table) ) {
870     my $h_old_statement = $old->_h_statement('replace_old');
871     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
872     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
873   } else {
874     $h_old_sth = '';
875   }
876
877   my $h_new_sth;
878   if ( defined $dbdef->table('h_'. $new->table) ) {
879     my $h_new_statement = $new->_h_statement('replace_new');
880     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
881     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
882   } else {
883     $h_new_sth = '';
884   }
885
886   # For virtual fields we have three cases with different SQL 
887   # statements: add, replace, delete
888   my $v_add_sth;
889   my $v_rep_sth;
890   my $v_del_sth;
891   my (@add_vfields, @rep_vfields, @del_vfields);
892   my $vfp = $old->vfieldpart_hashref;
893   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
894     if($diff{$_} eq '') {
895       # Delete
896       unless(@del_vfields) {
897         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
898                  "AND vfieldpart = ?";
899         warn "[debug]$me $st\n" if $DEBUG > 2;
900         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
901       }
902       push @del_vfields, $_;
903     } elsif($old->getfield($_) eq '') {
904       # Add
905       unless(@add_vfields) {
906         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
907                  "VALUES (?, ?, ?)";
908         warn "[debug]$me $st\n" if $DEBUG > 2;
909         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
910       }
911       push @add_vfields, $_;
912     } else {
913       # Replace
914       unless(@rep_vfields) {
915         my $st = "UPDATE virtual_field SET value = ? ".
916                  "WHERE recnum = ? AND vfieldpart = ?";
917         warn "[debug]$me $st\n" if $DEBUG > 2;
918         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
919       }
920       push @rep_vfields, $_;
921     }
922   }
923
924   local $SIG{HUP} = 'IGNORE';
925   local $SIG{INT} = 'IGNORE';
926   local $SIG{QUIT} = 'IGNORE'; 
927   local $SIG{TERM} = 'IGNORE';
928   local $SIG{TSTP} = 'IGNORE';
929   local $SIG{PIPE} = 'IGNORE';
930
931   my $rc = $sth->execute or return $sth->errstr;
932   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
933   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
934   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
935
936   $v_del_sth->execute($old->getfield($primary_key),
937                       $vfp->{$_})
938         or return $v_del_sth->errstr
939       foreach(@del_vfields);
940
941   $v_add_sth->execute($new->getfield($_),
942                       $old->getfield($primary_key),
943                       $vfp->{$_})
944         or return $v_add_sth->errstr
945       foreach(@add_vfields);
946
947   $v_rep_sth->execute($new->getfield($_),
948                       $old->getfield($primary_key),
949                       $vfp->{$_})
950         or return $v_rep_sth->errstr
951       foreach(@rep_vfields);
952
953   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
954
955   '';
956
957 }
958
959 =item rep
960
961 Depriciated (use replace instead).
962
963 =cut
964
965 sub rep {
966   cluck "warning: FS::Record::rep deprecated!";
967   replace @_; #call method in this scope
968 }
969
970 =item check
971
972 Checks virtual fields (using check_blocks).  Subclasses should still provide 
973 a check method to validate real fields, foreign keys, etc., and call this 
974 method via $self->SUPER::check.
975
976 (FIXME: Should this method try to make sure that it I<is> being called from 
977 a subclass's check method, to keep the current semantics as far as possible?)
978
979 =cut
980
981 sub check {
982   #confess "FS::Record::check not implemented; supply one in subclass!";
983   my $self = shift;
984
985   foreach my $field ($self->virtual_fields) {
986     for ($self->getfield($field)) {
987       # See notes on check_block in FS::part_virtual_field.
988       eval $self->pvf($field)->check_block;
989       if ( $@ ) {
990         #this is bad, probably want to follow the stack backtrace up and see
991         #wtf happened
992         my $err = "Fatal error checking $field for $self";
993         cluck "$err: $@";
994         return "$err (see log for backtrace): $@";
995
996       }
997       $self->setfield($field, $_);
998     }
999   }
1000   '';
1001 }
1002
1003 sub _h_statement {
1004   my( $self, $action ) = @_;
1005
1006   my @fields =
1007     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1008     real_fields($self->table);
1009   ;
1010   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1011
1012   "INSERT INTO h_". $self->table. " ( ".
1013       join(', ', qw(history_date history_user history_action), @fields ).
1014     ") VALUES (".
1015       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
1016     ")"
1017   ;
1018 }
1019
1020 =item unique COLUMN
1021
1022 B<Warning>: External use is B<deprecated>.  
1023
1024 Replaces COLUMN in record with a unique number, using counters in the
1025 filesystem.  Used by the B<insert> method on single-field unique columns
1026 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1027 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1028
1029 Returns the new value.
1030
1031 =cut
1032
1033 sub unique {
1034   my($self,$field) = @_;
1035   my($table)=$self->table;
1036
1037   croak "Unique called on field $field, but it is ",
1038         $self->getfield($field),
1039         ", not null!"
1040     if $self->getfield($field);
1041
1042   #warn "table $table is tainted" if is_tainted($table);
1043   #warn "field $field is tainted" if is_tainted($field);
1044
1045   my($counter) = new File::CounterFile "$table.$field",0;
1046 # hack for web demo
1047 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1048 #  my($user)=$1;
1049 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1050 # endhack
1051
1052   my $index = $counter->inc;
1053   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1054
1055   $index =~ /^(\d*)$/;
1056   $index=$1;
1057
1058   $self->setfield($field,$index);
1059
1060 }
1061
1062 =item ut_float COLUMN
1063
1064 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1065 null.  If there is an error, returns the error, otherwise returns false.
1066
1067 =cut
1068
1069 sub ut_float {
1070   my($self,$field)=@_ ;
1071   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1072    $self->getfield($field) =~ /^(\d+)$/ ||
1073    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1074    $self->getfield($field) =~ /^(\d+e\d+)$/)
1075     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1076   $self->setfield($field,$1);
1077   '';
1078 }
1079
1080 =item ut_snumber COLUMN
1081
1082 Check/untaint signed numeric data (whole numbers).  May not be null.  If there
1083 is an error, returns the error, otherwise returns false.
1084
1085 =cut
1086
1087 sub ut_snumber {
1088   my($self, $field) = @_;
1089   $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1090     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1091   $self->setfield($field, "$1$2");
1092   '';
1093 }
1094
1095 =item ut_number COLUMN
1096
1097 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1098 is an error, returns the error, otherwise returns false.
1099
1100 =cut
1101
1102 sub ut_number {
1103   my($self,$field)=@_;
1104   $self->getfield($field) =~ /^(\d+)$/
1105     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1106   $self->setfield($field,$1);
1107   '';
1108 }
1109
1110 =item ut_numbern COLUMN
1111
1112 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1113 an error, returns the error, otherwise returns false.
1114
1115 =cut
1116
1117 sub ut_numbern {
1118   my($self,$field)=@_;
1119   $self->getfield($field) =~ /^(\d*)$/
1120     or return "Illegal (numeric) $field: ". $self->getfield($field);
1121   $self->setfield($field,$1);
1122   '';
1123 }
1124
1125 =item ut_money COLUMN
1126
1127 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1128 is an error, returns the error, otherwise returns false.
1129
1130 =cut
1131
1132 sub ut_money {
1133   my($self,$field)=@_;
1134   $self->setfield($field, 0) if $self->getfield($field) eq '';
1135   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1136     or return "Illegal (money) $field: ". $self->getfield($field);
1137   #$self->setfield($field, "$1$2$3" || 0);
1138   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1139   '';
1140 }
1141
1142 =item ut_text COLUMN
1143
1144 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1145 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1146 May not be null.  If there is an error, returns the error, otherwise returns
1147 false.
1148
1149 =cut
1150
1151 sub ut_text {
1152   my($self,$field)=@_;
1153   #warn "msgcat ". \&msgcat. "\n";
1154   #warn "notexist ". \&notexist. "\n";
1155   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1156   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1157     or return gettext('illegal_or_empty_text'). " $field: ".
1158                $self->getfield($field);
1159   $self->setfield($field,$1);
1160   '';
1161 }
1162
1163 =item ut_textn COLUMN
1164
1165 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1166 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1167 May be null.  If there is an error, returns the error, otherwise returns false.
1168
1169 =cut
1170
1171 sub ut_textn {
1172   my($self,$field)=@_;
1173   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1174     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1175   $self->setfield($field,$1);
1176   '';
1177 }
1178
1179 =item ut_alpha COLUMN
1180
1181 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1182 an error, returns the error, otherwise returns false.
1183
1184 =cut
1185
1186 sub ut_alpha {
1187   my($self,$field)=@_;
1188   $self->getfield($field) =~ /^(\w+)$/
1189     or return "Illegal or empty (alphanumeric) $field: ".
1190               $self->getfield($field);
1191   $self->setfield($field,$1);
1192   '';
1193 }
1194
1195 =item ut_alpha COLUMN
1196
1197 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1198 error, returns the error, otherwise returns false.
1199
1200 =cut
1201
1202 sub ut_alphan {
1203   my($self,$field)=@_;
1204   $self->getfield($field) =~ /^(\w*)$/ 
1205     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1206   $self->setfield($field,$1);
1207   '';
1208 }
1209
1210 =item ut_phonen COLUMN [ COUNTRY ]
1211
1212 Check/untaint phone numbers.  May be null.  If there is an error, returns
1213 the error, otherwise returns false.
1214
1215 Takes an optional two-letter ISO country code; without it or with unsupported
1216 countries, ut_phonen simply calls ut_alphan.
1217
1218 =cut
1219
1220 sub ut_phonen {
1221   my( $self, $field, $country ) = @_;
1222   return $self->ut_alphan($field) unless defined $country;
1223   my $phonen = $self->getfield($field);
1224   if ( $phonen eq '' ) {
1225     $self->setfield($field,'');
1226   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1227     $phonen =~ s/\D//g;
1228     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1229       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1230     $phonen = "$1-$2-$3";
1231     $phonen .= " x$4" if $4;
1232     $self->setfield($field,$phonen);
1233   } else {
1234     warn "warning: don't know how to check phone numbers for country $country";
1235     return $self->ut_textn($field);
1236   }
1237   '';
1238 }
1239
1240 =item ut_ip COLUMN
1241
1242 Check/untaint ip addresses.  IPv4 only for now.
1243
1244 =cut
1245
1246 sub ut_ip {
1247   my( $self, $field ) = @_;
1248   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1249     or return "Illegal (IP address) $field: ". $self->getfield($field);
1250   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1251   $self->setfield($field, "$1.$2.$3.$4");
1252   '';
1253 }
1254
1255 =item ut_ipn COLUMN
1256
1257 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1258
1259 =cut
1260
1261 sub ut_ipn {
1262   my( $self, $field ) = @_;
1263   if ( $self->getfield($field) =~ /^()$/ ) {
1264     $self->setfield($field,'');
1265     '';
1266   } else {
1267     $self->ut_ip($field);
1268   }
1269 }
1270
1271 =item ut_domain COLUMN
1272
1273 Check/untaint host and domain names.
1274
1275 =cut
1276
1277 sub ut_domain {
1278   my( $self, $field ) = @_;
1279   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1280   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1281     or return "Illegal (domain) $field: ". $self->getfield($field);
1282   $self->setfield($field,$1);
1283   '';
1284 }
1285
1286 =item ut_name COLUMN
1287
1288 Check/untaint proper names; allows alphanumerics, spaces and the following
1289 punctuation: , . - '
1290
1291 May not be null.
1292
1293 =cut
1294
1295 sub ut_name {
1296   my( $self, $field ) = @_;
1297   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1298     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1299   $self->setfield($field,$1);
1300   '';
1301 }
1302
1303 =item ut_zip COLUMN
1304
1305 Check/untaint zip codes.
1306
1307 =cut
1308
1309 sub ut_zip {
1310   my( $self, $field, $country ) = @_;
1311   if ( $country eq 'US' ) {
1312     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1313       or return gettext('illegal_zip'). " $field for country $country: ".
1314                 $self->getfield($field);
1315     $self->setfield($field,$1);
1316   } else {
1317     if ( $self->getfield($field) =~ /^\s*$/ ) {
1318       $self->setfield($field,'');
1319     } else {
1320       $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1321         or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1322       $self->setfield($field,$1);
1323     }
1324   }
1325   '';
1326 }
1327
1328 =item ut_country COLUMN
1329
1330 Check/untaint country codes.  Country names are changed to codes, if possible -
1331 see L<Locale::Country>.
1332
1333 =cut
1334
1335 sub ut_country {
1336   my( $self, $field ) = @_;
1337   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1338     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1339          && country2code($1) ) {
1340       $self->setfield($field,uc(country2code($1)));
1341     }
1342   }
1343   $self->getfield($field) =~ /^(\w\w)$/
1344     or return "Illegal (country) $field: ". $self->getfield($field);
1345   $self->setfield($field,uc($1));
1346   '';
1347 }
1348
1349 =item ut_anything COLUMN
1350
1351 Untaints arbitrary data.  Be careful.
1352
1353 =cut
1354
1355 sub ut_anything {
1356   my( $self, $field ) = @_;
1357   $self->getfield($field) =~ /^(.*)$/s
1358     or return "Illegal $field: ". $self->getfield($field);
1359   $self->setfield($field,$1);
1360   '';
1361 }
1362
1363 =item ut_enum COLUMN CHOICES_ARRAYREF
1364
1365 Check/untaint a column, supplying all possible choices, like the "enum" type.
1366
1367 =cut
1368
1369 sub ut_enum {
1370   my( $self, $field, $choices ) = @_;
1371   foreach my $choice ( @$choices ) {
1372     if ( $self->getfield($field) eq $choice ) {
1373       $self->setfield($choice);
1374       return '';
1375     }
1376   }
1377   return "Illegal (enum) field $field: ". $self->getfield($field);
1378 }
1379
1380 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1381
1382 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1383 on the column first.
1384
1385 =cut
1386
1387 sub ut_foreign_key {
1388   my( $self, $field, $table, $foreign ) = @_;
1389   qsearchs($table, { $foreign => $self->getfield($field) })
1390     or return "Can't find $field ". $self->getfield($field).
1391               " in $table.$foreign";
1392   '';
1393 }
1394
1395 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1396
1397 Like ut_foreign_key, except the null value is also allowed.
1398
1399 =cut
1400
1401 sub ut_foreign_keyn {
1402   my( $self, $field, $table, $foreign ) = @_;
1403   $self->getfield($field)
1404     ? $self->ut_foreign_key($field, $table, $foreign)
1405     : '';
1406 }
1407
1408
1409 =item virtual_fields [ TABLE ]
1410
1411 Returns a list of virtual fields defined for the table.  This should not 
1412 be exported, and should only be called as an instance or class method.
1413
1414 =cut
1415
1416 sub virtual_fields {
1417   my $self = shift;
1418   my $table;
1419   $table = $self->table or confess "virtual_fields called on non-table";
1420
1421   confess "Unknown table $table" unless $dbdef->table($table);
1422
1423   return () unless $self->dbdef->table('part_virtual_field');
1424
1425   unless ( $virtual_fields_cache{$table} ) {
1426     my $query = 'SELECT name from part_virtual_field ' .
1427                 "WHERE dbtable = '$table'";
1428     my $dbh = dbh;
1429     my $result = $dbh->selectcol_arrayref($query);
1430     confess $dbh->errstr if $dbh->err;
1431     $virtual_fields_cache{$table} = $result;
1432   }
1433
1434   @{$virtual_fields_cache{$table}};
1435
1436 }
1437
1438
1439 =item fields [ TABLE ]
1440
1441 This is a wrapper for real_fields and virtual_fields.  Code that called
1442 fields before should probably continue to call fields.
1443
1444 =cut
1445
1446 sub fields {
1447   my $something = shift;
1448   my $table;
1449   if($something->isa('FS::Record')) {
1450     $table = $something->table;
1451   } else {
1452     $table = $something;
1453     $something = "FS::$table";
1454   }
1455   return (real_fields($table), $something->virtual_fields());
1456 }
1457
1458 =back
1459
1460 =item pvf FIELD_NAME
1461
1462 Returns the FS::part_virtual_field object corresponding to a field in the 
1463 record (specified by FIELD_NAME).
1464
1465 =cut
1466
1467 sub pvf {
1468   my ($self, $name) = (shift, shift);
1469
1470   if(grep /^$name$/, $self->virtual_fields) {
1471     return qsearchs('part_virtual_field', { dbtable => $self->table,
1472                                             name    => $name } );
1473   }
1474   ''
1475 }
1476
1477 =head1 SUBROUTINES
1478
1479 =over 4
1480
1481 =item real_fields [ TABLE ]
1482
1483 Returns a list of the real columns in the specified table.  Called only by 
1484 fields() and other subroutines elsewhere in FS::Record.
1485
1486 =cut
1487
1488 sub real_fields {
1489   my $table = shift;
1490
1491   my($table_obj) = $dbdef->table($table);
1492   confess "Unknown table $table" unless $table_obj;
1493   $table_obj->columns;
1494 }
1495
1496 =item reload_dbdef([FILENAME])
1497
1498 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1499 non-default filename.  This command is executed at startup unless
1500 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1501
1502 =cut
1503
1504 sub reload_dbdef {
1505   my $file = shift || $dbdef_file;
1506
1507   unless ( exists $dbdef_cache{$file} ) {
1508     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1509     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1510                             or die "can't load database schema from $file";
1511   } else {
1512     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1513   }
1514   $dbdef = $dbdef_cache{$file};
1515 }
1516
1517 =item dbdef
1518
1519 Returns the current database definition.  See L<DBIx::DBSchema>.
1520
1521 =cut
1522
1523 sub dbdef { $dbdef; }
1524
1525 =item _quote VALUE, TABLE, COLUMN
1526
1527 This is an internal function used to construct SQL statements.  It returns
1528 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1529 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1530
1531 =cut
1532
1533 sub _quote {
1534   my($value, $table, $column) = @_;
1535   my $column_obj = $dbdef->table($table)->column($column);
1536   my $column_type = $column_obj->type;
1537
1538   if ( $value eq '' && $column_type =~ /^int/ ) {
1539     if ( $column_obj->null ) {
1540       'NULL';
1541     } else {
1542       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1543             "using 0 instead";
1544       0;
1545     }
1546   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1547             ! $column_type =~ /(char|binary|text)$/i ) {
1548     $value;
1549   } else {
1550     dbh->quote($value);
1551   }
1552 }
1553
1554 =item vfieldpart_hashref TABLE
1555
1556 Returns a hashref of virtual field names and vfieldparts applicable to the given
1557 TABLE.
1558
1559 =cut
1560
1561 sub vfieldpart_hashref {
1562   my $self = shift;
1563   my $table = $self->table;
1564
1565   return {} unless $self->dbdef->table('part_virtual_field');
1566
1567   my $dbh = dbh;
1568   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1569                   "dbtable = '$table'";
1570   my $sth = $dbh->prepare($statement);
1571   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1572   return { map { $_->{name}, $_->{vfieldpart} } 
1573     @{$sth->fetchall_arrayref({})} };
1574
1575 }
1576
1577
1578 =item hfields TABLE
1579
1580 This is deprecated.  Don't use it.
1581
1582 It returns a hash-type list with the fields of this record's table set true.
1583
1584 =cut
1585
1586 sub hfields {
1587   carp "warning: hfields is deprecated";
1588   my($table)=@_;
1589   my(%hash);
1590   foreach (fields($table)) {
1591     $hash{$_}=1;
1592   }
1593   \%hash;
1594 }
1595
1596 sub _dump {
1597   my($self)=@_;
1598   join("\n", map {
1599     "$_: ". $self->getfield($_). "|"
1600   } (fields($self->table)) );
1601 }
1602
1603 sub DESTROY { return; }
1604
1605 #sub DESTROY {
1606 #  my $self = shift;
1607 #  #use Carp qw(cluck);
1608 #  #cluck "DESTROYING $self";
1609 #  warn "DESTROYING $self";
1610 #}
1611
1612 #sub is_tainted {
1613 #             return ! eval { join('',@_), kill 0; 1; };
1614 #         }
1615
1616 =back
1617
1618 =head1 BUGS
1619
1620 This module should probably be renamed, since much of the functionality is
1621 of general use.  It is not completely unlike Adapter::DBI (see below).
1622
1623 Exported qsearch and qsearchs should be deprecated in favor of method calls
1624 (against an FS::Record object like the old search and searchs that qsearch
1625 and qsearchs were on top of.)
1626
1627 The whole fields / hfields mess should be removed.
1628
1629 The various WHERE clauses should be subroutined.
1630
1631 table string should be deprecated in favor of DBIx::DBSchema::Table.
1632
1633 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1634 true maps to the database (and WHERE clauses) would also help.
1635
1636 The ut_ methods should ask the dbdef for a default length.
1637
1638 ut_sqltype (like ut_varchar) should all be defined
1639
1640 A fallback check method should be provided which uses the dbdef.
1641
1642 The ut_money method assumes money has two decimal digits.
1643
1644 The Pg money kludge in the new method only strips `$'.
1645
1646 The ut_phonen method only checks US-style phone numbers.
1647
1648 The _quote function should probably use ut_float instead of a regex.
1649
1650 All the subroutines probably should be methods, here or elsewhere.
1651
1652 Probably should borrow/use some dbdef methods where appropriate (like sub
1653 fields)
1654
1655 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1656 or allow it to be set.  Working around it is ugly any way around - DBI should
1657 be fixed.  (only affects RDBMS which return uppercase column names)
1658
1659 ut_zip should take an optional country like ut_phone.
1660
1661 =head1 SEE ALSO
1662
1663 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1664
1665 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1666
1667 =cut
1668
1669 1;
1670