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