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