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