session monitor updates
[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 use subs qw(reload_dbdef);
6 use Exporter;
7 use Carp qw(carp cluck croak confess);
8 use File::CounterFile;
9 use FS::UID qw(dbh checkruid swapuid getotaker datasrc driver_name);
10 use FS::dbdef;
11
12 @ISA = qw(Exporter);
13 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef);
14
15 $DEBUG = 0;
16
17 #ask FS::UID to run this stuff for us later
18 $FS::UID::callback{'FS::Record'} = sub { 
19   $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
20   $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
21   &reload_dbdef unless $setup_hack; #$setup_hack needed now?
22 };
23
24 =head1 NAME
25
26 FS::Record - Database record objects
27
28 =head1 SYNOPSIS
29
30     use FS::Record;
31     use FS::Record qw(dbh fields qsearch qsearchs dbdef);
32
33     $record = new FS::Record 'table', \%hash;
34     $record = new FS::Record 'table', { 'column' => 'value', ... };
35
36     $record  = qsearchs FS::Record 'table', \%hash;
37     $record  = qsearchs FS::Record 'table', { 'column' => 'value', ... };
38     @records = qsearch  FS::Record 'table', \%hash; 
39     @records = qsearch  FS::Record 'table', { 'column' => 'value', ... };
40
41     $table = $record->table;
42     $dbdef_table = $record->dbdef_table;
43
44     $value = $record->get('column');
45     $value = $record->getfield('column');
46     $value = $record->column;
47
48     $record->set( 'column' => 'value' );
49     $record->setfield( 'column' => 'value' );
50     $record->column('value');
51
52     %hash = $record->hash;
53
54     $hashref = $record->hashref;
55
56     $error = $record->insert;
57     #$error = $record->add; #depriciated
58
59     $error = $record->delete;
60     #$error = $record->del; #depriciated
61
62     $error = $new_record->replace($old_record);
63     #$error = $new_record->rep($old_record); #depriciated
64
65     $value = $record->unique('column');
66
67     $value = $record->ut_float('column');
68     $value = $record->ut_number('column');
69     $value = $record->ut_numbern('column');
70     $value = $record->ut_money('column');
71     $value = $record->ut_text('column');
72     $value = $record->ut_textn('column');
73     $value = $record->ut_alpha('column');
74     $value = $record->ut_alphan('column');
75     $value = $record->ut_phonen('column');
76     $value = $record->ut_anythingn('column');
77
78     $dbdef = reload_dbdef;
79     $dbdef = reload_dbdef "/non/standard/filename";
80     $dbdef = dbdef;
81
82     $quoted_value = _quote($value,'table','field');
83
84     #depriciated
85     $fields = hfields('table');
86     if ( $fields->{Field} ) { # etc.
87
88     @fields = fields 'table'; #as a subroutine
89     @fields = $record->fields; #as a method call
90
91
92 =head1 DESCRIPTION
93
94 (Mostly) object-oriented interface to database records.  Records are currently
95 implemented on top of DBI.  FS::Record is intended as a base class for
96 table-specific classes to inherit from, i.e. FS::cust_main.
97
98 =head1 CONSTRUCTORS
99
100 =over 4
101
102 =item new [ TABLE, ] HASHREF
103
104 Creates a new record.  It doesn't store it in the database, though.  See
105 L<"insert"> for that.
106
107 Note that the object stores this hash reference, not a distinct copy of the
108 hash it points to.  You can ask the object for a copy with the I<hash> 
109 method.
110
111 TABLE can only be omitted when a dervived class overrides the table method.
112
113 =cut
114
115 sub new { 
116   my $proto = shift;
117   my $class = ref($proto) || $proto;
118   my $self = {};
119   bless ($self, $class);
120
121   $self->{'Table'} = shift unless defined ( $self->table );
122
123   my $hashref = $self->{'Hash'} = shift;
124
125   foreach my $field ( $self->fields ) { 
126     $hashref->{$field}='' unless defined $hashref->{$field};
127     #trim the '$' and ',' from money fields for Pg (belong HERE?)
128     #(what about Pg i18n?)
129     if ( driver_name eq 'Pg' 
130          && $self->dbdef_table->column($field)->type eq 'money' ) {
131       ${$hashref}{$field} =~ s/^\$//;
132       ${$hashref}{$field} =~ s/\,//;
133     }
134   }
135
136   $self;
137 }
138
139 sub create {
140   my $proto = shift;
141   my $class = ref($proto) || $proto;
142   my $self = {};
143   bless ($self, $class);
144   if ( defined $self->table ) {
145     cluck "create constructor is depriciated, use new!";
146     $self->new(@_);
147   } else {
148     croak "FS::Record::create called (not from a subclass)!";
149   }
150 }
151
152 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL
153
154 Searches the database for all records matching (at least) the key/value pairs
155 in HASHREF.  Returns all the records found as `FS::TABLE' objects if that
156 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
157 objects.
158
159 ###oops, argh, FS::Record::new only lets us create database fields.
160 #Normal behaviour if SELECT is not specified is `*', as in
161 #C<SELECT * FROM table WHERE ...>.  However, there is an experimental new
162 #feature where you can specify SELECT - remember, the objects returned,
163 #although blessed into the appropriate `FS::TABLE' package, will only have the
164 #fields you specify.  This might have unwanted results if you then go calling
165 #regular FS::TABLE methods
166 #on it.
167
168 =cut
169
170 sub qsearch {
171   my($table, $record, $select, $extra_sql ) = @_;
172   $select ||= '*';
173   my $dbh = dbh;
174
175   my @fields = grep exists($record->{$_}), fields($table);
176
177   my $statement = "SELECT $select FROM $table";
178   if ( @fields ) {
179     $statement .= " WHERE ". join(' AND ', map {
180       if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
181         if ( driver_name eq 'Pg' ) {
182           "$_ IS NULL";
183         } else {
184           qq-( $_ IS NULL OR $_ = "" )-;
185         }
186       } else {
187         "$_ = ?";
188       }
189     } @fields );
190   }
191   $statement .= " $extra_sql" if defined($extra_sql);
192
193   warn $statement if $DEBUG;
194   my $sth = $dbh->prepare_cached($statement) or croak $dbh->errstr;
195
196   $sth->execute( map $record->{$_},
197     grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
198   ) or croak $dbh->errstr;
199
200   if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
201     if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
202       #derivied class didn't override new method, so this optimization is safe
203       map {
204         new( "FS::$table", { %{$_} } )
205       } @{$sth->fetchall_arrayref( {} )};
206     } else {
207       warn "untested code (class FS::$table uses custom new method)";
208       map {
209         eval 'FS::'. $table. '->new( { %{$_} } )';
210       } @{$sth->fetchall_arrayref( {} )};
211     }
212   } else {
213     cluck "warning: FS::$table not loaded; returning FS::Record objects";
214     map {
215       FS::Record->new( $table, { %{$_} } );
216     } @{$sth->fetchall_arrayref( {} )};
217   }
218
219 }
220
221 =item qsearchs TABLE, HASHREF
222
223 Same as qsearch, except that if more than one record matches, it B<carp>s but
224 returns the first.  If this happens, you either made a logic error in asking
225 for a single item, or your data is corrupted.
226
227 =cut
228
229 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
230   my(@result) = qsearch(@_);
231   carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
232     #should warn more vehemently if the search was on a primary key?
233   scalar(@result) ? ($result[0]) : ();
234 }
235
236 =back
237
238 =head1 METHODS
239
240 =over 4
241
242 =item table
243
244 Returns the table name.
245
246 =cut
247
248 sub table {
249 #  cluck "warning: FS::Record::table depriciated; supply one in subclass!";
250   my $self = shift;
251   $self -> {'Table'};
252 }
253
254 =item dbdef_table
255
256 Returns the FS::dbdef_table object for the table.
257
258 =cut
259
260 sub dbdef_table {
261   my($self)=@_;
262   my($table)=$self->table;
263   $dbdef->table($table);
264 }
265
266 =item get, getfield COLUMN
267
268 Returns the value of the column/field/key COLUMN.
269
270 =cut
271
272 sub get {
273   my($self,$field) = @_;
274   # to avoid "Use of unitialized value" errors
275   if ( defined ( $self->{Hash}->{$field} ) ) {
276     $self->{Hash}->{$field};
277   } else { 
278     '';
279   }
280 }
281 sub getfield {
282   my $self = shift;
283   $self->get(@_);
284 }
285
286 =item set, setfield COLUMN, VALUE
287
288 Sets the value of the column/field/key COLUMN to VALUE.  Returns VALUE.
289
290 =cut
291
292 sub set { 
293   my($self,$field,$value) = @_;
294   $self->{'Hash'}->{$field} = $value;
295 }
296 sub setfield {
297   my $self = shift;
298   $self->set(@_);
299 }
300
301 =item AUTLOADED METHODS
302
303 $record->column is a synonym for $record->get('column');
304
305 $record->column('value') is a synonym for $record->set('column','value');
306
307 =cut
308
309 sub AUTOLOAD {
310   my($self,$value)=@_;
311   my($field)=$AUTOLOAD;
312   $field =~ s/.*://;
313   if ( defined($value) ) {
314     $self->setfield($field,$value);
315   } else {
316     $self->getfield($field);
317   }    
318 }
319
320 =item hash
321
322 Returns a list of the column/value pairs, usually for assigning to a new hash.
323
324 To make a distinct duplicate of an FS::Record object, you can do:
325
326     $new = new FS::Record ( $old->table, { $old->hash } );
327
328 =cut
329
330 sub hash {
331   my($self) = @_;
332   %{ $self->{'Hash'} }; 
333 }
334
335 =item hashref
336
337 Returns a reference to the column/value hash.
338
339 =cut
340
341 sub hashref {
342   my($self) = @_;
343   $self->{'Hash'};
344 }
345
346 =item insert
347
348 Inserts this record to the database.  If there is an error, returns the error,
349 otherwise returns false.
350
351 =cut
352
353 sub insert {
354   my $self = shift;
355
356   my $error = $self->check;
357   return $error if $error;
358
359   #single-field unique keys are given a value if false
360   #(like MySQL's AUTO_INCREMENT)
361   foreach ( $self->dbdef_table->unique->singles ) {
362     $self->unique($_) unless $self->getfield($_);
363   }
364   #and also the primary key
365   my $primary_key = $self->dbdef_table->primary_key;
366   $self->unique($primary_key) 
367     if $primary_key && ! $self->getfield($primary_key);
368
369   my @fields =
370     grep defined($self->getfield($_)) && $self->getfield($_) ne "",
371     $self->fields
372   ;
373
374   my $statement = "INSERT INTO ". $self->table. " ( ".
375       join(', ',@fields ).
376     ") VALUES (".
377       join(', ',map(_quote($self->getfield($_),$self->table,$_), @fields)).
378     ")"
379   ;
380   my $sth = dbh->prepare($statement) or return dbh->errstr;
381
382   local $SIG{HUP} = 'IGNORE';
383   local $SIG{INT} = 'IGNORE';
384   local $SIG{QUIT} = 'IGNORE'; 
385   local $SIG{TERM} = 'IGNORE';
386   local $SIG{TSTP} = 'IGNORE';
387   local $SIG{PIPE} = 'IGNORE';
388
389   $sth->execute or return $sth->errstr;
390
391   '';
392 }
393
394 =item add
395
396 Depriciated (use insert instead).
397
398 =cut
399
400 sub add {
401   cluck "warning: FS::Record::add depriciated!";
402   insert @_; #call method in this scope
403 }
404
405 =item delete
406
407 Delete this record from the database.  If there is an error, returns the error,
408 otherwise returns false.
409
410 =cut
411
412 sub delete {
413   my $self = shift;
414
415   my($statement)="DELETE FROM ". $self->table. " WHERE ". join(' AND ',
416     map {
417       $self->getfield($_) eq ''
418         #? "( $_ IS NULL OR $_ = \"\" )"
419         ? ( driver_name eq 'Pg' 
420               ? "$_ IS NULL"
421               : "( $_ IS NULL OR $_ = \"\" )"
422           )
423         : "$_ = ". _quote($self->getfield($_),$self->table,$_)
424     } ( $self->dbdef_table->primary_key )
425           ? ( $self->dbdef_table->primary_key)
426           : $self->fields
427   );
428   my $sth = dbh->prepare($statement) or return dbh->errstr;
429
430   local $SIG{HUP} = 'IGNORE';
431   local $SIG{INT} = 'IGNORE';
432   local $SIG{QUIT} = 'IGNORE'; 
433   local $SIG{TERM} = 'IGNORE';
434   local $SIG{TSTP} = 'IGNORE';
435   local $SIG{PIPE} = 'IGNORE';
436
437   my $rc = $sth->execute or return $sth->errstr;
438   #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
439
440   undef $self; #no need to keep object!
441
442   '';
443 }
444
445 =item del
446
447 Depriciated (use delete instead).
448
449 =cut
450
451 sub del {
452   cluck "warning: FS::Record::del depriciated!";
453   &delete(@_); #call method in this scope
454 }
455
456 =item replace OLD_RECORD
457
458 Replace the OLD_RECORD with this one in the database.  If there is an error,
459 returns the error, otherwise returns false.
460
461 =cut
462
463 sub replace {
464   my ( $new, $old ) = ( shift, shift );
465
466   my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
467   unless ( @diff ) {
468     carp "warning: records identical";
469     return '';
470   }
471
472   return "Records not in same table!" unless $new->table eq $old->table;
473
474   my $primary_key = $old->dbdef_table->primary_key;
475   return "Can't change $primary_key"
476     if $primary_key
477        && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
478
479   my $error = $new->check;
480   return $error if $error;
481
482   my $statement = "UPDATE ". $old->table. " SET ". join(', ',
483     map {
484       "$_ = ". _quote($new->getfield($_),$old->table,$_) 
485     } @diff
486   ). ' WHERE '.
487     join(' AND ',
488       map {
489         $old->getfield($_) eq ''
490           #? "( $_ IS NULL OR $_ = \"\" )"
491           ? ( driver_name eq 'Pg' 
492                 ? "$_ IS NULL"
493                 : "( $_ IS NULL OR $_ = \"\" )"
494             )
495           : "$_ = ". _quote($old->getfield($_),$old->table,$_)
496       } ( $primary_key ? ( $primary_key ) : $old->fields )
497     )
498   ;
499   my $sth = dbh->prepare($statement) or return dbh->errstr;
500
501   local $SIG{HUP} = 'IGNORE';
502   local $SIG{INT} = 'IGNORE';
503   local $SIG{QUIT} = 'IGNORE'; 
504   local $SIG{TERM} = 'IGNORE';
505   local $SIG{TSTP} = 'IGNORE';
506   local $SIG{PIPE} = 'IGNORE';
507
508   my $rc = $sth->execute or return $sth->errstr;
509   #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
510
511   '';
512
513 }
514
515 =item rep
516
517 Depriciated (use replace instead).
518
519 =cut
520
521 sub rep {
522   cluck "warning: FS::Record::rep depriciated!";
523   replace @_; #call method in this scope
524 }
525
526 =item check
527
528 Not yet implemented, croaks.  Derived classes should provide a check method.
529
530 =cut
531
532 sub check {
533   confess "FS::Record::check not implemented; supply one in subclass!";
534 }
535
536 =item unique COLUMN
537
538 Replaces COLUMN in record with a unique number.  Called by the B<add> method
539 on primary keys and single-field unique columns (see L<FS::dbdef_table>).
540 Returns the new value.
541
542 =cut
543
544 sub unique {
545   my($self,$field) = @_;
546   my($table)=$self->table;
547
548   croak("&FS::UID::checkruid failed") unless &checkruid;
549
550   croak "Unique called on field $field, but it is ",
551         $self->getfield($field),
552         ", not null!"
553     if $self->getfield($field);
554
555   #warn "table $table is tainted" if is_tainted($table);
556   #warn "field $field is tainted" if is_tainted($field);
557
558   &swapuid;
559   my($counter) = new File::CounterFile "$table.$field",0;
560 # hack for web demo
561 #  getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
562 #  my($user)=$1;
563 #  my($counter) = new File::CounterFile "$user/$table.$field",0;
564 # endhack
565
566   my($index)=$counter->inc;
567   $index=$counter->inc
568     while qsearchs($table,{$field=>$index}); #just in case
569   &swapuid;
570
571   $index =~ /^(\d*)$/;
572   $index=$1;
573
574   $self->setfield($field,$index);
575
576 }
577
578 =item ut_float COLUMN
579
580 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10.  May not be
581 null.  If there is an error, returns the error, otherwise returns false.
582
583 =cut
584
585 sub ut_float {
586   my($self,$field)=@_ ;
587   ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
588    $self->getfield($field) =~ /^(\d+)$/ ||
589    $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
590    $self->getfield($field) =~ /^(\d+e\d+)$/)
591     or return "Illegal or empty (float) $field: ". $self->getfield($field);
592   $self->setfield($field,$1);
593   '';
594 }
595
596 =item ut_number COLUMN
597
598 Check/untaint simple numeric data (whole numbers).  May not be null.  If there
599 is an error, returns the error, otherwise returns false.
600
601 =cut
602
603 sub ut_number {
604   my($self,$field)=@_;
605   $self->getfield($field) =~ /^(\d+)$/
606     or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
607   $self->setfield($field,$1);
608   '';
609 }
610
611 =item ut_numbern COLUMN
612
613 Check/untaint simple numeric data (whole numbers).  May be null.  If there is
614 an error, returns the error, otherwise returns false.
615
616 =cut
617
618 sub ut_numbern {
619   my($self,$field)=@_;
620   $self->getfield($field) =~ /^(\d*)$/
621     or return "Illegal (numeric) $field: ". $self->getfield($field);
622   $self->setfield($field,$1);
623   '';
624 }
625
626 =item ut_money COLUMN
627
628 Check/untaint monetary numbers.  May be negative.  Set to 0 if null.  If there
629 is an error, returns the error, otherwise returns false.
630
631 =cut
632
633 sub ut_money {
634   my($self,$field)=@_;
635   $self->setfield($field, 0) if $self->getfield($field) eq '';
636   $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
637     or return "Illegal (money) $field: ". $self->getfield($field);
638   #$self->setfield($field, "$1$2$3" || 0);
639   $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
640   '';
641 }
642
643 =item ut_text COLUMN
644
645 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
646 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
647 May not be null.  If there is an error, returns the error, otherwise returns
648 false.
649
650 =cut
651
652 sub ut_text {
653   my($self,$field)=@_;
654   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]+)$/
655     or return "Illegal or empty (text) $field: ". $self->getfield($field);
656   $self->setfield($field,$1);
657   '';
658 }
659
660 =item ut_textn COLUMN
661
662 Check/untaint text.  Alphanumerics, spaces, and the following punctuation
663 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
664 May be null.  If there is an error, returns the error, otherwise returns false.
665
666 =cut
667
668 sub ut_textn {
669   my($self,$field)=@_;
670   $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]*)$/
671     or return "Illegal (text) $field: ". $self->getfield($field);
672   $self->setfield($field,$1);
673   '';
674 }
675
676 =item ut_alpha COLUMN
677
678 Check/untaint alphanumeric strings (no spaces).  May not be null.  If there is
679 an error, returns the error, otherwise returns false.
680
681 =cut
682
683 sub ut_alpha {
684   my($self,$field)=@_;
685   $self->getfield($field) =~ /^(\w+)$/
686     or return "Illegal or empty (alphanumeric) $field: ".
687               $self->getfield($field);
688   $self->setfield($field,$1);
689   '';
690 }
691
692 =item ut_alpha COLUMN
693
694 Check/untaint alphanumeric strings (no spaces).  May be null.  If there is an
695 error, returns the error, otherwise returns false.
696
697 =cut
698
699 sub ut_alphan {
700   my($self,$field)=@_;
701   $self->getfield($field) =~ /^(\w*)$/ 
702     or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
703   $self->setfield($field,$1);
704   '';
705 }
706
707 =item ut_phonen COLUMN [ COUNTRY ]
708
709 Check/untaint phone numbers.  May be null.  If there is an error, returns
710 the error, otherwise returns false.
711
712 Takes an optional two-letter ISO country code; without it or with unsupported
713 countries, ut_phonen simply calls ut_alphan.
714
715 =cut
716
717 sub ut_phonen {
718   my( $self, $field, $country ) = @_;
719   return $self->ut_alphan($field) unless defined $country;
720   my $phonen = $self->getfield($field);
721   if ( $phonen eq '' ) {
722     $self->setfield($field,'');
723   } elsif ( $country eq 'US' ) {
724     $phonen =~ s/\D//g;
725     $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
726       or return "Illegal (phone) $field: ". $self->getfield($field);
727     $phonen = "$1-$2-$3";
728     $phonen .= " x$4" if $4;
729     $self->setfield($field,$phonen);
730   } else {
731     warn "don't know how to check phone numbers for country $country";
732     return $self->ut_alphan($field);
733   }
734   '';
735 }
736
737 =item ut_ip COLUMN
738
739 Check/untaint ip addresses.  IPv4 only for now.
740
741 =cut
742
743 sub ut_ip {
744   my( $self, $field ) = @_;
745   $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
746     or return "Illegal (IP address) $field: ". $self->getfield($field);
747   for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
748   $self->setfield($field, "$1.$2.$3.$3");
749   '';
750 }
751
752 =item ut_ipn COLUMN
753
754 Check/untaint ip addresses.  IPv4 only for now.  May be null.
755
756 =cut
757
758 sub ut_ipn {
759   my( $self, $field ) = @_;
760   if ( $self->getfield($field) =~ /^()$/ ) {
761     $self->setfield($field,'');
762     '';
763   } else {
764     $self->ut_ip($field);
765   }
766 }
767
768 =item ut_domain COLUMN
769
770 Check/untaint host and domain names.
771
772 =cut
773
774 sub ut_domain {
775   my( $self, $field ) = @_;
776   #$self->getfield($field) =~/^(\w+\.)*\w+$/
777   $self->getfield($field) =~/^(\w+\.)*\w+$/
778     or return "Illegal (domain) $field: ". $self->getfield($field);
779   $self->setfield($field,$1);
780   '';
781 }
782
783 =cut
784
785 =item ut_anything COLUMN
786
787 Untaints arbitrary data.  Be careful.
788
789 =cut
790
791 sub ut_anything {
792   my($self,$field)=@_;
793   $self->getfield($field) =~ /^(.*)$/
794     or return "Illegal $field: ". $self->getfield($field);
795   $self->setfield($field,$1);
796   '';
797 }
798
799 =item fields [ TABLE ]
800
801 This can be used as both a subroutine and a method call.  It returns a list
802 of the columns in this record's table, or an explicitly specified table.
803 (See L<FS::dbdef_table>).
804
805 =cut
806
807 # Usage: @fields = fields($table);
808 #        @fields = $record->fields;
809 sub fields {
810   my $something = shift;
811   my $table;
812   if ( ref($something) ) {
813     $table = $something->table;
814   } else {
815     $table = $something;
816   }
817   #croak "Usage: \@fields = fields(\$table)\n   or: \@fields = \$record->fields" unless $table;
818   my($table_obj) = $dbdef->table($table);
819   croak "Unknown table $table" unless $table_obj;
820   $table_obj->columns;
821 }
822
823 =head1 SUBROUTINES
824
825 =over 4
826
827 =item reload_dbdef([FILENAME])
828
829 Load a database definition (see L<FS::dbdef>), optionally from a non-default
830 filename.  This command is executed at startup unless
831 I<$FS::Record::setup_hack> is true.  Returns a FS::dbdef object.
832
833 =cut
834
835 sub reload_dbdef {
836   my $file = shift || $dbdef_file;
837   $dbdef = load FS::dbdef ($file);
838 }
839
840 =item dbdef
841
842 Returns the current database definition.  See L<FS::dbdef>.
843
844 =cut
845
846 sub dbdef { $dbdef; }
847
848 =item _quote VALUE, TABLE, COLUMN
849
850 This is an internal function used to construct SQL statements.  It returns
851 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
852 type (see L<FS::dbdef_column>) does not end in `char' or `binary'.
853
854 =cut
855
856 sub _quote {
857   my($value,$table,$field)=@_;
858   my($dbh)=dbh;
859   if ( $value =~ /^\d+(\.\d+)?$/ && 
860 #       ! ( datatype($table,$field) =~ /^char/ ) 
861        ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i ) 
862   ) {
863     $value;
864   } else {
865     $dbh->quote($value);
866   }
867 }
868
869 =item hfields TABLE
870
871 This is depriciated.  Don't use it.
872
873 It returns a hash-type list with the fields of this record's table set true.
874
875 =cut
876
877 sub hfields {
878   carp "warning: hfields is depriciated";
879   my($table)=@_;
880   my(%hash);
881   foreach (fields($table)) {
882     $hash{$_}=1;
883   }
884   \%hash;
885 }
886
887 #sub _dump {
888 #  my($self)=@_;
889 #  join("\n", map {
890 #    "$_: ". $self->getfield($_). "|"
891 #  } (fields($self->table)) );
892 #}
893
894 #sub DESTROY {
895 #  my $self = shift;
896 #  #use Carp qw(cluck);
897 #  #cluck "DESTROYING $self";
898 #  warn "DESTROYING $self";
899 #}
900
901 #sub is_tainted {
902 #             return ! eval { join('',@_), kill 0; 1; };
903 #         }
904
905 =back
906
907 =head1 VERSION
908
909 $Id: Record.pm,v 1.10 2000-12-03 20:25:20 ivan Exp $
910
911 =head1 BUGS
912
913 This module should probably be renamed, since much of the functionality is
914 of general use.  It is not completely unlike Adapter::DBI (see below).
915
916 Exported qsearch and qsearchs should be depriciated in favor of method calls
917 (against an FS::Record object like the old search and searchs that qsearch
918 and qsearchs were on top of.)
919
920 The whole fields / hfields mess should be removed.
921
922 The various WHERE clauses should be subroutined.
923
924 table string should be depriciated in favor of FS::dbdef_table.
925
926 No doubt we could benefit from a Tied hash.  Documenting how exists / defined
927 true maps to the database (and WHERE clauses) would also help.
928
929 The ut_ methods should ask the dbdef for a default length.
930
931 ut_sqltype (like ut_varchar) should all be defined
932
933 A fallback check method should be provided which uses the dbdef.
934
935 The ut_money method assumes money has two decimal digits.
936
937 The Pg money kludge in the new method only strips `$'.
938
939 The ut_phonen method assumes US-style phone numbers.
940
941 The _quote function should probably use ut_float instead of a regex.
942
943 All the subroutines probably should be methods, here or elsewhere.
944
945 Probably should borrow/use some dbdef methods where appropriate (like sub
946 fields)
947
948 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
949 or allow it to be set.  Working around it is ugly any way around - DBI should
950 be fixed.  (only affects RDBMS which return uppercase column names)
951
952 =head1 SEE ALSO
953
954 L<FS::dbdef>, L<FS::UID>, L<DBI>
955
956 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
957
958 =cut
959
960 1;
961