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