4 use vars qw($dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK);
5 use subs qw(reload_dbdef);
7 use Carp qw(carp cluck croak confess);
9 use FS::UID qw(dbh checkruid swapuid getotaker datasrc);
13 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef);
15 #ask FS::UID to run this stuff for us later
16 $FS::UID::callback{'FS::Record'} = sub {
17 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
18 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
19 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
24 FS::Record - Database record objects
29 use FS::Record qw(dbh fields hfields qsearch qsearchs dbdef);
31 $record = new FS::Record 'table', \%hash;
32 $record = new FS::Record 'table', { 'column' => 'value', ... };
34 $record = qsearchs FS::Record 'table', \%hash;
35 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
36 @records = qsearch FS::Record 'table', \%hash;
37 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
39 $table = $record->table;
40 $dbdef_table = $record->dbdef_table;
42 $value = $record->get('column');
43 $value = $record->getfield('column');
44 $value = $record->column;
46 $record->set( 'column' => 'value' );
47 $record->setfield( 'column' => 'value' );
48 $record->column('value');
50 %hash = $record->hash;
52 $hashref = $record->hashref;
54 $error = $record->add;
56 $error = $record->del;
58 $error = $new_record->rep($old_record);
60 $value = $record->unique('column');
62 $value = $record->ut_float('column');
63 $value = $record->ut_number('column');
64 $value = $record->ut_numbern('column');
65 $value = $record->ut_money('column');
66 $value = $record->ut_text('column');
67 $value = $record->ut_textn('column');
68 $value = $record->ut_alpha('column');
69 $value = $record->ut_alphan('column');
70 $value = $record->ut_phonen('column');
71 $value = $record->ut_anythingn('column');
73 $dbdef = reload_dbdef;
74 $dbdef = reload_dbdef "/non/standard/filename";
77 $quoted_value = _quote($value,'table','field');
80 $fields = hfields('table');
81 if ( $fields->{Field} ) { # etc.
83 @fields = fields 'table';
88 (Mostly) object-oriented interface to database records. Records are currently
89 implemented on top of DBI. FS::Record is intended as a base class for
90 table-specific classes to inherit from, i.e. FS::cust_main.
96 =item new TABLE, HASHREF
98 Creates a new record. It doesn't store it in the database, though. See
101 Note that the object stores this hash reference, not a distinct copy of the
102 hash it points to. You can ask the object for a copy with the I<hash>
108 my($proto,$table,$hashref) = @_;
109 confess "Second arguement to FS::Record->new is not a HASH ref: ",
110 ref($hashref), " ", $hashref, "\n"
111 unless ref($hashref) eq 'HASH'; #bad practice?
113 #check to make sure $table exists? (ask dbdef)
115 foreach my $field ( FS::Record::fields $table ) {
116 $hashref->{$field}='' unless defined $hashref->{$field};
119 # mySQL must rtrim the inbound text strings or store them z-terminated
120 # I simulate this for Postgres below
121 # Turned off in favor of ChopBlanks in UID.pm (see man DBI)
122 #if (datasrc =~ m/Pg/)
124 # foreach my $index (keys %$hashref)
126 # $$hashref{$index} = unpack("A255", $$hashref{$index})
127 # if ($$hashref{$index} =~ m/ $/) ;
131 foreach my $column ( FS::Record::fields $table ) {
132 #trim the '$' from money fields for Pg (beong HERE?)
133 #(what about Pg i18n?)
134 if ( datasrc =~ m/Pg/
135 && $dbdef->table($table)->column($column)->type eq 'money' ) {
136 ${$hashref}{$column} =~ s/^\$//;
138 #foreach my $column ( grep $dbdef->table($table)->column($_)->type eq 'money', keys %{$hashref} ) {
139 # ${$hashref}{$column} =~ s/^\$//;
143 my $class = ref($proto) || $proto;
144 my $self = { 'Table' => $table,
148 bless ($self, $class);
152 =item qsearch TABLE, HASHREF
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
161 # Usage: @records = &FS::Search::qsearch($table,\%hash);
162 # Each element of @records is a FS::Record object.
164 my($table,$record) = @_;
167 my(@fields)=grep exists($record->{$_}), fields($table);
170 my($statement) = "SELECT * FROM $table". ( @fields
171 ? " WHERE ". join(' AND ',
175 : "$_ = ". _quote($record->{$_},$table,$_)
179 $sth=$dbh->prepare($statement)
180 or croak $dbh->errstr; #is that a little too harsh? hmm.
182 if ( eval ' scalar(@FS::'. $table. '::ISA);' ) {
184 eval 'create FS::'. $table. ' ( $sth->fetchrow_hashref );';
185 } ( 1 .. $sth->execute );
187 cluck "qsearch: warning: FS::$table not loaded; returning generic FS::Record objects";
189 new FS::Record ($table,$sth->fetchrow_hashref);
190 } ( 1 .. $sth->execute );
195 =item qsearchs TABLE, HASHREF
197 Same as qsearch, except that if more than one record matches, it B<carp>s but
198 returns the first. If this happens, you either made a logic error in asking
199 for a single item, or your data is corrupted.
203 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
204 my(@result) = qsearch(@_);
205 carp "Multiple records in scalar search!" if scalar(@result) > 1;
206 #should warn more vehemently if the search was on a primary key?
212 Returns the table name.
223 Returns the FS::dbdef_table object for the table.
229 my($table)=$self->table;
230 $dbdef->table($table);
233 =item get, getfield COLUMN
235 Returns the value of the column/field/key COLUMN.
240 my($self,$field) = @_;
241 # to avoid "Use of unitialized value" errors
242 if ( defined ( $self->{Hash}->{$field} ) ) {
243 $self->{Hash}->{$field};
252 =item set, setfield COLUMN, VALUE
254 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
259 my($self,$field,$value) = @_;
260 $self->{'Hash'}->{$field} = $value;
266 =item AUTLOADED METHODS
268 $record->column is a synonym for $record->get('column');
270 $record->column('value') is a synonym for $record->set('column','value');
276 my($field)=$AUTOLOAD;
278 if ( defined($value) ) {
279 $self->setfield($field,$value);
281 $self->getfield($field);
287 Returns a list of the column/value pairs, usually for assigning to a new hash.
289 To make a distinct duplicate of an FS::Record object, you can do:
291 $new = new FS::Record ( $old->table, { $old->hash } );
297 %{ $self->{'Hash'} };
302 Returns a reference to the column/value hash.
313 Adds this record to the database. If there is an error, returns the error,
314 otherwise returns false.
321 my($table)=$self->table;
323 #single-field unique keys are given a value if false
324 #(like MySQL's AUTO_INCREMENT)
325 foreach ( $dbdef->table($table)->unique->singles ) {
326 $self->unique($_) unless $self->getfield($_);
328 #and also the primary key
329 my($primary_key)=$dbdef->table($table)->primary_key;
330 $self->unique($primary_key)
331 if $primary_key && ! $self->getfield($primary_key);
334 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
339 my($statement)="INSERT INTO $table ( ".
342 join(', ',map(_quote($self->getfield($_),$table,$_), @fields)).
345 $sth = $dbh->prepare($statement) or return $dbh->errstr;
347 local $SIG{HUP} = 'IGNORE';
348 local $SIG{INT} = 'IGNORE';
349 local $SIG{QUIT} = 'IGNORE';
350 local $SIG{TERM} = 'IGNORE';
351 local $SIG{TSTP} = 'IGNORE';
353 $sth->execute or return $sth->errstr;
360 Delete this record from the database. If there is an error, returns the error,
361 otherwise returns false.
368 my($table)=$self->table;
371 my($statement)="DELETE FROM $table WHERE ". join(' AND ',
373 $self->getfield($_) eq ''
375 : "$_ = ". _quote($self->getfield($_),$table,$_)
376 } ( $dbdef->table($table)->primary_key )
377 ? ($dbdef->table($table)->primary_key)
380 $sth = $dbh->prepare($statement) or return $dbh->errstr;
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';
389 $rc=$sth->execute or return $sth->errstr;
390 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
392 undef $self; #no need to keep object!
399 Replace the OLD_RECORD with this one in the database. If there is an error,
400 returns the error, otherwise returns false.
407 my($table)=$old->table;
408 my(@fields)=fields($table);
409 my(@diff)=grep $new->getfield($_) ne $old->getfield($_), @fields;
411 if ( scalar(@diff) == 0 ) {
412 carp "warning: records identical";
416 return "Records not in same table!" unless $new->table eq $table;
419 my($statement)="UPDATE $table SET ". join(', ',
421 "$_ = ". _quote($new->getfield($_),$table,$_)
426 $old->getfield($_) eq ''
428 : "$_ = ". _quote($old->getfield($_),$table,$_)
430 # } ( primary_key($table) ? (primary_key($table)) : @fields )
431 } ( $dbdef->table($table)->primary_key
432 ? ($dbdef->table($table)->primary_key)
438 $sth = $dbh->prepare($statement) or return $dbh->errstr;
440 local $SIG{HUP} = 'IGNORE';
441 local $SIG{INT} = 'IGNORE';
442 local $SIG{QUIT} = 'IGNORE';
443 local $SIG{TERM} = 'IGNORE';
444 local $SIG{TSTP} = 'IGNORE';
447 $rc=$sth->execute or return $sth->errstr;
448 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
456 Replaces COLUMN in record with a unique number. Called by the B<add> method
457 on primary keys and single-field unique columns (see L<FS::dbdef_table>).
458 Returns the new value.
463 my($self,$field) = @_;
464 my($table)=$self->table;
466 croak("&FS::UID::checkruid failed") unless &checkruid;
468 croak "Unique called on field $field, but it is ",
469 $self->getfield($field),
471 if $self->getfield($field);
473 #warn "table $table is tainted" if is_tainted($table);
474 #warn "field $field is tainted" if is_tainted($field);
477 my($counter) = new File::CounterFile "$table.$field",0;
479 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
481 # my($counter) = new File::CounterFile "$user/$table.$field",0;
484 my($index)=$counter->inc;
486 while qsearchs($table,{$field=>$index}); #just in case
492 $self->setfield($field,$index);
496 =item ut_float COLUMN
498 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
499 null. If there is an error, returns the error, otherwise returns false.
504 my($self,$field)=@_ ;
505 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
506 $self->getfield($field) =~ /^(\d+)$/ ||
507 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
508 $self->getfield($field) =~ /^(\d+e\d+)$/)
509 or return "Illegal or empty (float) $field!";
510 $self->setfield($field,$1);
514 =item ut_number COLUMN
516 Check/untaint simple numeric data (whole numbers). May not be null. If there
517 is an error, returns the error, otherwise returns false.
523 $self->getfield($field) =~ /^(\d+)$/
524 or return "Illegal or empty (numeric) $field!";
525 $self->setfield($field,$1);
529 =item ut_numbern COLUMN
531 Check/untaint simple numeric data (whole numbers). May be null. If there is
532 an error, returns the error, otherwise returns false.
538 $self->getfield($field) =~ /^(\d*)$/
539 or return "Illegal (numeric) $field!";
540 $self->setfield($field,$1);
544 =item ut_money COLUMN
546 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
547 is an error, returns the error, otherwise returns false.
553 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
554 or return "Illegal (money) $field!";
555 $self->setfield($field,"$1$2$3" || 0);
561 Check/untaint text. Alphanumerics, spaces, and the following punctuation
562 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
563 May not be null. If there is an error, returns the error, otherwise returns
570 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]+)$/
571 or return "Illegal or empty (text) $field";
572 $self->setfield($field,$1);
576 =item ut_textn COLUMN
578 Check/untaint text. Alphanumerics, spaces, and the following punctuation
579 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
580 May be null. If there is an error, returns the error, otherwise returns false.
586 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]*)$/
587 or return "Illegal (text) $field";
588 $self->setfield($field,$1);
592 =item ut_alpha COLUMN
594 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
595 an error, returns the error, otherwise returns false.
601 $self->getfield($field) =~ /^(\w+)$/
602 or return "Illegal or empty (alphanumeric) $field!";
603 $self->setfield($field,$1);
607 =item ut_alpha COLUMN
609 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
610 error, returns the error, otherwise returns false.
616 $self->getfield($field) =~ /^(\w*)$/
617 or return "Illegal (alphanumeric) $field!";
618 $self->setfield($field,$1);
622 =item ut_phonen COLUMN
624 Check/untaint phone numbers. May be null. If there is an error, returns
625 the error, otherwise returns false.
631 my $phonen = $self->getfield($field);
632 if ( $phonen eq '' ) {
633 $self->setfield($field,'');
636 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
637 or return "Illegal (phone) $field!";
638 $phonen = "$1-$2-$3";
639 $phonen .= " x$4" if $4;
640 $self->setfield($field,$phonen);
645 =item ut_anything COLUMN
647 Untaints arbitrary data. Be careful.
653 $self->getfield($field) =~ /^(.*)$/ or return "Illegal $field!";
654 $self->setfield($field,$1);
663 =item reload_dbdef([FILENAME])
665 Load a database definition (see L<FS::dbdef>), optionally from a non-default
666 filename. This command is executed at startup unless
667 I<$FS::Record::setup_hack> is true. Returns a FS::dbdef object.
672 my $file = shift || $dbdef_file;
673 $dbdef = load FS::dbdef ($file);
678 Returns the current database definition. See L<FS::dbdef>.
682 sub dbdef { $dbdef; }
684 =item _quote VALUE, TABLE, COLUMN
686 This is an internal function used to construct SQL statements. It returns
687 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
688 type (see L<dbdef_column>) does not end in `char' or `binary'.
693 my($value,$table,$field)=@_;
695 if ( $value =~ /^\d+(\.\d+)?$/ &&
696 # ! ( datatype($table,$field) =~ /^char/ )
697 ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i )
707 This is depriciated. Don't use it.
709 It returns a hash-type list with the fields of this record's table set true.
714 carp "hfields is depriciated";
717 foreach (fields($table)) {
725 This returns a list of the columns in this record's table
726 (See L<dbdef_table>).
730 # Usage: @fields = fields($table);
733 #my(@fields) = $dbdef->table($table)->columns;
734 croak "Usage: \@fields = fields(\$table)" unless $table;
735 my($table_obj) = $dbdef->table($table);
736 croak "Unknown table $table" unless $table_obj;
743 # "$_: ". $self->getfield($_). "|"
744 # } (fields($self->table)) );
749 # #use Carp qw(cluck);
750 # #cluck "DESTROYING $self";
751 # warn "DESTROYING $self";
755 # return ! eval { join('',@_), kill 0; 1; };
762 $Id: Record.pm,v 1.9 1998-11-21 07:26:45 ivan Exp $
766 This module should probably be renamed, since much of the functionality is
767 of general use. It is not completely unlike Adapter::DBI (see below).
769 Exported qsearch and qsearchs should be depriciated in favor of method calls
770 (against an FS::Record object like the old search and searchs that qsearch
771 and qsearchs were on top of.)
773 The whole fields / hfields mess should be removed.
775 The various WHERE clauses should be subroutined.
777 table string should be depriciated in favor of FS::dbdef_table.
779 No doubt we could benefit from a Tied hash. Documenting how exists / defined
780 true maps to the database (and WHERE clauses) would also help.
782 The ut_ methods should ask the dbdef for a default length.
784 ut_sqltype (like ut_varchar) should all be defined
786 A fallback check method should be provided whith uses the dbdef.
788 The ut_money method assumes money has two decimal digits.
790 The Pg money kludge in the new method only strips `$'.
792 The ut_phonen method assumes US-style phone numbers.
794 The _quote function should probably use ut_float instead of a regex.
796 All the subroutines probably should be methods, here or elsewhere.
800 L<FS::dbdef>, L<FS::UID>, L<DBI>
802 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
806 ivan@voicenet.com 97-jun-2 - 9, 19, 25, 27, 30
809 ivan@sisd.com 97-nov-8 - 12
811 cleaned up, added autoloaded $self->any_field calls, moved DBI login stuff
813 ivan@sisd.com 97-nov-21-23
815 since AUTO_INCREMENT is MySQL specific, use my own unique number generator
817 ivan@sisd.com 97-dec-4
819 untaint $user in unique (web demo hack...bah)
820 make unique skip multiple-field unique's from dbdef
821 ivan@sisd.com 97-dec-11
823 merge with FS::Search, which after all was just alternate constructors for
824 FS::Record objects. Makes lots of things cleaner. :)
825 ivan@sisd.com 97-dec-13
827 use FS::dbdef::primary key in replace searches, hopefully for all practical
828 purposes the string/number problem in SQL statements should be gone?
830 ivan@sisd.com 98-jan-20
832 Put all SQL statments in $statment before we $sth=$dbh->prepare( them,
833 for debugging reasons (warn $statement) ivan@sisd.com 98-feb-19
835 (sigh)... use dbdef type (char, etc.) instead of a regex to decide
836 what to quote in _quote (more sillines...) SQL bites.
837 ivan@sisd.com 98-feb-20
839 more friendly error messages ivan@sisd.com 98-mar-13
841 Added import of datasrc from FS::UID to allow Pg6.3 to work
842 Added code to right-trim strings read from Pg6.3 databases
843 Modified 'add' to only insert fields that actually have data
844 Added ut_float to handle floating point numbers (for sales tax).
845 Pg6.3 does not have a "SHOW FIELDS" statement, so I faked it 8).
846 bmccane@maxbaud.net 98-apr-3
848 commented out Pg wrapper around `` Modified 'add' to only insert fields that
849 actually have data '' ivan@sisd.com 98-apr-16
851 dbdef usage changes ivan@sisd.com 98-jun-1
853 sub fields now asks dbdef, not database ivan@sisd.com 98-jun-2
855 added debugging method ->_dump ivan@sisd.com 98-jun-16
857 use FS::dbdef::primary key in delete searches as well as replace
858 searches (SQL still bites) ivan@sisd.com 98-jun-22
860 sub dbdef_table ivan@sisd.com 98-jun-28
862 removed Pg wrapper around `` Modified 'add' to only insert fields that
863 actually have data '' ivan@sisd.com 98-jul-14
865 sub fields croaks on errors ivan@sisd.com 98-jul-17
867 $rc eq '0E0' doesn't mean we couldn't delete for all rdbmss
868 ivan@sisd.com 98-jul-18
870 commented out code to right-trim strings read from Pg6.3 databases;
871 ChopBlanks is in UID.pm ivan@sisd.com 98-aug-16
873 added code (with Pg wrapper) to deal with Pg money fields
874 ivan@sisd.com 98-aug-18
876 added pod documentation ivan@sisd.com 98-sep-6
878 ut_phonen got ''; at the end ivan@sisd.com 98-sep-27
881 Revision 1.9 1998-11-21 07:26:45 ivan
882 "Records identical" carp tells us it is just a warning.
884 Revision 1.8 1998/11/15 11:02:04 ivan
887 Revision 1.7 1998/11/15 10:56:31 ivan
888 qsearch gets sames "IS NULL" semantics as other WHERE clauses
890 Revision 1.6 1998/11/15 05:31:03 ivan
891 bugfix for new config layout
893 Revision 1.5 1998/11/13 09:56:51 ivan
894 change configuration file layout to support multiple distinct databases (with
895 own set of config files, export, etc.)
897 Revision 1.4 1998/11/10 07:45:25 ivan
900 Revision 1.2 1998/11/07 05:17:18 ivan
901 In sub new, Pg wrapper for money fields from dbdef (FS::Record::fields $table),
902 not keys of supplied hashref.