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