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