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