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.21;
13 use FS::UID qw(dbh 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;
64 $error = $record->delete;
66 $error = $new_record->replace($old_record);
68 # external use deprecated - handled by the database (at least for Pg, mysql)
69 $value = $record->unique('column');
71 $error = $record->ut_float('column');
72 $error = $record->ut_number('column');
73 $error = $record->ut_numbern('column');
74 $error = $record->ut_money('column');
75 $error = $record->ut_text('column');
76 $error = $record->ut_textn('column');
77 $error = $record->ut_alpha('column');
78 $error = $record->ut_alphan('column');
79 $error = $record->ut_phonen('column');
80 $error = $record->ut_anything('column');
81 $error = $record->ut_name('column');
83 $dbdef = reload_dbdef;
84 $dbdef = reload_dbdef "/non/standard/filename";
87 $quoted_value = _quote($value,'table','field');
90 $fields = hfields('table');
91 if ( $fields->{Field} ) { # etc.
93 @fields = fields 'table'; #as a subroutine
94 @fields = $record->fields; #as a method call
99 (Mostly) object-oriented interface to database records. Records are currently
100 implemented on top of DBI. FS::Record is intended as a base class for
101 table-specific classes to inherit from, i.e. FS::cust_main.
107 =item new [ TABLE, ] HASHREF
109 Creates a new record. It doesn't store it in the database, though. See
110 L<"insert"> for that.
112 Note that the object stores this hash reference, not a distinct copy of the
113 hash it points to. You can ask the object for a copy with the I<hash>
116 TABLE can only be omitted when a dervived class overrides the table method.
122 my $class = ref($proto) || $proto;
124 bless ($self, $class);
126 unless ( defined ( $self->table ) ) {
127 $self->{'Table'} = shift;
128 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
131 my $hashref = $self->{'Hash'} = shift;
133 foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) {
134 $hashref->{$field}='';
137 $self->_cache($hashref, shift) if $self->can('_cache') && @_;
144 my $class = ref($proto) || $proto;
146 bless ($self, $class);
148 $self->{'Table'} = shift unless defined ( $self->table );
150 my $hashref = $self->{'Hash'} = shift;
152 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
153 my $obj = $cache->cache->{$hashref->{$cache->key}};
154 $obj->_cache($hashref, $cache) if $obj->can('_cache');
157 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
164 my $class = ref($proto) || $proto;
166 bless ($self, $class);
167 if ( defined $self->table ) {
168 cluck "create constructor is deprecated, use new!";
171 croak "FS::Record::create called (not from a subclass)!";
175 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
177 Searches the database for all records matching (at least) the key/value pairs
178 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
179 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
182 ###oops, argh, FS::Record::new only lets us create database fields.
183 #Normal behaviour if SELECT is not specified is `*', as in
184 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
185 #feature where you can specify SELECT - remember, the objects returned,
186 #although blessed into the appropriate `FS::TABLE' package, will only have the
187 #fields you specify. This might have unwanted results if you then go calling
188 #regular FS::TABLE methods
194 my($stable, $record, $select, $extra_sql, $cache ) = @_;
195 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
197 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
202 my $table = $cache ? $cache->table : $stable;
204 my @fields = grep exists($record->{$_}), fields($table);
206 my $statement = "SELECT $select FROM $stable";
208 $statement .= ' WHERE '. join(' AND ', map {
212 if ( ref($record->{$_}) ) {
213 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
214 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
215 if ( uc($op) eq 'ILIKE' ) {
217 $record->{$_}{'value'} = lc($record->{$_}{'value'});
218 $column = "LOWER($_)";
220 $record->{$_} = $record->{$_}{'value'}
223 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
225 if ( driver_name eq 'Pg' ) {
226 qq-( $column IS NULL OR $column = '' )-;
228 qq-( $column IS NULL OR $column = "" )-;
230 } elsif ( $op eq '!=' ) {
231 if ( driver_name eq 'Pg' ) {
232 qq-( $column IS NOT NULL AND $column != '' )-;
234 qq-( $column IS NOT NULL AND $column != "" )-;
237 if ( driver_name eq 'Pg' ) {
238 qq-( $column $op '' )-;
240 qq-( $column $op "" )-;
248 $statement .= " $extra_sql" if defined($extra_sql);
250 warn "[debug]$me $statement\n" if $DEBUG > 1;
251 my $sth = $dbh->prepare($statement)
252 or croak "$dbh->errstr doing $statement";
257 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
259 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
260 && $dbdef->table($table)->column($field)->type =~ /(int)/i
262 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
264 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
268 # $sth->execute( map $record->{$_},
269 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
270 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
272 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
274 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
276 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
277 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
278 #derivied class didn't override new method, so this optimization is safe
281 new_or_cached( "FS::$table", { %{$_} }, $cache )
282 } @{$sth->fetchall_arrayref( {} )};
285 new( "FS::$table", { %{$_} } )
286 } @{$sth->fetchall_arrayref( {} )};
289 warn "untested code (class FS::$table uses custom new method)";
291 eval 'FS::'. $table. '->new( { %{$_} } )';
292 } @{$sth->fetchall_arrayref( {} )};
295 cluck "warning: FS::$table not loaded; returning FS::Record objects";
297 FS::Record->new( $table, { %{$_} } );
298 } @{$sth->fetchall_arrayref( {} )};
303 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
305 Experimental JOINed search method. Using this method, you can execute a
306 single SELECT spanning multiple tables, and cache the results for subsequent
307 method calls. Interface will almost definately change in an incompatible
315 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
316 my $cache = FS::SearchCache->new( $ptable, $pkey );
319 grep { !$saw{$_->getfield($pkey)}++ }
320 qsearch($table, $record, $select, $extra_sql, $cache )
324 =item qsearchs TABLE, HASHREF
326 Same as qsearch, except that if more than one record matches, it B<carp>s but
327 returns the first. If this happens, you either made a logic error in asking
328 for a single item, or your data is corrupted.
332 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
333 my(@result) = qsearch(@_);
334 carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
335 #should warn more vehemently if the search was on a primary key?
336 scalar(@result) ? ($result[0]) : ();
347 Returns the table name.
352 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
359 Returns the DBIx::DBSchema::Table object for the table.
365 my($table)=$self->table;
366 $dbdef->table($table);
369 =item get, getfield COLUMN
371 Returns the value of the column/field/key COLUMN.
376 my($self,$field) = @_;
377 # to avoid "Use of unitialized value" errors
378 if ( defined ( $self->{Hash}->{$field} ) ) {
379 $self->{Hash}->{$field};
389 =item set, setfield COLUMN, VALUE
391 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
396 my($self,$field,$value) = @_;
397 $self->{'Hash'}->{$field} = $value;
404 =item AUTLOADED METHODS
406 $record->column is a synonym for $record->get('column');
408 $record->column('value') is a synonym for $record->set('column','value');
415 my($field)=$AUTOLOAD;
417 if ( defined($value) ) {
418 confess "errant AUTOLOAD $field for $self (arg $value)"
419 unless $self->can('setfield');
420 $self->setfield($field,$value);
422 confess "errant AUTOLOAD $field for $self (no args)"
423 unless $self->can('getfield');
424 $self->getfield($field);
430 # my $field = $AUTOLOAD;
432 # if ( defined($_[1]) ) {
433 # $_[0]->setfield($field, $_[1]);
435 # $_[0]->getfield($field);
441 Returns a list of the column/value pairs, usually for assigning to a new hash.
443 To make a distinct duplicate of an FS::Record object, you can do:
445 $new = new FS::Record ( $old->table, { $old->hash } );
451 %{ $self->{'Hash'} };
456 Returns a reference to the column/value hash.
467 Inserts this record to the database. If there is an error, returns the error,
468 otherwise returns false.
475 my $error = $self->check;
476 return $error if $error;
478 #single-field unique keys are given a value if false
479 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
480 foreach ( $self->dbdef_table->unique->singles ) {
481 $self->unique($_) unless $self->getfield($_);
484 #and also the primary key, if the database isn't going to
485 my $primary_key = $self->dbdef_table->primary_key;
487 if ( $primary_key ) {
488 my $col = $self->dbdef_table->column($primary_key);
491 uc($col->type) eq 'SERIAL'
492 || ( driver_name eq 'Pg'
493 && defined($col->default)
494 && $col->default =~ /^nextval\(/i
496 || ( driver_name eq 'mysql'
497 && defined($col->local)
498 && $col->local =~ /AUTO_INCREMENT/i
500 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
503 my $table = $self->table;
504 #false laziness w/delete
506 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
509 my @values = map { _quote( $self->getfield($_), $table, $_) } @fields;
512 my $statement = "INSERT INTO $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;
521 local $SIG{HUP} = 'IGNORE';
522 local $SIG{INT} = 'IGNORE';
523 local $SIG{QUIT} = 'IGNORE';
524 local $SIG{TERM} = 'IGNORE';
525 local $SIG{TSTP} = 'IGNORE';
526 local $SIG{PIPE} = 'IGNORE';
528 $sth->execute or return $sth->errstr;
530 if ( $db_seq ) { # get inserted id from the database, if applicable
531 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
533 if ( driver_name eq 'Pg' ) {
535 my $oid = $sth->{'pg_oid_status'};
536 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
537 my $i_sth = dbh->prepare($i_sql) or do {
538 dbh->rollback if $FS::UID::AutoCommit;
541 $i_sth->execute($oid) or do {
542 dbh->rollback if $FS::UID::AutoCommit;
543 return $i_sth->errstr;
545 $insertid = $i_sth->fetchrow_arrayref->[0];
547 } elsif ( driver_name eq 'mysql' ) {
549 $insertid = dbh->{'mysql_insertid'};
550 # work around mysql_insertid being null some of the time, ala RT :/
551 unless ( $insertid ) {
552 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
553 "using SELECT LAST_INSERT_ID();";
554 my $i_sql = "SELECT LAST_INSERT_ID()";
555 my $i_sth = dbh->prepare($i_sql) or do {
556 dbh->rollback if $FS::UID::AutoCommit;
559 $i_sth->execute or do {
560 dbh->rollback if $FS::UID::AutoCommit;
561 return $i_sth->errstr;
563 $insertid = $i_sth->fetchrow_arrayref->[0];
567 dbh->rollback if $FS::UID::AutoCommit;
568 return "don't know how to retreive inserted ids from ". driver_name.
569 ", try using counterfiles (maybe run dbdef-create?)";
571 $self->setfield($primary_key, $insertid);
575 if ( defined $dbdef->table('h_'. $table) ) {
576 my $h_statement = $self->_h_statement('insert');
577 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
578 $h_sth = dbh->prepare($h_statement) or do {
579 dbh->rollback if $FS::UID::AutoCommit;
585 $h_sth->execute or return $h_sth->errstr if $h_sth;
587 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
594 Depriciated (use insert instead).
599 cluck "warning: FS::Record::add deprecated!";
600 insert @_; #call method in this scope
605 Delete this record from the database. If there is an error, returns the error,
606 otherwise returns false.
613 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
615 $self->getfield($_) eq ''
616 #? "( $_ IS NULL OR $_ = \"\" )"
617 ? ( driver_name eq 'Pg'
619 : "( $_ IS NULL OR $_ = \"\" )"
621 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
622 } ( $self->dbdef_table->primary_key )
623 ? ( $self->dbdef_table->primary_key)
626 warn "[debug]$me $statement\n" if $DEBUG > 1;
627 my $sth = dbh->prepare($statement) or return dbh->errstr;
630 if ( defined $dbdef->table('h_'. $self->table) ) {
631 my $h_statement = $self->_h_statement('delete');
632 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
633 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
638 local $SIG{HUP} = 'IGNORE';
639 local $SIG{INT} = 'IGNORE';
640 local $SIG{QUIT} = 'IGNORE';
641 local $SIG{TERM} = 'IGNORE';
642 local $SIG{TSTP} = 'IGNORE';
643 local $SIG{PIPE} = 'IGNORE';
645 my $rc = $sth->execute or return $sth->errstr;
646 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
647 $h_sth->execute or return $h_sth->errstr if $h_sth;
648 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
650 #no need to needlessly destoy the data either (causes problems actually)
651 #undef $self; #no need to keep object!
658 Depriciated (use delete instead).
663 cluck "warning: FS::Record::del deprecated!";
664 &delete(@_); #call method in this scope
667 =item replace OLD_RECORD
669 Replace the OLD_RECORD with this one in the database. If there is an error,
670 returns the error, otherwise returns false.
675 my ( $new, $old ) = ( shift, shift );
676 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
678 return "Records not in same table!" unless $new->table eq $old->table;
680 my $primary_key = $old->dbdef_table->primary_key;
681 return "Can't change $primary_key"
683 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
685 my $error = $new->check;
686 return $error if $error;
688 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
690 carp "[warning]$me $new -> replace $old: records identical";
694 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
696 "$_ = ". _quote($new->getfield($_),$old->table,$_)
701 $old->getfield($_) eq ''
702 #? "( $_ IS NULL OR $_ = \"\" )"
703 ? ( driver_name eq 'Pg'
705 : "( $_ IS NULL OR $_ = \"\" )"
707 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
708 } ( $primary_key ? ( $primary_key ) : $old->fields )
711 warn "[debug]$me $statement\n" if $DEBUG > 1;
712 my $sth = dbh->prepare($statement) or return dbh->errstr;
715 if ( defined $dbdef->table('h_'. $old->table) ) {
716 my $h_old_statement = $old->_h_statement('replace_old');
717 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
718 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
724 if ( defined $dbdef->table('h_'. $new->table) ) {
725 my $h_new_statement = $new->_h_statement('replace_new');
726 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
727 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
732 local $SIG{HUP} = 'IGNORE';
733 local $SIG{INT} = 'IGNORE';
734 local $SIG{QUIT} = 'IGNORE';
735 local $SIG{TERM} = 'IGNORE';
736 local $SIG{TSTP} = 'IGNORE';
737 local $SIG{PIPE} = 'IGNORE';
739 my $rc = $sth->execute or return $sth->errstr;
740 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
741 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
742 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
743 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
751 Depriciated (use replace instead).
756 cluck "warning: FS::Record::rep deprecated!";
757 replace @_; #call method in this scope
762 Not yet implemented, croaks. Derived classes should provide a check method.
767 confess "FS::Record::check not implemented; supply one in subclass!";
771 my( $self, $action ) = @_;
774 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
777 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
779 "INSERT INTO h_". $self->table. " ( ".
780 join(', ', qw(history_date history_user history_action), @fields ).
782 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
789 B<Warning>: External use is B<deprecated>.
791 Replaces COLUMN in record with a unique number, using counters in the
792 filesystem. Used by the B<insert> method on single-field unique columns
793 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
794 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
796 Returns the new value.
801 my($self,$field) = @_;
802 my($table)=$self->table;
804 croak "Unique called on field $field, but it is ",
805 $self->getfield($field),
807 if $self->getfield($field);
809 #warn "table $table is tainted" if is_tainted($table);
810 #warn "field $field is tainted" if is_tainted($field);
812 my($counter) = new File::CounterFile "$table.$field",0;
814 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
816 # my($counter) = new File::CounterFile "$user/$table.$field",0;
819 my $index = $counter->inc;
820 $index = $counter->inc while qsearchs($table, { $field=>$index } );
825 $self->setfield($field,$index);
829 =item ut_float COLUMN
831 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
832 null. If there is an error, returns the error, otherwise returns false.
837 my($self,$field)=@_ ;
838 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
839 $self->getfield($field) =~ /^(\d+)$/ ||
840 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
841 $self->getfield($field) =~ /^(\d+e\d+)$/)
842 or return "Illegal or empty (float) $field: ". $self->getfield($field);
843 $self->setfield($field,$1);
847 =item ut_number COLUMN
849 Check/untaint simple numeric data (whole numbers). May not be null. If there
850 is an error, returns the error, otherwise returns false.
856 $self->getfield($field) =~ /^(\d+)$/
857 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
858 $self->setfield($field,$1);
862 =item ut_numbern COLUMN
864 Check/untaint simple numeric data (whole numbers). May be null. If there is
865 an error, returns the error, otherwise returns false.
871 $self->getfield($field) =~ /^(\d*)$/
872 or return "Illegal (numeric) $field: ". $self->getfield($field);
873 $self->setfield($field,$1);
877 =item ut_money COLUMN
879 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
880 is an error, returns the error, otherwise returns false.
886 $self->setfield($field, 0) if $self->getfield($field) eq '';
887 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
888 or return "Illegal (money) $field: ". $self->getfield($field);
889 #$self->setfield($field, "$1$2$3" || 0);
890 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
896 Check/untaint text. Alphanumerics, spaces, and the following punctuation
897 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
898 May not be null. If there is an error, returns the error, otherwise returns
905 #warn "msgcat ". \&msgcat. "\n";
906 #warn "notexist ". \¬exist. "\n";
907 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
908 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
909 or return gettext('illegal_or_empty_text'). " $field: ".
910 $self->getfield($field);
911 $self->setfield($field,$1);
915 =item ut_textn COLUMN
917 Check/untaint text. Alphanumerics, spaces, and the following punctuation
918 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
919 May be null. If there is an error, returns the error, otherwise returns false.
925 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
926 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
927 $self->setfield($field,$1);
931 =item ut_alpha COLUMN
933 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
934 an error, returns the error, otherwise returns false.
940 $self->getfield($field) =~ /^(\w+)$/
941 or return "Illegal or empty (alphanumeric) $field: ".
942 $self->getfield($field);
943 $self->setfield($field,$1);
947 =item ut_alpha COLUMN
949 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
950 error, returns the error, otherwise returns false.
956 $self->getfield($field) =~ /^(\w*)$/
957 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
958 $self->setfield($field,$1);
962 =item ut_phonen COLUMN [ COUNTRY ]
964 Check/untaint phone numbers. May be null. If there is an error, returns
965 the error, otherwise returns false.
967 Takes an optional two-letter ISO country code; without it or with unsupported
968 countries, ut_phonen simply calls ut_alphan.
973 my( $self, $field, $country ) = @_;
974 return $self->ut_alphan($field) unless defined $country;
975 my $phonen = $self->getfield($field);
976 if ( $phonen eq '' ) {
977 $self->setfield($field,'');
978 } elsif ( $country eq 'US' || $country eq 'CA' ) {
980 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
981 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
982 $phonen = "$1-$2-$3";
983 $phonen .= " x$4" if $4;
984 $self->setfield($field,$phonen);
986 warn "warning: don't know how to check phone numbers for country $country";
987 return $self->ut_textn($field);
994 Check/untaint ip addresses. IPv4 only for now.
999 my( $self, $field ) = @_;
1000 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1001 or return "Illegal (IP address) $field: ". $self->getfield($field);
1002 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1003 $self->setfield($field, "$1.$2.$3.$4");
1009 Check/untaint ip addresses. IPv4 only for now. May be null.
1014 my( $self, $field ) = @_;
1015 if ( $self->getfield($field) =~ /^()$/ ) {
1016 $self->setfield($field,'');
1019 $self->ut_ip($field);
1023 =item ut_domain COLUMN
1025 Check/untaint host and domain names.
1030 my( $self, $field ) = @_;
1031 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1032 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1033 or return "Illegal (domain) $field: ". $self->getfield($field);
1034 $self->setfield($field,$1);
1038 =item ut_name COLUMN
1040 Check/untaint proper names; allows alphanumerics, spaces and the following
1041 punctuation: , . - '
1048 my( $self, $field ) = @_;
1049 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1050 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1051 $self->setfield($field,$1);
1057 Check/untaint zip codes.
1062 my( $self, $field, $country ) = @_;
1063 if ( $country eq 'US' ) {
1064 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1065 or return gettext('illegal_zip'). " $field for country $country: ".
1066 $self->getfield($field);
1067 $self->setfield($field,$1);
1069 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1070 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1071 $self->setfield($field,$1);
1076 =item ut_country COLUMN
1078 Check/untaint country codes. Country names are changed to codes, if possible -
1079 see L<Locale::Country>.
1084 my( $self, $field ) = @_;
1085 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1086 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1087 && country2code($1) ) {
1088 $self->setfield($field,uc(country2code($1)));
1091 $self->getfield($field) =~ /^(\w\w)$/
1092 or return "Illegal (country) $field: ". $self->getfield($field);
1093 $self->setfield($field,uc($1));
1097 =item ut_anything COLUMN
1099 Untaints arbitrary data. Be careful.
1104 my( $self, $field ) = @_;
1105 $self->getfield($field) =~ /^(.*)$/s
1106 or return "Illegal $field: ". $self->getfield($field);
1107 $self->setfield($field,$1);
1111 =item ut_enum COLUMN CHOICES_ARRAYREF
1113 Check/untaint a column, supplying all possible choices, like the "enum" type.
1118 my( $self, $field, $choices ) = @_;
1119 foreach my $choice ( @$choices ) {
1120 if ( $self->getfield($field) eq $choice ) {
1121 $self->setfield($choice);
1125 return "Illegal (enum) field $field: ". $self->getfield($field);
1128 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1130 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1131 on the column first.
1135 sub ut_foreign_key {
1136 my( $self, $field, $table, $foreign ) = @_;
1137 qsearchs($table, { $foreign => $self->getfield($field) })
1138 or return "Can't find $field ". $self->getfield($field).
1139 " in $table.$foreign";
1143 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1145 Like ut_foreign_key, except the null value is also allowed.
1149 sub ut_foreign_keyn {
1150 my( $self, $field, $table, $foreign ) = @_;
1151 $self->getfield($field)
1152 ? $self->ut_foreign_key($field, $table, $foreign)
1156 =item fields [ TABLE ]
1158 This can be used as both a subroutine and a method call. It returns a list
1159 of the columns in this record's table, or an explicitly specified table.
1160 (See L<DBIx::DBSchema::Table>).
1164 # Usage: @fields = fields($table);
1165 # @fields = $record->fields;
1167 my $something = shift;
1169 if ( ref($something) ) {
1170 $table = $something->table;
1172 $table = $something;
1174 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1175 my($table_obj) = $dbdef->table($table);
1176 confess "Unknown table $table" unless $table_obj;
1177 $table_obj->columns;
1186 =item reload_dbdef([FILENAME])
1188 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1189 non-default filename. This command is executed at startup unless
1190 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1195 my $file = shift || $dbdef_file;
1197 unless ( exists $dbdef_cache{$file} ) {
1198 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1199 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1200 or die "can't load database schema from $file";
1202 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1204 $dbdef = $dbdef_cache{$file};
1209 Returns the current database definition. See L<DBIx::DBSchema>.
1213 sub dbdef { $dbdef; }
1215 =item _quote VALUE, TABLE, COLUMN
1217 This is an internal function used to construct SQL statements. It returns
1218 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1219 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1224 my($value,$table,$field)=@_;
1226 if ( $value =~ /^\d+(\.\d+)?$/ &&
1227 # ! ( datatype($table,$field) =~ /^char/ )
1228 ! $dbdef->table($table)->column($field)->type =~ /(char|binary|text)$/i
1232 $dbh->quote($value);
1238 This is deprecated. Don't use it.
1240 It returns a hash-type list with the fields of this record's table set true.
1245 carp "warning: hfields is deprecated";
1248 foreach (fields($table)) {
1257 "$_: ". $self->getfield($_). "|"
1258 } (fields($self->table)) );
1261 sub DESTROY { return; }
1265 # #use Carp qw(cluck);
1266 # #cluck "DESTROYING $self";
1267 # warn "DESTROYING $self";
1271 # return ! eval { join('',@_), kill 0; 1; };
1278 This module should probably be renamed, since much of the functionality is
1279 of general use. It is not completely unlike Adapter::DBI (see below).
1281 Exported qsearch and qsearchs should be deprecated in favor of method calls
1282 (against an FS::Record object like the old search and searchs that qsearch
1283 and qsearchs were on top of.)
1285 The whole fields / hfields mess should be removed.
1287 The various WHERE clauses should be subroutined.
1289 table string should be deprecated in favor of DBIx::DBSchema::Table.
1291 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1292 true maps to the database (and WHERE clauses) would also help.
1294 The ut_ methods should ask the dbdef for a default length.
1296 ut_sqltype (like ut_varchar) should all be defined
1298 A fallback check method should be provided which uses the dbdef.
1300 The ut_money method assumes money has two decimal digits.
1302 The Pg money kludge in the new method only strips `$'.
1304 The ut_phonen method only checks US-style phone numbers.
1306 The _quote function should probably use ut_float instead of a regex.
1308 All the subroutines probably should be methods, here or elsewhere.
1310 Probably should borrow/use some dbdef methods where appropriate (like sub
1313 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1314 or allow it to be set. Working around it is ugly any way around - DBI should
1315 be fixed. (only affects RDBMS which return uppercase column names)
1317 ut_zip should take an optional country like ut_phone.
1321 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1323 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.