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