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);
334 my(@result) = qsearch(@_);
335 carp "warning: Multiple records in scalar search ($table)"
336 if scalar(@result) > 1;
337 #should warn more vehemently if the search was on a primary key?
338 scalar(@result) ? ($result[0]) : ();
349 Returns the table name.
354 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
361 Returns the DBIx::DBSchema::Table object for the table.
367 my($table)=$self->table;
368 $dbdef->table($table);
371 =item get, getfield COLUMN
373 Returns the value of the column/field/key COLUMN.
378 my($self,$field) = @_;
379 # to avoid "Use of unitialized value" errors
380 if ( defined ( $self->{Hash}->{$field} ) ) {
381 $self->{Hash}->{$field};
391 =item set, setfield COLUMN, VALUE
393 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
398 my($self,$field,$value) = @_;
399 $self->{'Hash'}->{$field} = $value;
406 =item AUTLOADED METHODS
408 $record->column is a synonym for $record->get('column');
410 $record->column('value') is a synonym for $record->set('column','value');
417 my($field)=$AUTOLOAD;
419 if ( defined($value) ) {
420 confess "errant AUTOLOAD $field for $self (arg $value)"
421 unless $self->can('setfield');
422 $self->setfield($field,$value);
424 confess "errant AUTOLOAD $field for $self (no args)"
425 unless $self->can('getfield');
426 $self->getfield($field);
432 # my $field = $AUTOLOAD;
434 # if ( defined($_[1]) ) {
435 # $_[0]->setfield($field, $_[1]);
437 # $_[0]->getfield($field);
443 Returns a list of the column/value pairs, usually for assigning to a new hash.
445 To make a distinct duplicate of an FS::Record object, you can do:
447 $new = new FS::Record ( $old->table, { $old->hash } );
453 %{ $self->{'Hash'} };
458 Returns a reference to the column/value hash.
469 Inserts this record to the database. If there is an error, returns the error,
470 otherwise returns false.
477 my $error = $self->check;
478 return $error if $error;
480 #single-field unique keys are given a value if false
481 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
482 foreach ( $self->dbdef_table->unique->singles ) {
483 $self->unique($_) unless $self->getfield($_);
486 #and also the primary key, if the database isn't going to
487 my $primary_key = $self->dbdef_table->primary_key;
489 if ( $primary_key ) {
490 my $col = $self->dbdef_table->column($primary_key);
493 uc($col->type) eq 'SERIAL'
494 || ( driver_name eq 'Pg'
495 && defined($col->default)
496 && $col->default =~ /^nextval\(/i
498 || ( driver_name eq 'mysql'
499 && defined($col->local)
500 && $col->local =~ /AUTO_INCREMENT/i
502 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
505 my $table = $self->table;
506 #false laziness w/delete
508 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
511 my @values = map { _quote( $self->getfield($_), $table, $_) } @fields;
514 my $statement = "INSERT INTO $table ( ".
515 join( ', ', @fields ).
517 join( ', ', @values ).
520 warn "[debug]$me $statement\n" if $DEBUG > 1;
521 my $sth = dbh->prepare($statement) or return dbh->errstr;
523 local $SIG{HUP} = 'IGNORE';
524 local $SIG{INT} = 'IGNORE';
525 local $SIG{QUIT} = 'IGNORE';
526 local $SIG{TERM} = 'IGNORE';
527 local $SIG{TSTP} = 'IGNORE';
528 local $SIG{PIPE} = 'IGNORE';
530 $sth->execute or return $sth->errstr;
532 if ( $db_seq ) { # get inserted id from the database, if applicable
533 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
535 if ( driver_name eq 'Pg' ) {
537 my $oid = $sth->{'pg_oid_status'};
538 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
539 my $i_sth = dbh->prepare($i_sql) or do {
540 dbh->rollback if $FS::UID::AutoCommit;
543 $i_sth->execute($oid) or do {
544 dbh->rollback if $FS::UID::AutoCommit;
545 return $i_sth->errstr;
547 $insertid = $i_sth->fetchrow_arrayref->[0];
549 } elsif ( driver_name eq 'mysql' ) {
551 $insertid = dbh->{'mysql_insertid'};
552 # work around mysql_insertid being null some of the time, ala RT :/
553 unless ( $insertid ) {
554 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
555 "using SELECT LAST_INSERT_ID();";
556 my $i_sql = "SELECT LAST_INSERT_ID()";
557 my $i_sth = dbh->prepare($i_sql) or do {
558 dbh->rollback if $FS::UID::AutoCommit;
561 $i_sth->execute or do {
562 dbh->rollback if $FS::UID::AutoCommit;
563 return $i_sth->errstr;
565 $insertid = $i_sth->fetchrow_arrayref->[0];
569 dbh->rollback if $FS::UID::AutoCommit;
570 return "don't know how to retreive inserted ids from ". driver_name.
571 ", try using counterfiles (maybe run dbdef-create?)";
573 $self->setfield($primary_key, $insertid);
577 if ( defined $dbdef->table('h_'. $table) ) {
578 my $h_statement = $self->_h_statement('insert');
579 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
580 $h_sth = dbh->prepare($h_statement) or do {
581 dbh->rollback if $FS::UID::AutoCommit;
587 $h_sth->execute or return $h_sth->errstr if $h_sth;
589 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
596 Depriciated (use insert instead).
601 cluck "warning: FS::Record::add deprecated!";
602 insert @_; #call method in this scope
607 Delete this record from the database. If there is an error, returns the error,
608 otherwise returns false.
615 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
617 $self->getfield($_) eq ''
618 #? "( $_ IS NULL OR $_ = \"\" )"
619 ? ( driver_name eq 'Pg'
621 : "( $_ IS NULL OR $_ = \"\" )"
623 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
624 } ( $self->dbdef_table->primary_key )
625 ? ( $self->dbdef_table->primary_key)
628 warn "[debug]$me $statement\n" if $DEBUG > 1;
629 my $sth = dbh->prepare($statement) or return dbh->errstr;
632 if ( defined $dbdef->table('h_'. $self->table) ) {
633 my $h_statement = $self->_h_statement('delete');
634 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
635 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
640 local $SIG{HUP} = 'IGNORE';
641 local $SIG{INT} = 'IGNORE';
642 local $SIG{QUIT} = 'IGNORE';
643 local $SIG{TERM} = 'IGNORE';
644 local $SIG{TSTP} = 'IGNORE';
645 local $SIG{PIPE} = 'IGNORE';
647 my $rc = $sth->execute or return $sth->errstr;
648 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
649 $h_sth->execute or return $h_sth->errstr if $h_sth;
650 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
652 #no need to needlessly destoy the data either (causes problems actually)
653 #undef $self; #no need to keep object!
660 Depriciated (use delete instead).
665 cluck "warning: FS::Record::del deprecated!";
666 &delete(@_); #call method in this scope
669 =item replace OLD_RECORD
671 Replace the OLD_RECORD with this one in the database. If there is an error,
672 returns the error, otherwise returns false.
677 my ( $new, $old ) = ( shift, shift );
678 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
680 return "Records not in same table!" unless $new->table eq $old->table;
682 my $primary_key = $old->dbdef_table->primary_key;
683 return "Can't change $primary_key"
685 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
687 my $error = $new->check;
688 return $error if $error;
690 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
692 carp "[warning]$me $new -> replace $old: records identical";
696 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
698 "$_ = ". _quote($new->getfield($_),$old->table,$_)
703 $old->getfield($_) eq ''
704 #? "( $_ IS NULL OR $_ = \"\" )"
705 ? ( driver_name eq 'Pg'
707 : "( $_ IS NULL OR $_ = \"\" )"
709 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
710 } ( $primary_key ? ( $primary_key ) : $old->fields )
713 warn "[debug]$me $statement\n" if $DEBUG > 1;
714 my $sth = dbh->prepare($statement) or return dbh->errstr;
717 if ( defined $dbdef->table('h_'. $old->table) ) {
718 my $h_old_statement = $old->_h_statement('replace_old');
719 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
720 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
726 if ( defined $dbdef->table('h_'. $new->table) ) {
727 my $h_new_statement = $new->_h_statement('replace_new');
728 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
729 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
734 local $SIG{HUP} = 'IGNORE';
735 local $SIG{INT} = 'IGNORE';
736 local $SIG{QUIT} = 'IGNORE';
737 local $SIG{TERM} = 'IGNORE';
738 local $SIG{TSTP} = 'IGNORE';
739 local $SIG{PIPE} = 'IGNORE';
741 my $rc = $sth->execute or return $sth->errstr;
742 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
743 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
744 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
745 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
753 Depriciated (use replace instead).
758 cluck "warning: FS::Record::rep deprecated!";
759 replace @_; #call method in this scope
764 Not yet implemented, croaks. Derived classes should provide a check method.
769 confess "FS::Record::check not implemented; supply one in subclass!";
773 my( $self, $action ) = @_;
776 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
779 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
781 "INSERT INTO h_". $self->table. " ( ".
782 join(', ', qw(history_date history_user history_action), @fields ).
784 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
791 B<Warning>: External use is B<deprecated>.
793 Replaces COLUMN in record with a unique number, using counters in the
794 filesystem. Used by the B<insert> method on single-field unique columns
795 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
796 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
798 Returns the new value.
803 my($self,$field) = @_;
804 my($table)=$self->table;
806 croak "Unique called on field $field, but it is ",
807 $self->getfield($field),
809 if $self->getfield($field);
811 #warn "table $table is tainted" if is_tainted($table);
812 #warn "field $field is tainted" if is_tainted($field);
814 my($counter) = new File::CounterFile "$table.$field",0;
816 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
818 # my($counter) = new File::CounterFile "$user/$table.$field",0;
821 my $index = $counter->inc;
822 $index = $counter->inc while qsearchs($table, { $field=>$index } );
827 $self->setfield($field,$index);
831 =item ut_float COLUMN
833 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
834 null. If there is an error, returns the error, otherwise returns false.
839 my($self,$field)=@_ ;
840 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
841 $self->getfield($field) =~ /^(\d+)$/ ||
842 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
843 $self->getfield($field) =~ /^(\d+e\d+)$/)
844 or return "Illegal or empty (float) $field: ". $self->getfield($field);
845 $self->setfield($field,$1);
849 =item ut_number COLUMN
851 Check/untaint simple numeric data (whole numbers). May not be null. If there
852 is an error, returns the error, otherwise returns false.
858 $self->getfield($field) =~ /^(\d+)$/
859 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
860 $self->setfield($field,$1);
864 =item ut_numbern COLUMN
866 Check/untaint simple numeric data (whole numbers). May be null. If there is
867 an error, returns the error, otherwise returns false.
873 $self->getfield($field) =~ /^(\d*)$/
874 or return "Illegal (numeric) $field: ". $self->getfield($field);
875 $self->setfield($field,$1);
879 =item ut_money COLUMN
881 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
882 is an error, returns the error, otherwise returns false.
888 $self->setfield($field, 0) if $self->getfield($field) eq '';
889 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
890 or return "Illegal (money) $field: ". $self->getfield($field);
891 #$self->setfield($field, "$1$2$3" || 0);
892 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
898 Check/untaint text. Alphanumerics, spaces, and the following punctuation
899 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
900 May not be null. If there is an error, returns the error, otherwise returns
907 #warn "msgcat ". \&msgcat. "\n";
908 #warn "notexist ". \¬exist. "\n";
909 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
910 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
911 or return gettext('illegal_or_empty_text'). " $field: ".
912 $self->getfield($field);
913 $self->setfield($field,$1);
917 =item ut_textn COLUMN
919 Check/untaint text. Alphanumerics, spaces, and the following punctuation
920 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
921 May be null. If there is an error, returns the error, otherwise returns false.
927 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
928 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
929 $self->setfield($field,$1);
933 =item ut_alpha COLUMN
935 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
936 an error, returns the error, otherwise returns false.
942 $self->getfield($field) =~ /^(\w+)$/
943 or return "Illegal or empty (alphanumeric) $field: ".
944 $self->getfield($field);
945 $self->setfield($field,$1);
949 =item ut_alpha COLUMN
951 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
952 error, returns the error, otherwise returns false.
958 $self->getfield($field) =~ /^(\w*)$/
959 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
960 $self->setfield($field,$1);
964 =item ut_phonen COLUMN [ COUNTRY ]
966 Check/untaint phone numbers. May be null. If there is an error, returns
967 the error, otherwise returns false.
969 Takes an optional two-letter ISO country code; without it or with unsupported
970 countries, ut_phonen simply calls ut_alphan.
975 my( $self, $field, $country ) = @_;
976 return $self->ut_alphan($field) unless defined $country;
977 my $phonen = $self->getfield($field);
978 if ( $phonen eq '' ) {
979 $self->setfield($field,'');
980 } elsif ( $country eq 'US' || $country eq 'CA' ) {
982 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
983 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
984 $phonen = "$1-$2-$3";
985 $phonen .= " x$4" if $4;
986 $self->setfield($field,$phonen);
988 warn "warning: don't know how to check phone numbers for country $country";
989 return $self->ut_textn($field);
996 Check/untaint ip addresses. IPv4 only for now.
1001 my( $self, $field ) = @_;
1002 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1003 or return "Illegal (IP address) $field: ". $self->getfield($field);
1004 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1005 $self->setfield($field, "$1.$2.$3.$4");
1011 Check/untaint ip addresses. IPv4 only for now. May be null.
1016 my( $self, $field ) = @_;
1017 if ( $self->getfield($field) =~ /^()$/ ) {
1018 $self->setfield($field,'');
1021 $self->ut_ip($field);
1025 =item ut_domain COLUMN
1027 Check/untaint host and domain names.
1032 my( $self, $field ) = @_;
1033 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1034 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1035 or return "Illegal (domain) $field: ". $self->getfield($field);
1036 $self->setfield($field,$1);
1040 =item ut_name COLUMN
1042 Check/untaint proper names; allows alphanumerics, spaces and the following
1043 punctuation: , . - '
1050 my( $self, $field ) = @_;
1051 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1052 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1053 $self->setfield($field,$1);
1059 Check/untaint zip codes.
1064 my( $self, $field, $country ) = @_;
1065 if ( $country eq 'US' ) {
1066 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1067 or return gettext('illegal_zip'). " $field for country $country: ".
1068 $self->getfield($field);
1069 $self->setfield($field,$1);
1071 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1072 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1073 $self->setfield($field,$1);
1078 =item ut_country COLUMN
1080 Check/untaint country codes. Country names are changed to codes, if possible -
1081 see L<Locale::Country>.
1086 my( $self, $field ) = @_;
1087 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1088 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1089 && country2code($1) ) {
1090 $self->setfield($field,uc(country2code($1)));
1093 $self->getfield($field) =~ /^(\w\w)$/
1094 or return "Illegal (country) $field: ". $self->getfield($field);
1095 $self->setfield($field,uc($1));
1099 =item ut_anything COLUMN
1101 Untaints arbitrary data. Be careful.
1106 my( $self, $field ) = @_;
1107 $self->getfield($field) =~ /^(.*)$/s
1108 or return "Illegal $field: ". $self->getfield($field);
1109 $self->setfield($field,$1);
1113 =item ut_enum COLUMN CHOICES_ARRAYREF
1115 Check/untaint a column, supplying all possible choices, like the "enum" type.
1120 my( $self, $field, $choices ) = @_;
1121 foreach my $choice ( @$choices ) {
1122 if ( $self->getfield($field) eq $choice ) {
1123 $self->setfield($choice);
1127 return "Illegal (enum) field $field: ". $self->getfield($field);
1130 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1132 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1133 on the column first.
1137 sub ut_foreign_key {
1138 my( $self, $field, $table, $foreign ) = @_;
1139 qsearchs($table, { $foreign => $self->getfield($field) })
1140 or return "Can't find $field ". $self->getfield($field).
1141 " in $table.$foreign";
1145 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1147 Like ut_foreign_key, except the null value is also allowed.
1151 sub ut_foreign_keyn {
1152 my( $self, $field, $table, $foreign ) = @_;
1153 $self->getfield($field)
1154 ? $self->ut_foreign_key($field, $table, $foreign)
1158 =item fields [ TABLE ]
1160 This can be used as both a subroutine and a method call. It returns a list
1161 of the columns in this record's table, or an explicitly specified table.
1162 (See L<DBIx::DBSchema::Table>).
1166 # Usage: @fields = fields($table);
1167 # @fields = $record->fields;
1169 my $something = shift;
1171 if ( ref($something) ) {
1172 $table = $something->table;
1174 $table = $something;
1176 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1177 my($table_obj) = $dbdef->table($table);
1178 confess "Unknown table $table" unless $table_obj;
1179 $table_obj->columns;
1188 =item reload_dbdef([FILENAME])
1190 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1191 non-default filename. This command is executed at startup unless
1192 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1197 my $file = shift || $dbdef_file;
1199 unless ( exists $dbdef_cache{$file} ) {
1200 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1201 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1202 or die "can't load database schema from $file";
1204 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1206 $dbdef = $dbdef_cache{$file};
1211 Returns the current database definition. See L<DBIx::DBSchema>.
1215 sub dbdef { $dbdef; }
1217 =item _quote VALUE, TABLE, COLUMN
1219 This is an internal function used to construct SQL statements. It returns
1220 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1221 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1226 my($value,$table,$field)=@_;
1228 if ( $value =~ /^\d+(\.\d+)?$/ &&
1229 # ! ( datatype($table,$field) =~ /^char/ )
1230 ! $dbdef->table($table)->column($field)->type =~ /(char|binary|text)$/i
1234 $dbh->quote($value);
1240 This is deprecated. Don't use it.
1242 It returns a hash-type list with the fields of this record's table set true.
1247 carp "warning: hfields is deprecated";
1250 foreach (fields($table)) {
1259 "$_: ". $self->getfield($_). "|"
1260 } (fields($self->table)) );
1263 sub DESTROY { return; }
1267 # #use Carp qw(cluck);
1268 # #cluck "DESTROYING $self";
1269 # warn "DESTROYING $self";
1273 # return ! eval { join('',@_), kill 0; 1; };
1280 This module should probably be renamed, since much of the functionality is
1281 of general use. It is not completely unlike Adapter::DBI (see below).
1283 Exported qsearch and qsearchs should be deprecated in favor of method calls
1284 (against an FS::Record object like the old search and searchs that qsearch
1285 and qsearchs were on top of.)
1287 The whole fields / hfields mess should be removed.
1289 The various WHERE clauses should be subroutined.
1291 table string should be deprecated in favor of DBIx::DBSchema::Table.
1293 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1294 true maps to the database (and WHERE clauses) would also help.
1296 The ut_ methods should ask the dbdef for a default length.
1298 ut_sqltype (like ut_varchar) should all be defined
1300 A fallback check method should be provided which uses the dbdef.
1302 The ut_money method assumes money has two decimal digits.
1304 The Pg money kludge in the new method only strips `$'.
1306 The ut_phonen method only checks US-style phone numbers.
1308 The _quote function should probably use ut_float instead of a regex.
1310 All the subroutines probably should be methods, here or elsewhere.
1312 Probably should borrow/use some dbdef methods where appropriate (like sub
1315 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1316 or allow it to be set. Working around it is ugly any way around - DBI should
1317 be fixed. (only affects RDBMS which return uppercase column names)
1319 ut_zip should take an optional country like ut_phone.
1323 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1325 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.