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 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->insert;
55 #$error = $record->add; #depriciated
57 $error = $record->delete;
58 #$error = $record->del; #depriciated
60 $error = $new_record->replace($old_record);
61 #$error = $new_record->rep($old_record); #depriciated
63 $value = $record->unique('column');
65 $value = $record->ut_float('column');
66 $value = $record->ut_number('column');
67 $value = $record->ut_numbern('column');
68 $value = $record->ut_money('column');
69 $value = $record->ut_text('column');
70 $value = $record->ut_textn('column');
71 $value = $record->ut_alpha('column');
72 $value = $record->ut_alphan('column');
73 $value = $record->ut_phonen('column');
74 $value = $record->ut_anythingn('column');
76 $dbdef = reload_dbdef;
77 $dbdef = reload_dbdef "/non/standard/filename";
80 $quoted_value = _quote($value,'table','field');
83 $fields = hfields('table');
84 if ( $fields->{Field} ) { # etc.
86 @fields = fields 'table'; #as a subroutine
87 @fields = $record->fields; #as a method call
92 (Mostly) object-oriented interface to database records. Records are currently
93 implemented on top of DBI. FS::Record is intended as a base class for
94 table-specific classes to inherit from, i.e. FS::cust_main.
100 =item new [ TABLE, ] HASHREF
102 Creates a new record. It doesn't store it in the database, though. See
103 L<"insert"> for that.
105 Note that the object stores this hash reference, not a distinct copy of the
106 hash it points to. You can ask the object for a copy with the I<hash>
109 TABLE can only be omitted when a dervived class overrides the table method.
115 my $class = ref($proto) || $proto;
117 bless ($self, $class);
119 $self->{'Table'} = shift unless defined ( $self->table );
121 my $hashref = $self->{'Hash'} = shift;
123 foreach my $field ( $self->fields ) {
124 $hashref->{$field}='' unless defined $hashref->{$field};
125 #trim the '$' and ',' from money fields for Pg (belong HERE?)
126 #(what about Pg i18n?)
127 if ( datasrc =~ m/Pg/
128 && $self->dbdef_table->column($field)->type eq 'money' ) {
129 ${$hashref}{$field} =~ s/^\$//;
130 ${$hashref}{$field} =~ s/\,//;
139 my $class = ref($proto) || $proto;
141 bless ($self, $class);
142 if ( defined $self->table ) {
143 cluck "create constructor is depriciated, use new!";
146 croak "FS::Record::create called (not from a subclass)!";
150 =item qsearch TABLE, HASHREF
152 Searches the database for all records matching (at least) the key/value pairs
153 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
154 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
160 my($table,$record) = @_;
163 my(@fields)=grep exists($record->{$_}), fields($table);
166 my($statement) = "SELECT * FROM $table". ( @fields
167 ? " WHERE ". join(' AND ',
172 : "( $_ IS NULL OR $_ = \"\" )"
174 : "$_ = ". _quote($record->{$_},$table,$_)
178 $sth=$dbh->prepare($statement)
179 or croak $dbh->errstr; #is that a little too harsh? hmm.
180 #warn $statement #if $debug # or some such;
182 if ( eval ' scalar(@FS::'. $table. '::ISA);' ) {
184 eval 'new 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 "warning: Multiple records in scalar search!" if scalar(@result) > 1;
206 #should warn more vehemently if the search was on a primary key?
218 Returns the table name.
223 # cluck "warning: FS::Record::table depriciated; supply one in subclass!";
230 Returns the FS::dbdef_table object for the table.
236 my($table)=$self->table;
237 $dbdef->table($table);
240 =item get, getfield COLUMN
242 Returns the value of the column/field/key COLUMN.
247 my($self,$field) = @_;
248 # to avoid "Use of unitialized value" errors
249 if ( defined ( $self->{Hash}->{$field} ) ) {
250 $self->{Hash}->{$field};
260 =item set, setfield COLUMN, VALUE
262 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
267 my($self,$field,$value) = @_;
268 $self->{'Hash'}->{$field} = $value;
275 =item AUTLOADED METHODS
277 $record->column is a synonym for $record->get('column');
279 $record->column('value') is a synonym for $record->set('column','value');
285 my($field)=$AUTOLOAD;
287 if ( defined($value) ) {
288 $self->setfield($field,$value);
290 $self->getfield($field);
296 Returns a list of the column/value pairs, usually for assigning to a new hash.
298 To make a distinct duplicate of an FS::Record object, you can do:
300 $new = new FS::Record ( $old->table, { $old->hash } );
306 %{ $self->{'Hash'} };
311 Returns a reference to the column/value hash.
322 Inserts this record to the database. If there is an error, returns the error,
323 otherwise returns false.
330 my $error = $self->check;
331 return $error if $error;
333 #single-field unique keys are given a value if false
334 #(like MySQL's AUTO_INCREMENT)
335 foreach ( $self->dbdef_table->unique->singles ) {
336 $self->unique($_) unless $self->getfield($_);
338 #and also the primary key
339 my $primary_key = $self->dbdef_table->primary_key;
340 $self->unique($primary_key)
341 if $primary_key && ! $self->getfield($primary_key);
344 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
348 my $statement = "INSERT INTO ". $self->table. " ( ".
351 join(', ',map(_quote($self->getfield($_),$self->table,$_), @fields)).
354 my $sth = dbh->prepare($statement) or return dbh->errstr;
356 local $SIG{HUP} = 'IGNORE';
357 local $SIG{INT} = 'IGNORE';
358 local $SIG{QUIT} = 'IGNORE';
359 local $SIG{TERM} = 'IGNORE';
360 local $SIG{TSTP} = 'IGNORE';
361 local $SIG{PIPE} = 'IGNORE';
363 $sth->execute or return $sth->errstr;
370 Depriciated (use insert instead).
375 cluck "warning: FS::Record::add depriciated!";
376 insert @_; #call method in this scope
381 Delete this record from the database. If there is an error, returns the error,
382 otherwise returns false.
389 my($statement)="DELETE FROM ". $self->table. " WHERE ". join(' AND ',
391 $self->getfield($_) eq ''
392 #? "( $_ IS NULL OR $_ = \"\" )"
395 : "( $_ IS NULL OR $_ = \"\" )"
397 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
398 } ( $self->dbdef_table->primary_key )
399 ? ( $self->dbdef_table->primary_key)
402 my $sth = dbh->prepare($statement) or return dbh->errstr;
404 local $SIG{HUP} = 'IGNORE';
405 local $SIG{INT} = 'IGNORE';
406 local $SIG{QUIT} = 'IGNORE';
407 local $SIG{TERM} = 'IGNORE';
408 local $SIG{TSTP} = 'IGNORE';
409 local $SIG{PIPE} = 'IGNORE';
411 my $rc = $sth->execute or return $sth->errstr;
412 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
414 undef $self; #no need to keep object!
421 Depriciated (use delete instead).
426 cluck "warning: FS::Record::del depriciated!";
427 &delete(@_); #call method in this scope
430 =item replace OLD_RECORD
432 Replace the OLD_RECORD with this one in the database. If there is an error,
433 returns the error, otherwise returns false.
438 my ( $new, $old ) = ( shift, shift );
440 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
442 carp "warning: records identical";
446 return "Records not in same table!" unless $new->table eq $old->table;
448 my $primary_key = $old->dbdef_table->primary_key;
449 return "Can't change $primary_key"
451 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
453 my $error = $new->check;
454 return $error if $error;
456 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
458 "$_ = ". _quote($new->getfield($_),$old->table,$_)
463 $old->getfield($_) eq ''
464 #? "( $_ IS NULL OR $_ = \"\" )"
467 : "( $_ IS NULL OR $_ = \"\" )"
469 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
470 } ( $primary_key ? ( $primary_key ) : $old->fields )
473 my $sth = dbh->prepare($statement) or return dbh->errstr;
475 local $SIG{HUP} = 'IGNORE';
476 local $SIG{INT} = 'IGNORE';
477 local $SIG{QUIT} = 'IGNORE';
478 local $SIG{TERM} = 'IGNORE';
479 local $SIG{TSTP} = 'IGNORE';
480 local $SIG{PIPE} = 'IGNORE';
482 my $rc = $sth->execute or return $sth->errstr;
483 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
491 Depriciated (use replace instead).
496 cluck "warning: FS::Record::rep depriciated!";
497 replace @_; #call method in this scope
502 Not yet implemented, croaks. Derived classes should provide a check method.
507 croak "FS::Record::check not implemented; supply one in subclass!";
512 Replaces COLUMN in record with a unique number. Called by the B<add> method
513 on primary keys and single-field unique columns (see L<FS::dbdef_table>).
514 Returns the new value.
519 my($self,$field) = @_;
520 my($table)=$self->table;
522 croak("&FS::UID::checkruid failed") unless &checkruid;
524 croak "Unique called on field $field, but it is ",
525 $self->getfield($field),
527 if $self->getfield($field);
529 #warn "table $table is tainted" if is_tainted($table);
530 #warn "field $field is tainted" if is_tainted($field);
533 my($counter) = new File::CounterFile "$table.$field",0;
535 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
537 # my($counter) = new File::CounterFile "$user/$table.$field",0;
540 my($index)=$counter->inc;
542 while qsearchs($table,{$field=>$index}); #just in case
548 $self->setfield($field,$index);
552 =item ut_float COLUMN
554 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
555 null. If there is an error, returns the error, otherwise returns false.
560 my($self,$field)=@_ ;
561 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
562 $self->getfield($field) =~ /^(\d+)$/ ||
563 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
564 $self->getfield($field) =~ /^(\d+e\d+)$/)
565 or return "Illegal or empty (float) $field: ". $self->getfield($field);
566 $self->setfield($field,$1);
570 =item ut_number COLUMN
572 Check/untaint simple numeric data (whole numbers). May not be null. If there
573 is an error, returns the error, otherwise returns false.
579 $self->getfield($field) =~ /^(\d+)$/
580 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
581 $self->setfield($field,$1);
585 =item ut_numbern COLUMN
587 Check/untaint simple numeric data (whole numbers). May be null. If there is
588 an error, returns the error, otherwise returns false.
594 $self->getfield($field) =~ /^(\d*)$/
595 or return "Illegal (numeric) $field: ". $self->getfield($field);
596 $self->setfield($field,$1);
600 =item ut_money COLUMN
602 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
603 is an error, returns the error, otherwise returns false.
609 $self->setfield($field, 0) if $self->getfield($field) eq '';
610 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
611 or return "Illegal (money) $field: ". $self->getfield($field);
612 #$self->setfield($field, "$1$2$3" || 0);
613 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
619 Check/untaint text. Alphanumerics, spaces, and the following punctuation
620 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
621 May not be null. If there is an error, returns the error, otherwise returns
628 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]+)$/
629 or return "Illegal or empty (text) $field: ". $self->getfield($field);
630 $self->setfield($field,$1);
634 =item ut_textn COLUMN
636 Check/untaint text. Alphanumerics, spaces, and the following punctuation
637 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
638 May be null. If there is an error, returns the error, otherwise returns false.
644 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]*)$/
645 or return "Illegal (text) $field: ". $self->getfield($field);
646 $self->setfield($field,$1);
650 =item ut_alpha COLUMN
652 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
653 an error, returns the error, otherwise returns false.
659 $self->getfield($field) =~ /^(\w+)$/
660 or return "Illegal or empty (alphanumeric) $field: ".
661 $self->getfield($field);
662 $self->setfield($field,$1);
666 =item ut_alpha COLUMN
668 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
669 error, returns the error, otherwise returns false.
675 $self->getfield($field) =~ /^(\w*)$/
676 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
677 $self->setfield($field,$1);
681 =item ut_phonen COLUMN
683 Check/untaint phone numbers. May be null. If there is an error, returns
684 the error, otherwise returns false.
690 my $phonen = $self->getfield($field);
691 if ( $phonen eq '' ) {
692 $self->setfield($field,'');
695 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
696 or return "Illegal (phone) $field: ". $self->getfield($field);
697 $phonen = "$1-$2-$3";
698 $phonen .= " x$4" if $4;
699 $self->setfield($field,$phonen);
704 =item ut_anything COLUMN
706 Untaints arbitrary data. Be careful.
712 $self->getfield($field) =~ /^(.*)$/
713 or return "Illegal $field: ". $self->getfield($field);
714 $self->setfield($field,$1);
718 =item fields [ TABLE ]
720 This can be used as both a subroutine and a method call. It returns a list
721 of the columns in this record's table, or an explicitly specified table.
722 (See L<dbdef_table>).
726 # Usage: @fields = fields($table);
727 # @fields = $record->fields;
729 my $something = shift;
731 if ( ref($something) ) {
732 $table = $something->table;
736 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
737 my($table_obj) = $dbdef->table($table);
738 croak "Unknown table $table" unless $table_obj;
746 =item reload_dbdef([FILENAME])
748 Load a database definition (see L<FS::dbdef>), optionally from a non-default
749 filename. This command is executed at startup unless
750 I<$FS::Record::setup_hack> is true. Returns a FS::dbdef object.
755 my $file = shift || $dbdef_file;
756 $dbdef = load FS::dbdef ($file);
761 Returns the current database definition. See L<FS::dbdef>.
765 sub dbdef { $dbdef; }
767 =item _quote VALUE, TABLE, COLUMN
769 This is an internal function used to construct SQL statements. It returns
770 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
771 type (see L<dbdef_column>) does not end in `char' or `binary'.
776 my($value,$table,$field)=@_;
778 if ( $value =~ /^\d+(\.\d+)?$/ &&
779 # ! ( datatype($table,$field) =~ /^char/ )
780 ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i )
790 This is depriciated. Don't use it.
792 It returns a hash-type list with the fields of this record's table set true.
797 carp "warning: hfields is depriciated";
800 foreach (fields($table)) {
809 # "$_: ". $self->getfield($_). "|"
810 # } (fields($self->table)) );
815 # #use Carp qw(cluck);
816 # #cluck "DESTROYING $self";
817 # warn "DESTROYING $self";
821 # return ! eval { join('',@_), kill 0; 1; };
828 $Id: Record.pm,v 1.16 1999-04-10 07:03:38 ivan Exp $
832 This module should probably be renamed, since much of the functionality is
833 of general use. It is not completely unlike Adapter::DBI (see below).
835 Exported qsearch and qsearchs should be depriciated in favor of method calls
836 (against an FS::Record object like the old search and searchs that qsearch
837 and qsearchs were on top of.)
839 The whole fields / hfields mess should be removed.
841 The various WHERE clauses should be subroutined.
843 table string should be depriciated in favor of FS::dbdef_table.
845 No doubt we could benefit from a Tied hash. Documenting how exists / defined
846 true maps to the database (and WHERE clauses) would also help.
848 The ut_ methods should ask the dbdef for a default length.
850 ut_sqltype (like ut_varchar) should all be defined
852 A fallback check method should be provided whith uses the dbdef.
854 The ut_money method assumes money has two decimal digits.
856 The Pg money kludge in the new method only strips `$'.
858 The ut_phonen method assumes US-style phone numbers.
860 The _quote function should probably use ut_float instead of a regex.
862 All the subroutines probably should be methods, here or elsewhere.
864 Probably should borrow/use some dbdef methods where appropriate (like sub
869 L<FS::dbdef>, L<FS::UID>, L<DBI>
871 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.
875 ivan@voicenet.com 97-jun-2 - 9, 19, 25, 27, 30
878 ivan@sisd.com 97-nov-8 - 12
880 cleaned up, added autoloaded $self->any_field calls, moved DBI login stuff
882 ivan@sisd.com 97-nov-21-23
884 since AUTO_INCREMENT is MySQL specific, use my own unique number generator
886 ivan@sisd.com 97-dec-4
888 untaint $user in unique (web demo hack...bah)
889 make unique skip multiple-field unique's from dbdef
890 ivan@sisd.com 97-dec-11
892 merge with FS::Search, which after all was just alternate constructors for
893 FS::Record objects. Makes lots of things cleaner. :)
894 ivan@sisd.com 97-dec-13
896 use FS::dbdef::primary key in replace searches, hopefully for all practical
897 purposes the string/number problem in SQL statements should be gone?
899 ivan@sisd.com 98-jan-20
901 Put all SQL statments in $statment before we $sth=$dbh->prepare( them,
902 for debugging reasons (warn $statement) ivan@sisd.com 98-feb-19
904 (sigh)... use dbdef type (char, etc.) instead of a regex to decide
905 what to quote in _quote (more sillines...) SQL bites.
906 ivan@sisd.com 98-feb-20
908 more friendly error messages ivan@sisd.com 98-mar-13
910 Added import of datasrc from FS::UID to allow Pg6.3 to work
911 Added code to right-trim strings read from Pg6.3 databases
912 Modified 'add' to only insert fields that actually have data
913 Added ut_float to handle floating point numbers (for sales tax).
914 Pg6.3 does not have a "SHOW FIELDS" statement, so I faked it 8).
915 bmccane@maxbaud.net 98-apr-3
917 commented out Pg wrapper around `` Modified 'add' to only insert fields that
918 actually have data '' ivan@sisd.com 98-apr-16
920 dbdef usage changes ivan@sisd.com 98-jun-1
922 sub fields now asks dbdef, not database ivan@sisd.com 98-jun-2
924 added debugging method ->_dump ivan@sisd.com 98-jun-16
926 use FS::dbdef::primary key in delete searches as well as replace
927 searches (SQL still bites) ivan@sisd.com 98-jun-22
929 sub dbdef_table ivan@sisd.com 98-jun-28
931 removed Pg wrapper around `` Modified 'add' to only insert fields that
932 actually have data '' ivan@sisd.com 98-jul-14
934 sub fields croaks on errors ivan@sisd.com 98-jul-17
936 $rc eq '0E0' doesn't mean we couldn't delete for all rdbmss
937 ivan@sisd.com 98-jul-18
939 commented out code to right-trim strings read from Pg6.3 databases;
940 ChopBlanks is in UID.pm ivan@sisd.com 98-aug-16
942 added code (with Pg wrapper) to deal with Pg money fields
943 ivan@sisd.com 98-aug-18
945 added pod documentation ivan@sisd.com 98-sep-6
947 ut_phonen got ''; at the end ivan@sisd.com 98-sep-27
950 Revision 1.16 1999-04-10 07:03:38 ivan
951 return the value with ut_* error messages, to assist in debugging
953 Revision 1.15 1999/04/08 12:08:59 ivan
954 fix up PostgreSQL money fields so you can actually use them as numbers. bah.
956 Revision 1.14 1999/04/07 14:58:31 ivan
957 more kludges to get around different null/empty handling in Perl vs. MySQL vs.
960 Revision 1.13 1999/03/29 11:55:43 ivan
961 eliminate warnings in ut_money
963 Revision 1.12 1999/01/25 12:26:06 ivan
964 yet more mod_perl stuff
966 Revision 1.11 1999/01/18 09:22:38 ivan
967 changes to track email addresses for email invoicing
969 Revision 1.10 1998/12/29 11:59:33 ivan
970 mostly properly OO, some work still to be done with svc_ stuff
972 Revision 1.9 1998/11/21 07:26:45 ivan
973 "Records identical" carp tells us it is just a warning.
975 Revision 1.8 1998/11/15 11:02:04 ivan
978 Revision 1.7 1998/11/15 10:56:31 ivan
979 qsearch gets sames "IS NULL" semantics as other WHERE clauses
981 Revision 1.6 1998/11/15 05:31:03 ivan
982 bugfix for new config layout
984 Revision 1.5 1998/11/13 09:56:51 ivan
985 change configuration file layout to support multiple distinct databases (with
986 own set of config files, export, etc.)
988 Revision 1.4 1998/11/10 07:45:25 ivan
991 Revision 1.2 1998/11/07 05:17:18 ivan
992 In sub new, Pg wrapper for money fields from dbdef (FS::Record::fields $table),
993 not keys of supplied hashref.