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 {
211 if ( ref($record->{$_}) ) {
212 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
213 $op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
214 $record->{$_} = $record->{$_}{'value'}
217 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
219 if ( driver_name eq 'Pg' ) {
220 qq-( $_ IS NULL OR $_ = '' )-;
222 qq-( $_ IS NULL OR $_ = "" )-;
224 } elsif ( $op eq '!=' ) {
225 if ( driver_name eq 'Pg' ) {
226 qq-( $_ IS NOT NULL AND $_ != '' )-;
228 qq-( $_ IS NOT NULL AND $_ != "" )-;
231 if ( driver_name eq 'Pg' ) {
242 $statement .= " $extra_sql" if defined($extra_sql);
244 warn "[debug]$me $statement\n" if $DEBUG > 1;
245 my $sth = $dbh->prepare($statement)
246 or croak "$dbh->errstr doing $statement";
251 grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
253 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
254 && $dbdef->table($table)->column($field)->type =~ /(int)/i
256 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
258 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
262 # $sth->execute( map $record->{$_},
263 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
264 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
266 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
268 $dbh->commit or croak $dbh->errstr if $FS::UID::AutoCommit;
270 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
271 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
272 #derivied class didn't override new method, so this optimization is safe
275 new_or_cached( "FS::$table", { %{$_} }, $cache )
276 } @{$sth->fetchall_arrayref( {} )};
279 new( "FS::$table", { %{$_} } )
280 } @{$sth->fetchall_arrayref( {} )};
283 warn "untested code (class FS::$table uses custom new method)";
285 eval 'FS::'. $table. '->new( { %{$_} } )';
286 } @{$sth->fetchall_arrayref( {} )};
289 cluck "warning: FS::$table not loaded; returning FS::Record objects";
291 FS::Record->new( $table, { %{$_} } );
292 } @{$sth->fetchall_arrayref( {} )};
297 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
299 Experimental JOINed search method. Using this method, you can execute a
300 single SELECT spanning multiple tables, and cache the results for subsequent
301 method calls. Interface will almost definately change in an incompatible
309 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
310 my $cache = FS::SearchCache->new( $ptable, $pkey );
313 grep { !$saw{$_->getfield($pkey)}++ }
314 qsearch($table, $record, $select, $extra_sql, $cache )
318 =item qsearchs TABLE, HASHREF
320 Same as qsearch, except that if more than one record matches, it B<carp>s but
321 returns the first. If this happens, you either made a logic error in asking
322 for a single item, or your data is corrupted.
326 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
327 my(@result) = qsearch(@_);
328 carp "warning: Multiple records in scalar search!" if scalar(@result) > 1;
329 #should warn more vehemently if the search was on a primary key?
330 scalar(@result) ? ($result[0]) : ();
341 Returns the table name.
346 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
353 Returns the DBIx::DBSchema::Table object for the table.
359 my($table)=$self->table;
360 $dbdef->table($table);
363 =item get, getfield COLUMN
365 Returns the value of the column/field/key COLUMN.
370 my($self,$field) = @_;
371 # to avoid "Use of unitialized value" errors
372 if ( defined ( $self->{Hash}->{$field} ) ) {
373 $self->{Hash}->{$field};
383 =item set, setfield COLUMN, VALUE
385 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
390 my($self,$field,$value) = @_;
391 $self->{'Hash'}->{$field} = $value;
398 =item AUTLOADED METHODS
400 $record->column is a synonym for $record->get('column');
402 $record->column('value') is a synonym for $record->set('column','value');
409 my($field)=$AUTOLOAD;
411 if ( defined($value) ) {
412 confess "errant AUTOLOAD $field for $self (arg $value)"
413 unless $self->can('setfield');
414 $self->setfield($field,$value);
416 confess "errant AUTOLOAD $field for $self (no args)"
417 unless $self->can('getfield');
418 $self->getfield($field);
424 # my $field = $AUTOLOAD;
426 # if ( defined($_[1]) ) {
427 # $_[0]->setfield($field, $_[1]);
429 # $_[0]->getfield($field);
435 Returns a list of the column/value pairs, usually for assigning to a new hash.
437 To make a distinct duplicate of an FS::Record object, you can do:
439 $new = new FS::Record ( $old->table, { $old->hash } );
445 %{ $self->{'Hash'} };
450 Returns a reference to the column/value hash.
461 Inserts this record to the database. If there is an error, returns the error,
462 otherwise returns false.
469 my $error = $self->check;
470 return $error if $error;
472 #single-field unique keys are given a value if false
473 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
474 foreach ( $self->dbdef_table->unique->singles ) {
475 $self->unique($_) unless $self->getfield($_);
478 #and also the primary key, if the database isn't going to
479 my $primary_key = $self->dbdef_table->primary_key;
481 if ( $primary_key ) {
482 my $col = $self->dbdef_table->column($primary_key);
485 uc($col->type) eq 'SERIAL'
486 || ( driver_name eq 'Pg'
487 && defined($col->default)
488 && $col->default =~ /^nextval\(/i
490 || ( driver_name eq 'mysql'
491 && defined($col->local)
492 && $col->local =~ /AUTO_INCREMENT/i
494 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
497 my $table = $self->table;
498 #false laziness w/delete
500 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
503 my @values = map { _quote( $self->getfield($_), $table, $_) } @fields;
506 my $statement = "INSERT INTO $table ( ".
507 join( ', ', @fields ).
509 join( ', ', @values ).
512 warn "[debug]$me $statement\n" if $DEBUG > 1;
513 my $sth = dbh->prepare($statement) or return dbh->errstr;
515 local $SIG{HUP} = 'IGNORE';
516 local $SIG{INT} = 'IGNORE';
517 local $SIG{QUIT} = 'IGNORE';
518 local $SIG{TERM} = 'IGNORE';
519 local $SIG{TSTP} = 'IGNORE';
520 local $SIG{PIPE} = 'IGNORE';
522 $sth->execute or return $sth->errstr;
524 if ( $db_seq ) { # get inserted id from the database, if applicable
525 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
527 if ( driver_name eq 'Pg' ) {
529 my $oid = $sth->{'pg_oid_status'};
530 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
531 my $i_sth = dbh->prepare($i_sql) or do {
532 dbh->rollback if $FS::UID::AutoCommit;
535 $i_sth->execute($oid) or do {
536 dbh->rollback if $FS::UID::AutoCommit;
537 return $i_sth->errstr;
539 $insertid = $i_sth->fetchrow_arrayref->[0];
541 } elsif ( driver_name eq 'mysql' ) {
543 $insertid = dbh->{'mysql_insertid'};
544 # work around mysql_insertid being null some of the time, ala RT :/
545 unless ( $insertid ) {
546 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
547 "using SELECT LAST_INSERT_ID();";
548 my $i_sql = "SELECT LAST_INSERT_ID()";
549 my $i_sth = dbh->prepare($i_sql) or do {
550 dbh->rollback if $FS::UID::AutoCommit;
553 $i_sth->execute or do {
554 dbh->rollback if $FS::UID::AutoCommit;
555 return $i_sth->errstr;
557 $insertid = $i_sth->fetchrow_arrayref->[0];
561 dbh->rollback if $FS::UID::AutoCommit;
562 return "don't know how to retreive inserted ids from ". driver_name.
563 ", try using counterfiles (maybe run dbdef-create?)";
565 $self->setfield($primary_key, $insertid);
569 if ( defined $dbdef->table('h_'. $table) ) {
570 my $h_statement = $self->_h_statement('insert');
571 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
572 $h_sth = dbh->prepare($h_statement) or do {
573 dbh->rollback if $FS::UID::AutoCommit;
579 $h_sth->execute or return $h_sth->errstr if $h_sth;
581 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
588 Depriciated (use insert instead).
593 cluck "warning: FS::Record::add deprecated!";
594 insert @_; #call method in this scope
599 Delete this record from the database. If there is an error, returns the error,
600 otherwise returns false.
607 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
609 $self->getfield($_) eq ''
610 #? "( $_ IS NULL OR $_ = \"\" )"
611 ? ( driver_name eq 'Pg'
613 : "( $_ IS NULL OR $_ = \"\" )"
615 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
616 } ( $self->dbdef_table->primary_key )
617 ? ( $self->dbdef_table->primary_key)
620 warn "[debug]$me $statement\n" if $DEBUG > 1;
621 my $sth = dbh->prepare($statement) or return dbh->errstr;
624 if ( defined $dbdef->table('h_'. $self->table) ) {
625 my $h_statement = $self->_h_statement('delete');
626 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
627 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
632 local $SIG{HUP} = 'IGNORE';
633 local $SIG{INT} = 'IGNORE';
634 local $SIG{QUIT} = 'IGNORE';
635 local $SIG{TERM} = 'IGNORE';
636 local $SIG{TSTP} = 'IGNORE';
637 local $SIG{PIPE} = 'IGNORE';
639 my $rc = $sth->execute or return $sth->errstr;
640 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
641 $h_sth->execute or return $h_sth->errstr if $h_sth;
642 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
644 #no need to needlessly destoy the data either (causes problems actually)
645 #undef $self; #no need to keep object!
652 Depriciated (use delete instead).
657 cluck "warning: FS::Record::del deprecated!";
658 &delete(@_); #call method in this scope
661 =item replace OLD_RECORD
663 Replace the OLD_RECORD with this one in the database. If there is an error,
664 returns the error, otherwise returns false.
669 my ( $new, $old ) = ( shift, shift );
670 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
672 return "Records not in same table!" unless $new->table eq $old->table;
674 my $primary_key = $old->dbdef_table->primary_key;
675 return "Can't change $primary_key"
677 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
679 my $error = $new->check;
680 return $error if $error;
682 my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
684 carp "[warning]$me $new -> replace $old: records identical";
688 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
690 "$_ = ". _quote($new->getfield($_),$old->table,$_)
695 $old->getfield($_) eq ''
696 #? "( $_ IS NULL OR $_ = \"\" )"
697 ? ( driver_name eq 'Pg'
699 : "( $_ IS NULL OR $_ = \"\" )"
701 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
702 } ( $primary_key ? ( $primary_key ) : $old->fields )
705 warn "[debug]$me $statement\n" if $DEBUG > 1;
706 my $sth = dbh->prepare($statement) or return dbh->errstr;
709 if ( defined $dbdef->table('h_'. $old->table) ) {
710 my $h_old_statement = $old->_h_statement('replace_old');
711 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
712 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
718 if ( defined $dbdef->table('h_'. $new->table) ) {
719 my $h_new_statement = $new->_h_statement('replace_new');
720 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
721 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
726 local $SIG{HUP} = 'IGNORE';
727 local $SIG{INT} = 'IGNORE';
728 local $SIG{QUIT} = 'IGNORE';
729 local $SIG{TERM} = 'IGNORE';
730 local $SIG{TSTP} = 'IGNORE';
731 local $SIG{PIPE} = 'IGNORE';
733 my $rc = $sth->execute or return $sth->errstr;
734 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
735 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
736 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
737 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
745 Depriciated (use replace instead).
750 cluck "warning: FS::Record::rep deprecated!";
751 replace @_; #call method in this scope
756 Not yet implemented, croaks. Derived classes should provide a check method.
761 confess "FS::Record::check not implemented; supply one in subclass!";
765 my( $self, $action ) = @_;
768 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
771 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
773 "INSERT INTO h_". $self->table. " ( ".
774 join(', ', qw(history_date history_user history_action), @fields ).
776 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
783 B<Warning>: External use is B<deprecated>.
785 Replaces COLUMN in record with a unique number, using counters in the
786 filesystem. Used by the B<insert> method on single-field unique columns
787 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
788 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
790 Returns the new value.
795 my($self,$field) = @_;
796 my($table)=$self->table;
798 croak "Unique called on field $field, but it is ",
799 $self->getfield($field),
801 if $self->getfield($field);
803 #warn "table $table is tainted" if is_tainted($table);
804 #warn "field $field is tainted" if is_tainted($field);
806 my($counter) = new File::CounterFile "$table.$field",0;
808 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
810 # my($counter) = new File::CounterFile "$user/$table.$field",0;
813 my $index = $counter->inc;
814 $index = $counter->inc while qsearchs($table, { $field=>$index } );
819 $self->setfield($field,$index);
823 =item ut_float COLUMN
825 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
826 null. If there is an error, returns the error, otherwise returns false.
831 my($self,$field)=@_ ;
832 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
833 $self->getfield($field) =~ /^(\d+)$/ ||
834 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
835 $self->getfield($field) =~ /^(\d+e\d+)$/)
836 or return "Illegal or empty (float) $field: ". $self->getfield($field);
837 $self->setfield($field,$1);
841 =item ut_number COLUMN
843 Check/untaint simple numeric data (whole numbers). May not be null. If there
844 is an error, returns the error, otherwise returns false.
850 $self->getfield($field) =~ /^(\d+)$/
851 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
852 $self->setfield($field,$1);
856 =item ut_numbern COLUMN
858 Check/untaint simple numeric data (whole numbers). May be null. If there is
859 an error, returns the error, otherwise returns false.
865 $self->getfield($field) =~ /^(\d*)$/
866 or return "Illegal (numeric) $field: ". $self->getfield($field);
867 $self->setfield($field,$1);
871 =item ut_money COLUMN
873 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
874 is an error, returns the error, otherwise returns false.
880 $self->setfield($field, 0) if $self->getfield($field) eq '';
881 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
882 or return "Illegal (money) $field: ". $self->getfield($field);
883 #$self->setfield($field, "$1$2$3" || 0);
884 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
890 Check/untaint text. Alphanumerics, spaces, and the following punctuation
891 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
892 May not be null. If there is an error, returns the error, otherwise returns
899 #warn "msgcat ". \&msgcat. "\n";
900 #warn "notexist ". \¬exist. "\n";
901 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
902 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
903 or return gettext('illegal_or_empty_text'). " $field: ".
904 $self->getfield($field);
905 $self->setfield($field,$1);
909 =item ut_textn COLUMN
911 Check/untaint text. Alphanumerics, spaces, and the following punctuation
912 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
913 May be null. If there is an error, returns the error, otherwise returns false.
919 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
920 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
921 $self->setfield($field,$1);
925 =item ut_alpha COLUMN
927 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
928 an error, returns the error, otherwise returns false.
934 $self->getfield($field) =~ /^(\w+)$/
935 or return "Illegal or empty (alphanumeric) $field: ".
936 $self->getfield($field);
937 $self->setfield($field,$1);
941 =item ut_alpha COLUMN
943 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
944 error, returns the error, otherwise returns false.
950 $self->getfield($field) =~ /^(\w*)$/
951 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
952 $self->setfield($field,$1);
956 =item ut_phonen COLUMN [ COUNTRY ]
958 Check/untaint phone numbers. May be null. If there is an error, returns
959 the error, otherwise returns false.
961 Takes an optional two-letter ISO country code; without it or with unsupported
962 countries, ut_phonen simply calls ut_alphan.
967 my( $self, $field, $country ) = @_;
968 return $self->ut_alphan($field) unless defined $country;
969 my $phonen = $self->getfield($field);
970 if ( $phonen eq '' ) {
971 $self->setfield($field,'');
972 } elsif ( $country eq 'US' || $country eq 'CA' ) {
974 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
975 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
976 $phonen = "$1-$2-$3";
977 $phonen .= " x$4" if $4;
978 $self->setfield($field,$phonen);
980 warn "warning: don't know how to check phone numbers for country $country";
981 return $self->ut_textn($field);
988 Check/untaint ip addresses. IPv4 only for now.
993 my( $self, $field ) = @_;
994 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
995 or return "Illegal (IP address) $field: ". $self->getfield($field);
996 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
997 $self->setfield($field, "$1.$2.$3.$4");
1003 Check/untaint ip addresses. IPv4 only for now. May be null.
1008 my( $self, $field ) = @_;
1009 if ( $self->getfield($field) =~ /^()$/ ) {
1010 $self->setfield($field,'');
1013 $self->ut_ip($field);
1017 =item ut_domain COLUMN
1019 Check/untaint host and domain names.
1024 my( $self, $field ) = @_;
1025 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1026 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1027 or return "Illegal (domain) $field: ". $self->getfield($field);
1028 $self->setfield($field,$1);
1032 =item ut_name COLUMN
1034 Check/untaint proper names; allows alphanumerics, spaces and the following
1035 punctuation: , . - '
1042 my( $self, $field ) = @_;
1043 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1044 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1045 $self->setfield($field,$1);
1051 Check/untaint zip codes.
1056 my( $self, $field, $country ) = @_;
1057 if ( $country eq 'US' ) {
1058 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1059 or return gettext('illegal_zip'). " $field for country $country: ".
1060 $self->getfield($field);
1061 $self->setfield($field,$1);
1063 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1064 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1065 $self->setfield($field,$1);
1070 =item ut_country COLUMN
1072 Check/untaint country codes. Country names are changed to codes, if possible -
1073 see L<Locale::Country>.
1078 my( $self, $field ) = @_;
1079 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1080 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1081 && country2code($1) ) {
1082 $self->setfield($field,uc(country2code($1)));
1085 $self->getfield($field) =~ /^(\w\w)$/
1086 or return "Illegal (country) $field: ". $self->getfield($field);
1087 $self->setfield($field,uc($1));
1091 =item ut_anything COLUMN
1093 Untaints arbitrary data. Be careful.
1098 my( $self, $field ) = @_;
1099 $self->getfield($field) =~ /^(.*)$/s
1100 or return "Illegal $field: ". $self->getfield($field);
1101 $self->setfield($field,$1);
1105 =item ut_enum COLUMN CHOICES_ARRAYREF
1107 Check/untaint a column, supplying all possible choices, like the "enum" type.
1112 my( $self, $field, $choices ) = @_;
1113 foreach my $choice ( @$choices ) {
1114 if ( $self->getfield($field) eq $choice ) {
1115 $self->setfield($choice);
1119 return "Illegal (enum) field $field: ". $self->getfield($field);
1122 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1124 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1125 on the column first.
1129 sub ut_foreign_key {
1130 my( $self, $field, $table, $foreign ) = @_;
1131 qsearchs($table, { $foreign => $self->getfield($field) })
1132 or return "Can't find $field ". $self->getfield($field).
1133 " in $table.$foreign";
1137 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1139 Like ut_foreign_key, except the null value is also allowed.
1143 sub ut_foreign_keyn {
1144 my( $self, $field, $table, $foreign ) = @_;
1145 $self->getfield($field)
1146 ? $self->ut_foreign_key($field, $table, $foreign)
1150 =item fields [ TABLE ]
1152 This can be used as both a subroutine and a method call. It returns a list
1153 of the columns in this record's table, or an explicitly specified table.
1154 (See L<DBIx::DBSchema::Table>).
1158 # Usage: @fields = fields($table);
1159 # @fields = $record->fields;
1161 my $something = shift;
1163 if ( ref($something) ) {
1164 $table = $something->table;
1166 $table = $something;
1168 #croak "Usage: \@fields = fields(\$table)\n or: \@fields = \$record->fields" unless $table;
1169 my($table_obj) = $dbdef->table($table);
1170 confess "Unknown table $table" unless $table_obj;
1171 $table_obj->columns;
1180 =item reload_dbdef([FILENAME])
1182 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1183 non-default filename. This command is executed at startup unless
1184 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1189 my $file = shift || $dbdef_file;
1191 unless ( exists $dbdef_cache{$file} ) {
1192 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1193 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1194 or die "can't load database schema from $file";
1196 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1198 $dbdef = $dbdef_cache{$file};
1203 Returns the current database definition. See L<DBIx::DBSchema>.
1207 sub dbdef { $dbdef; }
1209 =item _quote VALUE, TABLE, COLUMN
1211 This is an internal function used to construct SQL statements. It returns
1212 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1213 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1218 my($value,$table,$field)=@_;
1220 if ( $value =~ /^\d+(\.\d+)?$/ &&
1221 # ! ( datatype($table,$field) =~ /^char/ )
1222 ! $dbdef->table($table)->column($field)->type =~ /(char|binary|text)$/i
1226 $dbh->quote($value);
1232 This is deprecated. 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 deprecated";
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 deprecated 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 deprecated 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.