4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 use subs qw(reload_dbdef);
8 use Carp qw(carp cluck croak confess);
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.19;
13 use FS::UID qw(dbh checkruid getotaker datasrc driver_name);
17 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
22 #ask FS::UID to run this stuff for us later
23 $FS::UID::callback{'FS::Record'} = sub {
24 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
25 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
26 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
31 FS::Record - Database record objects
36 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
38 $record = new FS::Record 'table', \%hash;
39 $record = new FS::Record 'table', { 'column' => 'value', ... };
41 $record = qsearchs FS::Record 'table', \%hash;
42 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
43 @records = qsearch FS::Record 'table', \%hash;
44 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
46 $table = $record->table;
47 $dbdef_table = $record->dbdef_table;
49 $value = $record->get('column');
50 $value = $record->getfield('column');
51 $value = $record->column;
53 $record->set( 'column' => 'value' );
54 $record->setfield( 'column' => 'value' );
55 $record->column('value');
57 %hash = $record->hash;
59 $hashref = $record->hashref;
61 $error = $record->insert;
62 #$error = $record->add; #deprecated
64 $error = $record->delete;
65 #$error = $record->del; #deprecated
67 $error = $new_record->replace($old_record);
68 #$error = $new_record->rep($old_record); #deprecated
70 $value = $record->unique('column');
72 $error = $record->ut_float('column');
73 $error = $record->ut_number('column');
74 $error = $record->ut_numbern('column');
75 $error = $record->ut_money('column');
76 $error = $record->ut_text('column');
77 $error = $record->ut_textn('column');
78 $error = $record->ut_alpha('column');
79 $error = $record->ut_alphan('column');
80 $error = $record->ut_phonen('column');
81 $error = $record->ut_anything('column');
82 $error = $record->ut_name('column');
84 $dbdef = reload_dbdef;
85 $dbdef = reload_dbdef "/non/standard/filename";
88 $quoted_value = _quote($value,'table','field');
91 $fields = hfields('table');
92 if ( $fields->{Field} ) { # etc.
94 @fields = fields 'table'; #as a subroutine
95 @fields = $record->fields; #as a method call
100 (Mostly) object-oriented interface to database records. Records are currently
101 implemented on top of DBI. FS::Record is intended as a base class for
102 table-specific classes to inherit from, i.e. FS::cust_main.
108 =item new [ TABLE, ] HASHREF
110 Creates a new record. It doesn't store it in the database, though. See
111 L<"insert"> for that.
113 Note that the object stores this hash reference, not a distinct copy of the
114 hash it points to. You can ask the object for a copy with the I<hash>
117 TABLE can only be omitted when a dervived class overrides the table method.
123 my $class = ref($proto) || $proto;
125 bless ($self, $class);
127 unless ( defined ( $self->table ) ) {
128 $self->{'Table'} = shift;
129 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
132 my $hashref = $self->{'Hash'} = shift;
134 foreach my $field ( $self->fields ) {
135 $hashref->{$field}='' unless defined $hashref->{$field};
136 #trim the '$' and ',' from money fields for Pg (belong HERE?)
137 #(what about Pg i18n?)
138 if ( driver_name =~ /^Pg$/i
139 && $self->dbdef_table->column($field)->type eq 'money' ) {
140 ${$hashref}{$field} =~ s/^\$//;
141 ${$hashref}{$field} =~ s/\,//;
145 $self->_cache($hashref, shift) if $self->can('_cache') && @_;
152 my $class = ref($proto) || $proto;
154 bless ($self, $class);
156 $self->{'Table'} = shift unless defined ( $self->table );
158 my $hashref = $self->{'Hash'} = shift;
160 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
161 my $obj = $cache->cache->{$hashref->{$cache->key}};
162 $obj->_cache($hashref, $cache) if $obj->can('_cache');
165 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
172 my $class = ref($proto) || $proto;
174 bless ($self, $class);
175 if ( defined $self->table ) {
176 cluck "create constructor is depriciated, use new!";
179 croak "FS::Record::create called (not from a subclass)!";
183 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
185 Searches the database for all records matching (at least) the key/value pairs
186 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
187 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
190 ###oops, argh, FS::Record::new only lets us create database fields.
191 #Normal behaviour if SELECT is not specified is `*', as in
192 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
193 #feature where you can specify SELECT - remember, the objects returned,
194 #although blessed into the appropriate `FS::TABLE' package, will only have the
195 #fields you specify. This might have unwanted results if you then go calling
196 #regular FS::TABLE methods
202 my($stable, $record, $select, $extra_sql, $cache ) = @_;
203 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
205 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
210 my $table = $cache ? $cache->table : $stable;
212 my @fields = grep exists($record->{$_}), fields($table);
214 my $statement = "SELECT $select FROM $stable";
216 $statement .= ' WHERE '. join(' AND ', map {
219 if ( ref($record->{$_}) ) {
220 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
221 $op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name !~ /^Pg$/i;
222 $record->{$_} = $record->{$_}{'value'}
225 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
226 if ( driver_name =~ /^Pg$/i ) {
227 qq-( $_ IS NULL OR $_ = '' )-;
229 qq-( $_ IS NULL OR $_ = "" )-;
236 $statement .= " $extra_sql" if defined($extra_sql);
238 warn "[debug]$me $statement\n" if $DEBUG;
239 my $sth = $dbh->prepare($statement)
240 or croak "$dbh->errstr doing $statement";
245 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
247 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
248 && $dbdef->table($table)->column($field)->type =~ /(int)/i
250 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
252 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
256 # $sth->execute( map $record->{$_},
257 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
258 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
260 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
262 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
264 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
265 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
266 #derivied class didn't override new method, so this optimization is safe
269 new_or_cached( "FS::$table", { %{$_} }, $cache )
270 } @{$sth->fetchall_arrayref( {} )};
273 new( "FS::$table", { %{$_} } )
274 } @{$sth->fetchall_arrayref( {} )};
277 warn "untested code (class FS::$table uses custom new method)";
279 eval 'FS::'. $table. '->new( { %{$_} } )';
280 } @{$sth->fetchall_arrayref( {} )};
283 cluck "warning: FS::$table not loaded; returning FS::Record objects";
285 FS::Record->new( $table, { %{$_} } );
286 } @{$sth->fetchall_arrayref( {} )};
291 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
293 Experimental JOINed search method. Using this method, you can execute a
294 single SELECT spanning multiple tables, and cache the results for subsequent
295 method calls. Interface will almost definately change in an incompatible
303 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
304 my $cache = FS::SearchCache->new( $ptable, $pkey );
307 grep { !$saw{$_->getfield($pkey)}++ }
308 qsearch($table, $record, $select, $extra_sql, $cache )
312 =item qsearchs TABLE, HASHREF
314 Same as qsearch, except that if more than one record matches, it B<carp>s but
315 returns the first. If this happens, you either made a logic error in asking
316 for a single item, or your data is corrupted.
320 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
321 my(@result) = qsearch(@_);
322 carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
323 #should warn more vehemently if the search was on a primary key?
324 scalar(@result) ? ($result[0]) : ();
335 Returns the table name.
340 # cluck "warning: FS::Record::table depriciated; supply one in subclass!";
347 Returns the DBIx::DBSchema::Table object for the table.
353 my($table)=$self->table;
354 $dbdef->table($table);
357 =item get, getfield COLUMN
359 Returns the value of the column/field/key COLUMN.
364 my($self,$field) = @_;
365 # to avoid "Use of unitialized value" errors
366 if ( defined ( $self->{Hash}->{$field} ) ) {
367 $self->{Hash}->{$field};
377 =item set, setfield COLUMN, VALUE
379 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
384 my($self,$field,$value) = @_;
385 $self->{'Hash'}->{$field} = $value;
392 =item AUTLOADED METHODS
394 $record->column is a synonym for $record->get('column');
396 $record->column('value') is a synonym for $record->set('column','value');
402 # my($self,$value)=@_;
403 # my($field)=$AUTOLOAD;
405 # if ( defined($value) ) {
406 # confess "errant AUTOLOAD $field for $self (arg $value)"
407 # unless $self->can('setfield');
408 # $self->setfield($field,$value);
410 # confess "errant AUTOLOAD $field for $self (no args)"
411 # unless $self->can('getfield');
412 # $self->getfield($field);
418 my $field = $AUTOLOAD;
420 if ( defined($_[1]) ) {
421 $_[0]->setfield($field, $_[1]);
423 $_[0]->getfield($field);
429 Returns a list of the column/value pairs, usually for assigning to a new hash.
431 To make a distinct duplicate of an FS::Record object, you can do:
433 $new = new FS::Record ( $old->table, { $old->hash } );
439 %{ $self->{'Hash'} };
444 Returns a reference to the column/value hash.
455 Inserts this record to the database. If there is an error, returns the error,
456 otherwise returns false.
463 my $error = $self->check;
464 return $error if $error;
466 #single-field unique keys are given a value if false
467 #(like MySQL's AUTO_INCREMENT)
468 foreach ( $self->dbdef_table->unique->singles ) {
469 $self->unique($_) unless $self->getfield($_);
471 #and also the primary key
472 my $primary_key = $self->dbdef_table->primary_key;
473 $self->unique($primary_key)
474 if $primary_key && ! $self->getfield($primary_key);
476 #false laziness w/delete
478 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
481 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
484 my $statement = "INSERT INTO ". $self->table. " ( ".
485 join( ', ', @fields ).
487 join( ', ', @values ).
490 warn "[debug]$me $statement\n" if $DEBUG;
491 my $sth = dbh->prepare($statement) or return dbh->errstr;
494 if ( defined $dbdef->table('h_'. $self->table) ) {
495 my $h_statement = $self->_h_statement('insert');
496 warn "[debug]$me $h_statement\n" if $DEBUG;
497 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
502 local $SIG{HUP} = 'IGNORE';
503 local $SIG{INT} = 'IGNORE';
504 local $SIG{QUIT} = 'IGNORE';
505 local $SIG{TERM} = 'IGNORE';
506 local $SIG{TSTP} = 'IGNORE';
507 local $SIG{PIPE} = 'IGNORE';
509 $sth->execute or return $sth->errstr;
510 $h_sth->execute or return $h_sth->errstr if $h_sth;
511 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
518 Depriciated (use insert instead).
523 cluck "warning: FS::Record::add depriciated!";
524 insert @_; #call method in this scope
529 Delete this record from the database. If there is an error, returns the error,
530 otherwise returns false.
537 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
539 $self->getfield($_) eq ''
540 #? "( $_ IS NULL OR $_ = \"\" )"
541 ? ( driver_name =~ /^Pg$/i
543 : "( $_ IS NULL OR $_ = \"\" )"
545 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
546 } ( $self->dbdef_table->primary_key )
547 ? ( $self->dbdef_table->primary_key)
550 warn "[debug]$me $statement\n" if $DEBUG;
551 my $sth = dbh->prepare($statement) or return dbh->errstr;
554 if ( defined $dbdef->table('h_'. $self->table) ) {
555 my $h_statement = $self->_h_statement('delete');
556 warn "[debug]$me $h_statement\n" if $DEBUG;
557 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
562 local $SIG{HUP} = 'IGNORE';
563 local $SIG{INT} = 'IGNORE';
564 local $SIG{QUIT} = 'IGNORE';
565 local $SIG{TERM} = 'IGNORE';
566 local $SIG{TSTP} = 'IGNORE';
567 local $SIG{PIPE} = 'IGNORE';
569 my $rc = $sth->execute or return $sth->errstr;
570 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
571 $h_sth->execute or return $h_sth->errstr if $h_sth;
572 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
574 undef $self; #no need to keep object!
581 Depriciated (use delete instead).
586 cluck "warning: FS::Record::del depriciated!";
587 &delete(@_); #call method in this scope
590 =item replace OLD_RECORD
592 Replace the OLD_RECORD with this one in the database. If there is an error,
593 returns the error, otherwise returns false.
598 my ( $new, $old ) = ( shift, shift );
599 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
601 return "Records not in same table!" unless $new->table eq $old->table;
603 my $primary_key = $old->dbdef_table->primary_key;
604 return "Can't change $primary_key"
606 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
608 my $error = $new->check;
609 return $error if $error;
611 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
613 carp "[warning]$me $new -> replace $old: records identical";
617 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
619 "$_ = ". _quote($new->getfield($_),$old->table,$_)
624 $old->getfield($_) eq ''
625 #? "( $_ IS NULL OR $_ = \"\" )"
626 ? ( driver_name =~ /^Pg$/i
628 : "( $_ IS NULL OR $_ = \"\" )"
630 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
631 } ( $primary_key ? ( $primary_key ) : $old->fields )
634 warn "[debug]$me $statement\n" if $DEBUG;
635 my $sth = dbh->prepare($statement) or return dbh->errstr;
638 if ( defined $dbdef->table('h_'. $old->table) ) {
639 my $h_old_statement = $old->_h_statement('replace_old');
640 warn "[debug]$me $h_old_statement\n" if $DEBUG;
641 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
647 if ( defined $dbdef->table('h_'. $new->table) ) {
648 my $h_new_statement = $new->_h_statement('replace_new');
649 warn "[debug]$me $h_new_statement\n" if $DEBUG;
650 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
655 local $SIG{HUP} = 'IGNORE';
656 local $SIG{INT} = 'IGNORE';
657 local $SIG{QUIT} = 'IGNORE';
658 local $SIG{TERM} = 'IGNORE';
659 local $SIG{TSTP} = 'IGNORE';
660 local $SIG{PIPE} = 'IGNORE';
662 my $rc = $sth->execute or return $sth->errstr;
663 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
664 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
665 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
666 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
674 Depriciated (use replace instead).
679 cluck "warning: FS::Record::rep depriciated!";
680 replace @_; #call method in this scope
685 Not yet implemented, croaks. Derived classes should provide a check method.
690 confess "FS::Record::check not implemented; supply one in subclass!";
694 my( $self, $action ) = @_;
697 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
700 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
702 "INSERT INTO h_". $self->table. " ( ".
703 join(', ', qw(history_date history_user history_action), @fields ).
705 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
712 Replaces COLUMN in record with a unique number. Called by the B<add> method
713 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
714 Returns the new value.
719 my($self,$field) = @_;
720 my($table)=$self->table;
722 croak("&FS::UID::checkruid failed") unless &checkruid;
724 croak "Unique called on field $field, but it is ",
725 $self->getfield($field),
727 if $self->getfield($field);
729 #warn "table $table is tainted" if is_tainted($table);
730 #warn "field $field is tainted" if is_tainted($field);
732 my($counter) = new File::CounterFile "$table.$field",0;
734 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
736 # my($counter) = new File::CounterFile "$user/$table.$field",0;
739 my($index)=$counter->inc;
741 while qsearchs($table,{$field=>$index}); #just in case
746 $self->setfield($field,$index);
750 =item ut_float COLUMN
752 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
753 null. If there is an error, returns the error, otherwise returns false.
758 my($self,$field)=@_ ;
759 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
760 $self->getfield($field) =~ /^(\d+)$/ ||
761 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
762 $self->getfield($field) =~ /^(\d+e\d+)$/)
763 or return "Illegal or empty (float) $field: ". $self->getfield($field);
764 $self->setfield($field,$1);
768 =item ut_number COLUMN
770 Check/untaint simple numeric data (whole numbers). May not be null. If there
771 is an error, returns the error, otherwise returns false.
777 $self->getfield($field) =~ /^(\d+)$/
778 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
779 $self->setfield($field,$1);
783 =item ut_numbern COLUMN
785 Check/untaint simple numeric data (whole numbers). May be null. If there is
786 an error, returns the error, otherwise returns false.
792 $self->getfield($field) =~ /^(\d*)$/
793 or return "Illegal (numeric) $field: ". $self->getfield($field);
794 $self->setfield($field,$1);
798 =item ut_money COLUMN
800 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
801 is an error, returns the error, otherwise returns false.
807 $self->setfield($field, 0) if $self->getfield($field) eq '';
808 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
809 or return "Illegal (money) $field: ". $self->getfield($field);
810 #$self->setfield($field, "$1$2$3" || 0);
811 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
817 Check/untaint text. Alphanumerics, spaces, and the following punctuation
818 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
819 May not be null. If there is an error, returns the error, otherwise returns
826 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]+)$/
827 or return "Illegal or empty (text) $field: ". $self->getfield($field);
828 $self->setfield($field,$1);
832 =item ut_textn COLUMN
834 Check/untaint text. Alphanumerics, spaces, and the following punctuation
835 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
836 May be null. If there is an error, returns the error, otherwise returns false.
842 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/]*)$/
843 or return "Illegal (text) $field: ". $self->getfield($field);
844 $self->setfield($field,$1);
848 =item ut_alpha COLUMN
850 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
851 an error, returns the error, otherwise returns false.
857 $self->getfield($field) =~ /^(\w+)$/
858 or return "Illegal or empty (alphanumeric) $field: ".
859 $self->getfield($field);
860 $self->setfield($field,$1);
864 =item ut_alpha COLUMN
866 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
867 error, returns the error, otherwise returns false.
873 $self->getfield($field) =~ /^(\w*)$/
874 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
875 $self->setfield($field,$1);
879 =item ut_phonen COLUMN [ COUNTRY ]
881 Check/untaint phone numbers. May be null. If there is an error, returns
882 the error, otherwise returns false.
884 Takes an optional two-letter ISO country code; without it or with unsupported
885 countries, ut_phonen simply calls ut_alphan.
890 my( $self, $field, $country ) = @_;
891 return $self->ut_alphan($field) unless defined $country;
892 my $phonen = $self->getfield($field);
893 if ( $phonen eq '' ) {
894 $self->setfield($field,'');
895 } elsif ( $country eq 'US' || $country eq 'CA' ) {
897 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
898 or return "Illegal (phone) $field: ". $self->getfield($field);
899 $phonen = "$1-$2-$3";
900 $phonen .= " x$4" if $4;
901 $self->setfield($field,$phonen);
903 warn "warning: don't know how to check phone numbers for country $country";
904 return $self->ut_textn($field);
911 Check/untaint ip addresses. IPv4 only for now.
916 my( $self, $field ) = @_;
917 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
918 or return "Illegal (IP address) $field: ". $self->getfield($field);
919 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
920 $self->setfield($field, "$1.$2.$3.$3");
926 Check/untaint ip addresses. IPv4 only for now. May be null.
931 my( $self, $field ) = @_;
932 if ( $self->getfield($field) =~ /^()$/ ) {
933 $self->setfield($field,'');
936 $self->ut_ip($field);
940 =item ut_domain COLUMN
942 Check/untaint host and domain names.
947 my( $self, $field ) = @_;
948 #$self->getfield($field) =~/^(\w+\.)*\w+$/
949 $self->getfield($field) =~/^(\w+\.)*\w+$/
950 or return "Illegal (domain) $field: ". $self->getfield($field);
951 $self->setfield($field,$1);
957 Check/untaint proper names; allows alphanumerics, spaces and the following
965 my( $self, $field ) = @_;
966 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
967 or return "Illegal (name) $field: ". $self->getfield($field);
968 $self->setfield($field,$1);
974 Check/untaint zip codes.
979 my( $self, $field, $country ) = @_;
980 if ( $country eq 'US' ) {
981 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
982 or return "Illegal (zip) $field for country $country: ".
983 $self->getfield($field);
984 $self->setfield($field,$1);
986 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
987 or return "Illegal (zip) $field: ". $self->getfield($field);
988 $self->setfield($field,$1);
993 =item ut_country COLUMN
995 Check/untaint country codes. Country names are changed to codes, if possible -
996 see L<Locale::Country>.
1001 my( $self, $field ) = @_;
1002 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1003 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1004 && country2code($1) ) {
1005 $self->setfield($field,uc(country2code($1)));
1008 $self->getfield($field) =~ /^(\w\w)$/
1009 or return "Illegal (country) $field: ". $self->getfield($field);
1010 $self->setfield($field,uc($1));
1014 =item ut_anything COLUMN
1016 Untaints arbitrary data. Be careful.
1021 my( $self, $field ) = @_;
1022 $self->getfield($field) =~ /^(.*)$/s
1023 or return "Illegal $field: ". $self->getfield($field);
1024 $self->setfield($field,$1);
1028 =item ut_enum COLUMN CHOICES_ARRAYREF
1030 Check/untaint a column, supplying all possible choices, like the "enum" type.
1035 my( $self, $field, $choices ) = @_;
1036 foreach my $choice ( @$choices ) {
1037 if ( $self->getfield($field) eq $choice ) {
1038 $self->setfield($choice);
1042 return "Illegal (enum) field $field: ". $self->getfield($field);
1045 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1047 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1048 on the column first.
1052 sub ut_foreign_key {
1053 my( $self, $field, $table, $foreign ) = @_;
1054 qsearchs($table, { $foreign => $self->getfield($field) })
1055 or return "Can't find $field ". $self->getfield($field).
1056 " in $table.$foreign";
1060 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1062 Like ut_foreign_key, except the null value is also allowed.
1066 sub ut_foreign_keyn {
1067 my( $self, $field, $table, $foreign ) = @_;
1068 $self->getfield($field)
1069 ? $self->ut_foreign_key($field, $table, $foreign)
1073 =item fields [ TABLE ]
1075 This can be used as both a subroutine and a method call. It returns a list
1076 of the columns in this record's table, or an explicitly specified table.
1077 (See L<DBIx::DBSchema::Table>).
1081 # Usage: @fields = fields($table);
1082 # @fields = $record->fields;
1084 my $something = shift;
1086 if ( ref($something) ) {
1087 $table = $something->table;
1089 $table = $something;
1091 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1092 my($table_obj) = $dbdef->table($table);
1093 confess "Unknown table $table" unless $table_obj;
1094 $table_obj->columns;
1103 =item reload_dbdef([FILENAME])
1105 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1106 non-default filename. This command is executed at startup unless
1107 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1112 my $file = shift || $dbdef_file;
1113 $dbdef = load DBIx::DBSchema $file
1114 or die "can't load database schema from $file";
1119 Returns the current database definition. See L<DBIx::DBSchema>.
1123 sub dbdef { $dbdef; }
1125 =item _quote VALUE, TABLE, COLUMN
1127 This is an internal function used to construct SQL statements. It returns
1128 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1129 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1134 my($value,$table,$field)=@_;
1136 if ( $value =~ /^\d+(\.\d+)?$/ &&
1137 # ! ( datatype($table,$field) =~ /^char/ )
1138 ! ( $dbdef->table($table)->column($field)->type =~ /(char|binary)$/i )
1142 $dbh->quote($value);
1148 This is depriciated. Don't use it.
1150 It returns a hash-type list with the fields of this record's table set true.
1155 carp "warning: hfields is depriciated";
1158 foreach (fields($table)) {
1167 "$_: ". $self->getfield($_). "|"
1168 } (fields($self->table)) );
1171 sub DESTROY { return; }
1175 # #use Carp qw(cluck);
1176 # #cluck "DESTROYING $self";
1177 # warn "DESTROYING $self";
1181 # return ! eval { join('',@_), kill 0; 1; };
1188 This module should probably be renamed, since much of the functionality is
1189 of general use. It is not completely unlike Adapter::DBI (see below).
1191 Exported qsearch and qsearchs should be depriciated in favor of method calls
1192 (against an FS::Record object like the old search and searchs that qsearch
1193 and qsearchs were on top of.)
1195 The whole fields / hfields mess should be removed.
1197 The various WHERE clauses should be subroutined.
1199 table string should be depriciated in favor of DBIx::DBSchema::Table.
1201 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1202 true maps to the database (and WHERE clauses) would also help.
1204 The ut_ methods should ask the dbdef for a default length.
1206 ut_sqltype (like ut_varchar) should all be defined
1208 A fallback check method should be provided which uses the dbdef.
1210 The ut_money method assumes money has two decimal digits.
1212 The Pg money kludge in the new method only strips `$'.
1214 The ut_phonen method only checks US-style phone numbers.
1216 The _quote function should probably use ut_float instead of a regex.
1218 All the subroutines probably should be methods, here or elsewhere.
1220 Probably should borrow/use some dbdef methods where appropriate (like sub
1223 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1224 or allow it to be set. Working around it is ugly any way around - DBI should
1225 be fixed. (only affects RDBMS which return uppercase column names)
1227 ut_zip should take an optional country like ut_phone.
1231 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1233 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.