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