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