4 use vars qw($dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG);
5 use subs qw(reload_dbdef);
7 use Carp qw(carp cluck croak confess);
10 use FS::UID qw(dbh checkruid swapuid getotaker datasrc driver_name);
13 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef);
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?
26 FS::Record - Database record objects
31 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
33 $record = new FS::Record 'table', \%hash;
34 $record = new FS::Record 'table', { 'column' => 'value', ... };
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', ... };
41 $table = $record->table;
42 $dbdef_table = $record->dbdef_table;
44 $value = $record->get('column');
45 $value = $record->getfield('column');
46 $value = $record->column;
48 $record->set( 'column' => 'value' );
49 $record->setfield( 'column' => 'value' );
50 $record->column('value');
52 %hash = $record->hash;
54 $hashref = $record->hashref;
56 $error = $record->insert;
57 #$error = $record->add; #depriciated
59 $error = $record->delete;
60 #$error = $record->del; #depriciated
62 $error = $new_record->replace($old_record);
63 #$error = $new_record->rep($old_record); #depriciated
65 $value = $record->unique('column');
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 $value = $record->ut_name('column');
79 $dbdef = reload_dbdef;
80 $dbdef = reload_dbdef "/non/standard/filename";
83 $quoted_value = _quote($value,'table','field');
86 $fields = hfields('table');
87 if ( $fields->{Field} ) { # etc.
89 @fields = fields 'table'; #as a subroutine
90 @fields = $record->fields; #as a method call
95 (Mostly) object-oriented interface to database records. Records are currently
96 implemented on top of DBI. FS::Record is intended as a base class for
97 table-specific classes to inherit from, i.e. FS::cust_main.
103 =item new [ TABLE, ] HASHREF
105 Creates a new record. It doesn't store it in the database, though. See
106 L<"insert"> for that.
108 Note that the object stores this hash reference, not a distinct copy of the
109 hash it points to. You can ask the object for a copy with the I<hash>
112 TABLE can only be omitted when a dervived class overrides the table method.
118 my $class = ref($proto) || $proto;
120 bless ($self, $class);
122 $self->{'Table'} = shift unless defined ( $self->table );
124 my $hashref = $self->{'Hash'} = shift;
126 foreach my $field ( $self->fields ) {
127 $hashref->{$field}='' unless defined $hashref->{$field};
128 #trim the '$' and ',' from money fields for Pg (belong HERE?)
129 #(what about Pg i18n?)
130 if ( driver_name =~ /^Pg$/i
131 && $self->dbdef_table->column($field)->type eq 'money' ) {
132 ${$hashref}{$field} =~ s/^\$//;
133 ${$hashref}{$field} =~ s/\,//;
142 my $class = ref($proto) || $proto;
144 bless ($self, $class);
145 if ( defined $self->table ) {
146 cluck "create constructor is depriciated, use new!";
149 croak "FS::Record::create called (not from a subclass)!";
153 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL
155 Searches the database for all records matching (at least) the key/value pairs
156 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
157 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
160 ###oops, argh, FS::Record::new only lets us create database fields.
161 #Normal behaviour if SELECT is not specified is `*', as in
162 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
163 #feature where you can specify SELECT - remember, the objects returned,
164 #although blessed into the appropriate `FS::TABLE' package, will only have the
165 #fields you specify. This might have unwanted results if you then go calling
166 #regular FS::TABLE methods
172 my($table, $record, $select, $extra_sql ) = @_;
173 $table =~ /^([\w\_]+)$/ or die "Illegal table: $table";
178 my @fields = grep exists($record->{$_}), fields($table);
180 my $statement = "SELECT $select FROM $table";
182 $statement .= ' WHERE '. join(' AND ', map {
183 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
184 if ( driver_name =~ /^Pg$/i ) {
187 qq-( $_ IS NULL OR $_ = "" )-;
194 $statement .= " $extra_sql" if defined($extra_sql);
196 warn $statement if $DEBUG;
197 my $sth = $dbh->prepare($statement)
198 or croak "$dbh->errstr doing $statement";
200 $sth->execute( map $record->{$_},
201 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
202 ) or croak "Error executing \"$statement\": ". $dbh->errstr;
203 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
205 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
206 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
207 #derivied class didn't override new method, so this optimization is safe
209 new( "FS::$table", { %{$_} } )
210 } @{$sth->fetchall_arrayref( {} )};
212 warn "untested code (class FS::$table uses custom new method)";
214 eval 'FS::'. $table. '->new( { %{$_} } )';
215 } @{$sth->fetchall_arrayref( {} )};
218 cluck "warning: FS::$table not loaded; returning FS::Record objects";
220 FS::Record->new( $table, { %{$_} } );
221 } @{$sth->fetchall_arrayref( {} )};
226 =item qsearchs TABLE, HASHREF
228 Same as qsearch, except that if more than one record matches, it B<carp>s but
229 returns the first. If this happens, you either made a logic error in asking
230 for a single item, or your data is corrupted.
234 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
235 my(@result) = qsearch(@_);
236 carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
237 #should warn more vehemently if the search was on a primary key?
238 scalar(@result) ? ($result[0]) : ();
249 Returns the table name.
254 # cluck "warning: FS::Record::table depriciated; supply one in subclass!";
261 Returns the FS::dbdef_table object for the table.
267 my($table)=$self->table;
268 $dbdef->table($table);
271 =item get, getfield COLUMN
273 Returns the value of the column/field/key COLUMN.
278 my($self,$field) = @_;
279 # to avoid "Use of unitialized value" errors
280 if ( defined ( $self->{Hash}->{$field} ) ) {
281 $self->{Hash}->{$field};
291 =item set, setfield COLUMN, VALUE
293 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
298 my($self,$field,$value) = @_;
299 $self->{'Hash'}->{$field} = $value;
306 =item AUTLOADED METHODS
308 $record->column is a synonym for $record->get('column');
310 $record->column('value') is a synonym for $record->set('column','value');
316 my($field)=$AUTOLOAD;
318 if ( defined($value) ) {
319 confess "errant AUTOLOAD $field for $self (arg $value)"
320 unless $self->can('setfield');
321 $self->setfield($field,$value);
323 $self->getfield($field);
329 Returns a list of the column/value pairs, usually for assigning to a new hash.
331 To make a distinct duplicate of an FS::Record object, you can do:
333 $new = new FS::Record ( $old->table, { $old->hash } );
339 %{ $self->{'Hash'} };
344 Returns a reference to the column/value hash.
355 Inserts this record to the database. If there is an error, returns the error,
356 otherwise returns false.
363 my $error = $self->check;
364 return $error if $error;
366 #single-field unique keys are given a value if false
367 #(like MySQL's AUTO_INCREMENT)
368 foreach ( $self->dbdef_table->unique->singles ) {
369 $self->unique($_) unless $self->getfield($_);
371 #and also the primary key
372 my $primary_key = $self->dbdef_table->primary_key;
373 $self->unique($primary_key)
374 if $primary_key && ! $self->getfield($primary_key);
377 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
381 my $statement = "INSERT INTO ". $self->table. " ( ".
384 join(', ',map(_quote($self->getfield($_),$self->table,$_), @fields)).
387 my $sth = dbh->prepare($statement) or return dbh->errstr;
389 local $SIG{HUP} = 'IGNORE';
390 local $SIG{INT} = 'IGNORE';
391 local $SIG{QUIT} = 'IGNORE';
392 local $SIG{TERM} = 'IGNORE';
393 local $SIG{TSTP} = 'IGNORE';
394 local $SIG{PIPE} = 'IGNORE';
396 $sth->execute or return $sth->errstr;
397 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
404 Depriciated (use insert instead).
409 cluck "warning: FS::Record::add depriciated!";
410 insert @_; #call method in this scope
415 Delete this record from the database. If there is an error, returns the error,
416 otherwise returns false.
423 my($statement)="DELETE FROM ". $self->table. " WHERE ". join(' AND ',
425 $self->getfield($_) eq ''
426 #? "( $_ IS NULL OR $_ = \"\" )"
427 ? ( driver_name =~ /^Pg$/i
429 : "( $_ IS NULL OR $_ = \"\" )"
431 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
432 } ( $self->dbdef_table->primary_key )
433 ? ( $self->dbdef_table->primary_key)
436 my $sth = dbh->prepare($statement) or return dbh->errstr;
438 local $SIG{HUP} = 'IGNORE';
439 local $SIG{INT} = 'IGNORE';
440 local $SIG{QUIT} = 'IGNORE';
441 local $SIG{TERM} = 'IGNORE';
442 local $SIG{TSTP} = 'IGNORE';
443 local $SIG{PIPE} = 'IGNORE';
445 my $rc = $sth->execute or return $sth->errstr;
446 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
447 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
449 undef $self; #no need to keep object!
456 Depriciated (use delete instead).
461 cluck "warning: FS::Record::del depriciated!";
462 &delete(@_); #call method in this scope
465 =item replace OLD_RECORD
467 Replace the OLD_RECORD with this one in the database. If there is an error,
468 returns the error, otherwise returns false.
473 my ( $new, $old ) = ( shift, shift );
475 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
477 carp "warning: records identical";
481 return "Records not in same table!" unless $new->table eq $old->table;
483 my $primary_key = $old->dbdef_table->primary_key;
484 return "Can't change $primary_key"
486 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
488 my $error = $new->check;
489 return $error if $error;
491 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
493 "$_ = ". _quote($new->getfield($_),$old->table,$_)
498 $old->getfield($_) eq ''
499 #? "( $_ IS NULL OR $_ = \"\" )"
500 ? ( driver_name =~ /^Pg$/i
502 : "( $_ IS NULL OR $_ = \"\" )"
504 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
505 } ( $primary_key ? ( $primary_key ) : $old->fields )
508 my $sth = dbh->prepare($statement) or return dbh->errstr;
510 local $SIG{HUP} = 'IGNORE';
511 local $SIG{INT} = 'IGNORE';
512 local $SIG{QUIT} = 'IGNORE';
513 local $SIG{TERM} = 'IGNORE';
514 local $SIG{TSTP} = 'IGNORE';
515 local $SIG{PIPE} = 'IGNORE';
517 my $rc = $sth->execute or return $sth->errstr;
518 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
519 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
527 Depriciated (use replace instead).
532 cluck "warning: FS::Record::rep depriciated!";
533 replace @_; #call method in this scope
538 Not yet implemented, croaks. Derived classes should provide a check method.
543 confess "FS::Record::check not implemented; supply one in subclass!";
548 Replaces COLUMN in record with a unique number. Called by the B<add> method
549 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
550 Returns the new value.
555 my($self,$field) = @_;
556 my($table)=$self->table;
558 croak("&FS::UID::checkruid failed") unless &checkruid;
560 croak "Unique called on field $field, but it is ",
561 $self->getfield($field),
563 if $self->getfield($field);
565 #warn "table $table is tainted" if is_tainted($table);
566 #warn "field $field is tainted" if is_tainted($field);
569 my($counter) = new File::CounterFile "$table.$field",0;
571 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
573 # my($counter) = new File::CounterFile "$user/$table.$field",0;
576 my($index)=$counter->inc;
578 while qsearchs($table,{$field=>$index}); #just in case
584 $self->setfield($field,$index);
588 =item ut_float COLUMN
590 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
591 null. If there is an error, returns the error, otherwise returns false.
596 my($self,$field)=@_ ;
597 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
598 $self->getfield($field) =~ /^(\d+)$/ ||
599 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
600 $self->getfield($field) =~ /^(\d+e\d+)$/)
601 or return "Illegal or empty (float) $field: ". $self->getfield($field);
602 $self->setfield($field,$1);
606 =item ut_number COLUMN
608 Check/untaint simple numeric data (whole numbers). May not be null. If there
609 is an error, returns the error, otherwise returns false.
615 $self->getfield($field) =~ /^(\d+)$/
616 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
617 $self->setfield($field,$1);
621 =item ut_numbern COLUMN
623 Check/untaint simple numeric data (whole numbers). May be null. If there is
624 an error, returns the error, otherwise returns false.
630 $self->getfield($field) =~ /^(\d*)$/
631 or return "Illegal (numeric) $field: ". $self->getfield($field);
632 $self->setfield($field,$1);
636 =item ut_money COLUMN
638 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
639 is an error, returns the error, otherwise returns false.
645 $self->setfield($field, 0) if $self->getfield($field) eq '';
646 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
647 or return "Illegal (money) $field: ". $self->getfield($field);
648 #$self->setfield($field, "$1$2$3" || 0);
649 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
655 Check/untaint text. Alphanumerics, spaces, and the following punctuation
656 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
657 May not be null. If there is an error, returns the error, otherwise returns
664 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]+)$/
665 or return "Illegal or empty (text) $field: ". $self->getfield($field);
666 $self->setfield($field,$1);
670 =item ut_textn COLUMN
672 Check/untaint text. Alphanumerics, spaces, and the following punctuation
673 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
674 May be null. If there is an error, returns the error, otherwise returns false.
680 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]*)$/
681 or return "Illegal (text) $field: ". $self->getfield($field);
682 $self->setfield($field,$1);
686 =item ut_alpha COLUMN
688 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
689 an error, returns the error, otherwise returns false.
695 $self->getfield($field) =~ /^(\w+)$/
696 or return "Illegal or empty (alphanumeric) $field: ".
697 $self->getfield($field);
698 $self->setfield($field,$1);
702 =item ut_alpha COLUMN
704 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
705 error, returns the error, otherwise returns false.
711 $self->getfield($field) =~ /^(\w*)$/
712 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
713 $self->setfield($field,$1);
717 =item ut_phonen COLUMN [ COUNTRY ]
719 Check/untaint phone numbers. May be null. If there is an error, returns
720 the error, otherwise returns false.
722 Takes an optional two-letter ISO country code; without it or with unsupported
723 countries, ut_phonen simply calls ut_alphan.
728 my( $self, $field, $country ) = @_;
729 return $self->ut_alphan($field) unless defined $country;
730 my $phonen = $self->getfield($field);
731 if ( $phonen eq '' ) {
732 $self->setfield($field,'');
733 } elsif ( $country eq 'US' ) {
735 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
736 or return "Illegal (phone) $field: ". $self->getfield($field);
737 $phonen = "$1-$2-$3";
738 $phonen .= " x$4" if $4;
739 $self->setfield($field,$phonen);
741 warn "don't know how to check phone numbers for country $country";
742 return $self->ut_alphan($field);
749 Check/untaint ip addresses. IPv4 only for now.
754 my( $self, $field ) = @_;
755 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
756 or return "Illegal (IP address) $field: ". $self->getfield($field);
757 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
758 $self->setfield($field, "$1.$2.$3.$3");
764 Check/untaint ip addresses. IPv4 only for now. May be null.
769 my( $self, $field ) = @_;
770 if ( $self->getfield($field) =~ /^()$/ ) {
771 $self->setfield($field,'');
774 $self->ut_ip($field);
778 =item ut_domain COLUMN
780 Check/untaint host and domain names.
785 my( $self, $field ) = @_;
786 #$self->getfield($field) =~/^(\w+\.)*\w+$/
787 $self->getfield($field) =~/^(\w+\.)*\w+$/
788 or return "Illegal (domain) $field: ". $self->getfield($field);
789 $self->setfield($field,$1);
795 Check/untaint proper names; allows alphanumerics, spaces and the following
803 my( $self, $field ) = @_;
804 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
805 or return "Illegal (name) $field: ". $self->getfield($field);
806 $self->setfield($field,$1);
812 Check/untaint zip codes.
817 my( $self, $field ) = @_;
818 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
819 or return "Illegal (zip) $field: ". $self->getfield($field);
820 $self->setfield($field,$1);
824 =item ut_anything COLUMN
826 Untaints arbitrary data. Be careful.
832 $self->getfield($field) =~ /^(.*)$/
833 or return "Illegal $field: ". $self->getfield($field);
834 $self->setfield($field,$1);
838 =item fields [ TABLE ]
840 This can be used as both a subroutine and a method call. It returns a list
841 of the columns in this record's table, or an explicitly specified table.
842 (See L<DBIx::DBSchema::Table>).
846 # Usage: @fields = fields($table);
847 # @fields = $record->fields;
849 my $something = shift;
851 if ( ref($something) ) {
852 $table = $something->table;
856 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
857 my($table_obj) = $dbdef->table($table);
858 croak "Unknown table $table" unless $table_obj;
868 =item reload_dbdef([FILENAME])
870 Load a database definition (see L<DBIx::DBSchema>), optionally from a
871 non-default filename. This command is executed at startup unless
872 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
877 my $file = shift || $dbdef_file;
878 $dbdef = load DBIx::DBSchema $file;
883 Returns the current database definition. See L<FS::dbdef>.
887 sub dbdef { $dbdef; }
889 =item _quote VALUE, TABLE, COLUMN
891 This is an internal function used to construct SQL statements. It returns
892 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
893 type (see L<FS::dbdef_column>) does not end in `char' or `binary'.
898 my($value,$table,$field)=@_;
900 if ( $value =~ /^\d+(\.\d+)?$/ &&
901 # ! ( datatype($table,$field) =~ /^char/ )
902 ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i )
912 This is depriciated. Don't use it.
914 It returns a hash-type list with the fields of this record's table set true.
919 carp "warning: hfields is depriciated";
922 foreach (fields($table)) {
931 # "$_: ". $self->getfield($_). "|"
932 # } (fields($self->table)) );
935 sub DESTROY { return; }
939 # #use Carp qw(cluck);
940 # #cluck "DESTROYING $self";
941 # warn "DESTROYING $self";
945 # return ! eval { join('',@_), kill 0; 1; };
952 $Id: Record.pm,v 1.20 2001-08-08 04:44:41 ivan Exp $
956 This module should probably be renamed, since much of the functionality is
957 of general use. It is not completely unlike Adapter::DBI (see below).
959 Exported qsearch and qsearchs should be depriciated in favor of method calls
960 (against an FS::Record object like the old search and searchs that qsearch
961 and qsearchs were on top of.)
963 The whole fields / hfields mess should be removed.
965 The various WHERE clauses should be subroutined.
967 table string should be depriciated in favor of FS::dbdef_table.
969 No doubt we could benefit from a Tied hash. Documenting how exists / defined
970 true maps to the database (and WHERE clauses) would also help.
972 The ut_ methods should ask the dbdef for a default length.
974 ut_sqltype (like ut_varchar) should all be defined
976 A fallback check method should be provided which uses the dbdef.
978 The ut_money method assumes money has two decimal digits.
980 The Pg money kludge in the new method only strips `$'.
982 The ut_phonen method only checks US-style phone numbers.
984 The _quote function should probably use ut_float instead of a regex.
986 All the subroutines probably should be methods, here or elsewhere.
988 Probably should borrow/use some dbdef methods where appropriate (like sub
991 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
992 or allow it to be set. Working around it is ugly any way around - DBI should
993 be fixed. (only affects RDBMS which return uppercase column names)
995 ut_zip should take an optional country like ut_phone.
999 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1001 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.