treat serial columns as ints too!
[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 use FS::part_virtual_field;
18
19 use Tie::IxHash;
20
21 @ISA = qw(Exporter);
22 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
23
24 $DEBUG = 0;
25 $me = '[FS::Record]';
26
27 #ask FS::UID to run this stuff for us later
28 $FS::UID::callback{'FS::Record'} = sub { 
29   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
30   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
31   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
32 };
33
34 =head1 NAME
35
36 FS::Record - Database record objects
37
38 =head1 SYNOPSIS
39
40     use FS::Record;
41     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
42
43     $record = new FS::Record 'table', \%hash;
44     $record = new FS::Record 'table', { 'column' => 'value', ... };
45
46     $record  = qsearchs FS::Record 'table', \%hash;
47     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
48     @records = qsearch  FS::Record 'table', \%hash; 
49     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
50
51     $table = $record->table;
52     $dbdef_table = $record->dbdef_table;
53
54     $value = $record->get('column');
55     $value = $record->getfield('column');
56     $value = $record->column;
57
58     $record->set( 'column' => 'value' );
59     $record->setfield( 'column' => 'value' );
60     $record->column('value');
61
62     %hash = $record->hash;
63
64     $hashref = $record->hashref;
65
66     $error = $record->insert;
67
68     $error = $record->delete;
69
70     $error = $new_record->replace($old_record);
71
72     # external use deprecated - handled by the database (at least for Pg, mysql)
73     $value = $record->unique('column');
74
75     $error = $record->ut_float('column');
76     $error = $record->ut_number('column');
77     $error = $record->ut_numbern('column');
78     $error = $record->ut_money('column');
79     $error = $record->ut_text('column');
80     $error = $record->ut_textn('column');
81     $error = $record->ut_alpha('column');
82     $error = $record->ut_alphan('column');
83     $error = $record->ut_phonen('column');
84     $error = $record->ut_anything('column');
85     $error = $record->ut_name('column');
86
87     $dbdef = reload_dbdef;
88     $dbdef = reload_dbdef "/non/standard/filename";
89     $dbdef = dbdef;
90
91     $quoted_value = _quote($value,'table','field');
92
93     #deprecated
94     $fields = hfields('table');
95     if ( $fields->{Field} ) { # etc.
96
97     @fields = fields 'table'; #as a subroutine
98     @fields = $record->fields; #as a method call
99
100
101 =head1 DESCRIPTION
102
103 (Mostly) object-oriented interface to database records.  Records are currently
104 implemented on top of DBI.  FS::Record is intended as a base class for
105 table-specific classes to inherit from, i.e. FS::cust_main.
106
107 =head1 CONSTRUCTORS
108
109 =over 4
110
111 =item new [ TABLE, ] HASHREF
112
113 Creates a new record.  It doesn't store it in the database, though.  See
114 L<"insert"> for that.
115
116 Note that the object stores this hash reference, not a distinct copy of the
117 hash it points to.  You can ask the object for a copy with the I<hash> 
118 method.
119
120 TABLE can only be omitted when a dervived class overrides the table method.
121
122 =cut
123
124 sub new { 
125   my $proto = shift;
126   my $class = ref($proto) || $proto;
127   my $self = {};
128   bless ($self, $class);
129
130   unless ( defined ( $self->table ) ) {
131     $self->{'Table'} = shift;
132     carp "warning: FS::Record::new called with table name ". $self->{'Table'};
133   }
134
135   my $hashref = $self->{'Hash'} = shift;
136
137   foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) { 
138     $hashref->{$field}='';
139   }
140
141   $self->_cache($hashref, shift) if $self->can('_cache') && @_;
142
143   $self;
144 }
145
146 sub new_or_cached {
147   my $proto = shift;
148   my $class = ref($proto) || $proto;
149   my $self = {};
150   bless ($self, $class);
151
152   $self->{'Table'} = shift unless defined ( $self->table );
153
154   my $hashref = $self->{'Hash'} = shift;
155   my $cache = shift;
156   if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
157     my $obj = $cache->cache->{$hashref->{$cache->key}};
158     $obj->_cache($hashref, $cache) if $obj->can('_cache');
159     $obj;
160   } else {
161     $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
162   }
163
164 }
165
166 sub create {
167   my $proto = shift;
168   my $class = ref($proto) || $proto;
169   my $self = {};
170   bless ($self, $class);
171   if ( defined $self->table ) {
172     cluck "create constructor is deprecated, use new!";
173     $self->new(@_);
174   } else {
175     croak "FS::Record::create called (not from a subclass)!";
176   }
177 }
178
179 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
180
181 Searches the database for all records matching (at least) the key/value pairs
182 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
183 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
184 objects.
185
186 ###oops, argh, FS::Record::new only lets us create database fields.
187 #Normal behaviour if SELECT is not specified is `*', as in
188 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
189 #feature where you can specify SELECT - remember, the objects returned,
190 #although blessed into the appropriate `FS::TABLE' package, will only have the
191 #fields you specify.  This might have unwanted results if you then go calling
192 #regular FS::TABLE methods
193 #on it.
194
195 =cut
196
197 sub qsearch {
198   my($stable, $record, $select, $extra_sql, $cache ) = @_;
199   #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
200   #for jsearch
201   $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
202   $stable = $1;
203   $select ||= '*';
204   my $dbh = dbh;
205
206   my $table = $cache ? $cache->table : $stable;
207   my $pkey = $dbdef->table($table)->primary_key;
208
209   my @real_fields = grep exists($record->{$_}), real_fields($table);
210   my @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
211
212   my $statement = "SELECT $select FROM $stable";
213   if ( @real_fields or @virtual_fields ) {
214     $statement .= ' WHERE '. join(' AND ',
215       ( map {
216
217       my $op = '=';
218       my $column = $_;
219       if ( ref($record->{$_}) ) {
220         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
221         #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
222         if ( uc($op) eq 'ILIKE' ) {
223           $op = 'LIKE';
224           $record->{$_}{'value'} = lc($record->{$_}{'value'});
225           $column = "LOWER($_)";
226         }
227         $record->{$_} = $record->{$_}{'value'}
228       }
229
230       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
231         if ( $op eq '=' ) {
232           if ( driver_name eq 'Pg' ) {
233             if ( $dbdef->table($table)->column($column)->type =~ /(int)/i ) {
234               qq-( $column IS NULL )-;
235             } else {
236               qq-( $column IS NULL OR $column = '' )-;
237             }
238           } else {
239             qq-( $column IS NULL OR $column = "" )-;
240           }
241         } elsif ( $op eq '!=' ) {
242           if ( driver_name eq 'Pg' ) {
243             my $type = $dbdef->table($table)->column($column)->type;
244             if ( $type =~ /(int|serial)/i ) {
245               qq-( $column IS NOT NULL )-;
246             } else {
247               qq-( $column IS NOT NULL AND $column != '' )-;
248             }
249           } else {
250             qq-( $column IS NOT NULL AND $column != "" )-;
251           }
252         } else {
253           if ( driver_name eq 'Pg' ) {
254             qq-( $column $op '' )-;
255           } else {
256             qq-( $column $op "" )-;
257           }
258         }
259       } else {
260         "$column $op ?";
261       }
262     } @real_fields ), 
263     ( map {
264       my $op = '=';
265       my $column = $_;
266       if ( ref($record->{$_}) ) {
267         $op = $record->{$_}{'op'} if $record->{$_}{'op'};
268         if ( uc($op) eq 'ILIKE' ) {
269           $op = 'LIKE';
270           $record->{$_}{'value'} = lc($record->{$_}{'value'});
271           $column = "LOWER($_)";
272         }
273         $record->{$_} = $record->{$_}{'value'};
274       }
275
276       # ... EXISTS ( SELECT name, value FROM part_virtual_field
277       #              JOIN virtual_field
278       #              ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
279       #              WHERE recnum = svc_acct.svcnum
280       #              AND (name, value) = ('egad', 'brain') )
281
282       my $value = $record->{$_};
283
284       my $subq;
285
286       $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
287       "( SELECT part_virtual_field.name, virtual_field.value ".
288       "FROM part_virtual_field JOIN virtual_field ".
289       "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
290       "WHERE virtual_field.recnum = ${table}.${pkey} ".
291       "AND part_virtual_field.name = '${column}'".
292       ($value ? 
293         " AND virtual_field.value ${op} '${value}'"
294       : "") . ")";
295       $subq;
296
297     } @virtual_fields ) );
298
299   }
300
301   $statement .= " $extra_sql" if defined($extra_sql);
302
303   warn "[debug]$me $statement\n" if $DEBUG > 1;
304   my $sth = $dbh->prepare($statement)
305     or croak "$dbh->errstr doing $statement";
306
307   my $bind = 1;
308
309   foreach my $field (
310     grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
311   ) {
312     if ( $record->{$field} =~ /^\d+(\.\d+)?$/
313          && $dbdef->table($table)->column($field)->type =~ /(int)/i
314     ) {
315       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
316     } else {
317       $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
318     }
319   }
320
321 #  $sth->execute( map $record->{$_},
322 #    grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
323 #  ) or croak "Error executing \"$statement\": ". $sth->errstr;
324
325   $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
326
327   my %result;
328   tie %result, "Tie::IxHash";
329   @virtual_fields = "FS::$table"->virtual_fields;
330
331   my @stuff = @{ $sth->fetchall_arrayref( {} ) };
332   if($pkey) {
333     %result = map { $_->{$pkey}, $_ } @stuff;
334   } else {
335     @result{@stuff} = @stuff;
336   }
337
338   $sth->finish;
339   if ( keys(%result) and @virtual_fields ) {
340     $statement =
341       "SELECT virtual_field.recnum, part_virtual_field.name, ".
342              "virtual_field.value ".
343       "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
344       "WHERE part_virtual_field.dbtable = '$table' AND ".
345       "virtual_field.recnum IN (".
346       join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
347       join(q!', '!, @virtual_fields) . "')";
348     warn "[debug]$me $statement\n" if $DEBUG > 1;
349     $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
350     $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
351
352     foreach (@{ $sth->fetchall_arrayref({}) }) {
353       my $recnum = $_->{recnum};
354       my $name = $_->{name};
355       my $value = $_->{value};
356       if (exists($result{$recnum})) {
357         $result{$recnum}->{$name} = $value;
358       }
359     }
360   }
361   
362   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
363     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
364       #derivied class didn't override new method, so this optimization is safe
365       if ( $cache ) {
366         map {
367           new_or_cached( "FS::$table", { %{$_} }, $cache )
368         } values(%result);
369       } else {
370         map {
371           new( "FS::$table", { %{$_} } )
372         } values(%result);
373       }
374     } else {
375       warn "untested code (class FS::$table uses custom new method)";
376       map {
377         eval 'FS::'. $table. '->new( { %{$_} } )';
378       } values(%result);
379     }
380   } else {
381     cluck "warning: FS::$table not loaded; returning FS::Record objects";
382     map {
383       FS::Record->new( $table, { %{$_} } );
384     } values(%result);
385   }
386
387 }
388
389 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
390
391 Experimental JOINed search method.  Using this method, you can execute a
392 single SELECT spanning multiple tables, and cache the results for subsequent
393 method calls.  Interface will almost definately change in an incompatible
394 fashion.
395
396 Arguments: 
397
398 =cut
399
400 sub jsearch {
401   my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
402   my $cache = FS::SearchCache->new( $ptable, $pkey );
403   my %saw;
404   ( $cache,
405     grep { !$saw{$_->getfield($pkey)}++ }
406       qsearch($table, $record, $select, $extra_sql, $cache )
407   );
408 }
409
410 =item qsearchs TABLE, HASHREF
411
412 Same as qsearch, except that if more than one record matches, it B<carp>s but
413 returns the first.  If this happens, you either made a logic error in asking
414 for a single item, or your data is corrupted.
415
416 =cut
417
418 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
419   my $table = $_[0];
420   my(@result) = qsearch(@_);
421   carp "warning: Multiple records in scalar search ($table)"
422     if scalar(@result) > 1;
423   #should warn more vehemently if the search was on a primary key?
424   scalar(@result) ? ($result[0]) : ();
425 }
426
427 =back
428
429 =head1 METHODS
430
431 =over 4
432
433 =item table
434
435 Returns the table name.
436
437 =cut
438
439 sub table {
440 #  cluck "warning: FS::Record::table deprecated; supply one in subclass!";
441   my $self = shift;
442   $self -> {'Table'};
443 }
444
445 =item dbdef_table
446
447 Returns the DBIx::DBSchema::Table object for the table.
448
449 =cut
450
451 sub dbdef_table {
452   my($self)=@_;
453   my($table)=$self->table;
454   $dbdef->table($table);
455 }
456
457 =item get, getfield COLUMN
458
459 Returns the value of the column/field/key COLUMN.
460
461 =cut
462
463 sub get {
464   my($self,$field) = @_;
465   # to avoid "Use of unitialized value" errors
466   if ( defined ( $self->{Hash}->{$field} ) ) {
467     $self->{Hash}->{$field};
468   } else { 
469     '';
470   }
471 }
472 sub getfield {
473   my $self = shift;
474   $self->get(@_);
475 }
476
477 =item set, setfield COLUMN, VALUE
478
479 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
480
481 =cut
482
483 sub set { 
484   my($self,$field,$value) = @_;
485   $self->{'Hash'}->{$field} = $value;
486 }
487 sub setfield {
488   my $self = shift;
489   $self->set(@_);
490 }
491
492 =item AUTLOADED METHODS
493
494 $record->column is a synonym for $record->get('column');
495
496 $record->column('value') is a synonym for $record->set('column','value');
497
498 =cut
499
500 # readable/safe
501 sub AUTOLOAD {
502   my($self,$value)=@_;
503   my($field)=$AUTOLOAD;
504   $field =~ s/.*://;
505   if ( defined($value) ) {
506     confess "errant AUTOLOAD $field for $self (arg $value)"
507       unless ref($self) && $self->can('setfield');
508     $self->setfield($field,$value);
509   } else {
510     confess "errant AUTOLOAD $field for $self (no args)"
511       unless ref($self) && $self->can('getfield');
512     $self->getfield($field);
513   }    
514 }
515
516 # efficient
517 #sub AUTOLOAD {
518 #  my $field = $AUTOLOAD;
519 #  $field =~ s/.*://;
520 #  if ( defined($_[1]) ) {
521 #    $_[0]->setfield($field, $_[1]);
522 #  } else {
523 #    $_[0]->getfield($field);
524 #  }    
525 #}
526
527 =item hash
528
529 Returns a list of the column/value pairs, usually for assigning to a new hash.
530
531 To make a distinct duplicate of an FS::Record object, you can do:
532
533     $new = new FS::Record ( $old->table, { $old->hash } );
534
535 =cut
536
537 sub hash {
538   my($self) = @_;
539   %{ $self->{'Hash'} }; 
540 }
541
542 =item hashref
543
544 Returns a reference to the column/value hash.
545
546 =cut
547
548 sub hashref {
549   my($self) = @_;
550   $self->{'Hash'};
551 }
552
553 =item insert
554
555 Inserts this record to the database.  If there is an error, returns the error,
556 otherwise returns false.
557
558 =cut
559
560 sub insert {
561   my $self = shift;
562
563   my $error = $self->check;
564   return $error if $error;
565
566   #single-field unique keys are given a value if false
567   #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
568   foreach ( $self->dbdef_table->unique->singles ) {
569     $self->unique($_) unless $self->getfield($_);
570   }
571
572   #and also the primary key, if the database isn't going to
573   my $primary_key = $self->dbdef_table->primary_key;
574   my $db_seq = 0;
575   if ( $primary_key ) {
576     my $col = $self->dbdef_table->column($primary_key);
577     
578     $db_seq =
579       uc($col->type) eq 'SERIAL'
580       || ( driver_name eq 'Pg'
581              && defined($col->default)
582              && $col->default =~ /^nextval\(/i
583          )
584       || ( driver_name eq 'mysql'
585              && defined($col->local)
586              && $col->local =~ /AUTO_INCREMENT/i
587          );
588     $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
589   }
590
591   my $table = $self->table;
592   #false laziness w/delete
593   my @real_fields =
594     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
595     real_fields($table)
596   ;
597   my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
598   #eslaf
599
600   my $statement = "INSERT INTO $table ( ".
601       join( ', ', @real_fields ).
602     ") VALUES (".
603       join( ', ', @values ).
604     ")"
605   ;
606   warn "[debug]$me $statement\n" if $DEBUG > 1;
607   my $sth = dbh->prepare($statement) or return dbh->errstr;
608
609   local $SIG{HUP} = 'IGNORE';
610   local $SIG{INT} = 'IGNORE';
611   local $SIG{QUIT} = 'IGNORE'; 
612   local $SIG{TERM} = 'IGNORE';
613   local $SIG{TSTP} = 'IGNORE';
614   local $SIG{PIPE} = 'IGNORE';
615
616   $sth->execute or return $sth->errstr;
617
618   my $insertid = '';
619   if ( $db_seq ) { # get inserted id from the database, if applicable
620     warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
621     if ( driver_name eq 'Pg' ) {
622
623       my $oid = $sth->{'pg_oid_status'};
624       my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
625       my $i_sth = dbh->prepare($i_sql) or do {
626         dbh->rollback if $FS::UID::AutoCommit;
627         return dbh->errstr;
628       };
629       $i_sth->execute($oid) or do {
630         dbh->rollback if $FS::UID::AutoCommit;
631         return $i_sth->errstr;
632       };
633       $insertid = $i_sth->fetchrow_arrayref->[0];
634
635     } elsif ( driver_name eq 'mysql' ) {
636
637       $insertid = dbh->{'mysql_insertid'};
638       # work around mysql_insertid being null some of the time, ala RT :/
639       unless ( $insertid ) {
640         warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
641              "using SELECT LAST_INSERT_ID();";
642         my $i_sql = "SELECT LAST_INSERT_ID()";
643         my $i_sth = dbh->prepare($i_sql) or do {
644           dbh->rollback if $FS::UID::AutoCommit;
645           return dbh->errstr;
646         };
647         $i_sth->execute or do {
648           dbh->rollback if $FS::UID::AutoCommit;
649           return $i_sth->errstr;
650         };
651         $insertid = $i_sth->fetchrow_arrayref->[0];
652       }
653
654     } else {
655       dbh->rollback if $FS::UID::AutoCommit;
656       return "don't know how to retreive inserted ids from ". driver_name. 
657              ", try using counterfiles (maybe run dbdef-create?)";
658     }
659     $self->setfield($primary_key, $insertid);
660   }
661
662   my @virtual_fields = 
663       grep defined($self->getfield($_)) && $self->getfield($_) ne "",
664           $self->virtual_fields;
665   if (@virtual_fields) {
666     my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
667
668     my $vfieldpart = $self->vfieldpart_hashref;
669
670     my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
671                     "VALUES (?, ?, ?)";
672
673     my $v_sth = dbh->prepare($v_statement) or do {
674       dbh->rollback if $FS::UID::AutoCommit;
675       return dbh->errstr;
676     };
677
678     foreach (keys(%v_values)) {
679       $v_sth->execute($self->getfield($primary_key),
680                       $vfieldpart->{$_},
681                       $v_values{$_})
682       or do {
683         dbh->rollback if $FS::UID::AutoCommit;
684         return $v_sth->errstr;
685       };
686     }
687   }
688
689
690   my $h_sth;
691   if ( defined $dbdef->table('h_'. $table) ) {
692     my $h_statement = $self->_h_statement('insert');
693     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
694     $h_sth = dbh->prepare($h_statement) or do {
695       dbh->rollback if $FS::UID::AutoCommit;
696       return dbh->errstr;
697     };
698   } else {
699     $h_sth = '';
700   }
701   $h_sth->execute or return $h_sth->errstr if $h_sth;
702
703   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
704
705   '';
706 }
707
708 =item add
709
710 Depriciated (use insert instead).
711
712 =cut
713
714 sub add {
715   cluck "warning: FS::Record::add deprecated!";
716   insert @_; #call method in this scope
717 }
718
719 =item delete
720
721 Delete this record from the database.  If there is an error, returns the error,
722 otherwise returns false.
723
724 =cut
725
726 sub delete {
727   my $self = shift;
728
729   my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
730     map {
731       $self->getfield($_) eq ''
732         #? "( $_ IS NULL OR $_ = \"\" )"
733         ? ( driver_name eq 'Pg'
734               ? "$_ IS NULL"
735               : "( $_ IS NULL OR $_ = \"\" )"
736           )
737         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
738     } ( $self->dbdef_table->primary_key )
739           ? ( $self->dbdef_table->primary_key)
740           : real_fields($self->table)
741   );
742   warn "[debug]$me $statement\n" if $DEBUG > 1;
743   my $sth = dbh->prepare($statement) or return dbh->errstr;
744
745   my $h_sth;
746   if ( defined $dbdef->table('h_'. $self->table) ) {
747     my $h_statement = $self->_h_statement('delete');
748     warn "[debug]$me $h_statement\n" if $DEBUG > 2;
749     $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
750   } else {
751     $h_sth = '';
752   }
753
754   my $primary_key = $self->dbdef_table->primary_key;
755   my $v_sth;
756   my @del_vfields;
757   my $vfp = $self->vfieldpart_hashref;
758   foreach($self->virtual_fields) {
759     next if $self->getfield($_) eq '';
760     unless(@del_vfields) {
761       my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
762       $v_sth = dbh->prepare($st) or return dbh->errstr;
763     }
764     push @del_vfields, $_;
765   }
766
767   local $SIG{HUP} = 'IGNORE';
768   local $SIG{INT} = 'IGNORE';
769   local $SIG{QUIT} = 'IGNORE'; 
770   local $SIG{TERM} = 'IGNORE';
771   local $SIG{TSTP} = 'IGNORE';
772   local $SIG{PIPE} = 'IGNORE';
773
774   my $rc = $sth->execute or return $sth->errstr;
775   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
776   $h_sth->execute or return $h_sth->errstr if $h_sth;
777   $v_sth->execute($self->getfield($primary_key), $vfp->{$_}) 
778     or return $v_sth->errstr 
779         foreach (@del_vfields);
780   
781   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
782
783   #no need to needlessly destoy the data either (causes problems actually)
784   #undef $self; #no need to keep object!
785
786   '';
787 }
788
789 =item del
790
791 Depriciated (use delete instead).
792
793 =cut
794
795 sub del {
796   cluck "warning: FS::Record::del deprecated!";
797   &delete(@_); #call method in this scope
798 }
799
800 =item replace OLD_RECORD
801
802 Replace the OLD_RECORD with this one in the database.  If there is an error,
803 returns the error, otherwise returns false.
804
805 =cut
806
807 sub replace {
808   my ( $new, $old ) = ( shift, shift );
809   warn "[debug]$me $new ->replace $old\n" if $DEBUG;
810
811   return "Records not in same table!" unless $new->table eq $old->table;
812
813   my $primary_key = $old->dbdef_table->primary_key;
814   return "Can't change $primary_key"
815     if $primary_key
816        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
817
818   my $error = $new->check;
819   return $error if $error;
820
821   #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
822   my %diff = map { ($new->getfield($_) ne $old->getfield($_))
823                    ? ($_, $new->getfield($_)) : () } $old->fields;
824                    
825   unless ( keys(%diff) ) {
826     carp "[warning]$me $new -> replace $old: records identical";
827     return '';
828   }
829
830   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
831     map {
832       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
833     } real_fields($old->table)
834   ). ' WHERE '.
835     join(' AND ',
836       map {
837         $old->getfield($_) eq ''
838           #? "( $_ IS NULL OR $_ = \"\" )"
839           ? ( driver_name eq 'Pg'
840                 ? "$_ IS NULL"
841                 : "( $_ IS NULL OR $_ = \"\" )"
842             )
843           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
844       } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
845     )
846   ;
847   warn "[debug]$me $statement\n" if $DEBUG > 1;
848   my $sth = dbh->prepare($statement) or return dbh->errstr;
849
850   my $h_old_sth;
851   if ( defined $dbdef->table('h_'. $old->table) ) {
852     my $h_old_statement = $old->_h_statement('replace_old');
853     warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
854     $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
855   } else {
856     $h_old_sth = '';
857   }
858
859   my $h_new_sth;
860   if ( defined $dbdef->table('h_'. $new->table) ) {
861     my $h_new_statement = $new->_h_statement('replace_new');
862     warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
863     $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
864   } else {
865     $h_new_sth = '';
866   }
867
868   # For virtual fields we have three cases with different SQL 
869   # statements: add, replace, delete
870   my $v_add_sth;
871   my $v_rep_sth;
872   my $v_del_sth;
873   my (@add_vfields, @rep_vfields, @del_vfields);
874   my $vfp = $old->vfieldpart_hashref;
875   foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
876     if($diff{$_} eq '') {
877       # Delete
878       unless(@del_vfields) {
879         my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
880                  "AND vfieldpart = ?";
881         warn "[debug]$me $st\n" if $DEBUG > 2;
882         $v_del_sth = dbh->prepare($st) or return dbh->errstr;
883       }
884       push @del_vfields, $_;
885     } elsif($old->getfield($_) eq '') {
886       # Add
887       unless(@add_vfields) {
888         my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
889                  "VALUES (?, ?, ?)";
890         warn "[debug]$me $st\n" if $DEBUG > 2;
891         $v_add_sth = dbh->prepare($st) or return dbh->errstr;
892       }
893       push @add_vfields, $_;
894     } else {
895       # Replace
896       unless(@rep_vfields) {
897         my $st = "UPDATE virtual_field SET value = ? ".
898                  "WHERE recnum = ? AND vfieldpart = ?";
899         warn "[debug]$me $st\n" if $DEBUG > 2;
900         $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
901       }
902       push @rep_vfields, $_;
903     }
904   }
905
906   local $SIG{HUP} = 'IGNORE';
907   local $SIG{INT} = 'IGNORE';
908   local $SIG{QUIT} = 'IGNORE'; 
909   local $SIG{TERM} = 'IGNORE';
910   local $SIG{TSTP} = 'IGNORE';
911   local $SIG{PIPE} = 'IGNORE';
912
913   my $rc = $sth->execute or return $sth->errstr;
914   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
915   $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
916   $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
917
918   $v_del_sth->execute($old->getfield($primary_key),
919                       $vfp->{$_})
920         or return $v_del_sth->errstr
921       foreach(@del_vfields);
922
923   $v_add_sth->execute($new->getfield($_),
924                       $old->getfield($primary_key),
925                       $vfp->{$_})
926         or return $v_add_sth->errstr
927       foreach(@add_vfields);
928
929   $v_rep_sth->execute($new->getfield($_),
930                       $old->getfield($primary_key),
931                       $vfp->{$_})
932         or return $v_rep_sth->errstr
933       foreach(@rep_vfields);
934
935   dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
936
937   '';
938
939 }
940
941 =item rep
942
943 Depriciated (use replace instead).
944
945 =cut
946
947 sub rep {
948   cluck "warning: FS::Record::rep deprecated!";
949   replace @_; #call method in this scope
950 }
951
952 =item check
953
954 Checks virtual fields (using check_blocks).  Subclasses should still provide 
955 a check method to validate real fields, foreign keys, etc., and call this 
956 method via $self->SUPER::check.
957
958 (FIXME: Should this method try to make sure that it I<is> being called from 
959 a subclass's check method, to keep the current semantics as far as possible?)
960
961 =cut
962
963 sub check {
964   #confess "FS::Record::check not implemented; supply one in subclass!";
965   my $self = shift;
966
967   foreach my $field ($self->virtual_fields) {
968     for ($self->getfield($field)) {
969       # See notes on check_block in FS::part_virtual_field.
970       eval $self->pvf($field)->check_block;
971       return $@ if $@;
972       $self->setfield($field, $_);
973     }
974   }
975   '';
976 }
977
978 sub _h_statement {
979   my( $self, $action ) = @_;
980
981   my @fields =
982     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
983     real_fields($self->table);
984   ;
985   my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
986
987   "INSERT INTO h_". $self->table. " ( ".
988       join(', ', qw(history_date history_user history_action), @fields ).
989     ") VALUES (".
990       join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
991     ")"
992   ;
993 }
994
995 =item unique COLUMN
996
997 B<Warning>: External use is B<deprecated>.  
998
999 Replaces COLUMN in record with a unique number, using counters in the
1000 filesystem.  Used by the B<insert> method on single-field unique columns
1001 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1002 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1003
1004 Returns the new value.
1005
1006 =cut
1007
1008 sub unique {
1009   my($self,$field) = @_;
1010   my($table)=$self->table;
1011
1012   croak "Unique called on field $field, but it is ",
1013         $self->getfield($field),
1014         ", not null!"
1015     if $self->getfield($field);
1016
1017   #warn "table $table is tainted" if is_tainted($table);
1018   #warn "field $field is tainted" if is_tainted($field);
1019
1020   my($counter) = new File::CounterFile "$table.$field",0;
1021 # hack for web demo
1022 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1023 #  my($user)=$1;
1024 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
1025 # endhack
1026
1027   my $index = $counter->inc;
1028   $index = $counter->inc while qsearchs($table, { $field=>$index } );
1029
1030   $index =~ /^(\d*)$/;
1031   $index=$1;
1032
1033   $self->setfield($field,$index);
1034
1035 }
1036
1037 =item ut_float COLUMN
1038
1039 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
1040 null.  If there is an error, returns the error, otherwise returns false.
1041
1042 =cut
1043
1044 sub ut_float {
1045   my($self,$field)=@_ ;
1046   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1047    $self->getfield($field) =~ /^(\d+)$/ ||
1048    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1049    $self->getfield($field) =~ /^(\d+e\d+)$/)
1050     or return "Illegal or empty (float) $field: ". $self->getfield($field);
1051   $self->setfield($field,$1);
1052   '';
1053 }
1054
1055 =item ut_number COLUMN
1056
1057 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
1058 is an error, returns the error, otherwise returns false.
1059
1060 =cut
1061
1062 sub ut_number {
1063   my($self,$field)=@_;
1064   $self->getfield($field) =~ /^(\d+)$/
1065     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1066   $self->setfield($field,$1);
1067   '';
1068 }
1069
1070 =item ut_numbern COLUMN
1071
1072 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
1073 an error, returns the error, otherwise returns false.
1074
1075 =cut
1076
1077 sub ut_numbern {
1078   my($self,$field)=@_;
1079   $self->getfield($field) =~ /^(\d*)$/
1080     or return "Illegal (numeric) $field: ". $self->getfield($field);
1081   $self->setfield($field,$1);
1082   '';
1083 }
1084
1085 =item ut_money COLUMN
1086
1087 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
1088 is an error, returns the error, otherwise returns false.
1089
1090 =cut
1091
1092 sub ut_money {
1093   my($self,$field)=@_;
1094   $self->setfield($field, 0) if $self->getfield($field) eq '';
1095   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1096     or return "Illegal (money) $field: ". $self->getfield($field);
1097   #$self->setfield($field, "$1$2$3" || 0);
1098   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1099   '';
1100 }
1101
1102 =item ut_text COLUMN
1103
1104 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1105 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1106 May not be null.  If there is an error, returns the error, otherwise returns
1107 false.
1108
1109 =cut
1110
1111 sub ut_text {
1112   my($self,$field)=@_;
1113   #warn "msgcat ". \&msgcat. "\n";
1114   #warn "notexist ". \&notexist. "\n";
1115   #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1116   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1117     or return gettext('illegal_or_empty_text'). " $field: ".
1118                $self->getfield($field);
1119   $self->setfield($field,$1);
1120   '';
1121 }
1122
1123 =item ut_textn COLUMN
1124
1125 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
1126 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1127 May be null.  If there is an error, returns the error, otherwise returns false.
1128
1129 =cut
1130
1131 sub ut_textn {
1132   my($self,$field)=@_;
1133   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1134     or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1135   $self->setfield($field,$1);
1136   '';
1137 }
1138
1139 =item ut_alpha COLUMN
1140
1141 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
1142 an error, returns the error, otherwise returns false.
1143
1144 =cut
1145
1146 sub ut_alpha {
1147   my($self,$field)=@_;
1148   $self->getfield($field) =~ /^(\w+)$/
1149     or return "Illegal or empty (alphanumeric) $field: ".
1150               $self->getfield($field);
1151   $self->setfield($field,$1);
1152   '';
1153 }
1154
1155 =item ut_alpha COLUMN
1156
1157 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
1158 error, returns the error, otherwise returns false.
1159
1160 =cut
1161
1162 sub ut_alphan {
1163   my($self,$field)=@_;
1164   $self->getfield($field) =~ /^(\w*)$/ 
1165     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1166   $self->setfield($field,$1);
1167   '';
1168 }
1169
1170 =item ut_phonen COLUMN [ COUNTRY ]
1171
1172 Check/untaint phone numbers.  May be null.  If there is an error, returns
1173 the error, otherwise returns false.
1174
1175 Takes an optional two-letter ISO country code; without it or with unsupported
1176 countries, ut_phonen simply calls ut_alphan.
1177
1178 =cut
1179
1180 sub ut_phonen {
1181   my( $self, $field, $country ) = @_;
1182   return $self->ut_alphan($field) unless defined $country;
1183   my $phonen = $self->getfield($field);
1184   if ( $phonen eq '' ) {
1185     $self->setfield($field,'');
1186   } elsif ( $country eq 'US' || $country eq 'CA' ) {
1187     $phonen =~ s/\D//g;
1188     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1189       or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1190     $phonen = "$1-$2-$3";
1191     $phonen .= " x$4" if $4;
1192     $self->setfield($field,$phonen);
1193   } else {
1194     warn "warning: don't know how to check phone numbers for country $country";
1195     return $self->ut_textn($field);
1196   }
1197   '';
1198 }
1199
1200 =item ut_ip COLUMN
1201
1202 Check/untaint ip addresses.  IPv4 only for now.
1203
1204 =cut
1205
1206 sub ut_ip {
1207   my( $self, $field ) = @_;
1208   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1209     or return "Illegal (IP address) $field: ". $self->getfield($field);
1210   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1211   $self->setfield($field, "$1.$2.$3.$4");
1212   '';
1213 }
1214
1215 =item ut_ipn COLUMN
1216
1217 Check/untaint ip addresses.  IPv4 only for now.  May be null.
1218
1219 =cut
1220
1221 sub ut_ipn {
1222   my( $self, $field ) = @_;
1223   if ( $self->getfield($field) =~ /^()$/ ) {
1224     $self->setfield($field,'');
1225     '';
1226   } else {
1227     $self->ut_ip($field);
1228   }
1229 }
1230
1231 =item ut_domain COLUMN
1232
1233 Check/untaint host and domain names.
1234
1235 =cut
1236
1237 sub ut_domain {
1238   my( $self, $field ) = @_;
1239   #$self->getfield($field) =~/^(\w+\.)*\w+$/
1240   $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1241     or return "Illegal (domain) $field: ". $self->getfield($field);
1242   $self->setfield($field,$1);
1243   '';
1244 }
1245
1246 =item ut_name COLUMN
1247
1248 Check/untaint proper names; allows alphanumerics, spaces and the following
1249 punctuation: , . - '
1250
1251 May not be null.
1252
1253 =cut
1254
1255 sub ut_name {
1256   my( $self, $field ) = @_;
1257   $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1258     or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1259   $self->setfield($field,$1);
1260   '';
1261 }
1262
1263 =item ut_zip COLUMN
1264
1265 Check/untaint zip codes.
1266
1267 =cut
1268
1269 sub ut_zip {
1270   my( $self, $field, $country ) = @_;
1271   if ( $country eq 'US' ) {
1272     $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1273       or return gettext('illegal_zip'). " $field for country $country: ".
1274                 $self->getfield($field);
1275     $self->setfield($field,$1);
1276   } else {
1277     $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1278       or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1279     $self->setfield($field,$1);
1280   }
1281   '';
1282 }
1283
1284 =item ut_country COLUMN
1285
1286 Check/untaint country codes.  Country names are changed to codes, if possible -
1287 see L<Locale::Country>.
1288
1289 =cut
1290
1291 sub ut_country {
1292   my( $self, $field ) = @_;
1293   unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1294     if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/ 
1295          && country2code($1) ) {
1296       $self->setfield($field,uc(country2code($1)));
1297     }
1298   }
1299   $self->getfield($field) =~ /^(\w\w)$/
1300     or return "Illegal (country) $field: ". $self->getfield($field);
1301   $self->setfield($field,uc($1));
1302   '';
1303 }
1304
1305 =item ut_anything COLUMN
1306
1307 Untaints arbitrary data.  Be careful.
1308
1309 =cut
1310
1311 sub ut_anything {
1312   my( $self, $field ) = @_;
1313   $self->getfield($field) =~ /^(.*)$/s
1314     or return "Illegal $field: ". $self->getfield($field);
1315   $self->setfield($field,$1);
1316   '';
1317 }
1318
1319 =item ut_enum COLUMN CHOICES_ARRAYREF
1320
1321 Check/untaint a column, supplying all possible choices, like the "enum" type.
1322
1323 =cut
1324
1325 sub ut_enum {
1326   my( $self, $field, $choices ) = @_;
1327   foreach my $choice ( @$choices ) {
1328     if ( $self->getfield($field) eq $choice ) {
1329       $self->setfield($choice);
1330       return '';
1331     }
1332   }
1333   return "Illegal (enum) field $field: ". $self->getfield($field);
1334 }
1335
1336 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1337
1338 Check/untaint a foreign column key.  Call a regular ut_ method (like ut_number)
1339 on the column first.
1340
1341 =cut
1342
1343 sub ut_foreign_key {
1344   my( $self, $field, $table, $foreign ) = @_;
1345   qsearchs($table, { $foreign => $self->getfield($field) })
1346     or return "Can't find $field ". $self->getfield($field).
1347               " in $table.$foreign";
1348   '';
1349 }
1350
1351 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1352
1353 Like ut_foreign_key, except the null value is also allowed.
1354
1355 =cut
1356
1357 sub ut_foreign_keyn {
1358   my( $self, $field, $table, $foreign ) = @_;
1359   $self->getfield($field)
1360     ? $self->ut_foreign_key($field, $table, $foreign)
1361     : '';
1362 }
1363
1364
1365 =item virtual_fields [ TABLE ]
1366
1367 Returns a list of virtual fields defined for the table.  This should not 
1368 be exported, and should only be called as an instance or class method.
1369
1370 =cut
1371
1372 sub virtual_fields {
1373   my $self = shift;
1374   my $table;
1375   $table = $self->table or confess "virtual_fields called on non-table";
1376
1377   confess "Unknown table $table" unless $dbdef->table($table);
1378
1379   return () unless $self->dbdef->table('part_virtual_field');
1380
1381   # This should be smart enough to cache results.
1382
1383   my $query = 'SELECT name from part_virtual_field ' .
1384               "WHERE dbtable = '$table'";
1385   my $dbh = dbh;
1386   my $result = $dbh->selectcol_arrayref($query);
1387   confess $dbh->errstr if $dbh->err;
1388   return @$result;
1389 }
1390
1391
1392 =item fields [ TABLE ]
1393
1394 This is a wrapper for real_fields and virtual_fields.  Code that called
1395 fields before should probably continue to call fields.
1396
1397 =cut
1398
1399 sub fields {
1400   my $something = shift;
1401   my $table;
1402   if($something->isa('FS::Record')) {
1403     $table = $something->table;
1404   } else {
1405     $table = $something;
1406     $something = "FS::$table";
1407   }
1408   return (real_fields($table), $something->virtual_fields());
1409 }
1410
1411 =back
1412
1413 =item pvf FIELD_NAME
1414
1415 Returns the FS::part_virtual_field object corresponding to a field in the 
1416 record (specified by FIELD_NAME).
1417
1418 =cut
1419
1420 sub pvf {
1421   my ($self, $name) = (shift, shift);
1422
1423   if(grep /^$name$/, $self->virtual_fields) {
1424     return qsearchs('part_virtual_field', { dbtable => $self->table,
1425                                             name    => $name } );
1426   }
1427   ''
1428 }
1429
1430 =head1 SUBROUTINES
1431
1432 =over 4
1433
1434 =item real_fields [ TABLE ]
1435
1436 Returns a list of the real columns in the specified table.  Called only by 
1437 fields() and other subroutines elsewhere in FS::Record.
1438
1439 =cut
1440
1441 sub real_fields {
1442   my $table = shift;
1443
1444   my($table_obj) = $dbdef->table($table);
1445   confess "Unknown table $table" unless $table_obj;
1446   $table_obj->columns;
1447 }
1448
1449 =item reload_dbdef([FILENAME])
1450
1451 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1452 non-default filename.  This command is executed at startup unless
1453 I<$FS::Record::setup_hack> is true.  Returns a DBIx::DBSchema object.
1454
1455 =cut
1456
1457 sub reload_dbdef {
1458   my $file = shift || $dbdef_file;
1459
1460   unless ( exists $dbdef_cache{$file} ) {
1461     warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1462     $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1463                             or die "can't load database schema from $file";
1464   } else {
1465     warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1466   }
1467   $dbdef = $dbdef_cache{$file};
1468 }
1469
1470 =item dbdef
1471
1472 Returns the current database definition.  See L<DBIx::DBSchema>.
1473
1474 =cut
1475
1476 sub dbdef { $dbdef; }
1477
1478 =item _quote VALUE, TABLE, COLUMN
1479
1480 This is an internal function used to construct SQL statements.  It returns
1481 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1482 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1483
1484 =cut
1485
1486 sub _quote {
1487   my($value, $table, $column) = @_;
1488   my $column_obj = $dbdef->table($table)->column($column);
1489   my $column_type = $column_obj->type;
1490
1491   if ( $value eq '' && $column_type =~ /^int/ ) {
1492     if ( $column_obj->null ) {
1493       'NULL';
1494     } else {
1495       cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1496             "using 0 instead";
1497       0;
1498     }
1499   } elsif ( $value =~ /^\d+(\.\d+)?$/ && 
1500             ! $column_type =~ /(char|binary|text)$/i ) {
1501     $value;
1502   } else {
1503     dbh->quote($value);
1504   }
1505 }
1506
1507 =item vfieldpart_hashref TABLE
1508
1509 Returns a hashref of virtual field names and vfieldparts applicable to the given
1510 TABLE.
1511
1512 =cut
1513
1514 sub vfieldpart_hashref {
1515   my $self = shift;
1516   my $table = $self->table;
1517
1518   return {} unless $self->dbdef->table('part_virtual_field');
1519
1520   my $dbh = dbh;
1521   my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1522                   "dbtable = '$table'";
1523   my $sth = $dbh->prepare($statement);
1524   $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1525   return { map { $_->{name}, $_->{vfieldpart} } 
1526     @{$sth->fetchall_arrayref({})} };
1527
1528 }
1529
1530
1531 =item hfields TABLE
1532
1533 This is deprecated.  Don't use it.
1534
1535 It returns a hash-type list with the fields of this record's table set true.
1536
1537 =cut
1538
1539 sub hfields {
1540   carp "warning: hfields is deprecated";
1541   my($table)=@_;
1542   my(%hash);
1543   foreach (fields($table)) {
1544     $hash{$_}=1;
1545   }
1546   \%hash;
1547 }
1548
1549 sub _dump {
1550   my($self)=@_;
1551   join("\n", map {
1552     "$_: ". $self->getfield($_). "|"
1553   } (fields($self->table)) );
1554 }
1555
1556 sub DESTROY { return; }
1557
1558 #sub DESTROY {
1559 #  my $self = shift;
1560 #  #use Carp qw(cluck);
1561 #  #cluck "DESTROYING $self";
1562 #  warn "DESTROYING $self";
1563 #}
1564
1565 #sub is_tainted {
1566 #             return ! eval { join('',@_), kill 0; 1; };
1567 #         }
1568
1569 =back
1570
1571 =head1 BUGS
1572
1573 This module should probably be renamed, since much of the functionality is
1574 of general use.  It is not completely unlike Adapter::DBI (see below).
1575
1576 Exported qsearch and qsearchs should be deprecated in favor of method calls
1577 (against an FS::Record object like the old search and searchs that qsearch
1578 and qsearchs were on top of.)
1579
1580 The whole fields / hfields mess should be removed.
1581
1582 The various WHERE clauses should be subroutined.
1583
1584 table string should be deprecated in favor of DBIx::DBSchema::Table.
1585
1586 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
1587 true maps to the database (and WHERE clauses) would also help.
1588
1589 The ut_ methods should ask the dbdef for a default length.
1590
1591 ut_sqltype (like ut_varchar) should all be defined
1592
1593 A fallback check method should be provided which uses the dbdef.
1594
1595 The ut_money method assumes money has two decimal digits.
1596
1597 The Pg money kludge in the new method only strips `$'.
1598
1599 The ut_phonen method only checks US-style phone numbers.
1600
1601 The _quote function should probably use ut_float instead of a regex.
1602
1603 All the subroutines probably should be methods, here or elsewhere.
1604
1605 Probably should borrow/use some dbdef methods where appropriate (like sub
1606 fields)
1607
1608 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1609 or allow it to be set.  Working around it is ugly any way around - DBI should
1610 be fixed.  (only affects RDBMS which return uppercase column names)
1611
1612 ut_zip should take an optional country like ut_phone.
1613
1614 =head1 SEE ALSO
1615
1616 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1617
1618 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
1619
1620 =cut
1621
1622 1;
1623