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