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