4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $conf $conf_encryption $me
7 $nowarn_identical $nowarn_classload
8 $no_update_diff $no_check_foreign
11 use Carp qw(carp cluck croak confess);
12 use Scalar::Util qw( blessed );
13 use File::CounterFile;
16 use File::Slurp qw( slurp );
17 use DBI qw(:sql_types);
18 use DBIx::DBSchema 0.33;
19 use FS::UID qw(dbh getotaker datasrc driver_name);
21 use FS::Schema qw(dbdef);
23 use FS::Msgcat qw(gettext);
24 #use FS::Conf; #dependency loop bs, in install_callback below instead
26 use FS::part_virtual_field;
32 #export dbdef for now... everything else expects to find it here
33 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
34 str2time_sql str2time_sql_closing );
39 $nowarn_identical = 0;
40 $nowarn_classload = 0;
42 $no_check_foreign = 0;
50 $conf_encryption = '';
51 FS::UID->install_callback( sub {
54 $conf = FS::Conf->new;
55 $conf_encryption = $conf->exists('encryption');
56 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
62 FS::Record - Database record objects
67 use FS::Record qw(dbh fields qsearch qsearchs);
69 $record = new FS::Record 'table', \%hash;
70 $record = new FS::Record 'table', { 'column' => 'value', ... };
72 $record = qsearchs FS::Record 'table', \%hash;
73 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
74 @records = qsearch FS::Record 'table', \%hash;
75 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
77 $table = $record->table;
78 $dbdef_table = $record->dbdef_table;
80 $value = $record->get('column');
81 $value = $record->getfield('column');
82 $value = $record->column;
84 $record->set( 'column' => 'value' );
85 $record->setfield( 'column' => 'value' );
86 $record->column('value');
88 %hash = $record->hash;
90 $hashref = $record->hashref;
92 $error = $record->insert;
94 $error = $record->delete;
96 $error = $new_record->replace($old_record);
98 # external use deprecated - handled by the database (at least for Pg, mysql)
99 $value = $record->unique('column');
101 $error = $record->ut_float('column');
102 $error = $record->ut_floatn('column');
103 $error = $record->ut_number('column');
104 $error = $record->ut_numbern('column');
105 $error = $record->ut_snumber('column');
106 $error = $record->ut_snumbern('column');
107 $error = $record->ut_money('column');
108 $error = $record->ut_text('column');
109 $error = $record->ut_textn('column');
110 $error = $record->ut_alpha('column');
111 $error = $record->ut_alphan('column');
112 $error = $record->ut_phonen('column');
113 $error = $record->ut_anything('column');
114 $error = $record->ut_name('column');
116 $quoted_value = _quote($value,'table','field');
119 $fields = hfields('table');
120 if ( $fields->{Field} ) { # etc.
122 @fields = fields 'table'; #as a subroutine
123 @fields = $record->fields; #as a method call
128 (Mostly) object-oriented interface to database records. Records are currently
129 implemented on top of DBI. FS::Record is intended as a base class for
130 table-specific classes to inherit from, i.e. FS::cust_main.
136 =item new [ TABLE, ] HASHREF
138 Creates a new record. It doesn't store it in the database, though. See
139 L<"insert"> for that.
141 Note that the object stores this hash reference, not a distinct copy of the
142 hash it points to. You can ask the object for a copy with the I<hash>
145 TABLE can only be omitted when a dervived class overrides the table method.
151 my $class = ref($proto) || $proto;
153 bless ($self, $class);
155 unless ( defined ( $self->table ) ) {
156 $self->{'Table'} = shift;
157 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
158 unless $nowarn_classload;
161 $self->{'Hash'} = shift;
163 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
164 $self->{'Hash'}{$field}='';
167 $self->_rebless if $self->can('_rebless');
169 $self->{'modified'} = 0;
171 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
178 my $class = ref($proto) || $proto;
180 bless ($self, $class);
182 $self->{'Table'} = shift unless defined ( $self->table );
184 my $hashref = $self->{'Hash'} = shift;
186 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
187 my $obj = $cache->cache->{$hashref->{$cache->key}};
188 $obj->_cache($hashref, $cache) if $obj->can('_cache');
191 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
198 my $class = ref($proto) || $proto;
200 bless ($self, $class);
201 if ( defined $self->table ) {
202 cluck "create constructor is deprecated, use new!";
205 croak "FS::Record::create called (not from a subclass)!";
209 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
211 Searches the database for all records matching (at least) the key/value pairs
212 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
213 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
216 The preferred usage is to pass a hash reference of named parameters:
218 my @records = qsearch( {
219 'table' => 'table_name',
220 'hashref' => { 'field' => 'value'
221 'field' => { 'op' => '<',
226 #these are optional...
228 'extra_sql' => 'AND field ',
229 'order_by' => 'ORDER BY something',
230 #'cache_obj' => '', #optional
231 'addl_from' => 'LEFT JOIN othtable USING ( field )',
236 Much code still uses old-style positional parameters, this is also probably
237 fine in the common case where there are only two parameters:
239 my @records = qsearch( 'table', { 'field' => 'value' } );
241 ###oops, argh, FS::Record::new only lets us create database fields.
242 #Normal behaviour if SELECT is not specified is `*', as in
243 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
244 #feature where you can specify SELECT - remember, the objects returned,
245 #although blessed into the appropriate `FS::TABLE' package, will only have the
246 #fields you specify. This might have unwanted results if you then go calling
247 #regular FS::TABLE methods
252 my %TYPE = (); #for debugging
255 my ($type, $value) = @_;
256 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
257 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
265 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
267 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
269 $stable = $opt->{'table'} or die "table name is required";
270 $record = $opt->{'hashref'} || {};
271 $select = $opt->{'select'} || '*';
272 $extra_sql = $opt->{'extra_sql'} || '';
273 $order_by = $opt->{'order_by'} || '';
274 $cache = $opt->{'cache_obj'} || '';
275 $addl_from = $opt->{'addl_from'} || '';
276 $debug = $opt->{'debug'} || '';
278 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
282 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
284 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
288 my $table = $cache ? $cache->table : $stable;
289 my $dbdef_table = dbdef->table($table)
290 or die "No schema for table $table found - ".
291 "do you need to run freeside-upgrade?";
292 my $pkey = $dbdef_table->primary_key;
294 my @real_fields = grep exists($record->{$_}), real_fields($table);
296 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
297 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
299 cluck "warning: FS::$table not loaded; virtual fields not searchable"
300 unless $nowarn_classload;
301 @virtual_fields = ();
304 my $statement = "SELECT $select FROM $stable";
305 $statement .= " $addl_from" if $addl_from;
306 if ( @real_fields or @virtual_fields ) {
307 $statement .= ' WHERE '. join(' AND ',
308 get_real_fields($table, $record, \@real_fields) ,
309 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
313 $statement .= " $extra_sql" if defined($extra_sql);
314 $statement .= " $order_by" if defined($order_by);
316 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
317 my $sth = $dbh->prepare($statement)
318 or croak "$dbh->errstr doing $statement";
323 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
326 my $value = $record->{$field};
327 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
328 $value = $value->{'value'} if ref($value);
329 my $type = dbdef->table($table)->column($field)->type;
331 my $TYPE = SQL_VARCHAR;
332 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
335 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
336 #fixed by DBD::Pg 2.11.8
337 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
338 } elsif ( _is_fs_float( $type, $value ) ) {
344 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
346 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
349 #if this needs to be re-enabled, it needs to use a custom op like
350 #"APPROX=" or something (better name?, not '=', to avoid affecting other
352 #if ($TYPE eq SQL_DECIMAL && $op eq 'APPROX=' ) {
353 # # these values are arbitrary; better (faster?) ones welcome
354 # $sth->bind_param($bind++, $value*1.00001, { TYPE => $TYPE } );
355 # $sth->bind_param($bind++, $value*.99999, { TYPE => $TYPE } );
357 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
362 # $sth->execute( map $record->{$_},
363 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
364 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
366 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
368 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
369 @virtual_fields = "FS::$table"->virtual_fields;
371 cluck "warning: FS::$table not loaded; virtual fields not returned either"
372 unless $nowarn_classload;
373 @virtual_fields = ();
377 tie %result, "Tie::IxHash";
378 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
379 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
380 %result = map { $_->{$pkey}, $_ } @stuff;
382 @result{@stuff} = @stuff;
387 if ( keys(%result) and @virtual_fields ) {
389 "SELECT virtual_field.recnum, part_virtual_field.name, ".
390 "virtual_field.value ".
391 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
392 "WHERE part_virtual_field.dbtable = '$table' AND ".
393 "virtual_field.recnum IN (".
394 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
395 join(q!', '!, @virtual_fields) . "')";
396 warn "[debug]$me $statement\n" if $DEBUG > 1;
397 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
398 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
400 foreach (@{ $sth->fetchall_arrayref({}) }) {
401 my $recnum = $_->{recnum};
402 my $name = $_->{name};
403 my $value = $_->{value};
404 if (exists($result{$recnum})) {
405 $result{$recnum}->{$name} = $value;
410 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
411 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
412 #derivied class didn't override new method, so this optimization is safe
415 new_or_cached( "FS::$table", { %{$_} }, $cache )
419 new( "FS::$table", { %{$_} } )
423 #okay, its been tested
424 # warn "untested code (class FS::$table uses custom new method)";
426 eval 'FS::'. $table. '->new( { %{$_} } )';
430 # Check for encrypted fields and decrypt them.
431 ## only in the local copy, not the cached object
432 if ( $conf_encryption
433 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
434 foreach my $record (@return) {
435 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
436 # Set it directly... This may cause a problem in the future...
437 $record->setfield($field, $record->decrypt($record->getfield($field)));
442 cluck "warning: FS::$table not loaded; returning FS::Record objects"
443 unless $nowarn_classload;
445 FS::Record->new( $table, { %{$_} } );
451 ## makes this easier to read
453 sub get_virtual_fields {
457 my $virtual_fields = shift;
463 if ( ref($record->{$_}) ) {
464 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
465 if ( uc($op) eq 'ILIKE' ) {
467 $record->{$_}{'value'} = lc($record->{$_}{'value'});
468 $column = "LOWER($_)";
470 $record->{$_} = $record->{$_}{'value'};
473 # ... EXISTS ( SELECT name, value FROM part_virtual_field
475 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
476 # WHERE recnum = svc_acct.svcnum
477 # AND (name, value) = ('egad', 'brain') )
479 my $value = $record->{$_};
483 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
484 "( SELECT part_virtual_field.name, virtual_field.value ".
485 "FROM part_virtual_field JOIN virtual_field ".
486 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
487 "WHERE virtual_field.recnum = ${table}.${pkey} ".
488 "AND part_virtual_field.name = '${column}'".
490 " AND virtual_field.value ${op} '${value}'"
494 } @{ $virtual_fields } ) ;
497 sub get_real_fields {
500 my $real_fields = shift;
502 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
508 my $type = dbdef->table($table)->column($column)->type;
509 my $value = $record->{$column};
510 $value = $value->{'value'} if ref($value);
511 if ( ref($record->{$_}) ) {
512 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
513 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
514 if ( uc($op) eq 'ILIKE' ) {
516 $record->{$_}{'value'} = lc($record->{$_}{'value'});
517 $column = "LOWER($_)";
519 $record->{$_} = $record->{$_}{'value'}
522 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
524 if ( driver_name eq 'Pg' ) {
525 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
526 qq-( $column IS NULL )-;
528 qq-( $column IS NULL OR $column = '' )-;
531 qq-( $column IS NULL OR $column = "" )-;
533 } elsif ( $op eq '!=' ) {
534 if ( driver_name eq 'Pg' ) {
535 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
536 qq-( $column IS NOT NULL )-;
538 qq-( $column IS NOT NULL AND $column != '' )-;
541 qq-( $column IS NOT NULL AND $column != "" )-;
544 if ( driver_name eq 'Pg' ) {
545 qq-( $column $op '' )-;
547 qq-( $column $op "" )-;
550 #if this needs to be re-enabled, it needs to use a custom op like
551 #"APPROX=" or something (better name?, not '=', to avoid affecting other
553 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
554 # ( "$column <= ?", "$column >= ?" );
558 } @{ $real_fields } );
561 =item by_key PRIMARY_KEY_VALUE
563 This is a class method that returns the record with the given primary key
564 value. This method is only useful in FS::Record subclasses. For example:
566 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
570 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
575 my ($class, $pkey_value) = @_;
577 my $table = $class->table
578 or croak "No table for $class found";
580 my $dbdef_table = dbdef->table($table)
581 or die "No schema for table $table found - ".
582 "do you need to create it or run dbdef-create?";
583 my $pkey = $dbdef_table->primary_key
584 or die "No primary key for table $table";
586 return qsearchs($table, { $pkey => $pkey_value });
589 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
591 Experimental JOINed search method. Using this method, you can execute a
592 single SELECT spanning multiple tables, and cache the results for subsequent
593 method calls. Interface will almost definately change in an incompatible
601 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
602 my $cache = FS::SearchCache->new( $ptable, $pkey );
605 grep { !$saw{$_->getfield($pkey)}++ }
606 qsearch($table, $record, $select, $extra_sql, $cache )
610 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
612 Same as qsearch, except that if more than one record matches, it B<carp>s but
613 returns the first. If this happens, you either made a logic error in asking
614 for a single item, or your data is corrupted.
618 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
620 my(@result) = qsearch(@_);
621 cluck "warning: Multiple records in scalar search ($table)"
622 if scalar(@result) > 1;
623 #should warn more vehemently if the search was on a primary key?
624 scalar(@result) ? ($result[0]) : ();
635 Returns the table name.
640 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
647 Returns the DBIx::DBSchema::Table object for the table.
653 my($table)=$self->table;
654 dbdef->table($table);
659 Returns the primary key for the table.
665 my $pkey = $self->dbdef_table->primary_key;
668 =item get, getfield COLUMN
670 Returns the value of the column/field/key COLUMN.
675 my($self,$field) = @_;
676 # to avoid "Use of unitialized value" errors
677 if ( defined ( $self->{Hash}->{$field} ) ) {
678 $self->{Hash}->{$field};
688 =item set, setfield COLUMN, VALUE
690 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
695 my($self,$field,$value) = @_;
696 $self->{'modified'} = 1;
697 $self->{'Hash'}->{$field} = $value;
704 =item AUTLOADED METHODS
706 $record->column is a synonym for $record->get('column');
708 $record->column('value') is a synonym for $record->set('column','value');
715 my($field)=$AUTOLOAD;
717 if ( defined($value) ) {
718 confess "errant AUTOLOAD $field for $self (arg $value)"
719 unless blessed($self) && $self->can('setfield');
720 $self->setfield($field,$value);
722 confess "errant AUTOLOAD $field for $self (no args)"
723 unless blessed($self) && $self->can('getfield');
724 $self->getfield($field);
730 # my $field = $AUTOLOAD;
732 # if ( defined($_[1]) ) {
733 # $_[0]->setfield($field, $_[1]);
735 # $_[0]->getfield($field);
741 Returns a list of the column/value pairs, usually for assigning to a new hash.
743 To make a distinct duplicate of an FS::Record object, you can do:
745 $new = new FS::Record ( $old->table, { $old->hash } );
751 confess $self. ' -> hash: Hash attribute is undefined'
752 unless defined($self->{'Hash'});
753 %{ $self->{'Hash'} };
758 Returns a reference to the column/value hash. This may be deprecated in the
759 future; if there's a reason you can't just use the autoloaded or get/set
771 Returns true if any of this object's values have been modified with set (or via
772 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
782 =item select_for_update
784 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
789 sub select_for_update {
791 my $primary_key = $self->primary_key;
794 'table' => $self->table,
795 'hashref' => { $primary_key => $self->$primary_key() },
796 'extra_sql' => 'FOR UPDATE',
802 Locks this table with a database-driver specific lock method. This is used
803 as a mutex in order to do a duplicate search.
805 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
807 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
809 Errors are fatal; no useful return value.
811 Note: To use this method for new tables other than svc_acct and svc_phone,
812 edit freeside-upgrade and add those tables to the duplicate_lock list.
818 my $table = $self->table;
820 warn "$me locking $table table\n" if $DEBUG;
822 if ( driver_name =~ /^Pg/i ) {
824 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
827 } elsif ( driver_name =~ /^mysql/i ) {
829 dbh->do("SELECT * FROM duplicate_lock
830 WHERE lockname = '$table'
832 ) or die dbh->errstr;
836 die "unknown database ". driver_name. "; don't know how to lock table";
840 warn "$me acquired $table table lock\n" if $DEBUG;
846 Inserts this record to the database. If there is an error, returns the error,
847 otherwise returns false.
855 warn "$self -> insert" if $DEBUG;
857 my $error = $self->check;
858 return $error if $error;
860 #single-field unique keys are given a value if false
861 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
862 foreach ( $self->dbdef_table->unique_singles) {
863 $self->unique($_) unless $self->getfield($_);
866 #and also the primary key, if the database isn't going to
867 my $primary_key = $self->dbdef_table->primary_key;
869 if ( $primary_key ) {
870 my $col = $self->dbdef_table->column($primary_key);
873 uc($col->type) =~ /^(BIG)?SERIAL\d?/
874 || ( driver_name eq 'Pg'
875 && defined($col->default)
876 && $col->default =~ /^nextval\(/i
878 || ( driver_name eq 'mysql'
879 && defined($col->local)
880 && $col->local =~ /AUTO_INCREMENT/i
882 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
885 my $table = $self->table;
887 # Encrypt before the database
888 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
889 && scalar( eval '@FS::'. $table . '::encrypted_fields')
890 && $conf->exists('encryption')
892 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
893 $self->{'saved'} = $self->getfield($field);
894 $self->setfield($field, $self->encrypt($self->getfield($field)));
898 #false laziness w/delete
900 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
903 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
906 my $statement = "INSERT INTO $table ";
907 if ( @real_fields ) {
910 join( ', ', @real_fields ).
912 join( ', ', @values ).
916 $statement .= 'DEFAULT VALUES';
918 warn "[debug]$me $statement\n" if $DEBUG > 1;
919 my $sth = dbh->prepare($statement) or return dbh->errstr;
921 local $SIG{HUP} = 'IGNORE';
922 local $SIG{INT} = 'IGNORE';
923 local $SIG{QUIT} = 'IGNORE';
924 local $SIG{TERM} = 'IGNORE';
925 local $SIG{TSTP} = 'IGNORE';
926 local $SIG{PIPE} = 'IGNORE';
928 $sth->execute or return $sth->errstr;
930 # get inserted id from the database, if applicable & needed
931 if ( $db_seq && ! $self->getfield($primary_key) ) {
932 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
936 if ( driver_name eq 'Pg' ) {
938 #my $oid = $sth->{'pg_oid_status'};
939 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
941 my $default = $self->dbdef_table->column($primary_key)->default;
942 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
943 dbh->rollback if $FS::UID::AutoCommit;
944 return "can't parse $table.$primary_key default value".
945 " for sequence name: $default";
949 my $i_sql = "SELECT currval('$sequence')";
950 my $i_sth = dbh->prepare($i_sql) or do {
951 dbh->rollback if $FS::UID::AutoCommit;
954 $i_sth->execute() or do { #$i_sth->execute($oid)
955 dbh->rollback if $FS::UID::AutoCommit;
956 return $i_sth->errstr;
958 $insertid = $i_sth->fetchrow_arrayref->[0];
960 } elsif ( driver_name eq 'mysql' ) {
962 $insertid = dbh->{'mysql_insertid'};
963 # work around mysql_insertid being null some of the time, ala RT :/
964 unless ( $insertid ) {
965 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
966 "using SELECT LAST_INSERT_ID();";
967 my $i_sql = "SELECT LAST_INSERT_ID()";
968 my $i_sth = dbh->prepare($i_sql) or do {
969 dbh->rollback if $FS::UID::AutoCommit;
972 $i_sth->execute or do {
973 dbh->rollback if $FS::UID::AutoCommit;
974 return $i_sth->errstr;
976 $insertid = $i_sth->fetchrow_arrayref->[0];
981 dbh->rollback if $FS::UID::AutoCommit;
982 return "don't know how to retreive inserted ids from ". driver_name.
983 ", try using counterfiles (maybe run dbdef-create?)";
987 $self->setfield($primary_key, $insertid);
992 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
993 $self->virtual_fields;
994 if (@virtual_fields) {
995 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
997 my $vfieldpart = $self->vfieldpart_hashref;
999 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1002 my $v_sth = dbh->prepare($v_statement) or do {
1003 dbh->rollback if $FS::UID::AutoCommit;
1007 foreach (keys(%v_values)) {
1008 $v_sth->execute($self->getfield($primary_key),
1012 dbh->rollback if $FS::UID::AutoCommit;
1013 return $v_sth->errstr;
1020 if ( defined dbdef->table('h_'. $table) ) {
1021 my $h_statement = $self->_h_statement('insert');
1022 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1023 $h_sth = dbh->prepare($h_statement) or do {
1024 dbh->rollback if $FS::UID::AutoCommit;
1030 $h_sth->execute or return $h_sth->errstr if $h_sth;
1032 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1034 # Now that it has been saved, reset the encrypted fields so that $new
1035 # can still be used.
1036 foreach my $field (keys %{$saved}) {
1037 $self->setfield($field, $saved->{$field});
1045 Depriciated (use insert instead).
1050 cluck "warning: FS::Record::add deprecated!";
1051 insert @_; #call method in this scope
1056 Delete this record from the database. If there is an error, returns the error,
1057 otherwise returns false.
1064 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1066 $self->getfield($_) eq ''
1067 #? "( $_ IS NULL OR $_ = \"\" )"
1068 ? ( driver_name eq 'Pg'
1070 : "( $_ IS NULL OR $_ = \"\" )"
1072 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1073 } ( $self->dbdef_table->primary_key )
1074 ? ( $self->dbdef_table->primary_key)
1075 : real_fields($self->table)
1077 warn "[debug]$me $statement\n" if $DEBUG > 1;
1078 my $sth = dbh->prepare($statement) or return dbh->errstr;
1081 if ( defined dbdef->table('h_'. $self->table) ) {
1082 my $h_statement = $self->_h_statement('delete');
1083 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1084 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1089 my $primary_key = $self->dbdef_table->primary_key;
1092 my $vfp = $self->vfieldpart_hashref;
1093 foreach($self->virtual_fields) {
1094 next if $self->getfield($_) eq '';
1095 unless(@del_vfields) {
1096 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1097 $v_sth = dbh->prepare($st) or return dbh->errstr;
1099 push @del_vfields, $_;
1102 local $SIG{HUP} = 'IGNORE';
1103 local $SIG{INT} = 'IGNORE';
1104 local $SIG{QUIT} = 'IGNORE';
1105 local $SIG{TERM} = 'IGNORE';
1106 local $SIG{TSTP} = 'IGNORE';
1107 local $SIG{PIPE} = 'IGNORE';
1109 my $rc = $sth->execute or return $sth->errstr;
1110 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1111 $h_sth->execute or return $h_sth->errstr if $h_sth;
1112 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1113 or return $v_sth->errstr
1114 foreach (@del_vfields);
1116 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1118 #no need to needlessly destoy the data either (causes problems actually)
1119 #undef $self; #no need to keep object!
1126 Depriciated (use delete instead).
1131 cluck "warning: FS::Record::del deprecated!";
1132 &delete(@_); #call method in this scope
1135 =item replace OLD_RECORD
1137 Replace the OLD_RECORD with this one in the database. If there is an error,
1138 returns the error, otherwise returns false.
1143 my ($new, $old) = (shift, shift);
1145 $old = $new->replace_old unless defined($old);
1147 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1149 if ( $new->can('replace_check') ) {
1150 my $error = $new->replace_check($old);
1151 return $error if $error;
1154 return "Records not in same table!" unless $new->table eq $old->table;
1156 my $primary_key = $old->dbdef_table->primary_key;
1157 return "Can't change primary key $primary_key ".
1158 'from '. $old->getfield($primary_key).
1159 ' to ' . $new->getfield($primary_key)
1161 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1163 my $error = $new->check;
1164 return $error if $error;
1166 # Encrypt for replace
1168 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1169 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1170 $saved->{$field} = $new->getfield($field);
1171 $new->setfield($field, $new->encrypt($new->getfield($field)));
1175 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1176 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1177 ? ($_, $new->getfield($_)) : () } $old->fields;
1179 unless (keys(%diff) || $no_update_diff ) {
1180 carp "[warning]$me $new -> replace $old: records identical"
1181 unless $nowarn_identical;
1185 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1187 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1188 } real_fields($old->table)
1193 if ( $old->getfield($_) eq '' ) {
1195 #false laziness w/qsearch
1196 if ( driver_name eq 'Pg' ) {
1197 my $type = $old->dbdef_table->column($_)->type;
1198 if ( $type =~ /(int|(big)?serial)/i ) {
1201 qq-( $_ IS NULL OR $_ = '' )-;
1204 qq-( $_ IS NULL OR $_ = "" )-;
1208 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1211 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1214 warn "[debug]$me $statement\n" if $DEBUG > 1;
1215 my $sth = dbh->prepare($statement) or return dbh->errstr;
1218 if ( defined dbdef->table('h_'. $old->table) ) {
1219 my $h_old_statement = $old->_h_statement('replace_old');
1220 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1221 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1227 if ( defined dbdef->table('h_'. $new->table) ) {
1228 my $h_new_statement = $new->_h_statement('replace_new');
1229 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1230 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1235 # For virtual fields we have three cases with different SQL
1236 # statements: add, replace, delete
1240 my (@add_vfields, @rep_vfields, @del_vfields);
1241 my $vfp = $old->vfieldpart_hashref;
1242 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1243 if($diff{$_} eq '') {
1245 unless(@del_vfields) {
1246 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1247 "AND vfieldpart = ?";
1248 warn "[debug]$me $st\n" if $DEBUG > 2;
1249 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1251 push @del_vfields, $_;
1252 } elsif($old->getfield($_) eq '') {
1254 unless(@add_vfields) {
1255 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1257 warn "[debug]$me $st\n" if $DEBUG > 2;
1258 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1260 push @add_vfields, $_;
1263 unless(@rep_vfields) {
1264 my $st = "UPDATE virtual_field SET value = ? ".
1265 "WHERE recnum = ? AND vfieldpart = ?";
1266 warn "[debug]$me $st\n" if $DEBUG > 2;
1267 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1269 push @rep_vfields, $_;
1273 local $SIG{HUP} = 'IGNORE';
1274 local $SIG{INT} = 'IGNORE';
1275 local $SIG{QUIT} = 'IGNORE';
1276 local $SIG{TERM} = 'IGNORE';
1277 local $SIG{TSTP} = 'IGNORE';
1278 local $SIG{PIPE} = 'IGNORE';
1280 my $rc = $sth->execute or return $sth->errstr;
1281 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1282 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1283 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1285 $v_del_sth->execute($old->getfield($primary_key),
1287 or return $v_del_sth->errstr
1288 foreach(@del_vfields);
1290 $v_add_sth->execute($new->getfield($_),
1291 $old->getfield($primary_key),
1293 or return $v_add_sth->errstr
1294 foreach(@add_vfields);
1296 $v_rep_sth->execute($new->getfield($_),
1297 $old->getfield($primary_key),
1299 or return $v_rep_sth->errstr
1300 foreach(@rep_vfields);
1302 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1304 # Now that it has been saved, reset the encrypted fields so that $new
1305 # can still be used.
1306 foreach my $field (keys %{$saved}) {
1307 $new->setfield($field, $saved->{$field});
1315 my( $self ) = shift;
1316 warn "[$me] replace called with no arguments; autoloading old record\n"
1319 my $primary_key = $self->dbdef_table->primary_key;
1320 if ( $primary_key ) {
1321 $self->by_key( $self->$primary_key() ) #this is what's returned
1322 or croak "can't find ". $self->table. ".$primary_key ".
1323 $self->$primary_key();
1325 croak $self->table. " has no primary key; pass old record as argument";
1332 Depriciated (use replace instead).
1337 cluck "warning: FS::Record::rep deprecated!";
1338 replace @_; #call method in this scope
1343 Checks virtual fields (using check_blocks). Subclasses should still provide
1344 a check method to validate real fields, foreign keys, etc., and call this
1345 method via $self->SUPER::check.
1347 (FIXME: Should this method try to make sure that it I<is> being called from
1348 a subclass's check method, to keep the current semantics as far as possible?)
1353 #confess "FS::Record::check not implemented; supply one in subclass!";
1356 foreach my $field ($self->virtual_fields) {
1357 for ($self->getfield($field)) {
1358 # See notes on check_block in FS::part_virtual_field.
1359 eval $self->pvf($field)->check_block;
1361 #this is bad, probably want to follow the stack backtrace up and see
1363 my $err = "Fatal error checking $field for $self";
1365 return "$err (see log for backtrace): $@";
1368 $self->setfield($field, $_);
1374 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1376 Processes a batch import as a queued JSRPC job
1378 JOB is an FS::queue entry.
1380 OPTIONS_HASHREF can have the following keys:
1386 Table name (required).
1390 Listref of field names for static fields. They will be given values from the
1391 PARAMS hashref and passed as a "params" hashref to batch_import.
1395 Formats hashref. Keys are field names, values are listrefs that define the
1398 Each listref value can be a column name or a code reference. Coderefs are run
1399 with the row object, data and a FS::Conf object as the three parameters.
1400 For example, this coderef does the same thing as using the "columnname" string:
1403 my( $record, $data, $conf ) = @_;
1404 $record->columnname( $data );
1407 Coderefs are run after all "column name" fields are assigned.
1411 Optional format hashref of types. Keys are field names, values are "csv",
1412 "xls" or "fixedlength". Overrides automatic determination of file type
1415 =item format_headers
1417 Optional format hashref of header lines. Keys are field names, values are 0
1418 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1421 =item format_sep_chars
1423 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1424 CSV separation character.
1426 =item format_fixedlenth_formats
1428 Optional format hashref of fixed length format defintiions. Keys are field
1429 names, values Parse::FixedLength listrefs of field definitions.
1433 Set true to default to CSV file type if the filename does not contain a
1434 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1439 PARAMS is a base64-encoded Storable string containing the POSTed data as
1440 a hash ref. It normally contains at least one field, "uploaded files",
1441 generated by /elements/file-upload.html and containing the list of uploaded
1442 files. Currently only supports a single file named "file".
1446 use Storable qw(thaw);
1449 sub process_batch_import {
1450 my($job, $opt) = ( shift, shift );
1452 my $table = $opt->{table};
1453 my @pass_params = @{ $opt->{params} };
1454 my %formats = %{ $opt->{formats} };
1456 my $param = thaw(decode_base64(shift));
1457 warn Dumper($param) if $DEBUG;
1459 my $files = $param->{'uploaded_files'}
1460 or die "No files provided.\n";
1462 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1464 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1465 my $file = $dir. $files{'file'};
1468 FS::Record::batch_import( {
1471 formats => \%formats,
1472 format_types => $opt->{format_types},
1473 format_headers => $opt->{format_headers},
1474 format_sep_chars => $opt->{format_sep_chars},
1475 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1480 format => $param->{format},
1481 params => { map { $_ => $param->{$_} } @pass_params },
1483 default_csv => $opt->{default_csv},
1488 die "$error\n" if $error;
1491 =item batch_import PARAM_HASHREF
1493 Class method for batch imports. Available params:
1503 =item format_headers
1505 =item format_sep_chars
1507 =item format_fixedlength_formats
1513 FS::queue object, will be updated with progress
1519 csv, xls or fixedlength
1532 warn "$me batch_import call with params: \n". Dumper($param)
1535 my $table = $param->{table};
1536 my $formats = $param->{formats};
1538 my $job = $param->{job};
1539 my $file = $param->{file};
1540 my $format = $param->{'format'};
1541 my $params = $param->{params} || {};
1543 die "unknown format $format" unless exists $formats->{ $format };
1545 my $type = $param->{'format_types'}
1546 ? $param->{'format_types'}{ $format }
1547 : $param->{type} || 'csv';
1550 if ( $file =~ /\.(\w+)$/i ) {
1554 warn "can't parse file type from filename $file; defaulting to CSV";
1558 if $param->{'default_csv'} && $type ne 'xls';
1561 my $header = $param->{'format_headers'}
1562 ? $param->{'format_headers'}{ $param->{'format'} }
1565 my $sep_char = $param->{'format_sep_chars'}
1566 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1569 my $fixedlength_format =
1570 $param->{'format_fixedlength_formats'}
1571 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1574 my @fields = @{ $formats->{ $format } };
1580 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1582 if ( $type eq 'csv' ) {
1585 $attr{sep_char} = $sep_char if $sep_char;
1586 $parser = new Text::CSV_XS \%attr;
1588 } elsif ( $type eq 'fixedlength' ) {
1590 eval "use Parse::FixedLength;";
1592 $parser = new Parse::FixedLength $fixedlength_format;
1595 die "Unknown file type $type\n";
1598 @buffer = split(/\r?\n/, slurp($file) );
1599 splice(@buffer, 0, ($header || 0) );
1600 $count = scalar(@buffer);
1602 } elsif ( $type eq 'xls' ) {
1604 eval "use Spreadsheet::ParseExcel;";
1607 eval "use DateTime::Format::Excel;";
1608 #for now, just let the error be thrown if it is used, since only CDR
1609 # formats bill_west and troop use it, not other excel-parsing things
1612 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1614 $parser = $excel->{Worksheet}[0]; #first sheet
1616 $count = $parser->{MaxRow} || $parser->{MinRow};
1619 $row = $header || 0;
1622 die "Unknown file type $type\n";
1627 local $SIG{HUP} = 'IGNORE';
1628 local $SIG{INT} = 'IGNORE';
1629 local $SIG{QUIT} = 'IGNORE';
1630 local $SIG{TERM} = 'IGNORE';
1631 local $SIG{TSTP} = 'IGNORE';
1632 local $SIG{PIPE} = 'IGNORE';
1634 my $oldAutoCommit = $FS::UID::AutoCommit;
1635 local $FS::UID::AutoCommit = 0;
1640 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1644 if ( $type eq 'csv' ) {
1646 last unless scalar(@buffer);
1647 $line = shift(@buffer);
1649 $parser->parse($line) or do {
1650 $dbh->rollback if $oldAutoCommit;
1651 return "can't parse: ". $parser->error_input();
1653 @columns = $parser->fields();
1655 } elsif ( $type eq 'fixedlength' ) {
1657 @columns = $parser->parse($line);
1659 } elsif ( $type eq 'xls' ) {
1661 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1662 || ! $parser->{Cells}[$row];
1664 my @row = @{ $parser->{Cells}[$row] };
1665 @columns = map $_->{Val}, @row;
1668 #warn $z++. ": $_\n" for @columns;
1671 die "Unknown file type $type\n";
1675 my %hash = %$params;
1677 foreach my $field ( @fields ) {
1679 my $value = shift @columns;
1681 if ( ref($field) eq 'CODE' ) {
1682 #&{$field}(\%hash, $value);
1683 push @later, $field, $value;
1685 #??? $hash{$field} = $value if length($value);
1686 $hash{$field} = $value if defined($value) && length($value);
1691 my $class = "FS::$table";
1693 my $record = $class->new( \%hash );
1695 while ( scalar(@later) ) {
1696 my $sub = shift @later;
1697 my $data = shift @later;
1698 &{$sub}($record, $data, $conf); # $record->&{$sub}($data, $conf);
1701 my $error = $record->insert;
1704 $dbh->rollback if $oldAutoCommit;
1705 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1711 if ( $job && time - $min_sec > $last ) { #progress bar
1712 $job->update_statustext( int(100 * $imported / $count) );
1718 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1720 return "Empty file!" unless $imported || $param->{empty_ok};
1727 my( $self, $action, $time ) = @_;
1732 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1733 real_fields($self->table);
1736 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1737 # You can see if it changed by the paymask...
1738 if ($conf && $conf->exists('encryption') ) {
1739 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1741 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1743 "INSERT INTO h_". $self->table. " ( ".
1744 join(', ', qw(history_date history_user history_action), @fields ).
1746 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1753 B<Warning>: External use is B<deprecated>.
1755 Replaces COLUMN in record with a unique number, using counters in the
1756 filesystem. Used by the B<insert> method on single-field unique columns
1757 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1758 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1760 Returns the new value.
1765 my($self,$field) = @_;
1766 my($table)=$self->table;
1768 croak "Unique called on field $field, but it is ",
1769 $self->getfield($field),
1771 if $self->getfield($field);
1773 #warn "table $table is tainted" if is_tainted($table);
1774 #warn "field $field is tainted" if is_tainted($field);
1776 my($counter) = new File::CounterFile "$table.$field",0;
1778 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1780 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1783 my $index = $counter->inc;
1784 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1786 $index =~ /^(\d*)$/;
1789 $self->setfield($field,$index);
1793 =item ut_float COLUMN
1795 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1796 null. If there is an error, returns the error, otherwise returns false.
1801 my($self,$field)=@_ ;
1802 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1803 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1804 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1805 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1806 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1807 $self->setfield($field,$1);
1810 =item ut_floatn COLUMN
1812 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1813 null. If there is an error, returns the error, otherwise returns false.
1817 #false laziness w/ut_ipn
1819 my( $self, $field ) = @_;
1820 if ( $self->getfield($field) =~ /^()$/ ) {
1821 $self->setfield($field,'');
1824 $self->ut_float($field);
1828 =item ut_sfloat COLUMN
1830 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1831 May not be null. If there is an error, returns the error, otherwise returns
1837 my($self,$field)=@_ ;
1838 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1839 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1840 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1841 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1842 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1843 $self->setfield($field,$1);
1846 =item ut_sfloatn COLUMN
1848 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1849 null. If there is an error, returns the error, otherwise returns false.
1854 my( $self, $field ) = @_;
1855 if ( $self->getfield($field) =~ /^()$/ ) {
1856 $self->setfield($field,'');
1859 $self->ut_sfloat($field);
1863 =item ut_snumber COLUMN
1865 Check/untaint signed numeric data (whole numbers). If there is an error,
1866 returns the error, otherwise returns false.
1871 my($self, $field) = @_;
1872 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1873 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1874 $self->setfield($field, "$1$2");
1878 =item ut_snumbern COLUMN
1880 Check/untaint signed numeric data (whole numbers). If there is an error,
1881 returns the error, otherwise returns false.
1886 my($self, $field) = @_;
1887 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1888 or return "Illegal (numeric) $field: ". $self->getfield($field);
1890 return "Illegal (numeric) $field: ". $self->getfield($field)
1893 $self->setfield($field, "$1$2");
1897 =item ut_number COLUMN
1899 Check/untaint simple numeric data (whole numbers). May not be null. If there
1900 is an error, returns the error, otherwise returns false.
1905 my($self,$field)=@_;
1906 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1907 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1908 $self->setfield($field,$1);
1912 =item ut_numbern COLUMN
1914 Check/untaint simple numeric data (whole numbers). May be null. If there is
1915 an error, returns the error, otherwise returns false.
1920 my($self,$field)=@_;
1921 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1922 or return "Illegal (numeric) $field: ". $self->getfield($field);
1923 $self->setfield($field,$1);
1927 =item ut_money COLUMN
1929 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1930 is an error, returns the error, otherwise returns false.
1935 my($self,$field)=@_;
1936 $self->setfield($field, 0) if $self->getfield($field) eq '';
1937 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1938 or return "Illegal (money) $field: ". $self->getfield($field);
1939 #$self->setfield($field, "$1$2$3" || 0);
1940 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1944 =item ut_text COLUMN
1946 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1947 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
1948 May not be null. If there is an error, returns the error, otherwise returns
1954 my($self,$field)=@_;
1955 #warn "msgcat ". \&msgcat. "\n";
1956 #warn "notexist ". \¬exist. "\n";
1957 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1958 $self->getfield($field)
1959 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
1960 or return gettext('illegal_or_empty_text'). " $field: ".
1961 $self->getfield($field);
1962 $self->setfield($field,$1);
1966 =item ut_textn COLUMN
1968 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1969 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1970 May be null. If there is an error, returns the error, otherwise returns false.
1975 my($self,$field)=@_;
1976 $self->getfield($field)
1977 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1978 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1979 $self->setfield($field,$1);
1983 =item ut_alpha COLUMN
1985 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1986 an error, returns the error, otherwise returns false.
1991 my($self,$field)=@_;
1992 $self->getfield($field) =~ /^(\w+)$/
1993 or return "Illegal or empty (alphanumeric) $field: ".
1994 $self->getfield($field);
1995 $self->setfield($field,$1);
1999 =item ut_alpha COLUMN
2001 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2002 error, returns the error, otherwise returns false.
2007 my($self,$field)=@_;
2008 $self->getfield($field) =~ /^(\w*)$/
2009 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2010 $self->setfield($field,$1);
2014 =item ut_alpha_lower COLUMN
2016 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2017 there is an error, returns the error, otherwise returns false.
2021 sub ut_alpha_lower {
2022 my($self,$field)=@_;
2023 $self->getfield($field) =~ /[[:upper:]]/
2024 and return "Uppercase characters are not permitted in $field";
2025 $self->ut_alpha($field);
2028 =item ut_phonen COLUMN [ COUNTRY ]
2030 Check/untaint phone numbers. May be null. If there is an error, returns
2031 the error, otherwise returns false.
2033 Takes an optional two-letter ISO country code; without it or with unsupported
2034 countries, ut_phonen simply calls ut_alphan.
2039 my( $self, $field, $country ) = @_;
2040 return $self->ut_alphan($field) unless defined $country;
2041 my $phonen = $self->getfield($field);
2042 if ( $phonen eq '' ) {
2043 $self->setfield($field,'');
2044 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2046 $phonen = $conf->config('cust_main-default_areacode').$phonen
2047 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2048 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2049 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2050 $phonen = "$1-$2-$3";
2051 $phonen .= " x$4" if $4;
2052 $self->setfield($field,$phonen);
2054 warn "warning: don't know how to check phone numbers for country $country";
2055 return $self->ut_textn($field);
2062 Check/untaint hexadecimal values.
2067 my($self, $field) = @_;
2068 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2069 or return "Illegal (hex) $field: ". $self->getfield($field);
2070 $self->setfield($field, uc($1));
2074 =item ut_hexn COLUMN
2076 Check/untaint hexadecimal values. May be null.
2081 my($self, $field) = @_;
2082 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2083 or return "Illegal (hex) $field: ". $self->getfield($field);
2084 $self->setfield($field, uc($1));
2089 Check/untaint ip addresses. IPv4 only for now.
2094 my( $self, $field ) = @_;
2095 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2096 or return "Illegal (IP address) $field: ". $self->getfield($field);
2097 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2098 $self->setfield($field, "$1.$2.$3.$4");
2104 Check/untaint ip addresses. IPv4 only for now. May be null.
2109 my( $self, $field ) = @_;
2110 if ( $self->getfield($field) =~ /^()$/ ) {
2111 $self->setfield($field,'');
2114 $self->ut_ip($field);
2118 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2120 Check/untaint coordinates.
2121 Accepts the following forms:
2131 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2132 The latter form (that is, the MMM are thousands of minutes) is
2133 assumed if the "MMM" is exactly three digits or two digits > 59.
2135 To be safe, just use the DDD.DDDDD form.
2137 If LOWER or UPPER are specified, then the coordinate is checked
2138 for lower and upper bounds, respectively.
2144 my ($self, $field) = (shift, shift);
2146 my $lower = shift if scalar(@_);
2147 my $upper = shift if scalar(@_);
2148 my $coord = $self->getfield($field);
2149 my $neg = $coord =~ s/^(-)//;
2151 my ($d, $m, $s) = (0, 0, 0);
2154 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2155 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2156 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2158 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2161 return "Invalid (coordinate with minutes > 59) $field: "
2162 . $self->getfield($field);
2165 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2167 if (defined($lower) and ($coord < $lower)) {
2168 return "Invalid (coordinate < $lower) $field: "
2169 . $self->getfield($field);;
2172 if (defined($upper) and ($coord > $upper)) {
2173 return "Invalid (coordinate > $upper) $field: "
2174 . $self->getfield($field);;
2177 $self->setfield($field, $coord);
2181 return "Invalid (coordinate) $field: " . $self->getfield($field);
2185 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2187 Same as ut_coord, except optionally null.
2193 my ($self, $field) = (shift, shift);
2195 if ($self->getfield($field) =~ /^$/) {
2198 return $self->ut_coord($field, @_);
2204 =item ut_domain COLUMN
2206 Check/untaint host and domain names.
2211 my( $self, $field ) = @_;
2212 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2213 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2214 or return "Illegal (domain) $field: ". $self->getfield($field);
2215 $self->setfield($field,$1);
2219 =item ut_name COLUMN
2221 Check/untaint proper names; allows alphanumerics, spaces and the following
2222 punctuation: , . - '
2229 my( $self, $field ) = @_;
2230 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2231 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2232 $self->setfield($field,$1);
2238 Check/untaint zip codes.
2242 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2245 my( $self, $field, $country ) = @_;
2247 if ( $country eq 'US' ) {
2249 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2250 or return gettext('illegal_zip'). " $field for country $country: ".
2251 $self->getfield($field);
2252 $self->setfield($field, $1);
2254 } elsif ( $country eq 'CA' ) {
2256 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2257 or return gettext('illegal_zip'). " $field for country $country: ".
2258 $self->getfield($field);
2259 $self->setfield($field, "$1 $2");
2263 if ( $self->getfield($field) =~ /^\s*$/
2264 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2267 $self->setfield($field,'');
2269 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2270 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2271 $self->setfield($field,$1);
2279 =item ut_country COLUMN
2281 Check/untaint country codes. Country names are changed to codes, if possible -
2282 see L<Locale::Country>.
2287 my( $self, $field ) = @_;
2288 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2289 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2290 && country2code($1) ) {
2291 $self->setfield($field,uc(country2code($1)));
2294 $self->getfield($field) =~ /^(\w\w)$/
2295 or return "Illegal (country) $field: ". $self->getfield($field);
2296 $self->setfield($field,uc($1));
2300 =item ut_anything COLUMN
2302 Untaints arbitrary data. Be careful.
2307 my( $self, $field ) = @_;
2308 $self->getfield($field) =~ /^(.*)$/s
2309 or return "Illegal $field: ". $self->getfield($field);
2310 $self->setfield($field,$1);
2314 =item ut_enum COLUMN CHOICES_ARRAYREF
2316 Check/untaint a column, supplying all possible choices, like the "enum" type.
2321 my( $self, $field, $choices ) = @_;
2322 foreach my $choice ( @$choices ) {
2323 if ( $self->getfield($field) eq $choice ) {
2324 $self->setfield($choice);
2328 return "Illegal (enum) field $field: ". $self->getfield($field);
2331 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2333 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2334 on the column first.
2338 sub ut_foreign_key {
2339 my( $self, $field, $table, $foreign ) = @_;
2340 return '' if $no_check_foreign;
2341 qsearchs($table, { $foreign => $self->getfield($field) })
2342 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2343 " in $table.$foreign";
2347 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2349 Like ut_foreign_key, except the null value is also allowed.
2353 sub ut_foreign_keyn {
2354 my( $self, $field, $table, $foreign ) = @_;
2355 $self->getfield($field)
2356 ? $self->ut_foreign_key($field, $table, $foreign)
2360 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2362 Checks this column as an agentnum, taking into account the current users's
2363 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2364 right or rights allowing no agentnum.
2368 sub ut_agentnum_acl {
2369 my( $self, $field ) = (shift, shift);
2370 my $null_acl = scalar(@_) ? shift : [];
2371 $null_acl = [ $null_acl ] unless ref($null_acl);
2373 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2374 return "Illegal agentnum: $error" if $error;
2376 my $curuser = $FS::CurrentUser::CurrentUser;
2378 if ( $self->$field() ) {
2380 return "Access denied"
2381 unless $curuser->agentnum($self->$field());
2385 return "Access denied"
2386 unless grep $curuser->access_right($_), @$null_acl;
2394 =item virtual_fields [ TABLE ]
2396 Returns a list of virtual fields defined for the table. This should not
2397 be exported, and should only be called as an instance or class method.
2401 sub virtual_fields {
2404 $table = $self->table or confess "virtual_fields called on non-table";
2406 confess "Unknown table $table" unless dbdef->table($table);
2408 return () unless dbdef->table('part_virtual_field');
2410 unless ( $virtual_fields_cache{$table} ) {
2411 my $query = 'SELECT name from part_virtual_field ' .
2412 "WHERE dbtable = '$table'";
2414 my $result = $dbh->selectcol_arrayref($query);
2415 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2417 $virtual_fields_cache{$table} = $result;
2420 @{$virtual_fields_cache{$table}};
2425 =item fields [ TABLE ]
2427 This is a wrapper for real_fields and virtual_fields. Code that called
2428 fields before should probably continue to call fields.
2433 my $something = shift;
2435 if($something->isa('FS::Record')) {
2436 $table = $something->table;
2438 $table = $something;
2439 $something = "FS::$table";
2441 return (real_fields($table), $something->virtual_fields());
2444 =item pvf FIELD_NAME
2446 Returns the FS::part_virtual_field object corresponding to a field in the
2447 record (specified by FIELD_NAME).
2452 my ($self, $name) = (shift, shift);
2454 if(grep /^$name$/, $self->virtual_fields) {
2455 return qsearchs('part_virtual_field', { dbtable => $self->table,
2461 =item vfieldpart_hashref TABLE
2463 Returns a hashref of virtual field names and vfieldparts applicable to the given
2468 sub vfieldpart_hashref {
2470 my $table = $self->table;
2472 return {} unless dbdef->table('part_virtual_field');
2475 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2476 "dbtable = '$table'";
2477 my $sth = $dbh->prepare($statement);
2478 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2479 return { map { $_->{name}, $_->{vfieldpart} }
2480 @{$sth->fetchall_arrayref({})} };
2484 =item encrypt($value)
2486 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2488 Returns the encrypted string.
2490 You should generally not have to worry about calling this, as the system handles this for you.
2495 my ($self, $value) = @_;
2498 if ($conf->exists('encryption')) {
2499 if ($self->is_encrypted($value)) {
2500 # Return the original value if it isn't plaintext.
2501 $encrypted = $value;
2504 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2505 # RSA doesn't like the empty string so let's pack it up
2506 # The database doesn't like the RSA data so uuencode it
2507 my $length = length($value)+1;
2508 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2510 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2517 =item is_encrypted($value)
2519 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2525 my ($self, $value) = @_;
2526 # Possible Bug - Some work may be required here....
2528 if ($value =~ /^M/ && length($value) > 80) {
2535 =item decrypt($value)
2537 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2539 You should generally not have to worry about calling this, as the system handles this for you.
2544 my ($self,$value) = @_;
2545 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2546 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2548 if (ref($rsa_decrypt) =~ /::RSA/) {
2549 my $encrypted = unpack ("u*", $value);
2550 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2551 if ($@) {warn "Decryption Failed"};
2559 #Initialize the Module
2560 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2562 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2563 $rsa_module = $conf->config('encryptionmodule');
2567 eval ("require $rsa_module"); # No need to import the namespace
2570 # Initialize Encryption
2571 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2572 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2573 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2576 # Intitalize Decryption
2577 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2578 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2579 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2583 =item h_search ACTION
2585 Given an ACTION, either "insert", or "delete", returns the appropriate history
2586 record corresponding to this record, if any.
2591 my( $self, $action ) = @_;
2593 my $table = $self->table;
2596 my $primary_key = dbdef->table($table)->primary_key;
2599 'table' => "h_$table",
2600 'hashref' => { $primary_key => $self->$primary_key(),
2601 'history_action' => $action,
2609 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2610 appropriate history record corresponding to this record, if any.
2615 my($self, $action) = @_;
2616 my $h = $self->h_search($action);
2617 $h ? $h->history_date : '';
2626 =item real_fields [ TABLE ]
2628 Returns a list of the real columns in the specified table. Called only by
2629 fields() and other subroutines elsewhere in FS::Record.
2636 my($table_obj) = dbdef->table($table);
2637 confess "Unknown table $table" unless $table_obj;
2638 $table_obj->columns;
2641 =item _quote VALUE, TABLE, COLUMN
2643 This is an internal function used to construct SQL statements. It returns
2644 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2645 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2650 my($value, $table, $column) = @_;
2651 my $column_obj = dbdef->table($table)->column($column);
2652 my $column_type = $column_obj->type;
2653 my $nullable = $column_obj->null;
2655 warn " $table.$column: $value ($column_type".
2656 ( $nullable ? ' NULL' : ' NOT NULL' ).
2657 ")\n" if $DEBUG > 2;
2659 if ( $value eq '' && $nullable ) {
2661 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2662 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2665 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2666 ! $column_type =~ /(char|binary|text)$/i ) {
2675 This is deprecated. Don't use it.
2677 It returns a hash-type list with the fields of this record's table set true.
2682 carp "warning: hfields is deprecated";
2685 foreach (fields($table)) {
2694 "$_: ". $self->getfield($_). "|"
2695 } (fields($self->table)) );
2698 sub DESTROY { return; }
2702 # #use Carp qw(cluck);
2703 # #cluck "DESTROYING $self";
2704 # warn "DESTROYING $self";
2708 # return ! eval { join('',@_), kill 0; 1; };
2711 =item str2time_sql [ DRIVER_NAME ]
2713 Returns a function to convert to unix time based on database type, such as
2714 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2715 the str2time_sql_closing method to return a closing string rather than just
2716 using a closing parenthesis as previously suggested.
2718 You can pass an optional driver name such as "Pg", "mysql" or
2719 $dbh->{Driver}->{Name} to return a function for that database instead of
2720 the current database.
2725 my $driver = shift || driver_name;
2727 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2728 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2730 warn "warning: unknown database type $driver; guessing how to convert ".
2731 "dates to UNIX timestamps";
2732 return 'EXTRACT(EPOCH FROM ';
2736 =item str2time_sql_closing [ DRIVER_NAME ]
2738 Returns the closing suffix of a function to convert to unix time based on
2739 database type, such as ")::integer" for Pg or ")" for mysql.
2741 You can pass an optional driver name such as "Pg", "mysql" or
2742 $dbh->{Driver}->{Name} to return a function for that database instead of
2743 the current database.
2747 sub str2time_sql_closing {
2748 my $driver = shift || driver_name;
2750 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2758 This module should probably be renamed, since much of the functionality is
2759 of general use. It is not completely unlike Adapter::DBI (see below).
2761 Exported qsearch and qsearchs should be deprecated in favor of method calls
2762 (against an FS::Record object like the old search and searchs that qsearch
2763 and qsearchs were on top of.)
2765 The whole fields / hfields mess should be removed.
2767 The various WHERE clauses should be subroutined.
2769 table string should be deprecated in favor of DBIx::DBSchema::Table.
2771 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2772 true maps to the database (and WHERE clauses) would also help.
2774 The ut_ methods should ask the dbdef for a default length.
2776 ut_sqltype (like ut_varchar) should all be defined
2778 A fallback check method should be provided which uses the dbdef.
2780 The ut_money method assumes money has two decimal digits.
2782 The Pg money kludge in the new method only strips `$'.
2784 The ut_phonen method only checks US-style phone numbers.
2786 The _quote function should probably use ut_float instead of a regex.
2788 All the subroutines probably should be methods, here or elsewhere.
2790 Probably should borrow/use some dbdef methods where appropriate (like sub
2793 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2794 or allow it to be set. Working around it is ugly any way around - DBI should
2795 be fixed. (only affects RDBMS which return uppercase column names)
2797 ut_zip should take an optional country like ut_phone.
2801 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2803 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.