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