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