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 if ( $dbdef->table($table)->column($column)->type =~ /(int)/i ) {
227 qq-( $column IS NULL )-;
229 qq-( $column IS NULL OR $column = '' )-;
232 qq-( $column IS NULL OR $column = "" )-;
234 } elsif ( $op eq '!=' ) {
235 if ( driver_name eq 'Pg' ) {
236 if ( $dbdef->table($table)->column($column)->type =~ /(int)/i ) {
237 qq-( $column IS NOT NULL )-;
239 qq-( $column IS NOT NULL AND $column != '' )-;
242 qq-( $column IS NOT NULL AND $column != "" )-;
245 if ( driver_name eq 'Pg' ) {
246 qq-( $column $op '' )-;
248 qq-( $column $op "" )-;
256 $statement .= " $extra_sql" if defined($extra_sql);
258 warn "[debug]$me $statement\n" if $DEBUG > 1;
259 my $sth = $dbh->prepare($statement)
260 or croak "$dbh->errstr doing $statement";
265 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
267 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
268 && $dbdef->table($table)->column($field)->type =~ /(int)/i
270 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
272 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
276 # $sth->execute( map $record->{$_},
277 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
278 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
280 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
282 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
284 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
285 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
286 #derivied class didn't override new method, so this optimization is safe
289 new_or_cached( "FS::$table", { %{$_} }, $cache )
290 } @{$sth->fetchall_arrayref( {} )};
293 new( "FS::$table", { %{$_} } )
294 } @{$sth->fetchall_arrayref( {} )};
297 warn "untested code (class FS::$table uses custom new method)";
299 eval 'FS::'. $table. '->new( { %{$_} } )';
300 } @{$sth->fetchall_arrayref( {} )};
303 cluck "warning: FS::$table not loaded; returning FS::Record objects";
305 FS::Record->new( $table, { %{$_} } );
306 } @{$sth->fetchall_arrayref( {} )};
311 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
313 Experimental JOINed search method. Using this method, you can execute a
314 single SELECT spanning multiple tables, and cache the results for subsequent
315 method calls. Interface will almost definately change in an incompatible
323 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
324 my $cache = FS::SearchCache->new( $ptable, $pkey );
327 grep { !$saw{$_->getfield($pkey)}++ }
328 qsearch($table, $record, $select, $extra_sql, $cache )
332 =item qsearchs TABLE, HASHREF
334 Same as qsearch, except that if more than one record matches, it B<carp>s but
335 returns the first. If this happens, you either made a logic error in asking
336 for a single item, or your data is corrupted.
340 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
342 my(@result) = qsearch(@_);
343 carp "warning: Multiple records in scalar search ($table)"
344 if scalar(@result) > 1;
345 #should warn more vehemently if the search was on a primary key?
346 scalar(@result) ? ($result[0]) : ();
357 Returns the table name.
362 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
369 Returns the DBIx::DBSchema::Table object for the table.
375 my($table)=$self->table;
376 $dbdef->table($table);
379 =item get, getfield COLUMN
381 Returns the value of the column/field/key COLUMN.
386 my($self,$field) = @_;
387 # to avoid "Use of unitialized value" errors
388 if ( defined ( $self->{Hash}->{$field} ) ) {
389 $self->{Hash}->{$field};
399 =item set, setfield COLUMN, VALUE
401 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
406 my($self,$field,$value) = @_;
407 $self->{'Hash'}->{$field} = $value;
414 =item AUTLOADED METHODS
416 $record->column is a synonym for $record->get('column');
418 $record->column('value') is a synonym for $record->set('column','value');
425 my($field)=$AUTOLOAD;
427 if ( defined($value) ) {
428 confess "errant AUTOLOAD $field for $self (arg $value)"
429 unless $self->can('setfield');
430 $self->setfield($field,$value);
432 confess "errant AUTOLOAD $field for $self (no args)"
433 unless $self->can('getfield');
434 $self->getfield($field);
440 # my $field = $AUTOLOAD;
442 # if ( defined($_[1]) ) {
443 # $_[0]->setfield($field, $_[1]);
445 # $_[0]->getfield($field);
451 Returns a list of the column/value pairs, usually for assigning to a new hash.
453 To make a distinct duplicate of an FS::Record object, you can do:
455 $new = new FS::Record ( $old->table, { $old->hash } );
461 %{ $self->{'Hash'} };
466 Returns a reference to the column/value hash.
477 Inserts this record to the database. If there is an error, returns the error,
478 otherwise returns false.
485 my $error = $self->check;
486 return $error if $error;
488 #single-field unique keys are given a value if false
489 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
490 foreach ( $self->dbdef_table->unique->singles ) {
491 $self->unique($_) unless $self->getfield($_);
494 #and also the primary key, if the database isn't going to
495 my $primary_key = $self->dbdef_table->primary_key;
497 if ( $primary_key ) {
498 my $col = $self->dbdef_table->column($primary_key);
501 uc($col->type) eq 'SERIAL'
502 || ( driver_name eq 'Pg'
503 && defined($col->default)
504 && $col->default =~ /^nextval\(/i
506 || ( driver_name eq 'mysql'
507 && defined($col->local)
508 && $col->local =~ /AUTO_INCREMENT/i
510 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
513 my $table = $self->table;
514 #false laziness w/delete
516 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
519 my @values = map { _quote( $self->getfield($_), $table, $_) } @fields;
522 my $statement = "INSERT INTO $table ( ".
523 join( ', ', @fields ).
525 join( ', ', @values ).
528 warn "[debug]$me $statement\n" if $DEBUG > 1;
529 my $sth = dbh->prepare($statement) or return dbh->errstr;
531 local $SIG{HUP} = 'IGNORE';
532 local $SIG{INT} = 'IGNORE';
533 local $SIG{QUIT} = 'IGNORE';
534 local $SIG{TERM} = 'IGNORE';
535 local $SIG{TSTP} = 'IGNORE';
536 local $SIG{PIPE} = 'IGNORE';
538 $sth->execute or return $sth->errstr;
540 if ( $db_seq ) { # get inserted id from the database, if applicable
541 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
543 if ( driver_name eq 'Pg' ) {
545 my $oid = $sth->{'pg_oid_status'};
546 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
547 my $i_sth = dbh->prepare($i_sql) or do {
548 dbh->rollback if $FS::UID::AutoCommit;
551 $i_sth->execute($oid) or do {
552 dbh->rollback if $FS::UID::AutoCommit;
553 return $i_sth->errstr;
555 $insertid = $i_sth->fetchrow_arrayref->[0];
557 } elsif ( driver_name eq 'mysql' ) {
559 $insertid = dbh->{'mysql_insertid'};
560 # work around mysql_insertid being null some of the time, ala RT :/
561 unless ( $insertid ) {
562 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
563 "using SELECT LAST_INSERT_ID();";
564 my $i_sql = "SELECT LAST_INSERT_ID()";
565 my $i_sth = dbh->prepare($i_sql) or do {
566 dbh->rollback if $FS::UID::AutoCommit;
569 $i_sth->execute or do {
570 dbh->rollback if $FS::UID::AutoCommit;
571 return $i_sth->errstr;
573 $insertid = $i_sth->fetchrow_arrayref->[0];
577 dbh->rollback if $FS::UID::AutoCommit;
578 return "don't know how to retreive inserted ids from ". driver_name.
579 ", try using counterfiles (maybe run dbdef-create?)";
581 $self->setfield($primary_key, $insertid);
585 if ( defined $dbdef->table('h_'. $table) ) {
586 my $h_statement = $self->_h_statement('insert');
587 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
588 $h_sth = dbh->prepare($h_statement) or do {
589 dbh->rollback if $FS::UID::AutoCommit;
595 $h_sth->execute or return $h_sth->errstr if $h_sth;
597 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
604 Depriciated (use insert instead).
609 cluck "warning: FS::Record::add deprecated!";
610 insert @_; #call method in this scope
615 Delete this record from the database. If there is an error, returns the error,
616 otherwise returns false.
623 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
625 $self->getfield($_) eq ''
626 #? "( $_ IS NULL OR $_ = \"\" )"
627 ? ( driver_name eq 'Pg'
629 : "( $_ IS NULL OR $_ = \"\" )"
631 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
632 } ( $self->dbdef_table->primary_key )
633 ? ( $self->dbdef_table->primary_key)
636 warn "[debug]$me $statement\n" if $DEBUG > 1;
637 my $sth = dbh->prepare($statement) or return dbh->errstr;
640 if ( defined $dbdef->table('h_'. $self->table) ) {
641 my $h_statement = $self->_h_statement('delete');
642 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
643 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
648 local $SIG{HUP} = 'IGNORE';
649 local $SIG{INT} = 'IGNORE';
650 local $SIG{QUIT} = 'IGNORE';
651 local $SIG{TERM} = 'IGNORE';
652 local $SIG{TSTP} = 'IGNORE';
653 local $SIG{PIPE} = 'IGNORE';
655 my $rc = $sth->execute or return $sth->errstr;
656 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
657 $h_sth->execute or return $h_sth->errstr if $h_sth;
658 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
660 #no need to needlessly destoy the data either (causes problems actually)
661 #undef $self; #no need to keep object!
668 Depriciated (use delete instead).
673 cluck "warning: FS::Record::del deprecated!";
674 &delete(@_); #call method in this scope
677 =item replace OLD_RECORD
679 Replace the OLD_RECORD with this one in the database. If there is an error,
680 returns the error, otherwise returns false.
685 my ( $new, $old ) = ( shift, shift );
686 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
688 return "Records not in same table!" unless $new->table eq $old->table;
690 my $primary_key = $old->dbdef_table->primary_key;
691 return "Can't change $primary_key"
693 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
695 my $error = $new->check;
696 return $error if $error;
698 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
700 carp "[warning]$me $new -> replace $old: records identical";
704 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
706 "$_ = ". _quote($new->getfield($_),$old->table,$_)
711 $old->getfield($_) eq ''
712 #? "( $_ IS NULL OR $_ = \"\" )"
713 ? ( driver_name eq 'Pg'
715 : "( $_ IS NULL OR $_ = \"\" )"
717 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
718 } ( $primary_key ? ( $primary_key ) : $old->fields )
721 warn "[debug]$me $statement\n" if $DEBUG > 1;
722 my $sth = dbh->prepare($statement) or return dbh->errstr;
725 if ( defined $dbdef->table('h_'. $old->table) ) {
726 my $h_old_statement = $old->_h_statement('replace_old');
727 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
728 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
734 if ( defined $dbdef->table('h_'. $new->table) ) {
735 my $h_new_statement = $new->_h_statement('replace_new');
736 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
737 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
742 local $SIG{HUP} = 'IGNORE';
743 local $SIG{INT} = 'IGNORE';
744 local $SIG{QUIT} = 'IGNORE';
745 local $SIG{TERM} = 'IGNORE';
746 local $SIG{TSTP} = 'IGNORE';
747 local $SIG{PIPE} = 'IGNORE';
749 my $rc = $sth->execute or return $sth->errstr;
750 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
751 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
752 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
753 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
761 Depriciated (use replace instead).
766 cluck "warning: FS::Record::rep deprecated!";
767 replace @_; #call method in this scope
772 Not yet implemented, croaks. Derived classes should provide a check method.
777 confess "FS::Record::check not implemented; supply one in subclass!";
781 my( $self, $action ) = @_;
784 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
787 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
789 "INSERT INTO h_". $self->table. " ( ".
790 join(', ', qw(history_date history_user history_action), @fields ).
792 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
799 B<Warning>: External use is B<deprecated>.
801 Replaces COLUMN in record with a unique number, using counters in the
802 filesystem. Used by the B<insert> method on single-field unique columns
803 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
804 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
806 Returns the new value.
811 my($self,$field) = @_;
812 my($table)=$self->table;
814 croak "Unique called on field $field, but it is ",
815 $self->getfield($field),
817 if $self->getfield($field);
819 #warn "table $table is tainted" if is_tainted($table);
820 #warn "field $field is tainted" if is_tainted($field);
822 my($counter) = new File::CounterFile "$table.$field",0;
824 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
826 # my($counter) = new File::CounterFile "$user/$table.$field",0;
829 my $index = $counter->inc;
830 $index = $counter->inc while qsearchs($table, { $field=>$index } );
835 $self->setfield($field,$index);
839 =item ut_float COLUMN
841 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
842 null. If there is an error, returns the error, otherwise returns false.
847 my($self,$field)=@_ ;
848 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
849 $self->getfield($field) =~ /^(\d+)$/ ||
850 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
851 $self->getfield($field) =~ /^(\d+e\d+)$/)
852 or return "Illegal or empty (float) $field: ". $self->getfield($field);
853 $self->setfield($field,$1);
857 =item ut_number COLUMN
859 Check/untaint simple numeric data (whole numbers). May not be null. If there
860 is an error, returns the error, otherwise returns false.
866 $self->getfield($field) =~ /^(\d+)$/
867 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
868 $self->setfield($field,$1);
872 =item ut_numbern COLUMN
874 Check/untaint simple numeric data (whole numbers). May be null. If there is
875 an error, returns the error, otherwise returns false.
881 $self->getfield($field) =~ /^(\d*)$/
882 or return "Illegal (numeric) $field: ". $self->getfield($field);
883 $self->setfield($field,$1);
887 =item ut_money COLUMN
889 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
890 is an error, returns the error, otherwise returns false.
896 $self->setfield($field, 0) if $self->getfield($field) eq '';
897 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
898 or return "Illegal (money) $field: ". $self->getfield($field);
899 #$self->setfield($field, "$1$2$3" || 0);
900 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
906 Check/untaint text. Alphanumerics, spaces, and the following punctuation
907 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
908 May not be null. If there is an error, returns the error, otherwise returns
915 #warn "msgcat ". \&msgcat. "\n";
916 #warn "notexist ". \¬exist. "\n";
917 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
918 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
919 or return gettext('illegal_or_empty_text'). " $field: ".
920 $self->getfield($field);
921 $self->setfield($field,$1);
925 =item ut_textn COLUMN
927 Check/untaint text. Alphanumerics, spaces, and the following punctuation
928 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
929 May be null. If there is an error, returns the error, otherwise returns false.
935 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
936 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
937 $self->setfield($field,$1);
941 =item ut_alpha COLUMN
943 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
944 an error, returns the error, otherwise returns false.
950 $self->getfield($field) =~ /^(\w+)$/
951 or return "Illegal or empty (alphanumeric) $field: ".
952 $self->getfield($field);
953 $self->setfield($field,$1);
957 =item ut_alpha COLUMN
959 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
960 error, returns the error, otherwise returns false.
966 $self->getfield($field) =~ /^(\w*)$/
967 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
968 $self->setfield($field,$1);
972 =item ut_phonen COLUMN [ COUNTRY ]
974 Check/untaint phone numbers. May be null. If there is an error, returns
975 the error, otherwise returns false.
977 Takes an optional two-letter ISO country code; without it or with unsupported
978 countries, ut_phonen simply calls ut_alphan.
983 my( $self, $field, $country ) = @_;
984 return $self->ut_alphan($field) unless defined $country;
985 my $phonen = $self->getfield($field);
986 if ( $phonen eq '' ) {
987 $self->setfield($field,'');
988 } elsif ( $country eq 'US' || $country eq 'CA' ) {
990 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
991 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
992 $phonen = "$1-$2-$3";
993 $phonen .= " x$4" if $4;
994 $self->setfield($field,$phonen);
996 warn "warning: don't know how to check phone numbers for country $country";
997 return $self->ut_textn($field);
1004 Check/untaint ip addresses. IPv4 only for now.
1009 my( $self, $field ) = @_;
1010 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1011 or return "Illegal (IP address) $field: ". $self->getfield($field);
1012 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1013 $self->setfield($field, "$1.$2.$3.$4");
1019 Check/untaint ip addresses. IPv4 only for now. May be null.
1024 my( $self, $field ) = @_;
1025 if ( $self->getfield($field) =~ /^()$/ ) {
1026 $self->setfield($field,'');
1029 $self->ut_ip($field);
1033 =item ut_domain COLUMN
1035 Check/untaint host and domain names.
1040 my( $self, $field ) = @_;
1041 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1042 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1043 or return "Illegal (domain) $field: ". $self->getfield($field);
1044 $self->setfield($field,$1);
1048 =item ut_name COLUMN
1050 Check/untaint proper names; allows alphanumerics, spaces and the following
1051 punctuation: , . - '
1058 my( $self, $field ) = @_;
1059 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1060 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1061 $self->setfield($field,$1);
1067 Check/untaint zip codes.
1072 my( $self, $field, $country ) = @_;
1073 if ( $country eq 'US' ) {
1074 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1075 or return gettext('illegal_zip'). " $field for country $country: ".
1076 $self->getfield($field);
1077 $self->setfield($field,$1);
1079 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1080 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1081 $self->setfield($field,$1);
1086 =item ut_country COLUMN
1088 Check/untaint country codes. Country names are changed to codes, if possible -
1089 see L<Locale::Country>.
1094 my( $self, $field ) = @_;
1095 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1096 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1097 && country2code($1) ) {
1098 $self->setfield($field,uc(country2code($1)));
1101 $self->getfield($field) =~ /^(\w\w)$/
1102 or return "Illegal (country) $field: ". $self->getfield($field);
1103 $self->setfield($field,uc($1));
1107 =item ut_anything COLUMN
1109 Untaints arbitrary data. Be careful.
1114 my( $self, $field ) = @_;
1115 $self->getfield($field) =~ /^(.*)$/s
1116 or return "Illegal $field: ". $self->getfield($field);
1117 $self->setfield($field,$1);
1121 =item ut_enum COLUMN CHOICES_ARRAYREF
1123 Check/untaint a column, supplying all possible choices, like the "enum" type.
1128 my( $self, $field, $choices ) = @_;
1129 foreach my $choice ( @$choices ) {
1130 if ( $self->getfield($field) eq $choice ) {
1131 $self->setfield($choice);
1135 return "Illegal (enum) field $field: ". $self->getfield($field);
1138 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1140 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1141 on the column first.
1145 sub ut_foreign_key {
1146 my( $self, $field, $table, $foreign ) = @_;
1147 qsearchs($table, { $foreign => $self->getfield($field) })
1148 or return "Can't find $field ". $self->getfield($field).
1149 " in $table.$foreign";
1153 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1155 Like ut_foreign_key, except the null value is also allowed.
1159 sub ut_foreign_keyn {
1160 my( $self, $field, $table, $foreign ) = @_;
1161 $self->getfield($field)
1162 ? $self->ut_foreign_key($field, $table, $foreign)
1166 =item fields [ TABLE ]
1168 This can be used as both a subroutine and a method call. It returns a list
1169 of the columns in this record's table, or an explicitly specified table.
1170 (See L<DBIx::DBSchema::Table>).
1174 # Usage: @fields = fields($table);
1175 # @fields = $record->fields;
1177 my $something = shift;
1179 if ( ref($something) ) {
1180 $table = $something->table;
1182 $table = $something;
1184 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1185 my($table_obj) = $dbdef->table($table);
1186 confess "Unknown table $table" unless $table_obj;
1187 $table_obj->columns;
1196 =item reload_dbdef([FILENAME])
1198 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1199 non-default filename. This command is executed at startup unless
1200 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1205 my $file = shift || $dbdef_file;
1207 unless ( exists $dbdef_cache{$file} ) {
1208 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1209 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1210 or die "can't load database schema from $file";
1212 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1214 $dbdef = $dbdef_cache{$file};
1219 Returns the current database definition. See L<DBIx::DBSchema>.
1223 sub dbdef { $dbdef; }
1225 =item _quote VALUE, TABLE, COLUMN
1227 This is an internal function used to construct SQL statements. It returns
1228 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1229 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1234 my($value, $table, $column) = @_;
1235 my $column_obj = $dbdef->table($table)->column($column);
1236 my $column_type = $column_obj->type;
1238 if ( $value eq '' && $column_type =~ /^int/ ) {
1239 if ( $column_obj->null ) {
1242 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1246 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1247 ! $column_type =~ /(char|binary|text)$/i ) {
1256 This is deprecated. Don't use it.
1258 It returns a hash-type list with the fields of this record's table set true.
1263 carp "warning: hfields is deprecated";
1266 foreach (fields($table)) {
1275 "$_: ". $self->getfield($_). "|"
1276 } (fields($self->table)) );
1279 sub DESTROY { return; }
1283 # #use Carp qw(cluck);
1284 # #cluck "DESTROYING $self";
1285 # warn "DESTROYING $self";
1289 # return ! eval { join('',@_), kill 0; 1; };
1296 This module should probably be renamed, since much of the functionality is
1297 of general use. It is not completely unlike Adapter::DBI (see below).
1299 Exported qsearch and qsearchs should be deprecated in favor of method calls
1300 (against an FS::Record object like the old search and searchs that qsearch
1301 and qsearchs were on top of.)
1303 The whole fields / hfields mess should be removed.
1305 The various WHERE clauses should be subroutined.
1307 table string should be deprecated in favor of DBIx::DBSchema::Table.
1309 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1310 true maps to the database (and WHERE clauses) would also help.
1312 The ut_ methods should ask the dbdef for a default length.
1314 ut_sqltype (like ut_varchar) should all be defined
1316 A fallback check method should be provided which uses the dbdef.
1318 The ut_money method assumes money has two decimal digits.
1320 The Pg money kludge in the new method only strips `$'.
1322 The ut_phonen method only checks US-style phone numbers.
1324 The _quote function should probably use ut_float instead of a regex.
1326 All the subroutines probably should be methods, here or elsewhere.
1328 Probably should borrow/use some dbdef methods where appropriate (like sub
1331 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1332 or allow it to be set. Working around it is ugly any way around - DBI should
1333 be fixed. (only affects RDBMS which return uppercase column names)
1335 ut_zip should take an optional country like ut_phone.
1339 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1341 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.