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.23;
13 use FS::UID qw(dbh checkruid getotaker datasrc driver_name);
15 use FS::Msgcat qw(gettext);
18 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
23 #ask FS::UID to run this stuff for us later
24 $FS::UID::callback{'FS::Record'} = sub {
25 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
26 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
27 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
32 FS::Record - Database record objects
37 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
39 $record = new FS::Record 'table', \%hash;
40 $record = new FS::Record 'table', { 'column' => 'value', ... };
42 $record = qsearchs FS::Record 'table', \%hash;
43 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
44 @records = qsearch FS::Record 'table', \%hash;
45 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
47 $table = $record->table;
48 $dbdef_table = $record->dbdef_table;
50 $value = $record->get('column');
51 $value = $record->getfield('column');
52 $value = $record->column;
54 $record->set( 'column' => 'value' );
55 $record->setfield( 'column' => 'value' );
56 $record->column('value');
58 %hash = $record->hash;
60 $hashref = $record->hashref;
62 $error = $record->insert;
63 #$error = $record->add; #deprecated
65 $error = $record->delete;
66 #$error = $record->del; #deprecated
68 $error = $new_record->replace($old_record);
69 #$error = $new_record->rep($old_record); #deprecated
71 $value = $record->unique('column');
73 $error = $record->ut_float('column');
74 $error = $record->ut_number('column');
75 $error = $record->ut_numbern('column');
76 $error = $record->ut_money('column');
77 $error = $record->ut_text('column');
78 $error = $record->ut_textn('column');
79 $error = $record->ut_alpha('column');
80 $error = $record->ut_alphan('column');
81 $error = $record->ut_phonen('column');
82 $error = $record->ut_anything('column');
83 $error = $record->ut_name('column');
85 $dbdef = reload_dbdef;
86 $dbdef = reload_dbdef "/non/standard/filename";
89 $quoted_value = _quote($value,'table','field');
92 $fields = hfields('table');
93 if ( $fields->{Field} ) { # etc.
95 @fields = fields 'table'; #as a subroutine
96 @fields = $record->fields; #as a method call
101 (Mostly) object-oriented interface to database records. Records are currently
102 implemented on top of DBI. FS::Record is intended as a base class for
103 table-specific classes to inherit from, i.e. FS::cust_main.
109 =item new [ TABLE, ] HASHREF
111 Creates a new record. It doesn't store it in the database, though. See
112 L<"insert"> for that.
114 Note that the object stores this hash reference, not a distinct copy of the
115 hash it points to. You can ask the object for a copy with the I<hash>
118 TABLE can only be omitted when a dervived class overrides the table method.
124 my $class = ref($proto) || $proto;
126 bless ($self, $class);
128 unless ( defined ( $self->table ) ) {
129 $self->{'Table'} = shift;
130 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
133 my $hashref = $self->{'Hash'} = shift;
135 foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) {
136 $hashref->{$field}='';
139 $self->_cache($hashref, shift) if $self->can('_cache') && @_;
146 my $class = ref($proto) || $proto;
148 bless ($self, $class);
150 $self->{'Table'} = shift unless defined ( $self->table );
152 my $hashref = $self->{'Hash'} = shift;
154 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
155 my $obj = $cache->cache->{$hashref->{$cache->key}};
156 $obj->_cache($hashref, $cache) if $obj->can('_cache');
159 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
166 my $class = ref($proto) || $proto;
168 bless ($self, $class);
169 if ( defined $self->table ) {
170 cluck "create constructor is depriciated, use new!";
173 croak "FS::Record::create called (not from a subclass)!";
177 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
179 Searches the database for all records matching (at least) the key/value pairs
180 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
181 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
184 ###oops, argh, FS::Record::new only lets us create database fields.
185 #Normal behaviour if SELECT is not specified is `*', as in
186 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
187 #feature where you can specify SELECT - remember, the objects returned,
188 #although blessed into the appropriate `FS::TABLE' package, will only have the
189 #fields you specify. This might have unwanted results if you then go calling
190 #regular FS::TABLE methods
196 my($stable, $record, $select, $extra_sql, $cache ) = @_;
197 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
199 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
204 my $table = $cache ? $cache->table : $stable;
206 my @fields = grep exists($record->{$_}), fields($table);
208 my $statement = "SELECT $select FROM $stable";
210 $statement .= ' WHERE '. join(' AND ', map {
214 if ( ref($record->{$_}) ) {
215 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
216 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name !~ /^Pg$/i;
217 if ( uc($op) eq 'ILIKE' ) {
219 $record->{$_}{'value'} = lc($record->{$_}{'value'});
220 $column = "LOWER($_)";
222 $record->{$_} = $record->{$_}{'value'}
225 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
227 if ( driver_name eq 'Pg' ) {
228 my $type = $dbdef->table($table)->column($column)->type;
229 if ( $type =~ /(int|serial)/i ) {
230 qq-( $column IS NULL )-;
232 qq-( $column IS NULL OR $column = '' )-;
235 qq-( $column IS NULL OR $column = "" )-;
237 } elsif ( $op eq '!=' ) {
238 if ( driver_name eq 'Pg' ) {
239 my $type = $dbdef->table($table)->column($column)->type;
240 if ( $type =~ /(int|serial)/i ) {
241 qq-( $column IS NOT NULL )-;
243 qq-( $column IS NOT NULL AND $column != '' )-;
246 qq-( $column IS NOT NULL AND $column != "" )-;
249 if ( driver_name eq 'Pg' ) {
250 qq-( $column $op '' )-;
252 qq-( $column $op "" )-;
260 $statement .= " $extra_sql" if defined($extra_sql);
262 warn "[debug]$me $statement\n" if $DEBUG > 1;
263 my $sth = $dbh->prepare($statement)
264 or croak "$dbh->errstr doing $statement";
269 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
271 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
272 && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
274 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
276 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
280 # $sth->execute( map $record->{$_},
281 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
282 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
284 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
286 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
288 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
289 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
290 #derivied class didn't override new method, so this optimization is safe
293 new_or_cached( "FS::$table", { %{$_} }, $cache )
294 } @{$sth->fetchall_arrayref( {} )};
297 new( "FS::$table", { %{$_} } )
298 } @{$sth->fetchall_arrayref( {} )};
301 warn "untested code (class FS::$table uses custom new method)";
303 eval 'FS::'. $table. '->new( { %{$_} } )';
304 } @{$sth->fetchall_arrayref( {} )};
307 cluck "warning: FS::$table not loaded; returning FS::Record objects";
309 FS::Record->new( $table, { %{$_} } );
310 } @{$sth->fetchall_arrayref( {} )};
315 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
317 Experimental JOINed search method. Using this method, you can execute a
318 single SELECT spanning multiple tables, and cache the results for subsequent
319 method calls. Interface will almost definately change in an incompatible
327 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
328 my $cache = FS::SearchCache->new( $ptable, $pkey );
331 grep { !$saw{$_->getfield($pkey)}++ }
332 qsearch($table, $record, $select, $extra_sql, $cache )
336 =item qsearchs TABLE, HASHREF
338 Same as qsearch, except that if more than one record matches, it B<carp>s but
339 returns the first. If this happens, you either made a logic error in asking
340 for a single item, or your data is corrupted.
344 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
346 my(@result) = qsearch(@_);
347 carp "warning: Multiple records in scalar search ($table)"
348 if scalar(@result) > 1;
349 #should warn more vehemently if the search was on a primary key?
350 scalar(@result) ? ($result[0]) : ();
361 Returns the table name.
366 # cluck "warning: FS::Record::table depriciated; supply one in subclass!";
373 Returns the DBIx::DBSchema::Table object for the table.
379 my($table)=$self->table;
380 $dbdef->table($table);
383 =item get, getfield COLUMN
385 Returns the value of the column/field/key COLUMN.
390 my($self,$field) = @_;
391 # to avoid "Use of unitialized value" errors
392 if ( defined ( $self->{Hash}->{$field} ) ) {
393 $self->{Hash}->{$field};
403 =item set, setfield COLUMN, VALUE
405 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
410 my($self,$field,$value) = @_;
411 $self->{'Hash'}->{$field} = $value;
418 =item AUTLOADED METHODS
420 $record->column is a synonym for $record->get('column');
422 $record->column('value') is a synonym for $record->set('column','value');
429 my($field)=$AUTOLOAD;
431 if ( defined($value) ) {
432 confess "errant AUTOLOAD $field for $self (arg $value)"
433 unless ref($self) && $self->can('setfield');
434 $self->setfield($field,$value);
436 confess "errant AUTOLOAD $field for $self (no args)"
437 unless ref($self) && $self->can('getfield');
438 $self->getfield($field);
444 # my $field = $AUTOLOAD;
446 # if ( defined($_[1]) ) {
447 # $_[0]->setfield($field, $_[1]);
449 # $_[0]->getfield($field);
455 Returns a list of the column/value pairs, usually for assigning to a new hash.
457 To make a distinct duplicate of an FS::Record object, you can do:
459 $new = new FS::Record ( $old->table, { $old->hash } );
465 confess $self. ' -> hash: Hash attribute is undefined'
466 unless defined($self->{'Hash'});
467 %{ $self->{'Hash'} };
472 Returns a reference to the column/value hash.
483 Inserts this record to the database. If there is an error, returns the error,
484 otherwise returns false.
491 my $error = $self->check;
492 return $error if $error;
494 #single-field unique keys are given a value if false
495 #(like MySQL's AUTO_INCREMENT)
496 foreach ( $self->dbdef_table->unique->singles ) {
497 $self->unique($_) unless $self->getfield($_);
499 #and also the primary key
500 my $primary_key = $self->dbdef_table->primary_key;
501 $self->unique($primary_key)
502 if $primary_key && ! $self->getfield($primary_key);
504 #false laziness w/delete
506 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
509 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
512 my $statement = "INSERT INTO ". $self->table. " ( ".
513 join( ', ', @fields ).
515 join( ', ', @values ).
518 warn "[debug]$me $statement\n" if $DEBUG > 1;
519 my $sth = dbh->prepare($statement) or return dbh->errstr;
522 if ( defined $dbdef->table('h_'. $self->table) ) {
523 my $h_statement = $self->_h_statement('insert');
524 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
525 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
530 local $SIG{HUP} = 'IGNORE';
531 local $SIG{INT} = 'IGNORE';
532 local $SIG{QUIT} = 'IGNORE';
533 local $SIG{TERM} = 'IGNORE';
534 local $SIG{TSTP} = 'IGNORE';
535 local $SIG{PIPE} = 'IGNORE';
537 $sth->execute or return $sth->errstr;
538 $h_sth->execute or return $h_sth->errstr if $h_sth;
539 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
546 Depriciated (use insert instead).
551 cluck "warning: FS::Record::add depriciated!";
552 insert @_; #call method in this scope
557 Delete this record from the database. If there is an error, returns the error,
558 otherwise returns false.
565 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
567 $self->getfield($_) eq ''
568 #? "( $_ IS NULL OR $_ = \"\" )"
569 ? ( driver_name =~ /^Pg$/i
571 : "( $_ IS NULL OR $_ = \"\" )"
573 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
574 } ( $self->dbdef_table->primary_key )
575 ? ( $self->dbdef_table->primary_key)
578 warn "[debug]$me $statement\n" if $DEBUG > 1;
579 my $sth = dbh->prepare($statement) or return dbh->errstr;
582 if ( defined $dbdef->table('h_'. $self->table) ) {
583 my $h_statement = $self->_h_statement('delete');
584 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
585 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
590 local $SIG{HUP} = 'IGNORE';
591 local $SIG{INT} = 'IGNORE';
592 local $SIG{QUIT} = 'IGNORE';
593 local $SIG{TERM} = 'IGNORE';
594 local $SIG{TSTP} = 'IGNORE';
595 local $SIG{PIPE} = 'IGNORE';
597 my $rc = $sth->execute or return $sth->errstr;
598 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
599 $h_sth->execute or return $h_sth->errstr if $h_sth;
600 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
602 #no need to needlessly destoy the data either (causes problems actually)
603 #undef $self; #no need to keep object!
610 Depriciated (use delete instead).
615 cluck "warning: FS::Record::del depriciated!";
616 &delete(@_); #call method in this scope
619 =item replace OLD_RECORD
621 Replace the OLD_RECORD with this one in the database. If there is an error,
622 returns the error, otherwise returns false.
633 warn "[debug]$me replace called with no arguments; autoloading old record\n"
635 my $primary_key = $new->dbdef_table->primary_key;
636 if ( $primary_key ) {
637 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
638 or croak "can't find ". $new->table. ".$primary_key ".
639 $new->$primary_key();
641 croak $new->table. " has no primary key; pass old record as argument";
645 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
647 return "Records not in same table!" unless $new->table eq $old->table;
649 my $primary_key = $old->dbdef_table->primary_key;
650 return "Can't change $primary_key"
652 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
654 my $error = $new->check;
655 return $error if $error;
657 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
659 carp "[warning]$me $new -> replace $old: records identical";
663 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
665 "$_ = ". _quote($new->getfield($_),$old->table,$_)
670 $old->getfield($_) eq ''
671 #? "( $_ IS NULL OR $_ = \"\" )"
672 ? ( driver_name =~ /^Pg$/i
673 ? "( $_ IS NULL OR $_ = '' ) "
674 : "( $_ IS NULL OR $_ = \"\" )"
676 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
677 } ( $primary_key ? ( $primary_key ) : $old->fields )
680 warn "[debug]$me $statement\n" if $DEBUG > 1;
681 my $sth = dbh->prepare($statement) or return dbh->errstr;
684 if ( defined $dbdef->table('h_'. $old->table) ) {
685 my $h_old_statement = $old->_h_statement('replace_old');
686 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
687 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
693 if ( defined $dbdef->table('h_'. $new->table) ) {
694 my $h_new_statement = $new->_h_statement('replace_new');
695 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
696 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
701 local $SIG{HUP} = 'IGNORE';
702 local $SIG{INT} = 'IGNORE';
703 local $SIG{QUIT} = 'IGNORE';
704 local $SIG{TERM} = 'IGNORE';
705 local $SIG{TSTP} = 'IGNORE';
706 local $SIG{PIPE} = 'IGNORE';
708 my $rc = $sth->execute or return $sth->errstr;
709 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
710 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
711 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
712 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
720 Depriciated (use replace instead).
725 cluck "warning: FS::Record::rep depriciated!";
726 replace @_; #call method in this scope
731 Not yet implemented, croaks. Derived classes should provide a check method.
736 confess "FS::Record::check not implemented; supply one in subclass!";
740 my( $self, $action ) = @_;
743 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
746 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
748 "INSERT INTO h_". $self->table. " ( ".
749 join(', ', qw(history_date history_user history_action), @fields ).
751 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
758 Replaces COLUMN in record with a unique number. Called by the B<add> method
759 on primary keys and single-field unique columns (see L<DBIx::DBSchema::Table>).
760 Returns the new value.
765 my($self,$field) = @_;
766 my($table)=$self->table;
768 #croak("&FS::UID::checkruid failed") unless &checkruid;
770 croak "Unique called on field $field, but it is ",
771 $self->getfield($field),
773 if $self->getfield($field);
775 #warn "table $table is tainted" if is_tainted($table);
776 #warn "field $field is tainted" if is_tainted($field);
778 my($counter) = new File::CounterFile "$table.$field",0;
780 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
782 # my($counter) = new File::CounterFile "$user/$table.$field",0;
785 my($index)=$counter->inc;
787 while qsearchs($table,{$field=>$index}); #just in case
792 $self->setfield($field,$index);
796 =item ut_float COLUMN
798 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
799 null. If there is an error, returns the error, otherwise returns false.
804 my($self,$field)=@_ ;
805 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
806 $self->getfield($field) =~ /^(\d+)$/ ||
807 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
808 $self->getfield($field) =~ /^(\d+e\d+)$/)
809 or return "Illegal or empty (float) $field: ". $self->getfield($field);
810 $self->setfield($field,$1);
814 =item ut_snumber COLUMN
816 Check/untaint signed numeric data (whole numbers). May not be null. If there
817 is an error, returns the error, otherwise returns false.
822 my($self, $field) = @_;
823 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
824 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
825 $self->setfield($field, "$1$2");
829 =item ut_number COLUMN
831 Check/untaint simple numeric data (whole numbers). May not be null. If there
832 is an error, returns the error, otherwise returns false.
838 $self->getfield($field) =~ /^(\d+)$/
839 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
840 $self->setfield($field,$1);
844 =item ut_numbern COLUMN
846 Check/untaint simple numeric data (whole numbers). May be null. If there is
847 an error, returns the error, otherwise returns false.
853 $self->getfield($field) =~ /^(\d*)$/
854 or return "Illegal (numeric) $field: ". $self->getfield($field);
855 $self->setfield($field,$1);
859 =item ut_money COLUMN
861 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
862 is an error, returns the error, otherwise returns false.
868 $self->setfield($field, 0) if $self->getfield($field) eq '';
869 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
870 or return "Illegal (money) $field: ". $self->getfield($field);
871 #$self->setfield($field, "$1$2$3" || 0);
872 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
878 Check/untaint text. Alphanumerics, spaces, and the following punctuation
879 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
880 May not be null. If there is an error, returns the error, otherwise returns
887 #warn "msgcat ". \&msgcat. "\n";
888 #warn "notexist ". \¬exist. "\n";
889 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
890 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
891 or return gettext('illegal_or_empty_text'). " $field: ".
892 $self->getfield($field);
893 $self->setfield($field,$1);
897 =item ut_textn COLUMN
899 Check/untaint text. Alphanumerics, spaces, and the following punctuation
900 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
901 May be null. If there is an error, returns the error, otherwise returns false.
907 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
908 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
909 $self->setfield($field,$1);
913 =item ut_alpha COLUMN
915 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
916 an error, returns the error, otherwise returns false.
922 $self->getfield($field) =~ /^(\w+)$/
923 or return "Illegal or empty (alphanumeric) $field: ".
924 $self->getfield($field);
925 $self->setfield($field,$1);
929 =item ut_alpha COLUMN
931 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
932 error, returns the error, otherwise returns false.
938 $self->getfield($field) =~ /^(\w*)$/
939 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
940 $self->setfield($field,$1);
944 =item ut_phonen COLUMN [ COUNTRY ]
946 Check/untaint phone numbers. May be null. If there is an error, returns
947 the error, otherwise returns false.
949 Takes an optional two-letter ISO country code; without it or with unsupported
950 countries, ut_phonen simply calls ut_alphan.
955 my( $self, $field, $country ) = @_;
956 return $self->ut_alphan($field) unless defined $country;
957 my $phonen = $self->getfield($field);
958 if ( $phonen eq '' ) {
959 $self->setfield($field,'');
960 } elsif ( $country eq 'US' || $country eq 'CA' ) {
962 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
963 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
964 $phonen = "$1-$2-$3";
965 $phonen .= " x$4" if $4;
966 $self->setfield($field,$phonen);
968 warn "warning: don't know how to check phone numbers for country $country";
969 return $self->ut_textn($field);
976 Check/untaint ip addresses. IPv4 only for now.
981 my( $self, $field ) = @_;
982 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
983 or return "Illegal (IP address) $field: ". $self->getfield($field);
984 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
985 $self->setfield($field, "$1.$2.$3.$4");
991 Check/untaint ip addresses. IPv4 only for now. May be null.
996 my( $self, $field ) = @_;
997 if ( $self->getfield($field) =~ /^()$/ ) {
998 $self->setfield($field,'');
1001 $self->ut_ip($field);
1005 =item ut_domain COLUMN
1007 Check/untaint host and domain names.
1012 my( $self, $field ) = @_;
1013 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1014 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1015 or return "Illegal (domain) $field: ". $self->getfield($field);
1016 $self->setfield($field,$1);
1020 =item ut_name COLUMN
1022 Check/untaint proper names; allows alphanumerics, spaces and the following
1023 punctuation: , . - '
1030 my( $self, $field ) = @_;
1031 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1032 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1033 $self->setfield($field,$1);
1039 Check/untaint zip codes.
1044 my( $self, $field, $country ) = @_;
1045 if ( $country eq 'US' ) {
1046 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1047 or return gettext('illegal_zip'). " $field for country $country: ".
1048 $self->getfield($field);
1049 $self->setfield($field,$1);
1051 if ( $self->getfield($field) =~ /^\s*$/ ) {
1052 $self->setfield($field,'');
1054 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1055 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1056 $self->setfield($field,$1);
1062 =item ut_country COLUMN
1064 Check/untaint country codes. Country names are changed to codes, if possible -
1065 see L<Locale::Country>.
1070 my( $self, $field ) = @_;
1071 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1072 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1073 && country2code($1) ) {
1074 $self->setfield($field,uc(country2code($1)));
1077 $self->getfield($field) =~ /^(\w\w)$/
1078 or return "Illegal (country) $field: ". $self->getfield($field);
1079 $self->setfield($field,uc($1));
1083 =item ut_anything COLUMN
1085 Untaints arbitrary data. Be careful.
1090 my( $self, $field ) = @_;
1091 $self->getfield($field) =~ /^(.*)$/s
1092 or return "Illegal $field: ". $self->getfield($field);
1093 $self->setfield($field,$1);
1097 =item ut_enum COLUMN CHOICES_ARRAYREF
1099 Check/untaint a column, supplying all possible choices, like the "enum" type.
1104 my( $self, $field, $choices ) = @_;
1105 foreach my $choice ( @$choices ) {
1106 if ( $self->getfield($field) eq $choice ) {
1107 $self->setfield($choice);
1111 return "Illegal (enum) field $field: ". $self->getfield($field);
1114 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1116 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1117 on the column first.
1121 sub ut_foreign_key {
1122 my( $self, $field, $table, $foreign ) = @_;
1123 qsearchs($table, { $foreign => $self->getfield($field) })
1124 or return "Can't find $field ". $self->getfield($field).
1125 " in $table.$foreign";
1129 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1131 Like ut_foreign_key, except the null value is also allowed.
1135 sub ut_foreign_keyn {
1136 my( $self, $field, $table, $foreign ) = @_;
1137 $self->getfield($field)
1138 ? $self->ut_foreign_key($field, $table, $foreign)
1142 =item fields [ TABLE ]
1144 This can be used as both a subroutine and a method call. It returns a list
1145 of the columns in this record's table, or an explicitly specified table.
1146 (See L<DBIx::DBSchema::Table>).
1150 # Usage: @fields = fields($table);
1151 # @fields = $record->fields;
1153 my $something = shift;
1155 if ( ref($something) ) {
1156 $table = $something->table;
1158 $table = $something;
1160 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1161 my($table_obj) = $dbdef->table($table);
1162 confess "Unknown table $table" unless $table_obj;
1163 $table_obj->columns;
1172 =item reload_dbdef([FILENAME])
1174 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1175 non-default filename. This command is executed at startup unless
1176 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1181 my $file = shift || $dbdef_file;
1183 unless ( exists $dbdef_cache{$file} ) {
1184 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1185 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1186 or die "can't load database schema from $file";
1188 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1190 $dbdef = $dbdef_cache{$file};
1195 Returns the current database definition. See L<DBIx::DBSchema>.
1199 sub dbdef { $dbdef; }
1201 =item _quote VALUE, TABLE, COLUMN
1203 This is an internal function used to construct SQL statements. It returns
1204 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1205 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1210 my($value, $table, $column) = @_;
1211 my $column_obj = $dbdef->table($table)->column($column);
1212 my $column_type = $column_obj->type;
1214 if ( $value eq '' && $column_type =~ /^int/ ) {
1215 if ( $column_obj->null ) {
1218 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1222 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1223 ! $column_type =~ /(char|binary|text)$/i ) {
1232 This is depriciated. Don't use it.
1234 It returns a hash-type list with the fields of this record's table set true.
1239 carp "warning: hfields is depriciated";
1242 foreach (fields($table)) {
1251 "$_: ". $self->getfield($_). "|"
1252 } (fields($self->table)) );
1255 sub DESTROY { return; }
1259 # #use Carp qw(cluck);
1260 # #cluck "DESTROYING $self";
1261 # warn "DESTROYING $self";
1265 # return ! eval { join('',@_), kill 0; 1; };
1272 This module should probably be renamed, since much of the functionality is
1273 of general use. It is not completely unlike Adapter::DBI (see below).
1275 Exported qsearch and qsearchs should be depriciated in favor of method calls
1276 (against an FS::Record object like the old search and searchs that qsearch
1277 and qsearchs were on top of.)
1279 The whole fields / hfields mess should be removed.
1281 The various WHERE clauses should be subroutined.
1283 table string should be depriciated in favor of DBIx::DBSchema::Table.
1285 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1286 true maps to the database (and WHERE clauses) would also help.
1288 The ut_ methods should ask the dbdef for a default length.
1290 ut_sqltype (like ut_varchar) should all be defined
1292 A fallback check method should be provided which uses the dbdef.
1294 The ut_money method assumes money has two decimal digits.
1296 The Pg money kludge in the new method only strips `$'.
1298 The ut_phonen method only checks US-style phone numbers.
1300 The _quote function should probably use ut_float instead of a regex.
1302 All the subroutines probably should be methods, here or elsewhere.
1304 Probably should borrow/use some dbdef methods where appropriate (like sub
1307 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1308 or allow it to be set. Working around it is ugly any way around - DBI should
1309 be fixed. (only affects RDBMS which return uppercase column names)
1311 ut_zip should take an optional country like ut_phone.
1315 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1317 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.