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