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'};
160 $self->{'Hash'} = shift;
162 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
163 $self->{'Hash'}{$field}='';
166 $self->_rebless if $self->can('_rebless');
168 $self->{'modified'} = 0;
170 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
177 my $class = ref($proto) || $proto;
179 bless ($self, $class);
181 $self->{'Table'} = shift unless defined ( $self->table );
183 my $hashref = $self->{'Hash'} = shift;
185 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
186 my $obj = $cache->cache->{$hashref->{$cache->key}};
187 $obj->_cache($hashref, $cache) if $obj->can('_cache');
190 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
197 my $class = ref($proto) || $proto;
199 bless ($self, $class);
200 if ( defined $self->table ) {
201 cluck "create constructor is deprecated, use new!";
204 croak "FS::Record::create called (not from a subclass)!";
208 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
210 Searches the database for all records matching (at least) the key/value pairs
211 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
212 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
215 The preferred usage is to pass a hash reference of named parameters:
217 my @records = qsearch( {
218 'table' => 'table_name',
219 'hashref' => { 'field' => 'value'
220 'field' => { 'op' => '<',
225 #these are optional...
227 'extra_sql' => 'AND field ',
228 'order_by' => 'ORDER BY something',
229 #'cache_obj' => '', #optional
230 'addl_from' => 'LEFT JOIN othtable USING ( field )',
235 Much code still uses old-style positional parameters, this is also probably
236 fine in the common case where there are only two parameters:
238 my @records = qsearch( 'table', { 'field' => 'value' } );
240 ###oops, argh, FS::Record::new only lets us create database fields.
241 #Normal behaviour if SELECT is not specified is `*', as in
242 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
243 #feature where you can specify SELECT - remember, the objects returned,
244 #although blessed into the appropriate `FS::TABLE' package, will only have the
245 #fields you specify. This might have unwanted results if you then go calling
246 #regular FS::TABLE methods
251 my %TYPE = (); #for debugging
254 my ($type, $value) = @_;
255 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
256 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
264 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
266 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
268 $stable = $opt->{'table'} or die "table name is required";
269 $record = $opt->{'hashref'} || {};
270 $select = $opt->{'select'} || '*';
271 $extra_sql = $opt->{'extra_sql'} || '';
272 $order_by = $opt->{'order_by'} || '';
273 $cache = $opt->{'cache_obj'} || '';
274 $addl_from = $opt->{'addl_from'} || '';
275 $debug = $opt->{'debug'} || '';
277 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
281 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
283 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
287 my $table = $cache ? $cache->table : $stable;
288 my $dbdef_table = dbdef->table($table)
289 or die "No schema for table $table found - ".
290 "do you need to run freeside-upgrade?";
291 my $pkey = $dbdef_table->primary_key;
293 my @real_fields = grep exists($record->{$_}), real_fields($table);
295 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
296 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
298 cluck "warning: FS::$table not loaded; virtual fields not searchable"
299 unless $nowarn_classload;
300 @virtual_fields = ();
303 my $statement = "SELECT $select FROM $stable";
304 $statement .= " $addl_from" if $addl_from;
305 if ( @real_fields or @virtual_fields ) {
306 $statement .= ' WHERE '. join(' AND ',
307 get_real_fields($table, $record, \@real_fields) ,
308 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
312 $statement .= " $extra_sql" if defined($extra_sql);
313 $statement .= " $order_by" if defined($order_by);
315 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
316 my $sth = $dbh->prepare($statement)
317 or croak "$dbh->errstr doing $statement";
322 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
325 my $value = $record->{$field};
326 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
327 $value = $value->{'value'} if ref($value);
328 my $type = dbdef->table($table)->column($field)->type;
330 my $TYPE = SQL_VARCHAR;
331 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
334 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
335 #fixed by DBD::Pg 2.11.8
336 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
337 } elsif ( _is_fs_float( $type, $value ) ) {
343 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
345 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
348 #if this needs to be re-enabled, it needs to use a custom op like
349 #"APPROX=" or something (better name?, not '=', to avoid affecting other
351 #if ($TYPE eq SQL_DECIMAL && $op eq 'APPROX=' ) {
352 # # these values are arbitrary; better (faster?) ones welcome
353 # $sth->bind_param($bind++, $value*1.00001, { TYPE => $TYPE } );
354 # $sth->bind_param($bind++, $value*.99999, { TYPE => $TYPE } );
356 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
361 # $sth->execute( map $record->{$_},
362 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
363 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
365 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
367 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
368 @virtual_fields = "FS::$table"->virtual_fields;
370 cluck "warning: FS::$table not loaded; virtual fields not returned either"
371 unless $nowarn_classload;
372 @virtual_fields = ();
376 tie %result, "Tie::IxHash";
377 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
378 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
379 %result = map { $_->{$pkey}, $_ } @stuff;
381 @result{@stuff} = @stuff;
386 if ( keys(%result) and @virtual_fields ) {
388 "SELECT virtual_field.recnum, part_virtual_field.name, ".
389 "virtual_field.value ".
390 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
391 "WHERE part_virtual_field.dbtable = '$table' AND ".
392 "virtual_field.recnum IN (".
393 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
394 join(q!', '!, @virtual_fields) . "')";
395 warn "[debug]$me $statement\n" if $DEBUG > 1;
396 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
397 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
399 foreach (@{ $sth->fetchall_arrayref({}) }) {
400 my $recnum = $_->{recnum};
401 my $name = $_->{name};
402 my $value = $_->{value};
403 if (exists($result{$recnum})) {
404 $result{$recnum}->{$name} = $value;
409 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
410 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
411 #derivied class didn't override new method, so this optimization is safe
414 new_or_cached( "FS::$table", { %{$_} }, $cache )
418 new( "FS::$table", { %{$_} } )
422 #okay, its been tested
423 # warn "untested code (class FS::$table uses custom new method)";
425 eval 'FS::'. $table. '->new( { %{$_} } )';
429 # Check for encrypted fields and decrypt them.
430 ## only in the local copy, not the cached object
431 if ( $conf_encryption
432 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
433 foreach my $record (@return) {
434 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
435 # Set it directly... This may cause a problem in the future...
436 $record->setfield($field, $record->decrypt($record->getfield($field)));
441 cluck "warning: FS::$table not loaded; returning FS::Record objects"
442 unless $nowarn_classload;
444 FS::Record->new( $table, { %{$_} } );
450 ## makes this easier to read
452 sub get_virtual_fields {
456 my $virtual_fields = shift;
462 if ( ref($record->{$_}) ) {
463 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
464 if ( uc($op) eq 'ILIKE' ) {
466 $record->{$_}{'value'} = lc($record->{$_}{'value'});
467 $column = "LOWER($_)";
469 $record->{$_} = $record->{$_}{'value'};
472 # ... EXISTS ( SELECT name, value FROM part_virtual_field
474 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
475 # WHERE recnum = svc_acct.svcnum
476 # AND (name, value) = ('egad', 'brain') )
478 my $value = $record->{$_};
482 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
483 "( SELECT part_virtual_field.name, virtual_field.value ".
484 "FROM part_virtual_field JOIN virtual_field ".
485 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
486 "WHERE virtual_field.recnum = ${table}.${pkey} ".
487 "AND part_virtual_field.name = '${column}'".
489 " AND virtual_field.value ${op} '${value}'"
493 } @{ $virtual_fields } ) ;
496 sub get_real_fields {
499 my $real_fields = shift;
501 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
507 my $type = dbdef->table($table)->column($column)->type;
508 my $value = $record->{$column};
509 $value = $value->{'value'} if ref($value);
510 if ( ref($record->{$_}) ) {
511 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
512 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
513 if ( uc($op) eq 'ILIKE' ) {
515 $record->{$_}{'value'} = lc($record->{$_}{'value'});
516 $column = "LOWER($_)";
518 $record->{$_} = $record->{$_}{'value'}
521 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
523 if ( driver_name eq 'Pg' ) {
524 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
525 qq-( $column IS NULL )-;
527 qq-( $column IS NULL OR $column = '' )-;
530 qq-( $column IS NULL OR $column = "" )-;
532 } elsif ( $op eq '!=' ) {
533 if ( driver_name eq 'Pg' ) {
534 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
535 qq-( $column IS NOT NULL )-;
537 qq-( $column IS NOT NULL AND $column != '' )-;
540 qq-( $column IS NOT NULL AND $column != "" )-;
543 if ( driver_name eq 'Pg' ) {
544 qq-( $column $op '' )-;
546 qq-( $column $op "" )-;
549 #if this needs to be re-enabled, it needs to use a custom op like
550 #"APPROX=" or something (better name?, not '=', to avoid affecting other
552 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
553 # ( "$column <= ?", "$column >= ?" );
557 } @{ $real_fields } );
560 =item by_key PRIMARY_KEY_VALUE
562 This is a class method that returns the record with the given primary key
563 value. This method is only useful in FS::Record subclasses. For example:
565 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
569 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
574 my ($class, $pkey_value) = @_;
576 my $table = $class->table
577 or croak "No table for $class found";
579 my $dbdef_table = dbdef->table($table)
580 or die "No schema for table $table found - ".
581 "do you need to create it or run dbdef-create?";
582 my $pkey = $dbdef_table->primary_key
583 or die "No primary key for table $table";
585 return qsearchs($table, { $pkey => $pkey_value });
588 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
590 Experimental JOINed search method. Using this method, you can execute a
591 single SELECT spanning multiple tables, and cache the results for subsequent
592 method calls. Interface will almost definately change in an incompatible
600 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
601 my $cache = FS::SearchCache->new( $ptable, $pkey );
604 grep { !$saw{$_->getfield($pkey)}++ }
605 qsearch($table, $record, $select, $extra_sql, $cache )
609 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
611 Same as qsearch, except that if more than one record matches, it B<carp>s but
612 returns the first. If this happens, you either made a logic error in asking
613 for a single item, or your data is corrupted.
617 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
619 my(@result) = qsearch(@_);
620 cluck "warning: Multiple records in scalar search ($table)"
621 if scalar(@result) > 1;
622 #should warn more vehemently if the search was on a primary key?
623 scalar(@result) ? ($result[0]) : ();
634 Returns the table name.
639 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
646 Returns the DBIx::DBSchema::Table object for the table.
652 my($table)=$self->table;
653 dbdef->table($table);
658 Returns the primary key for the table.
664 my $pkey = $self->dbdef_table->primary_key;
667 =item get, getfield COLUMN
669 Returns the value of the column/field/key COLUMN.
674 my($self,$field) = @_;
675 # to avoid "Use of unitialized value" errors
676 if ( defined ( $self->{Hash}->{$field} ) ) {
677 $self->{Hash}->{$field};
687 =item set, setfield COLUMN, VALUE
689 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
694 my($self,$field,$value) = @_;
695 $self->{'modified'} = 1;
696 $self->{'Hash'}->{$field} = $value;
703 =item AUTLOADED METHODS
705 $record->column is a synonym for $record->get('column');
707 $record->column('value') is a synonym for $record->set('column','value');
714 my($field)=$AUTOLOAD;
716 if ( defined($value) ) {
717 confess "errant AUTOLOAD $field for $self (arg $value)"
718 unless blessed($self) && $self->can('setfield');
719 $self->setfield($field,$value);
721 confess "errant AUTOLOAD $field for $self (no args)"
722 unless blessed($self) && $self->can('getfield');
723 $self->getfield($field);
729 # my $field = $AUTOLOAD;
731 # if ( defined($_[1]) ) {
732 # $_[0]->setfield($field, $_[1]);
734 # $_[0]->getfield($field);
740 Returns a list of the column/value pairs, usually for assigning to a new hash.
742 To make a distinct duplicate of an FS::Record object, you can do:
744 $new = new FS::Record ( $old->table, { $old->hash } );
750 confess $self. ' -> hash: Hash attribute is undefined'
751 unless defined($self->{'Hash'});
752 %{ $self->{'Hash'} };
757 Returns a reference to the column/value hash. This may be deprecated in the
758 future; if there's a reason you can't just use the autoloaded or get/set
770 Returns true if any of this object's values have been modified with set (or via
771 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
781 =item select_for_update
783 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
788 sub select_for_update {
790 my $primary_key = $self->primary_key;
793 'table' => $self->table,
794 'hashref' => { $primary_key => $self->$primary_key() },
795 'extra_sql' => 'FOR UPDATE',
801 Locks this table with a database-driver specific lock method. This is used
802 as a mutex in order to do a duplicate search.
804 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
806 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
808 Errors are fatal; no useful return value.
810 Note: To use this method for new tables other than svc_acct and svc_phone,
811 edit freeside-upgrade and add those tables to the duplicate_lock list.
817 my $table = $self->table;
819 warn "$me locking $table table\n" if $DEBUG;
821 if ( driver_name =~ /^Pg/i ) {
823 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
826 } elsif ( driver_name =~ /^mysql/i ) {
828 dbh->do("SELECT * FROM duplicate_lock
829 WHERE lockname = '$table'
831 ) or die dbh->errstr;
835 die "unknown database ". driver_name. "; don't know how to lock table";
839 warn "$me acquired $table table lock\n" if $DEBUG;
845 Inserts this record to the database. If there is an error, returns the error,
846 otherwise returns false.
854 warn "$self -> insert" if $DEBUG;
856 my $error = $self->check;
857 return $error if $error;
859 #single-field unique keys are given a value if false
860 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
861 foreach ( $self->dbdef_table->unique_singles) {
862 $self->unique($_) unless $self->getfield($_);
865 #and also the primary key, if the database isn't going to
866 my $primary_key = $self->dbdef_table->primary_key;
868 if ( $primary_key ) {
869 my $col = $self->dbdef_table->column($primary_key);
872 uc($col->type) =~ /^(BIG)?SERIAL\d?/
873 || ( driver_name eq 'Pg'
874 && defined($col->default)
875 && $col->default =~ /^nextval\(/i
877 || ( driver_name eq 'mysql'
878 && defined($col->local)
879 && $col->local =~ /AUTO_INCREMENT/i
881 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
884 my $table = $self->table;
886 # Encrypt before the database
887 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
888 && scalar( eval '@FS::'. $table . '::encrypted_fields')
889 && $conf->exists('encryption')
891 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
892 $self->{'saved'} = $self->getfield($field);
893 $self->setfield($field, $self->encrypt($self->getfield($field)));
897 #false laziness w/delete
899 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
902 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
905 my $statement = "INSERT INTO $table ";
906 if ( @real_fields ) {
909 join( ', ', @real_fields ).
911 join( ', ', @values ).
915 $statement .= 'DEFAULT VALUES';
917 warn "[debug]$me $statement\n" if $DEBUG > 1;
918 my $sth = dbh->prepare($statement) or return dbh->errstr;
920 local $SIG{HUP} = 'IGNORE';
921 local $SIG{INT} = 'IGNORE';
922 local $SIG{QUIT} = 'IGNORE';
923 local $SIG{TERM} = 'IGNORE';
924 local $SIG{TSTP} = 'IGNORE';
925 local $SIG{PIPE} = 'IGNORE';
927 $sth->execute or return $sth->errstr;
929 # get inserted id from the database, if applicable & needed
930 if ( $db_seq && ! $self->getfield($primary_key) ) {
931 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
935 if ( driver_name eq 'Pg' ) {
937 #my $oid = $sth->{'pg_oid_status'};
938 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
940 my $default = $self->dbdef_table->column($primary_key)->default;
941 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
942 dbh->rollback if $FS::UID::AutoCommit;
943 return "can't parse $table.$primary_key default value".
944 " for sequence name: $default";
948 my $i_sql = "SELECT currval('$sequence')";
949 my $i_sth = dbh->prepare($i_sql) or do {
950 dbh->rollback if $FS::UID::AutoCommit;
953 $i_sth->execute() or do { #$i_sth->execute($oid)
954 dbh->rollback if $FS::UID::AutoCommit;
955 return $i_sth->errstr;
957 $insertid = $i_sth->fetchrow_arrayref->[0];
959 } elsif ( driver_name eq 'mysql' ) {
961 $insertid = dbh->{'mysql_insertid'};
962 # work around mysql_insertid being null some of the time, ala RT :/
963 unless ( $insertid ) {
964 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
965 "using SELECT LAST_INSERT_ID();";
966 my $i_sql = "SELECT LAST_INSERT_ID()";
967 my $i_sth = dbh->prepare($i_sql) or do {
968 dbh->rollback if $FS::UID::AutoCommit;
971 $i_sth->execute or do {
972 dbh->rollback if $FS::UID::AutoCommit;
973 return $i_sth->errstr;
975 $insertid = $i_sth->fetchrow_arrayref->[0];
980 dbh->rollback if $FS::UID::AutoCommit;
981 return "don't know how to retreive inserted ids from ". driver_name.
982 ", try using counterfiles (maybe run dbdef-create?)";
986 $self->setfield($primary_key, $insertid);
991 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
992 $self->virtual_fields;
993 if (@virtual_fields) {
994 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
996 my $vfieldpart = $self->vfieldpart_hashref;
998 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1001 my $v_sth = dbh->prepare($v_statement) or do {
1002 dbh->rollback if $FS::UID::AutoCommit;
1006 foreach (keys(%v_values)) {
1007 $v_sth->execute($self->getfield($primary_key),
1011 dbh->rollback if $FS::UID::AutoCommit;
1012 return $v_sth->errstr;
1019 if ( defined dbdef->table('h_'. $table) ) {
1020 my $h_statement = $self->_h_statement('insert');
1021 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1022 $h_sth = dbh->prepare($h_statement) or do {
1023 dbh->rollback if $FS::UID::AutoCommit;
1029 $h_sth->execute or return $h_sth->errstr if $h_sth;
1031 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1033 # Now that it has been saved, reset the encrypted fields so that $new
1034 # can still be used.
1035 foreach my $field (keys %{$saved}) {
1036 $self->setfield($field, $saved->{$field});
1044 Depriciated (use insert instead).
1049 cluck "warning: FS::Record::add deprecated!";
1050 insert @_; #call method in this scope
1055 Delete this record from the database. If there is an error, returns the error,
1056 otherwise returns false.
1063 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1065 $self->getfield($_) eq ''
1066 #? "( $_ IS NULL OR $_ = \"\" )"
1067 ? ( driver_name eq 'Pg'
1069 : "( $_ IS NULL OR $_ = \"\" )"
1071 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1072 } ( $self->dbdef_table->primary_key )
1073 ? ( $self->dbdef_table->primary_key)
1074 : real_fields($self->table)
1076 warn "[debug]$me $statement\n" if $DEBUG > 1;
1077 my $sth = dbh->prepare($statement) or return dbh->errstr;
1080 if ( defined dbdef->table('h_'. $self->table) ) {
1081 my $h_statement = $self->_h_statement('delete');
1082 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1083 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1088 my $primary_key = $self->dbdef_table->primary_key;
1091 my $vfp = $self->vfieldpart_hashref;
1092 foreach($self->virtual_fields) {
1093 next if $self->getfield($_) eq '';
1094 unless(@del_vfields) {
1095 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1096 $v_sth = dbh->prepare($st) or return dbh->errstr;
1098 push @del_vfields, $_;
1101 local $SIG{HUP} = 'IGNORE';
1102 local $SIG{INT} = 'IGNORE';
1103 local $SIG{QUIT} = 'IGNORE';
1104 local $SIG{TERM} = 'IGNORE';
1105 local $SIG{TSTP} = 'IGNORE';
1106 local $SIG{PIPE} = 'IGNORE';
1108 my $rc = $sth->execute or return $sth->errstr;
1109 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1110 $h_sth->execute or return $h_sth->errstr if $h_sth;
1111 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1112 or return $v_sth->errstr
1113 foreach (@del_vfields);
1115 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1117 #no need to needlessly destoy the data either (causes problems actually)
1118 #undef $self; #no need to keep object!
1125 Depriciated (use delete instead).
1130 cluck "warning: FS::Record::del deprecated!";
1131 &delete(@_); #call method in this scope
1134 =item replace OLD_RECORD
1136 Replace the OLD_RECORD with this one in the database. If there is an error,
1137 returns the error, otherwise returns false.
1142 my ($new, $old) = (shift, shift);
1144 $old = $new->replace_old unless defined($old);
1146 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1148 if ( $new->can('replace_check') ) {
1149 my $error = $new->replace_check($old);
1150 return $error if $error;
1153 return "Records not in same table!" unless $new->table eq $old->table;
1155 my $primary_key = $old->dbdef_table->primary_key;
1156 return "Can't change primary key $primary_key ".
1157 'from '. $old->getfield($primary_key).
1158 ' to ' . $new->getfield($primary_key)
1160 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1162 my $error = $new->check;
1163 return $error if $error;
1165 # Encrypt for replace
1167 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1168 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1169 $saved->{$field} = $new->getfield($field);
1170 $new->setfield($field, $new->encrypt($new->getfield($field)));
1174 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1175 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1176 ? ($_, $new->getfield($_)) : () } $old->fields;
1178 unless (keys(%diff) || $no_update_diff ) {
1179 carp "[warning]$me $new -> replace $old: records identical"
1180 unless $nowarn_identical;
1184 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1186 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1187 } real_fields($old->table)
1192 if ( $old->getfield($_) eq '' ) {
1194 #false laziness w/qsearch
1195 if ( driver_name eq 'Pg' ) {
1196 my $type = $old->dbdef_table->column($_)->type;
1197 if ( $type =~ /(int|(big)?serial)/i ) {
1200 qq-( $_ IS NULL OR $_ = '' )-;
1203 qq-( $_ IS NULL OR $_ = "" )-;
1207 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1210 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1213 warn "[debug]$me $statement\n" if $DEBUG > 1;
1214 my $sth = dbh->prepare($statement) or return dbh->errstr;
1217 if ( defined dbdef->table('h_'. $old->table) ) {
1218 my $h_old_statement = $old->_h_statement('replace_old');
1219 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1220 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1226 if ( defined dbdef->table('h_'. $new->table) ) {
1227 my $h_new_statement = $new->_h_statement('replace_new');
1228 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1229 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1234 # For virtual fields we have three cases with different SQL
1235 # statements: add, replace, delete
1239 my (@add_vfields, @rep_vfields, @del_vfields);
1240 my $vfp = $old->vfieldpart_hashref;
1241 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1242 if($diff{$_} eq '') {
1244 unless(@del_vfields) {
1245 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1246 "AND vfieldpart = ?";
1247 warn "[debug]$me $st\n" if $DEBUG > 2;
1248 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1250 push @del_vfields, $_;
1251 } elsif($old->getfield($_) eq '') {
1253 unless(@add_vfields) {
1254 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1256 warn "[debug]$me $st\n" if $DEBUG > 2;
1257 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1259 push @add_vfields, $_;
1262 unless(@rep_vfields) {
1263 my $st = "UPDATE virtual_field SET value = ? ".
1264 "WHERE recnum = ? AND vfieldpart = ?";
1265 warn "[debug]$me $st\n" if $DEBUG > 2;
1266 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1268 push @rep_vfields, $_;
1272 local $SIG{HUP} = 'IGNORE';
1273 local $SIG{INT} = 'IGNORE';
1274 local $SIG{QUIT} = 'IGNORE';
1275 local $SIG{TERM} = 'IGNORE';
1276 local $SIG{TSTP} = 'IGNORE';
1277 local $SIG{PIPE} = 'IGNORE';
1279 my $rc = $sth->execute or return $sth->errstr;
1280 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1281 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1282 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1284 $v_del_sth->execute($old->getfield($primary_key),
1286 or return $v_del_sth->errstr
1287 foreach(@del_vfields);
1289 $v_add_sth->execute($new->getfield($_),
1290 $old->getfield($primary_key),
1292 or return $v_add_sth->errstr
1293 foreach(@add_vfields);
1295 $v_rep_sth->execute($new->getfield($_),
1296 $old->getfield($primary_key),
1298 or return $v_rep_sth->errstr
1299 foreach(@rep_vfields);
1301 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1303 # Now that it has been saved, reset the encrypted fields so that $new
1304 # can still be used.
1305 foreach my $field (keys %{$saved}) {
1306 $new->setfield($field, $saved->{$field});
1314 my( $self ) = shift;
1315 warn "[$me] replace called with no arguments; autoloading old record\n"
1318 my $primary_key = $self->dbdef_table->primary_key;
1319 if ( $primary_key ) {
1320 $self->by_key( $self->$primary_key() ) #this is what's returned
1321 or croak "can't find ". $self->table. ".$primary_key ".
1322 $self->$primary_key();
1324 croak $self->table. " has no primary key; pass old record as argument";
1331 Depriciated (use replace instead).
1336 cluck "warning: FS::Record::rep deprecated!";
1337 replace @_; #call method in this scope
1342 Checks virtual fields (using check_blocks). Subclasses should still provide
1343 a check method to validate real fields, foreign keys, etc., and call this
1344 method via $self->SUPER::check.
1346 (FIXME: Should this method try to make sure that it I<is> being called from
1347 a subclass's check method, to keep the current semantics as far as possible?)
1352 #confess "FS::Record::check not implemented; supply one in subclass!";
1355 foreach my $field ($self->virtual_fields) {
1356 for ($self->getfield($field)) {
1357 # See notes on check_block in FS::part_virtual_field.
1358 eval $self->pvf($field)->check_block;
1360 #this is bad, probably want to follow the stack backtrace up and see
1362 my $err = "Fatal error checking $field for $self";
1364 return "$err (see log for backtrace): $@";
1367 $self->setfield($field, $_);
1373 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1375 Processes a batch import as a queued JSRPC job
1377 JOB is an FS::queue entry.
1379 OPTIONS_HASHREF can have the following keys:
1385 Table name (required).
1389 Listref of field names for static fields. They will be given values from the
1390 PARAMS hashref and passed as a "params" hashref to batch_import.
1394 Formats hashref. Keys are field names, values are listrefs that define the
1397 Each listref value can be a column name or a code reference. Coderefs are run
1398 with the row object, data and a FS::Conf object as the three parameters.
1399 For example, this coderef does the same thing as using the "columnname" string:
1402 my( $record, $data, $conf ) = @_;
1403 $record->columnname( $data );
1406 Coderefs are run after all "column name" fields are assigned.
1410 Optional format hashref of types. Keys are field names, values are "csv",
1411 "xls" or "fixedlength". Overrides automatic determination of file type
1414 =item format_headers
1416 Optional format hashref of header lines. Keys are field names, values are 0
1417 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1420 =item format_sep_chars
1422 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1423 CSV separation character.
1425 =item format_fixedlenth_formats
1427 Optional format hashref of fixed length format defintiions. Keys are field
1428 names, values Parse::FixedLength listrefs of field definitions.
1432 Set true to default to CSV file type if the filename does not contain a
1433 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1438 PARAMS is a base64-encoded Storable string containing the POSTed data as
1439 a hash ref. It normally contains at least one field, "uploaded files",
1440 generated by /elements/file-upload.html and containing the list of uploaded
1441 files. Currently only supports a single file named "file".
1445 use Storable qw(thaw);
1448 sub process_batch_import {
1449 my($job, $opt) = ( shift, shift );
1451 my $table = $opt->{table};
1452 my @pass_params = @{ $opt->{params} };
1453 my %formats = %{ $opt->{formats} };
1455 my $param = thaw(decode_base64(shift));
1456 warn Dumper($param) if $DEBUG;
1458 my $files = $param->{'uploaded_files'}
1459 or die "No files provided.\n";
1461 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1463 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1464 my $file = $dir. $files{'file'};
1467 FS::Record::batch_import( {
1470 formats => \%formats,
1471 format_types => $opt->{format_types},
1472 format_headers => $opt->{format_headers},
1473 format_sep_chars => $opt->{format_sep_chars},
1474 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1479 format => $param->{format},
1480 params => { map { $_ => $param->{$_} } @pass_params },
1482 default_csv => $opt->{default_csv},
1487 die "$error\n" if $error;
1490 =item batch_import PARAM_HASHREF
1492 Class method for batch imports. Available params:
1502 =item format_headers
1504 =item format_sep_chars
1506 =item format_fixedlength_formats
1512 FS::queue object, will be updated with progress
1518 csv, xls or fixedlength
1531 warn "$me batch_import call with params: \n". Dumper($param)
1534 my $table = $param->{table};
1535 my $formats = $param->{formats};
1537 my $job = $param->{job};
1538 my $file = $param->{file};
1539 my $format = $param->{'format'};
1540 my $params = $param->{params} || {};
1542 die "unknown format $format" unless exists $formats->{ $format };
1544 my $type = $param->{'format_types'}
1545 ? $param->{'format_types'}{ $format }
1546 : $param->{type} || 'csv';
1549 if ( $file =~ /\.(\w+)$/i ) {
1553 warn "can't parse file type from filename $file; defaulting to CSV";
1557 if $param->{'default_csv'} && $type ne 'xls';
1560 my $header = $param->{'format_headers'}
1561 ? $param->{'format_headers'}{ $param->{'format'} }
1564 my $sep_char = $param->{'format_sep_chars'}
1565 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1568 my $fixedlength_format =
1569 $param->{'format_fixedlength_formats'}
1570 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1573 my @fields = @{ $formats->{ $format } };
1579 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1581 if ( $type eq 'csv' ) {
1584 $attr{sep_char} = $sep_char if $sep_char;
1585 $parser = new Text::CSV_XS \%attr;
1587 } elsif ( $type eq 'fixedlength' ) {
1589 eval "use Parse::FixedLength;";
1591 $parser = new Parse::FixedLength $fixedlength_format;
1594 die "Unknown file type $type\n";
1597 @buffer = split(/\r?\n/, slurp($file) );
1598 splice(@buffer, 0, ($header || 0) );
1599 $count = scalar(@buffer);
1601 } elsif ( $type eq 'xls' ) {
1603 eval "use Spreadsheet::ParseExcel;";
1606 eval "use DateTime::Format::Excel;";
1607 #for now, just let the error be thrown if it is used, since only CDR
1608 # formats bill_west and troop use it, not other excel-parsing things
1611 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1613 $parser = $excel->{Worksheet}[0]; #first sheet
1615 $count = $parser->{MaxRow} || $parser->{MinRow};
1618 $row = $header || 0;
1621 die "Unknown file type $type\n";
1626 local $SIG{HUP} = 'IGNORE';
1627 local $SIG{INT} = 'IGNORE';
1628 local $SIG{QUIT} = 'IGNORE';
1629 local $SIG{TERM} = 'IGNORE';
1630 local $SIG{TSTP} = 'IGNORE';
1631 local $SIG{PIPE} = 'IGNORE';
1633 my $oldAutoCommit = $FS::UID::AutoCommit;
1634 local $FS::UID::AutoCommit = 0;
1639 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1643 if ( $type eq 'csv' ) {
1645 last unless scalar(@buffer);
1646 $line = shift(@buffer);
1648 $parser->parse($line) or do {
1649 $dbh->rollback if $oldAutoCommit;
1650 return "can't parse: ". $parser->error_input();
1652 @columns = $parser->fields();
1654 } elsif ( $type eq 'fixedlength' ) {
1656 @columns = $parser->parse($line);
1658 } elsif ( $type eq 'xls' ) {
1660 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1661 || ! $parser->{Cells}[$row];
1663 my @row = @{ $parser->{Cells}[$row] };
1664 @columns = map $_->{Val}, @row;
1667 #warn $z++. ": $_\n" for @columns;
1670 die "Unknown file type $type\n";
1674 my %hash = %$params;
1676 foreach my $field ( @fields ) {
1678 my $value = shift @columns;
1680 if ( ref($field) eq 'CODE' ) {
1681 #&{$field}(\%hash, $value);
1682 push @later, $field, $value;
1684 #??? $hash{$field} = $value if length($value);
1685 $hash{$field} = $value if defined($value) && length($value);
1690 my $class = "FS::$table";
1692 my $record = $class->new( \%hash );
1694 while ( scalar(@later) ) {
1695 my $sub = shift @later;
1696 my $data = shift @later;
1697 &{$sub}($record, $data, $conf); # $record->&{$sub}($data, $conf);
1700 my $error = $record->insert;
1703 $dbh->rollback if $oldAutoCommit;
1704 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1710 if ( $job && time - $min_sec > $last ) { #progress bar
1711 $job->update_statustext( int(100 * $imported / $count) );
1717 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1719 return "Empty file!" unless $imported || $param->{empty_ok};
1726 my( $self, $action, $time ) = @_;
1731 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1732 real_fields($self->table);
1735 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1736 # You can see if it changed by the paymask...
1737 if ($conf && $conf->exists('encryption') ) {
1738 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1740 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1742 "INSERT INTO h_". $self->table. " ( ".
1743 join(', ', qw(history_date history_user history_action), @fields ).
1745 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1752 B<Warning>: External use is B<deprecated>.
1754 Replaces COLUMN in record with a unique number, using counters in the
1755 filesystem. Used by the B<insert> method on single-field unique columns
1756 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1757 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1759 Returns the new value.
1764 my($self,$field) = @_;
1765 my($table)=$self->table;
1767 croak "Unique called on field $field, but it is ",
1768 $self->getfield($field),
1770 if $self->getfield($field);
1772 #warn "table $table is tainted" if is_tainted($table);
1773 #warn "field $field is tainted" if is_tainted($field);
1775 my($counter) = new File::CounterFile "$table.$field",0;
1777 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1779 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1782 my $index = $counter->inc;
1783 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1785 $index =~ /^(\d*)$/;
1788 $self->setfield($field,$index);
1792 =item ut_float COLUMN
1794 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1795 null. If there is an error, returns the error, otherwise returns false.
1800 my($self,$field)=@_ ;
1801 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1802 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1803 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1804 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1805 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1806 $self->setfield($field,$1);
1809 =item ut_floatn COLUMN
1811 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1812 null. If there is an error, returns the error, otherwise returns false.
1816 #false laziness w/ut_ipn
1818 my( $self, $field ) = @_;
1819 if ( $self->getfield($field) =~ /^()$/ ) {
1820 $self->setfield($field,'');
1823 $self->ut_float($field);
1827 =item ut_sfloat COLUMN
1829 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1830 May not be null. If there is an error, returns the error, otherwise returns
1836 my($self,$field)=@_ ;
1837 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1838 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1839 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1840 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1841 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1842 $self->setfield($field,$1);
1845 =item ut_sfloatn COLUMN
1847 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1848 null. If there is an error, returns the error, otherwise returns false.
1853 my( $self, $field ) = @_;
1854 if ( $self->getfield($field) =~ /^()$/ ) {
1855 $self->setfield($field,'');
1858 $self->ut_sfloat($field);
1862 =item ut_snumber COLUMN
1864 Check/untaint signed numeric data (whole numbers). If there is an error,
1865 returns the error, otherwise returns false.
1870 my($self, $field) = @_;
1871 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1872 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1873 $self->setfield($field, "$1$2");
1877 =item ut_snumbern COLUMN
1879 Check/untaint signed numeric data (whole numbers). If there is an error,
1880 returns the error, otherwise returns false.
1885 my($self, $field) = @_;
1886 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1887 or return "Illegal (numeric) $field: ". $self->getfield($field);
1889 return "Illegal (numeric) $field: ". $self->getfield($field)
1892 $self->setfield($field, "$1$2");
1896 =item ut_number COLUMN
1898 Check/untaint simple numeric data (whole numbers). May not be null. If there
1899 is an error, returns the error, otherwise returns false.
1904 my($self,$field)=@_;
1905 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1906 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1907 $self->setfield($field,$1);
1911 =item ut_numbern COLUMN
1913 Check/untaint simple numeric data (whole numbers). May be null. If there is
1914 an error, returns the error, otherwise returns false.
1919 my($self,$field)=@_;
1920 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1921 or return "Illegal (numeric) $field: ". $self->getfield($field);
1922 $self->setfield($field,$1);
1926 =item ut_money COLUMN
1928 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1929 is an error, returns the error, otherwise returns false.
1934 my($self,$field)=@_;
1935 $self->setfield($field, 0) if $self->getfield($field) eq '';
1936 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1937 or return "Illegal (money) $field: ". $self->getfield($field);
1938 #$self->setfield($field, "$1$2$3" || 0);
1939 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1943 =item ut_text COLUMN
1945 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1946 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1947 May not be null. If there is an error, returns the error, otherwise returns
1953 my($self,$field)=@_;
1954 #warn "msgcat ". \&msgcat. "\n";
1955 #warn "notexist ". \¬exist. "\n";
1956 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1957 $self->getfield($field)
1958 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1959 or return gettext('illegal_or_empty_text'). " $field: ".
1960 $self->getfield($field);
1961 $self->setfield($field,$1);
1965 =item ut_textn COLUMN
1967 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1968 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1969 May be null. If there is an error, returns the error, otherwise returns false.
1974 my($self,$field)=@_;
1975 $self->getfield($field)
1976 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1977 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1978 $self->setfield($field,$1);
1982 =item ut_alpha COLUMN
1984 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1985 an error, returns the error, otherwise returns false.
1990 my($self,$field)=@_;
1991 $self->getfield($field) =~ /^(\w+)$/
1992 or return "Illegal or empty (alphanumeric) $field: ".
1993 $self->getfield($field);
1994 $self->setfield($field,$1);
1998 =item ut_alpha COLUMN
2000 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2001 error, returns the error, otherwise returns false.
2006 my($self,$field)=@_;
2007 $self->getfield($field) =~ /^(\w*)$/
2008 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2009 $self->setfield($field,$1);
2013 =item ut_alpha_lower COLUMN
2015 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2016 there is an error, returns the error, otherwise returns false.
2020 sub ut_alpha_lower {
2021 my($self,$field)=@_;
2022 $self->getfield($field) =~ /[[:upper:]]/
2023 and return "Uppercase characters are not permitted in $field";
2024 $self->ut_alpha($field);
2027 =item ut_phonen COLUMN [ COUNTRY ]
2029 Check/untaint phone numbers. May be null. If there is an error, returns
2030 the error, otherwise returns false.
2032 Takes an optional two-letter ISO country code; without it or with unsupported
2033 countries, ut_phonen simply calls ut_alphan.
2038 my( $self, $field, $country ) = @_;
2039 return $self->ut_alphan($field) unless defined $country;
2040 my $phonen = $self->getfield($field);
2041 if ( $phonen eq '' ) {
2042 $self->setfield($field,'');
2043 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2045 $phonen = $conf->config('cust_main-default_areacode').$phonen
2046 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2047 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2048 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2049 $phonen = "$1-$2-$3";
2050 $phonen .= " x$4" if $4;
2051 $self->setfield($field,$phonen);
2053 warn "warning: don't know how to check phone numbers for country $country";
2054 return $self->ut_textn($field);
2061 Check/untaint hexadecimal values.
2066 my($self, $field) = @_;
2067 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2068 or return "Illegal (hex) $field: ". $self->getfield($field);
2069 $self->setfield($field, uc($1));
2073 =item ut_hexn COLUMN
2075 Check/untaint hexadecimal values. May be null.
2080 my($self, $field) = @_;
2081 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2082 or return "Illegal (hex) $field: ". $self->getfield($field);
2083 $self->setfield($field, uc($1));
2088 Check/untaint ip addresses. IPv4 only for now.
2093 my( $self, $field ) = @_;
2094 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2095 or return "Illegal (IP address) $field: ". $self->getfield($field);
2096 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2097 $self->setfield($field, "$1.$2.$3.$4");
2103 Check/untaint ip addresses. IPv4 only for now. May be null.
2108 my( $self, $field ) = @_;
2109 if ( $self->getfield($field) =~ /^()$/ ) {
2110 $self->setfield($field,'');
2113 $self->ut_ip($field);
2117 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2119 Check/untaint coordinates.
2120 Accepts the following forms:
2130 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2131 The latter form (that is, the MMM are thousands of minutes) is
2132 assumed if the "MMM" is exactly three digits or two digits > 59.
2134 To be safe, just use the DDD.DDDDD form.
2136 If LOWER or UPPER are specified, then the coordinate is checked
2137 for lower and upper bounds, respectively.
2143 my ($self, $field) = (shift, shift);
2145 my $lower = shift if scalar(@_);
2146 my $upper = shift if scalar(@_);
2147 my $coord = $self->getfield($field);
2148 my $neg = $coord =~ s/^(-)//;
2150 my ($d, $m, $s) = (0, 0, 0);
2153 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2154 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2155 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2157 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2160 return "Invalid (coordinate with minutes > 59) $field: "
2161 . $self->getfield($field);
2164 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2166 if (defined($lower) and ($coord < $lower)) {
2167 return "Invalid (coordinate < $lower) $field: "
2168 . $self->getfield($field);;
2171 if (defined($upper) and ($coord > $upper)) {
2172 return "Invalid (coordinate > $upper) $field: "
2173 . $self->getfield($field);;
2176 $self->setfield($field, $coord);
2180 return "Invalid (coordinate) $field: " . $self->getfield($field);
2184 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2186 Same as ut_coord, except optionally null.
2192 my ($self, $field) = (shift, shift);
2194 if ($self->getfield($field) =~ /^$/) {
2197 return $self->ut_coord($field, @_);
2203 =item ut_domain COLUMN
2205 Check/untaint host and domain names.
2210 my( $self, $field ) = @_;
2211 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2212 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2213 or return "Illegal (domain) $field: ". $self->getfield($field);
2214 $self->setfield($field,$1);
2218 =item ut_name COLUMN
2220 Check/untaint proper names; allows alphanumerics, spaces and the following
2221 punctuation: , . - '
2228 my( $self, $field ) = @_;
2229 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2230 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2231 $self->setfield($field,$1);
2237 Check/untaint zip codes.
2241 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2244 my( $self, $field, $country ) = @_;
2246 if ( $country eq 'US' ) {
2248 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2249 or return gettext('illegal_zip'). " $field for country $country: ".
2250 $self->getfield($field);
2251 $self->setfield($field, $1);
2253 } elsif ( $country eq 'CA' ) {
2255 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2256 or return gettext('illegal_zip'). " $field for country $country: ".
2257 $self->getfield($field);
2258 $self->setfield($field, "$1 $2");
2262 if ( $self->getfield($field) =~ /^\s*$/
2263 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2266 $self->setfield($field,'');
2268 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2269 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2270 $self->setfield($field,$1);
2278 =item ut_country COLUMN
2280 Check/untaint country codes. Country names are changed to codes, if possible -
2281 see L<Locale::Country>.
2286 my( $self, $field ) = @_;
2287 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2288 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2289 && country2code($1) ) {
2290 $self->setfield($field,uc(country2code($1)));
2293 $self->getfield($field) =~ /^(\w\w)$/
2294 or return "Illegal (country) $field: ". $self->getfield($field);
2295 $self->setfield($field,uc($1));
2299 =item ut_anything COLUMN
2301 Untaints arbitrary data. Be careful.
2306 my( $self, $field ) = @_;
2307 $self->getfield($field) =~ /^(.*)$/s
2308 or return "Illegal $field: ". $self->getfield($field);
2309 $self->setfield($field,$1);
2313 =item ut_enum COLUMN CHOICES_ARRAYREF
2315 Check/untaint a column, supplying all possible choices, like the "enum" type.
2320 my( $self, $field, $choices ) = @_;
2321 foreach my $choice ( @$choices ) {
2322 if ( $self->getfield($field) eq $choice ) {
2323 $self->setfield($choice);
2327 return "Illegal (enum) field $field: ". $self->getfield($field);
2330 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2332 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2333 on the column first.
2337 sub ut_foreign_key {
2338 my( $self, $field, $table, $foreign ) = @_;
2339 return '' if $no_check_foreign;
2340 qsearchs($table, { $foreign => $self->getfield($field) })
2341 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2342 " in $table.$foreign";
2346 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2348 Like ut_foreign_key, except the null value is also allowed.
2352 sub ut_foreign_keyn {
2353 my( $self, $field, $table, $foreign ) = @_;
2354 $self->getfield($field)
2355 ? $self->ut_foreign_key($field, $table, $foreign)
2359 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2361 Checks this column as an agentnum, taking into account the current users's
2362 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2363 right or rights allowing no agentnum.
2367 sub ut_agentnum_acl {
2368 my( $self, $field ) = (shift, shift);
2369 my $null_acl = scalar(@_) ? shift : [];
2370 $null_acl = [ $null_acl ] unless ref($null_acl);
2372 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2373 return "Illegal agentnum: $error" if $error;
2375 my $curuser = $FS::CurrentUser::CurrentUser;
2377 if ( $self->$field() ) {
2379 return "Access denied"
2380 unless $curuser->agentnum($self->$field());
2384 return "Access denied"
2385 unless grep $curuser->access_right($_), @$null_acl;
2393 =item virtual_fields [ TABLE ]
2395 Returns a list of virtual fields defined for the table. This should not
2396 be exported, and should only be called as an instance or class method.
2400 sub virtual_fields {
2403 $table = $self->table or confess "virtual_fields called on non-table";
2405 confess "Unknown table $table" unless dbdef->table($table);
2407 return () unless dbdef->table('part_virtual_field');
2409 unless ( $virtual_fields_cache{$table} ) {
2410 my $query = 'SELECT name from part_virtual_field ' .
2411 "WHERE dbtable = '$table'";
2413 my $result = $dbh->selectcol_arrayref($query);
2414 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2416 $virtual_fields_cache{$table} = $result;
2419 @{$virtual_fields_cache{$table}};
2424 =item fields [ TABLE ]
2426 This is a wrapper for real_fields and virtual_fields. Code that called
2427 fields before should probably continue to call fields.
2432 my $something = shift;
2434 if($something->isa('FS::Record')) {
2435 $table = $something->table;
2437 $table = $something;
2438 $something = "FS::$table";
2440 return (real_fields($table), $something->virtual_fields());
2443 =item pvf FIELD_NAME
2445 Returns the FS::part_virtual_field object corresponding to a field in the
2446 record (specified by FIELD_NAME).
2451 my ($self, $name) = (shift, shift);
2453 if(grep /^$name$/, $self->virtual_fields) {
2454 return qsearchs('part_virtual_field', { dbtable => $self->table,
2460 =item vfieldpart_hashref TABLE
2462 Returns a hashref of virtual field names and vfieldparts applicable to the given
2467 sub vfieldpart_hashref {
2469 my $table = $self->table;
2471 return {} unless dbdef->table('part_virtual_field');
2474 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2475 "dbtable = '$table'";
2476 my $sth = $dbh->prepare($statement);
2477 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2478 return { map { $_->{name}, $_->{vfieldpart} }
2479 @{$sth->fetchall_arrayref({})} };
2483 =item encrypt($value)
2485 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2487 Returns the encrypted string.
2489 You should generally not have to worry about calling this, as the system handles this for you.
2494 my ($self, $value) = @_;
2497 if ($conf->exists('encryption')) {
2498 if ($self->is_encrypted($value)) {
2499 # Return the original value if it isn't plaintext.
2500 $encrypted = $value;
2503 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2504 # RSA doesn't like the empty string so let's pack it up
2505 # The database doesn't like the RSA data so uuencode it
2506 my $length = length($value)+1;
2507 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2509 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2516 =item is_encrypted($value)
2518 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2524 my ($self, $value) = @_;
2525 # Possible Bug - Some work may be required here....
2527 if ($value =~ /^M/ && length($value) > 80) {
2534 =item decrypt($value)
2536 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2538 You should generally not have to worry about calling this, as the system handles this for you.
2543 my ($self,$value) = @_;
2544 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2545 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2547 if (ref($rsa_decrypt) =~ /::RSA/) {
2548 my $encrypted = unpack ("u*", $value);
2549 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2550 if ($@) {warn "Decryption Failed"};
2558 #Initialize the Module
2559 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2561 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2562 $rsa_module = $conf->config('encryptionmodule');
2566 eval ("require $rsa_module"); # No need to import the namespace
2569 # Initialize Encryption
2570 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2571 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2572 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2575 # Intitalize Decryption
2576 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2577 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2578 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2582 =item h_search ACTION
2584 Given an ACTION, either "insert", or "delete", returns the appropriate history
2585 record corresponding to this record, if any.
2590 my( $self, $action ) = @_;
2592 my $table = $self->table;
2595 my $primary_key = dbdef->table($table)->primary_key;
2598 'table' => "h_$table",
2599 'hashref' => { $primary_key => $self->$primary_key(),
2600 'history_action' => $action,
2608 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2609 appropriate history record corresponding to this record, if any.
2614 my($self, $action) = @_;
2615 my $h = $self->h_search($action);
2616 $h ? $h->history_date : '';
2625 =item real_fields [ TABLE ]
2627 Returns a list of the real columns in the specified table. Called only by
2628 fields() and other subroutines elsewhere in FS::Record.
2635 my($table_obj) = dbdef->table($table);
2636 confess "Unknown table $table" unless $table_obj;
2637 $table_obj->columns;
2640 =item _quote VALUE, TABLE, COLUMN
2642 This is an internal function used to construct SQL statements. It returns
2643 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2644 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2649 my($value, $table, $column) = @_;
2650 my $column_obj = dbdef->table($table)->column($column);
2651 my $column_type = $column_obj->type;
2652 my $nullable = $column_obj->null;
2654 warn " $table.$column: $value ($column_type".
2655 ( $nullable ? ' NULL' : ' NOT NULL' ).
2656 ")\n" if $DEBUG > 2;
2658 if ( $value eq '' && $nullable ) {
2660 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2661 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2664 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2665 ! $column_type =~ /(char|binary|text)$/i ) {
2674 This is deprecated. Don't use it.
2676 It returns a hash-type list with the fields of this record's table set true.
2681 carp "warning: hfields is deprecated";
2684 foreach (fields($table)) {
2693 "$_: ". $self->getfield($_). "|"
2694 } (fields($self->table)) );
2697 sub DESTROY { return; }
2701 # #use Carp qw(cluck);
2702 # #cluck "DESTROYING $self";
2703 # warn "DESTROYING $self";
2707 # return ! eval { join('',@_), kill 0; 1; };
2710 =item str2time_sql [ DRIVER_NAME ]
2712 Returns a function to convert to unix time based on database type, such as
2713 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2714 the str2time_sql_closing method to return a closing string rather than just
2715 using a closing parenthesis as previously suggested.
2717 You can pass an optional driver name such as "Pg", "mysql" or
2718 $dbh->{Driver}->{Name} to return a function for that database instead of
2719 the current database.
2724 my $driver = shift || driver_name;
2726 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2727 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2729 warn "warning: unknown database type $driver; guessing how to convert ".
2730 "dates to UNIX timestamps";
2731 return 'EXTRACT(EPOCH FROM ';
2735 =item str2time_sql_closing [ DRIVER_NAME ]
2737 Returns the closing suffix of a function to convert to unix time based on
2738 database type, such as ")::integer" for Pg or ")" for mysql.
2740 You can pass an optional driver name such as "Pg", "mysql" or
2741 $dbh->{Driver}->{Name} to return a function for that database instead of
2742 the current database.
2746 sub str2time_sql_closing {
2747 my $driver = shift || driver_name;
2749 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2757 This module should probably be renamed, since much of the functionality is
2758 of general use. It is not completely unlike Adapter::DBI (see below).
2760 Exported qsearch and qsearchs should be deprecated in favor of method calls
2761 (against an FS::Record object like the old search and searchs that qsearch
2762 and qsearchs were on top of.)
2764 The whole fields / hfields mess should be removed.
2766 The various WHERE clauses should be subroutined.
2768 table string should be deprecated in favor of DBIx::DBSchema::Table.
2770 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2771 true maps to the database (and WHERE clauses) would also help.
2773 The ut_ methods should ask the dbdef for a default length.
2775 ut_sqltype (like ut_varchar) should all be defined
2777 A fallback check method should be provided which uses the dbdef.
2779 The ut_money method assumes money has two decimal digits.
2781 The Pg money kludge in the new method only strips `$'.
2783 The ut_phonen method only checks US-style phone numbers.
2785 The _quote function should probably use ut_float instead of a regex.
2787 All the subroutines probably should be methods, here or elsewhere.
2789 Probably should borrow/use some dbdef methods where appropriate (like sub
2792 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2793 or allow it to be set. Working around it is ugly any way around - DBI should
2794 be fixed. (only affects RDBMS which return uppercase column names)
2796 ut_zip should take an optional country like ut_phone.
2800 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2802 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.