change ILIKE into LOWER() for compatibility with non-Pg and Pg before 7.1
[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(@result) = qsearch(@_);
334   carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
335     #should warn more vehemently if the search was on a primary key?
336   scalar(@result) ? ($result[0]) : ();
337 }
338
339 =back
340
341 =head1 METHODS
342
343 =over 4
344
345 =item table
346
347 Returns the table name.
348
349 =cut
350
351 sub table {
352 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
353   my $self = shift;
354   $self -> {'Table'};
355 }
356
357 =item dbdef_table
358
359 Returns the DBIx::DBSchema::Table object for the table.
360
361 =cut
362
363 sub dbdef_table {
364   my($self)=@_;
365   my($table)=$self->table;
366   $dbdef->table($table);
367 }
368
369 =item get, getfield COLUMN
370
371 Returns the value of the column/field/key COLUMN.
372
373 =cut
374
375 sub get {
376   my($self,$field) = @_;
377   # to avoid "Use of unitialized value" errors
378   if ( defined ( $self->{Hash}->{$field} ) ) {
379     $self->{Hash}->{$field};
380   } else { 
381     '';
382   }
383 }
384 sub getfield {
385   my $self = shift;
386   $self->get(@_);
387 }
388
389 =item set, setfield COLUMN, VALUE
390
391 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
392
393 =cut
394
395 sub set { 
396   my($self,$field,$value) = @_;
397   $self->{'Hash'}->{$field} = $value;
398 }
399 sub setfield {
400   my $self = shift;
401   $self->set(@_);
402 }
403
404 =item AUTLOADED METHODS
405
406 $record->column is a synonym for $record->get('column');
407
408 $record->column('value') is a synonym for $record->set('column','value');
409
410 =cut
411
412 # readable/safe
413 sub AUTOLOAD {
414   my($self,$value)=@_;
415   my($field)=$AUTOLOAD;
416   $field =~ s/.*://;
417   if ( defined($value) ) {
418     confess "errant AUTOLOAD $field for $self (arg $value)"
419       unless $self->can('setfield');
420     $self->setfield($field,$value);
421   } else {
422     confess "errant AUTOLOAD $field for $self (no args)"
423       unless $self->can('getfield');
424     $self->getfield($field);
425   }    
426 }
427
428 # efficient
429 #sub AUTOLOAD {
430 #  my $field = $AUTOLOAD;
431 #  $field =~ s/.*://;
432 #  if ( defined($_[1]) ) {
433 #    $_[0]->setfield($field, $_[1]);
434 #  } else {
435 #    $_[0]->getfield($field);
436 #  }    
437 #}
438
439 =item hash
440
441 Returns a list of the column/value pairs, usually for assigning to a new hash.
442
443 To make a distinct duplicate of an FS::Record object, you can do:
444
445     $new = new FS::Record ( $old->table, { $old->hash } );
446
447 =cut
448
449 sub hash {
450   my($self) = @_;
451   %{ $self->{'Hash'} }; 
452 }
453
454 =item hashref
455
456 Returns a reference to the column/value hash.
457
458 =cut
459
460 sub hashref {
461   my($self) = @_;
462   $self->{'Hash'};
463 }
464
465 =item insert
466
467 Inserts this record to the database.  If there is an error, returns the error,
468 otherwise returns false.
469
470 =cut
471
472 sub insert {
473   my $self = shift;
474
475   my $error = $self->check;
476   return $error if $error;
477
478   #single-field unique keys are given a value if false
479   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
480   foreach ( $self->dbdef_table->unique->singles ) {
481     $self->unique($_) unless $self->getfield($_);
482   }
483
484   #and also the primary key, if the database isn't going to
485   my $primary_key = $self->dbdef_table->primary_key;
486   my $db_seq = 0;
487   if ( $primary_key ) {
488     my $col = $self->dbdef_table->column($primary_key);
489     
490     $db_seq =
491       uc($col->type) eq 'SERIAL'
492       || ( driver_name eq 'Pg'
493              && defined($col->default)
494              && $col->default =~ /^nextval\(/i
495          )
496       || ( driver_name eq 'mysql'
497              && defined($col->local)
498              && $col->local =~ /AUTO_INCREMENT/i
499          );
500     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
501   }
502
503   my $table = $self->table;
504   #false laziness w/delete
505   my @fields =
506     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
507     $self->fields
508   ;
509   my @values = map { _quote( $self->getfield($_), $table, $_) } @fields;
510   #eslaf
511
512   my $statement = "INSERT INTO $table ( ".
513       join( ', ', @fields ).
514     ") VALUES (".
515       join( ', ', @values ).
516     ")"
517   ;
518   warn "[debug]$me $statement\n" if $DEBUG > 1;
519   my $sth = dbh->prepare($statement) or return dbh->errstr;
520
521   local $SIG{HUP} = 'IGNORE';
522   local $SIG{INT} = 'IGNORE';
523   local $SIG{QUIT} = 'IGNORE'; 
524   local $SIG{TERM} = 'IGNORE';
525   local $SIG{TSTP} = 'IGNORE';
526   local $SIG{PIPE} = 'IGNORE';
527
528   $sth->execute or return $sth->errstr;
529
530   if ( $db_seq ) { # get inserted id from the database, if applicable
531     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
532     my $insertid = '';
533     if ( driver_name eq 'Pg' ) {
534
535       my $oid = $sth->{'pg_oid_status'};
536       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
537       my $i_sth = dbh->prepare($i_sql) or do {
538         dbh->rollback if $FS::UID::AutoCommit;
539         return dbh->errstr;
540       };
541       $i_sth->execute($oid) or do {
542         dbh->rollback if $FS::UID::AutoCommit;
543         return $i_sth->errstr;
544       };
545       $insertid = $i_sth->fetchrow_arrayref->[0];
546
547     } elsif ( driver_name eq 'mysql' ) {
548
549       $insertid = dbh->{'mysql_insertid'};
550       # work around mysql_insertid being null some of the time, ala RT :/
551       unless ( $insertid ) {
552         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
553              "using SELECT LAST_INSERT_ID();";
554         my $i_sql = "SELECT LAST_INSERT_ID()";
555         my $i_sth = dbh->prepare($i_sql) or do {
556           dbh->rollback if $FS::UID::AutoCommit;
557           return dbh->errstr;
558         };
559         $i_sth->execute or do {
560           dbh->rollback if $FS::UID::AutoCommit;
561           return $i_sth->errstr;
562         };
563         $insertid = $i_sth->fetchrow_arrayref->[0];
564       }
565
566     } else {
567       dbh->rollback if $FS::UID::AutoCommit;
568       return "don't know how to retreive inserted ids from ". driver_name. 
569              ", try using counterfiles (maybe run dbdef-create?)";
570     }
571     $self->setfield($primary_key, $insertid);
572   }
573
574   my $h_sth;
575   if ( defined $dbdef->table('h_'. $table) ) {
576     my $h_statement = $self->_h_statement('insert');
577     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
578     $h_sth = dbh->prepare($h_statement) or do {
579       dbh->rollback if $FS::UID::AutoCommit;
580       return dbh->errstr;
581     };
582   } else {
583     $h_sth = '';
584   }
585   $h_sth->execute or return $h_sth->errstr if $h_sth;
586
587   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
588
589   '';
590 }
591
592 =item add
593
594 Depriciated (use insert instead).
595
596 =cut
597
598 sub add {
599   cluck "warning: FS::Record::add deprecated!";
600   insert @_; #call method in this scope
601 }
602
603 =item delete
604
605 Delete this record from the database.  If there is an error, returns the error,
606 otherwise returns false.
607
608 =cut
609
610 sub delete {
611   my $self = shift;
612
613   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
614     map {
615       $self->getfield($_) eq ''
616         #? "( $_ IS NULL OR $_ = \"\" )"
617         ? ( driver_name eq 'Pg'
618               ? "$_ IS NULL"
619               : "( $_ IS NULL OR $_ = \"\" )"
620           )
621         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
622     } ( $self->dbdef_table->primary_key )
623           ? ( $self->dbdef_table->primary_key)
624           : $self->fields
625   );
626   warn "[debug]$me $statement\n" if $DEBUG > 1;
627   my $sth = dbh->prepare($statement) or return dbh->errstr;
628
629   my $h_sth;
630   if ( defined $dbdef->table('h_'. $self->table) ) {
631     my $h_statement = $self->_h_statement('delete');
632     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
633     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
634   } else {
635     $h_sth = '';
636   }
637
638   local $SIG{HUP} = 'IGNORE';
639   local $SIG{INT} = 'IGNORE';
640   local $SIG{QUIT} = 'IGNORE'; 
641   local $SIG{TERM} = 'IGNORE';
642   local $SIG{TSTP} = 'IGNORE';
643   local $SIG{PIPE} = 'IGNORE';
644
645   my $rc = $sth->execute or return $sth->errstr;
646   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
647   $h_sth->execute or return $h_sth->errstr if $h_sth;
648   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
649
650   #no need to needlessly destoy the data either (causes problems actually)
651   #undef $self; #no need to keep object!
652
653   '';
654 }
655
656 =item del
657
658 Depriciated (use delete instead).
659
660 =cut
661
662 sub del {
663   cluck "warning: FS::Record::del deprecated!";
664   &delete(@_); #call method in this scope
665 }
666
667 =item replace OLD_RECORD
668
669 Replace the OLD_RECORD with this one in the database.  If there is an error,
670 returns the error, otherwise returns false.
671
672 =cut
673
674 sub replace {
675   my ( $new, $old ) = ( shift, shift );
676   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
677
678   return "Records not in same table!" unless $new->table eq $old->table;
679
680   my $primary_key = $old->dbdef_table->primary_key;
681   return "Can't change $primary_key"
682     if $primary_key
683        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
684
685   my $error = $new->check;
686   return $error if $error;
687
688   my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
689   unless ( @diff ) {
690     carp "[warning]$me $new -> replace $old: records identical";
691     return '';
692   }
693
694   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
695     map {
696       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
697     } @diff
698   ). ' WHERE '.
699     join(' AND ',
700       map {
701         $old->getfield($_) eq ''
702           #? "( $_ IS NULL OR $_ = \"\" )"
703           ? ( driver_name eq 'Pg'
704                 ? "$_ IS NULL"
705                 : "( $_ IS NULL OR $_ = \"\" )"
706             )
707           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
708       } ( $primary_key ? ( $primary_key ) : $old->fields )
709     )
710   ;
711   warn "[debug]$me $statement\n" if $DEBUG > 1;
712   my $sth = dbh->prepare($statement) or return dbh->errstr;
713
714   my $h_old_sth;
715   if ( defined $dbdef->table('h_'. $old->table) ) {
716     my $h_old_statement = $old->_h_statement('replace_old');
717     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
718     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
719   } else {
720     $h_old_sth = '';
721   }
722
723   my $h_new_sth;
724   if ( defined $dbdef->table('h_'. $new->table) ) {
725     my $h_new_statement = $new->_h_statement('replace_new');
726     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
727     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
728   } else {
729     $h_new_sth = '';
730   }
731
732   local $SIG{HUP} = 'IGNORE';
733   local $SIG{INT} = 'IGNORE';
734   local $SIG{QUIT} = 'IGNORE'; 
735   local $SIG{TERM} = 'IGNORE';
736   local $SIG{TSTP} = 'IGNORE';
737   local $SIG{PIPE} = 'IGNORE';
738
739   my $rc = $sth->execute or return $sth->errstr;
740   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
741   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
742   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
743   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
744
745   '';
746
747 }
748
749 =item rep
750
751 Depriciated (use replace instead).
752
753 =cut
754
755 sub rep {
756   cluck "warning: FS::Record::rep deprecated!";
757   replace @_; #call method in this scope
758 }
759
760 =item check
761
762 Not yet implemented, croaks.  Derived classes should provide a check method.
763
764 =cut
765
766 sub check {
767   confess "FS::Record::check not implemented; supply one in subclass!";
768 }
769
770 sub _h_statement {
771   my( $self, $action ) = @_;
772
773   my @fields =
774     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
775     $self->fields
776   ;
777   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
778
779   "INSERT INTO h_". $self->table. " ( ".
780       join(', ', qw(history_date history_user history_action), @fields ).
781     ") VALUES (".
782       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
783     ")"
784   ;
785 }
786
787 =item unique COLUMN
788
789 B<Warning>: External use is B<deprecated>.  
790
791 Replaces COLUMN in record with a unique number, using counters in the
792 filesystem.  Used by the B<insert> method on single-field unique columns
793 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
794 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
795
796 Returns the new value.
797
798 =cut
799
800 sub unique {
801   my($self,$field) = @_;
802   my($table)=$self->table;
803
804   croak "Unique called on field $field, but it is ",
805         $self->getfield($field),
806         ", not null!"
807     if $self->getfield($field);
808
809   #warn "table $table is tainted" if is_tainted($table);
810   #warn "field $field is tainted" if is_tainted($field);
811
812   my($counter) = new File::CounterFile "$table.$field",0;
813 # hack for web demo
814 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
815 #  my($user)=$1;
816 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
817 # endhack
818
819   my $index = $counter->inc;
820   $index = $counter->inc while qsearchs($table, { $field=>$index } );
821
822   $index =~ /^(\d*)$/;
823   $index=$1;
824
825   $self->setfield($field,$index);
826
827 }
828
829 =item ut_float COLUMN
830
831 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
832 null.  If there is an error, returns the error, otherwise returns false.
833
834 =cut
835
836 sub ut_float {
837   my($self,$field)=@_ ;
838   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
839    $self->getfield($field) =~ /^(\d+)$/ ||
840    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
841    $self->getfield($field) =~ /^(\d+e\d+)$/)
842     or return "Illegal or empty (float) $field: ". $self->getfield($field);
843   $self->setfield($field,$1);
844   '';
845 }
846
847 =item ut_number COLUMN
848
849 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
850 is an error, returns the error, otherwise returns false.
851
852 =cut
853
854 sub ut_number {
855   my($self,$field)=@_;
856   $self->getfield($field) =~ /^(\d+)$/
857     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
858   $self->setfield($field,$1);
859   '';
860 }
861
862 =item ut_numbern COLUMN
863
864 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
865 an error, returns the error, otherwise returns false.
866
867 =cut
868
869 sub ut_numbern {
870   my($self,$field)=@_;
871   $self->getfield($field) =~ /^(\d*)$/
872     or return "Illegal (numeric) $field: ". $self->getfield($field);
873   $self->setfield($field,$1);
874   '';
875 }
876
877 =item ut_money COLUMN
878
879 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
880 is an error, returns the error, otherwise returns false.
881
882 =cut
883
884 sub ut_money {
885   my($self,$field)=@_;
886   $self->setfield($field, 0) if $self->getfield($field) eq '';
887   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
888     or return "Illegal (money) $field: ". $self->getfield($field);
889   #$self->setfield($field, "$1$2$3" || 0);
890   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
891   '';
892 }
893
894 =item ut_text COLUMN
895
896 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
897 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
898 May not be null.  If there is an error, returns the error, otherwise returns
899 false.
900
901 =cut
902
903 sub ut_text {
904   my($self,$field)=@_;
905   #warn "msgcat ". \&msgcat. "\n";
906   #warn "notexist ". \&notexist. "\n";
907   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
908   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
909     or return gettext('illegal_or_empty_text'). " $field: ".
910                $self->getfield($field);
911   $self->setfield($field,$1);
912   '';
913 }
914
915 =item ut_textn COLUMN
916
917 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
918 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
919 May be null.  If there is an error, returns the error, otherwise returns false.
920
921 =cut
922
923 sub ut_textn {
924   my($self,$field)=@_;
925   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
926     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
927   $self->setfield($field,$1);
928   '';
929 }
930
931 =item ut_alpha COLUMN
932
933 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
934 an error, returns the error, otherwise returns false.
935
936 =cut
937
938 sub ut_alpha {
939   my($self,$field)=@_;
940   $self->getfield($field) =~ /^(\w+)$/
941     or return "Illegal or empty (alphanumeric) $field: ".
942               $self->getfield($field);
943   $self->setfield($field,$1);
944   '';
945 }
946
947 =item ut_alpha COLUMN
948
949 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
950 error, returns the error, otherwise returns false.
951
952 =cut
953
954 sub ut_alphan {
955   my($self,$field)=@_;
956   $self->getfield($field) =~ /^(\w*)$/ 
957     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
958   $self->setfield($field,$1);
959   '';
960 }
961
962 =item ut_phonen COLUMN [ COUNTRY ]
963
964 Check/untaint phone numbers.  May be null.  If there is an error, returns
965 the error, otherwise returns false.
966
967 Takes an optional two-letter ISO country code; without it or with unsupported
968 countries, ut_phonen simply calls ut_alphan.
969
970 =cut
971
972 sub ut_phonen {
973   my( $self, $field, $country ) = @_;
974   return $self->ut_alphan($field) unless defined $country;
975   my $phonen = $self->getfield($field);
976   if ( $phonen eq '' ) {
977     $self->setfield($field,'');
978   } elsif ( $country eq 'US' || $country eq 'CA' ) {
979     $phonen =~ s/\D//g;
980     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
981       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
982     $phonen = "$1-$2-$3";
983     $phonen .= " x$4" if $4;
984     $self->setfield($field,$phonen);
985   } else {
986     warn "warning: don't know how to check phone numbers for country $country";
987     return $self->ut_textn($field);
988   }
989   '';
990 }
991
992 =item ut_ip COLUMN
993
994 Check/untaint ip addresses.  IPv4 only for now.
995
996 =cut
997
998 sub ut_ip {
999   my( $self, $field ) = @_;
1000   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1001     or return "Illegal (IP address) $field: ". $self->getfield($field);
1002   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1003   $self->setfield($field, "$1.$2.$3.$4");
1004   '';
1005 }
1006
1007 =item ut_ipn COLUMN
1008
1009 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1010
1011 =cut
1012
1013 sub ut_ipn {
1014   my( $self, $field ) = @_;
1015   if ( $self->getfield($field) =~ /^()$/ ) {
1016     $self->setfield($field,'');
1017     '';
1018   } else {
1019     $self->ut_ip($field);
1020   }
1021 }
1022
1023 =item ut_domain COLUMN
1024
1025 Check/untaint host and domain names.
1026
1027 =cut
1028
1029 sub ut_domain {
1030   my( $self, $field ) = @_;
1031   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1032   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1033     or return "Illegal (domain) $field: ". $self->getfield($field);
1034   $self->setfield($field,$1);
1035   '';
1036 }
1037
1038 =item ut_name COLUMN
1039
1040 Check/untaint proper names; allows alphanumerics, spaces and the following
1041 punctuation: , . - '
1042
1043 May not be null.
1044
1045 =cut
1046
1047 sub ut_name {
1048   my( $self, $field ) = @_;
1049   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1050     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1051   $self->setfield($field,$1);
1052   '';
1053 }
1054
1055 =item ut_zip COLUMN
1056
1057 Check/untaint zip codes.
1058
1059 =cut
1060
1061 sub ut_zip {
1062   my( $self, $field, $country ) = @_;
1063   if ( $country eq 'US' ) {
1064     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1065       or return gettext('illegal_zip'). " $field for country $country: ".
1066                 $self->getfield($field);
1067     $self->setfield($field,$1);
1068   } else {
1069     $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1070       or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1071     $self->setfield($field,$1);
1072   }
1073   '';
1074 }
1075
1076 =item ut_country COLUMN
1077
1078 Check/untaint country codes.  Country names are changed to codes, if possible -
1079 see L<Locale::Country>.
1080
1081 =cut
1082
1083 sub ut_country {
1084   my( $self, $field ) = @_;
1085   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1086     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1087          && country2code($1) ) {
1088       $self->setfield($field,uc(country2code($1)));
1089     }
1090   }
1091   $self->getfield($field) =~ /^(\w\w)$/
1092     or return "Illegal (country) $field: ". $self->getfield($field);
1093   $self->setfield($field,uc($1));
1094   '';
1095 }
1096
1097 =item ut_anything COLUMN
1098
1099 Untaints arbitrary data.  Be careful.
1100
1101 =cut
1102
1103 sub ut_anything {
1104   my( $self, $field ) = @_;
1105   $self->getfield($field) =~ /^(.*)$/s
1106     or return "Illegal $field: ". $self->getfield($field);
1107   $self->setfield($field,$1);
1108   '';
1109 }
1110
1111 =item ut_enum COLUMN CHOICES_ARRAYREF
1112
1113 Check/untaint a column, supplying all possible choices, like the "enum" type.
1114
1115 =cut
1116
1117 sub ut_enum {
1118   my( $self, $field, $choices ) = @_;
1119   foreach my $choice ( @$choices ) {
1120     if ( $self->getfield($field) eq $choice ) {
1121       $self->setfield($choice);
1122       return '';
1123     }
1124   }
1125   return "Illegal (enum) field $field: ". $self->getfield($field);
1126 }
1127
1128 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1129
1130 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1131 on the column first.
1132
1133 =cut
1134
1135 sub ut_foreign_key {
1136   my( $self, $field, $table, $foreign ) = @_;
1137   qsearchs($table, { $foreign => $self->getfield($field) })
1138     or return "Can't find $field ". $self->getfield($field).
1139               " in $table.$foreign";
1140   '';
1141 }
1142
1143 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1144
1145 Like ut_foreign_key, except the null value is also allowed.
1146
1147 =cut
1148
1149 sub ut_foreign_keyn {
1150   my( $self, $field, $table, $foreign ) = @_;
1151   $self->getfield($field)
1152     ? $self->ut_foreign_key($field, $table, $foreign)
1153     : '';
1154 }
1155
1156 =item fields [ TABLE ]
1157
1158 This can be used as both a subroutine and a method call.  It returns a list
1159 of the columns in this record's table, or an explicitly specified table.
1160 (See L<DBIx::DBSchema::Table>).
1161
1162 =cut
1163
1164 # Usage: @fields = fields($table);
1165 #        @fields = $record->fields;
1166 sub fields {
1167   my $something = shift;
1168   my $table;
1169   if ( ref($something) ) {
1170     $table = $something->table;
1171   } else {
1172     $table = $something;
1173   }
1174   #croak "Usage: \@fields = fields(\$table)\n   or: \@fields = \$record->fields" unless $table;
1175   my($table_obj) = $dbdef->table($table);
1176   confess "Unknown table $table" unless $table_obj;
1177   $table_obj->columns;
1178 }
1179
1180 =back
1181
1182 =head1 SUBROUTINES
1183
1184 =over 4
1185
1186 =item reload_dbdef([FILENAME])
1187
1188 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1189 non-default filename.  This command is executed at startup unless
1190 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1191
1192 =cut
1193
1194 sub reload_dbdef {
1195   my $file = shift || $dbdef_file;
1196
1197   unless ( exists $dbdef_cache{$file} ) {
1198     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1199     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1200                             or die "can't load database schema from $file";
1201   } else {
1202     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1203   }
1204   $dbdef = $dbdef_cache{$file};
1205 }
1206
1207 =item dbdef
1208
1209 Returns the current database definition.  See L<DBIx::DBSchema>.
1210
1211 =cut
1212
1213 sub dbdef { $dbdef; }
1214
1215 =item _quote VALUE, TABLE, COLUMN
1216
1217 This is an internal function used to construct SQL statements.  It returns
1218 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1219 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1220
1221 =cut
1222
1223 sub _quote {
1224   my($value,$table,$field)=@_;
1225   my($dbh)=dbh;
1226   if ( $value =~ /^\d+(\.\d+)?$/ && 
1227 #       ! ( datatype($table,$field) =~ /^char/ ) 
1228        ! $dbdef->table($table)->column($field)->type =~ /(char|binary|text)$/i 
1229   ) {
1230     $value;
1231   } else {
1232     $dbh->quote($value);
1233   }
1234 }
1235
1236 =item hfields TABLE
1237
1238 This is deprecated.  Don't use it.
1239
1240 It returns a hash-type list with the fields of this record's table set true.
1241
1242 =cut
1243
1244 sub hfields {
1245   carp "warning: hfields is deprecated";
1246   my($table)=@_;
1247   my(%hash);
1248   foreach (fields($table)) {
1249     $hash{$_}=1;
1250   }
1251   \%hash;
1252 }
1253
1254 sub _dump {
1255   my($self)=@_;
1256   join("\n", map {
1257     "$_: ". $self->getfield($_). "|"
1258   } (fields($self->table)) );
1259 }
1260
1261 sub DESTROY { return; }
1262
1263 #sub DESTROY {
1264 #  my $self = shift;
1265 #  #use Carp qw(cluck);
1266 #  #cluck "DESTROYING $self";
1267 #  warn "DESTROYING $self";
1268 #}
1269
1270 #sub is_tainted {
1271 #             return ! eval { join('',@_), kill 0; 1; };
1272 #         }
1273
1274 =back
1275
1276 =head1 BUGS
1277
1278 This module should probably be renamed, since much of the functionality is
1279 of general use.  It is not completely unlike Adapter::DBI (see below).
1280
1281 Exported qsearch and qsearchs should be deprecated in favor of method calls
1282 (against an FS::Record object like the old search and searchs that qsearch
1283 and qsearchs were on top of.)
1284
1285 The whole fields / hfields mess should be removed.
1286
1287 The various WHERE clauses should be subroutined.
1288
1289 table string should be deprecated in favor of DBIx::DBSchema::Table.
1290
1291 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1292 true maps to the database (and WHERE clauses) would also help.
1293
1294 The ut_ methods should ask the dbdef for a default length.
1295
1296 ut_sqltype (like ut_varchar) should all be defined
1297
1298 A fallback check method should be provided which uses the dbdef.
1299
1300 The ut_money method assumes money has two decimal digits.
1301
1302 The Pg money kludge in the new method only strips `$'.
1303
1304 The ut_phonen method only checks US-style phone numbers.
1305
1306 The _quote function should probably use ut_float instead of a regex.
1307
1308 All the subroutines probably should be methods, here or elsewhere.
1309
1310 Probably should borrow/use some dbdef methods where appropriate (like sub
1311 fields)
1312
1313 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1314 or allow it to be set.  Working around it is ugly any way around - DBI should
1315 be fixed.  (only affects RDBMS which return uppercase column names)
1316
1317 ut_zip should take an optional country like ut_phone.
1318
1319 =head1 SEE ALSO
1320
1321 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1322
1323 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1324
1325 =cut
1326
1327 1;
1328