4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $conf $conf_encryption $me
7 $nowarn_identical $no_update_diff $no_check_foreign
10 use Carp qw(carp cluck croak confess);
11 use Scalar::Util qw( blessed );
12 use File::CounterFile;
15 use File::Slurp qw( slurp );
16 use DBI qw(:sql_types);
17 use DBIx::DBSchema 0.33;
18 use FS::UID qw(dbh getotaker datasrc driver_name);
20 use FS::Schema qw(dbdef);
22 use FS::Msgcat qw(gettext);
23 #use FS::Conf; #dependency loop bs, in install_callback below instead
25 use FS::part_virtual_field;
31 #export dbdef for now... everything else expects to find it here
32 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
33 str2time_sql str2time_sql_closing );
38 $nowarn_identical = 0;
40 $no_check_foreign = 0;
48 $conf_encryption = '';
49 FS::UID->install_callback( sub {
52 $conf = FS::Conf->new;
53 $conf_encryption = $conf->exists('encryption');
54 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
60 FS::Record - Database record objects
65 use FS::Record qw(dbh fields qsearch qsearchs);
67 $record = new FS::Record 'table', \%hash;
68 $record = new FS::Record 'table', { 'column' => 'value', ... };
70 $record = qsearchs FS::Record 'table', \%hash;
71 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
72 @records = qsearch FS::Record 'table', \%hash;
73 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
75 $table = $record->table;
76 $dbdef_table = $record->dbdef_table;
78 $value = $record->get('column');
79 $value = $record->getfield('column');
80 $value = $record->column;
82 $record->set( 'column' => 'value' );
83 $record->setfield( 'column' => 'value' );
84 $record->column('value');
86 %hash = $record->hash;
88 $hashref = $record->hashref;
90 $error = $record->insert;
92 $error = $record->delete;
94 $error = $new_record->replace($old_record);
96 # external use deprecated - handled by the database (at least for Pg, mysql)
97 $value = $record->unique('column');
99 $error = $record->ut_float('column');
100 $error = $record->ut_floatn('column');
101 $error = $record->ut_number('column');
102 $error = $record->ut_numbern('column');
103 $error = $record->ut_snumber('column');
104 $error = $record->ut_snumbern('column');
105 $error = $record->ut_money('column');
106 $error = $record->ut_text('column');
107 $error = $record->ut_textn('column');
108 $error = $record->ut_alpha('column');
109 $error = $record->ut_alphan('column');
110 $error = $record->ut_phonen('column');
111 $error = $record->ut_anything('column');
112 $error = $record->ut_name('column');
114 $quoted_value = _quote($value,'table','field');
117 $fields = hfields('table');
118 if ( $fields->{Field} ) { # etc.
120 @fields = fields 'table'; #as a subroutine
121 @fields = $record->fields; #as a method call
126 (Mostly) object-oriented interface to database records. Records are currently
127 implemented on top of DBI. FS::Record is intended as a base class for
128 table-specific classes to inherit from, i.e. FS::cust_main.
134 =item new [ TABLE, ] HASHREF
136 Creates a new record. It doesn't store it in the database, though. See
137 L<"insert"> for that.
139 Note that the object stores this hash reference, not a distinct copy of the
140 hash it points to. You can ask the object for a copy with the I<hash>
143 TABLE can only be omitted when a dervived class overrides the table method.
149 my $class = ref($proto) || $proto;
151 bless ($self, $class);
153 unless ( defined ( $self->table ) ) {
154 $self->{'Table'} = shift;
155 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
158 $self->{'Hash'} = shift;
160 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
161 $self->{'Hash'}{$field}='';
164 $self->_rebless if $self->can('_rebless');
166 $self->{'modified'} = 0;
168 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
175 my $class = ref($proto) || $proto;
177 bless ($self, $class);
179 $self->{'Table'} = shift unless defined ( $self->table );
181 my $hashref = $self->{'Hash'} = shift;
183 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
184 my $obj = $cache->cache->{$hashref->{$cache->key}};
185 $obj->_cache($hashref, $cache) if $obj->can('_cache');
188 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
195 my $class = ref($proto) || $proto;
197 bless ($self, $class);
198 if ( defined $self->table ) {
199 cluck "create constructor is deprecated, use new!";
202 croak "FS::Record::create called (not from a subclass)!";
206 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
208 Searches the database for all records matching (at least) the key/value pairs
209 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
210 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
213 The preferred usage is to pass a hash reference of named parameters:
215 my @records = qsearch( {
216 'table' => 'table_name',
217 'hashref' => { 'field' => 'value'
218 'field' => { 'op' => '<',
223 #these are optional...
225 'extra_sql' => 'AND field ',
226 'order_by' => 'ORDER BY something',
227 #'cache_obj' => '', #optional
228 'addl_from' => 'LEFT JOIN othtable USING ( field )',
233 Much code still uses old-style positional parameters, this is also probably
234 fine in the common case where there are only two parameters:
236 my @records = qsearch( 'table', { 'field' => 'value' } );
238 ###oops, argh, FS::Record::new only lets us create database fields.
239 #Normal behaviour if SELECT is not specified is `*', as in
240 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
241 #feature where you can specify SELECT - remember, the objects returned,
242 #although blessed into the appropriate `FS::TABLE' package, will only have the
243 #fields you specify. This might have unwanted results if you then go calling
244 #regular FS::TABLE methods
249 my %TYPE = (); #for debugging
252 my ($type, $value) = @_;
253 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
254 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
262 my($stable, $record, $select, $extra_sql, $order_by, $cache, $addl_from );
264 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
266 $stable = $opt->{'table'} or die "table name is required";
267 $record = $opt->{'hashref'} || {};
268 $select = $opt->{'select'} || '*';
269 $extra_sql = $opt->{'extra_sql'} || '';
270 $order_by = $opt->{'order_by'} || '';
271 $cache = $opt->{'cache_obj'} || '';
272 $addl_from = $opt->{'addl_from'} || '';
273 $debug = $opt->{'debug'} || '';
275 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
279 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
281 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
285 my $table = $cache ? $cache->table : $stable;
286 my $dbdef_table = dbdef->table($table)
287 or die "No schema for table $table found - ".
288 "do you need to run freeside-upgrade?";
289 my $pkey = $dbdef_table->primary_key;
291 my @real_fields = grep exists($record->{$_}), real_fields($table);
293 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
294 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
296 cluck "warning: FS::$table not loaded; virtual fields not searchable";
297 @virtual_fields = ();
300 my $statement = "SELECT $select FROM $stable";
301 $statement .= " $addl_from" if $addl_from;
302 if ( @real_fields or @virtual_fields ) {
303 $statement .= ' WHERE '. join(' AND ',
304 get_real_fields($table, $record, \@real_fields) ,
305 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
309 $statement .= " $extra_sql" if defined($extra_sql);
310 $statement .= " $order_by" if defined($order_by);
312 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
313 my $sth = $dbh->prepare($statement)
314 or croak "$dbh->errstr doing $statement";
319 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
322 my $value = $record->{$field};
323 $value = $value->{'value'} if ref($value);
324 my $type = dbdef->table($table)->column($field)->type;
326 my $TYPE = SQL_VARCHAR;
327 if ( $type =~ /(int|(big)?serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
330 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
331 #fixed by DBD::Pg 2.11.8
332 } elsif ( _is_fs_float( $type, $value ) ) {
338 %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
340 warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
343 if ($TYPE eq SQL_DECIMAL) {
344 # these values are arbitrary; better (faster?) ones welcome
345 $sth->bind_param($bind++, $value*1.00001, { TYPE => $TYPE } );
346 $sth->bind_param($bind++, $value*.99999, { TYPE => $TYPE } );
348 $sth->bind_param($bind++, $value, { TYPE => $TYPE } );
353 # $sth->execute( map $record->{$_},
354 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
355 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
357 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
359 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
360 @virtual_fields = "FS::$table"->virtual_fields;
362 cluck "warning: FS::$table not loaded; virtual fields not returned either";
363 @virtual_fields = ();
367 tie %result, "Tie::IxHash";
368 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
369 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
370 %result = map { $_->{$pkey}, $_ } @stuff;
372 @result{@stuff} = @stuff;
377 if ( keys(%result) and @virtual_fields ) {
379 "SELECT virtual_field.recnum, part_virtual_field.name, ".
380 "virtual_field.value ".
381 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
382 "WHERE part_virtual_field.dbtable = '$table' AND ".
383 "virtual_field.recnum IN (".
384 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
385 join(q!', '!, @virtual_fields) . "')";
386 warn "[debug]$me $statement\n" if $DEBUG > 1;
387 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
388 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
390 foreach (@{ $sth->fetchall_arrayref({}) }) {
391 my $recnum = $_->{recnum};
392 my $name = $_->{name};
393 my $value = $_->{value};
394 if (exists($result{$recnum})) {
395 $result{$recnum}->{$name} = $value;
400 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
401 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
402 #derivied class didn't override new method, so this optimization is safe
405 new_or_cached( "FS::$table", { %{$_} }, $cache )
409 new( "FS::$table", { %{$_} } )
413 #okay, its been tested
414 # warn "untested code (class FS::$table uses custom new method)";
416 eval 'FS::'. $table. '->new( { %{$_} } )';
420 # Check for encrypted fields and decrypt them.
421 ## only in the local copy, not the cached object
422 if ( $conf_encryption
423 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
424 foreach my $record (@return) {
425 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
426 # Set it directly... This may cause a problem in the future...
427 $record->setfield($field, $record->decrypt($record->getfield($field)));
432 cluck "warning: FS::$table not loaded; returning FS::Record objects";
434 FS::Record->new( $table, { %{$_} } );
440 ## makes this easier to read
442 sub get_virtual_fields {
446 my $virtual_fields = shift;
452 if ( ref($record->{$_}) ) {
453 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
454 if ( uc($op) eq 'ILIKE' ) {
456 $record->{$_}{'value'} = lc($record->{$_}{'value'});
457 $column = "LOWER($_)";
459 $record->{$_} = $record->{$_}{'value'};
462 # ... EXISTS ( SELECT name, value FROM part_virtual_field
464 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
465 # WHERE recnum = svc_acct.svcnum
466 # AND (name, value) = ('egad', 'brain') )
468 my $value = $record->{$_};
472 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
473 "( SELECT part_virtual_field.name, virtual_field.value ".
474 "FROM part_virtual_field JOIN virtual_field ".
475 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
476 "WHERE virtual_field.recnum = ${table}.${pkey} ".
477 "AND part_virtual_field.name = '${column}'".
479 " AND virtual_field.value ${op} '${value}'"
483 } @{ $virtual_fields } ) ;
486 sub get_real_fields {
489 my $real_fields = shift;
491 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
497 my $type = dbdef->table($table)->column($column)->type;
498 my $value = $record->{$column};
499 $value = $value->{'value'} if ref($value);
500 if ( ref($record->{$_}) ) {
501 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
502 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
503 if ( uc($op) eq 'ILIKE' ) {
505 $record->{$_}{'value'} = lc($record->{$_}{'value'});
506 $column = "LOWER($_)";
508 $record->{$_} = $record->{$_}{'value'}
511 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
513 if ( driver_name eq 'Pg' ) {
514 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
515 qq-( $column IS NULL )-;
517 qq-( $column IS NULL OR $column = '' )-;
520 qq-( $column IS NULL OR $column = "" )-;
522 } elsif ( $op eq '!=' ) {
523 if ( driver_name eq 'Pg' ) {
524 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
525 qq-( $column IS NOT NULL )-;
527 qq-( $column IS NOT NULL AND $column != '' )-;
530 qq-( $column IS NOT NULL AND $column != "" )-;
533 if ( driver_name eq 'Pg' ) {
534 qq-( $column $op '' )-;
536 qq-( $column $op "" )-;
539 } elsif ( $op eq '=' && _is_fs_float( $type, $value ) ) {
540 ( "$column <= ?", "$column >= ?" );
544 } @{ $real_fields } );
547 =item by_key PRIMARY_KEY_VALUE
549 This is a class method that returns the record with the given primary key
550 value. This method is only useful in FS::Record subclasses. For example:
552 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
556 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
561 my ($class, $pkey_value) = @_;
563 my $table = $class->table
564 or croak "No table for $class found";
566 my $dbdef_table = dbdef->table($table)
567 or die "No schema for table $table found - ".
568 "do you need to create it or run dbdef-create?";
569 my $pkey = $dbdef_table->primary_key
570 or die "No primary key for table $table";
572 return qsearchs($table, { $pkey => $pkey_value });
575 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
577 Experimental JOINed search method. Using this method, you can execute a
578 single SELECT spanning multiple tables, and cache the results for subsequent
579 method calls. Interface will almost definately change in an incompatible
587 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
588 my $cache = FS::SearchCache->new( $ptable, $pkey );
591 grep { !$saw{$_->getfield($pkey)}++ }
592 qsearch($table, $record, $select, $extra_sql, $cache )
596 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
598 Same as qsearch, except that if more than one record matches, it B<carp>s but
599 returns the first. If this happens, you either made a logic error in asking
600 for a single item, or your data is corrupted.
604 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
606 my(@result) = qsearch(@_);
607 cluck "warning: Multiple records in scalar search ($table)"
608 if scalar(@result) > 1;
609 #should warn more vehemently if the search was on a primary key?
610 scalar(@result) ? ($result[0]) : ();
621 Returns the table name.
626 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
633 Returns the DBIx::DBSchema::Table object for the table.
639 my($table)=$self->table;
640 dbdef->table($table);
645 Returns the primary key for the table.
651 my $pkey = $self->dbdef_table->primary_key;
654 =item get, getfield COLUMN
656 Returns the value of the column/field/key COLUMN.
661 my($self,$field) = @_;
662 # to avoid "Use of unitialized value" errors
663 if ( defined ( $self->{Hash}->{$field} ) ) {
664 $self->{Hash}->{$field};
674 =item set, setfield COLUMN, VALUE
676 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
681 my($self,$field,$value) = @_;
682 $self->{'modified'} = 1;
683 $self->{'Hash'}->{$field} = $value;
690 =item AUTLOADED METHODS
692 $record->column is a synonym for $record->get('column');
694 $record->column('value') is a synonym for $record->set('column','value');
701 my($field)=$AUTOLOAD;
703 if ( defined($value) ) {
704 confess "errant AUTOLOAD $field for $self (arg $value)"
705 unless blessed($self) && $self->can('setfield');
706 $self->setfield($field,$value);
708 confess "errant AUTOLOAD $field for $self (no args)"
709 unless blessed($self) && $self->can('getfield');
710 $self->getfield($field);
716 # my $field = $AUTOLOAD;
718 # if ( defined($_[1]) ) {
719 # $_[0]->setfield($field, $_[1]);
721 # $_[0]->getfield($field);
727 Returns a list of the column/value pairs, usually for assigning to a new hash.
729 To make a distinct duplicate of an FS::Record object, you can do:
731 $new = new FS::Record ( $old->table, { $old->hash } );
737 confess $self. ' -> hash: Hash attribute is undefined'
738 unless defined($self->{'Hash'});
739 %{ $self->{'Hash'} };
744 Returns a reference to the column/value hash. This may be deprecated in the
745 future; if there's a reason you can't just use the autoloaded or get/set
757 Returns true if any of this object's values have been modified with set (or via
758 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
768 =item select_for_update
770 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
775 sub select_for_update {
777 my $primary_key = $self->primary_key;
780 'table' => $self->table,
781 'hashref' => { $primary_key => $self->$primary_key() },
782 'extra_sql' => 'FOR UPDATE',
788 Locks this table with a database-driver specific lock method. This is used
789 as a mutex in order to do a duplicate search.
791 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
793 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
795 Errors are fatal; no useful return value.
797 Note: To use this method for new tables other than svc_acct and svc_phone,
798 edit freeside-upgrade and add those tables to the duplicate_lock list.
804 my $table = $self->table;
806 warn "$me locking $table table\n" if $DEBUG;
808 if ( driver_name =~ /^Pg/i ) {
810 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
813 } elsif ( driver_name =~ /^mysql/i ) {
815 dbh->do("SELECT * FROM duplicate_lock
816 WHERE lockname = '$table'
818 ) or die dbh->errstr;
822 die "unknown database ". driver_name. "; don't know how to lock table";
826 warn "$me acquired $table table lock\n" if $DEBUG;
832 Inserts this record to the database. If there is an error, returns the error,
833 otherwise returns false.
841 warn "$self -> insert" if $DEBUG;
843 my $error = $self->check;
844 return $error if $error;
846 #single-field unique keys are given a value if false
847 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
848 foreach ( $self->dbdef_table->unique_singles) {
849 $self->unique($_) unless $self->getfield($_);
852 #and also the primary key, if the database isn't going to
853 my $primary_key = $self->dbdef_table->primary_key;
855 if ( $primary_key ) {
856 my $col = $self->dbdef_table->column($primary_key);
859 uc($col->type) =~ /^(BIG)?SERIAL\d?/
860 || ( driver_name eq 'Pg'
861 && defined($col->default)
862 && $col->default =~ /^nextval\(/i
864 || ( driver_name eq 'mysql'
865 && defined($col->local)
866 && $col->local =~ /AUTO_INCREMENT/i
868 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
871 my $table = $self->table;
873 # Encrypt before the database
874 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
875 && scalar( eval '@FS::'. $table . '::encrypted_fields')
876 && $conf->exists('encryption')
878 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
879 $self->{'saved'} = $self->getfield($field);
880 $self->setfield($field, $self->encrypt($self->getfield($field)));
884 #false laziness w/delete
886 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
889 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
892 my $statement = "INSERT INTO $table ";
893 if ( @real_fields ) {
896 join( ', ', @real_fields ).
898 join( ', ', @values ).
902 $statement .= 'DEFAULT VALUES';
904 warn "[debug]$me $statement\n" if $DEBUG > 1;
905 my $sth = dbh->prepare($statement) or return dbh->errstr;
907 local $SIG{HUP} = 'IGNORE';
908 local $SIG{INT} = 'IGNORE';
909 local $SIG{QUIT} = 'IGNORE';
910 local $SIG{TERM} = 'IGNORE';
911 local $SIG{TSTP} = 'IGNORE';
912 local $SIG{PIPE} = 'IGNORE';
914 $sth->execute or return $sth->errstr;
916 # get inserted id from the database, if applicable & needed
917 if ( $db_seq && ! $self->getfield($primary_key) ) {
918 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
922 if ( driver_name eq 'Pg' ) {
924 #my $oid = $sth->{'pg_oid_status'};
925 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
927 my $default = $self->dbdef_table->column($primary_key)->default;
928 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
929 dbh->rollback if $FS::UID::AutoCommit;
930 return "can't parse $table.$primary_key default value".
931 " for sequence name: $default";
935 my $i_sql = "SELECT currval('$sequence')";
936 my $i_sth = dbh->prepare($i_sql) or do {
937 dbh->rollback if $FS::UID::AutoCommit;
940 $i_sth->execute() or do { #$i_sth->execute($oid)
941 dbh->rollback if $FS::UID::AutoCommit;
942 return $i_sth->errstr;
944 $insertid = $i_sth->fetchrow_arrayref->[0];
946 } elsif ( driver_name eq 'mysql' ) {
948 $insertid = dbh->{'mysql_insertid'};
949 # work around mysql_insertid being null some of the time, ala RT :/
950 unless ( $insertid ) {
951 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
952 "using SELECT LAST_INSERT_ID();";
953 my $i_sql = "SELECT LAST_INSERT_ID()";
954 my $i_sth = dbh->prepare($i_sql) or do {
955 dbh->rollback if $FS::UID::AutoCommit;
958 $i_sth->execute or do {
959 dbh->rollback if $FS::UID::AutoCommit;
960 return $i_sth->errstr;
962 $insertid = $i_sth->fetchrow_arrayref->[0];
967 dbh->rollback if $FS::UID::AutoCommit;
968 return "don't know how to retreive inserted ids from ". driver_name.
969 ", try using counterfiles (maybe run dbdef-create?)";
973 $self->setfield($primary_key, $insertid);
978 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
979 $self->virtual_fields;
980 if (@virtual_fields) {
981 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
983 my $vfieldpart = $self->vfieldpart_hashref;
985 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
988 my $v_sth = dbh->prepare($v_statement) or do {
989 dbh->rollback if $FS::UID::AutoCommit;
993 foreach (keys(%v_values)) {
994 $v_sth->execute($self->getfield($primary_key),
998 dbh->rollback if $FS::UID::AutoCommit;
999 return $v_sth->errstr;
1006 if ( defined dbdef->table('h_'. $table) ) {
1007 my $h_statement = $self->_h_statement('insert');
1008 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1009 $h_sth = dbh->prepare($h_statement) or do {
1010 dbh->rollback if $FS::UID::AutoCommit;
1016 $h_sth->execute or return $h_sth->errstr if $h_sth;
1018 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1020 # Now that it has been saved, reset the encrypted fields so that $new
1021 # can still be used.
1022 foreach my $field (keys %{$saved}) {
1023 $self->setfield($field, $saved->{$field});
1031 Depriciated (use insert instead).
1036 cluck "warning: FS::Record::add deprecated!";
1037 insert @_; #call method in this scope
1042 Delete this record from the database. If there is an error, returns the error,
1043 otherwise returns false.
1050 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1052 $self->getfield($_) eq ''
1053 #? "( $_ IS NULL OR $_ = \"\" )"
1054 ? ( driver_name eq 'Pg'
1056 : "( $_ IS NULL OR $_ = \"\" )"
1058 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1059 } ( $self->dbdef_table->primary_key )
1060 ? ( $self->dbdef_table->primary_key)
1061 : real_fields($self->table)
1063 warn "[debug]$me $statement\n" if $DEBUG > 1;
1064 my $sth = dbh->prepare($statement) or return dbh->errstr;
1067 if ( defined dbdef->table('h_'. $self->table) ) {
1068 my $h_statement = $self->_h_statement('delete');
1069 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1070 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1075 my $primary_key = $self->dbdef_table->primary_key;
1078 my $vfp = $self->vfieldpart_hashref;
1079 foreach($self->virtual_fields) {
1080 next if $self->getfield($_) eq '';
1081 unless(@del_vfields) {
1082 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1083 $v_sth = dbh->prepare($st) or return dbh->errstr;
1085 push @del_vfields, $_;
1088 local $SIG{HUP} = 'IGNORE';
1089 local $SIG{INT} = 'IGNORE';
1090 local $SIG{QUIT} = 'IGNORE';
1091 local $SIG{TERM} = 'IGNORE';
1092 local $SIG{TSTP} = 'IGNORE';
1093 local $SIG{PIPE} = 'IGNORE';
1095 my $rc = $sth->execute or return $sth->errstr;
1096 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1097 $h_sth->execute or return $h_sth->errstr if $h_sth;
1098 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1099 or return $v_sth->errstr
1100 foreach (@del_vfields);
1102 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1104 #no need to needlessly destoy the data either (causes problems actually)
1105 #undef $self; #no need to keep object!
1112 Depriciated (use delete instead).
1117 cluck "warning: FS::Record::del deprecated!";
1118 &delete(@_); #call method in this scope
1121 =item replace OLD_RECORD
1123 Replace the OLD_RECORD with this one in the database. If there is an error,
1124 returns the error, otherwise returns false.
1129 my ($new, $old) = (shift, shift);
1131 $old = $new->replace_old unless defined($old);
1133 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1135 if ( $new->can('replace_check') ) {
1136 my $error = $new->replace_check($old);
1137 return $error if $error;
1140 return "Records not in same table!" unless $new->table eq $old->table;
1142 my $primary_key = $old->dbdef_table->primary_key;
1143 return "Can't change primary key $primary_key ".
1144 'from '. $old->getfield($primary_key).
1145 ' to ' . $new->getfield($primary_key)
1147 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1149 my $error = $new->check;
1150 return $error if $error;
1152 # Encrypt for replace
1154 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1155 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1156 $saved->{$field} = $new->getfield($field);
1157 $new->setfield($field, $new->encrypt($new->getfield($field)));
1161 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1162 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1163 ? ($_, $new->getfield($_)) : () } $old->fields;
1165 unless (keys(%diff) || $no_update_diff ) {
1166 carp "[warning]$me $new -> replace $old: records identical"
1167 unless $nowarn_identical;
1171 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1173 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1174 } real_fields($old->table)
1179 if ( $old->getfield($_) eq '' ) {
1181 #false laziness w/qsearch
1182 if ( driver_name eq 'Pg' ) {
1183 my $type = $old->dbdef_table->column($_)->type;
1184 if ( $type =~ /(int|(big)?serial)/i ) {
1187 qq-( $_ IS NULL OR $_ = '' )-;
1190 qq-( $_ IS NULL OR $_ = "" )-;
1194 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1197 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1200 warn "[debug]$me $statement\n" if $DEBUG > 1;
1201 my $sth = dbh->prepare($statement) or return dbh->errstr;
1204 if ( defined dbdef->table('h_'. $old->table) ) {
1205 my $h_old_statement = $old->_h_statement('replace_old');
1206 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1207 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1213 if ( defined dbdef->table('h_'. $new->table) ) {
1214 my $h_new_statement = $new->_h_statement('replace_new');
1215 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1216 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1221 # For virtual fields we have three cases with different SQL
1222 # statements: add, replace, delete
1226 my (@add_vfields, @rep_vfields, @del_vfields);
1227 my $vfp = $old->vfieldpart_hashref;
1228 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1229 if($diff{$_} eq '') {
1231 unless(@del_vfields) {
1232 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1233 "AND vfieldpart = ?";
1234 warn "[debug]$me $st\n" if $DEBUG > 2;
1235 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1237 push @del_vfields, $_;
1238 } elsif($old->getfield($_) eq '') {
1240 unless(@add_vfields) {
1241 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1243 warn "[debug]$me $st\n" if $DEBUG > 2;
1244 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1246 push @add_vfields, $_;
1249 unless(@rep_vfields) {
1250 my $st = "UPDATE virtual_field SET value = ? ".
1251 "WHERE recnum = ? AND vfieldpart = ?";
1252 warn "[debug]$me $st\n" if $DEBUG > 2;
1253 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1255 push @rep_vfields, $_;
1259 local $SIG{HUP} = 'IGNORE';
1260 local $SIG{INT} = 'IGNORE';
1261 local $SIG{QUIT} = 'IGNORE';
1262 local $SIG{TERM} = 'IGNORE';
1263 local $SIG{TSTP} = 'IGNORE';
1264 local $SIG{PIPE} = 'IGNORE';
1266 my $rc = $sth->execute or return $sth->errstr;
1267 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1268 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1269 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1271 $v_del_sth->execute($old->getfield($primary_key),
1273 or return $v_del_sth->errstr
1274 foreach(@del_vfields);
1276 $v_add_sth->execute($new->getfield($_),
1277 $old->getfield($primary_key),
1279 or return $v_add_sth->errstr
1280 foreach(@add_vfields);
1282 $v_rep_sth->execute($new->getfield($_),
1283 $old->getfield($primary_key),
1285 or return $v_rep_sth->errstr
1286 foreach(@rep_vfields);
1288 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1290 # Now that it has been saved, reset the encrypted fields so that $new
1291 # can still be used.
1292 foreach my $field (keys %{$saved}) {
1293 $new->setfield($field, $saved->{$field});
1301 my( $self ) = shift;
1302 warn "[$me] replace called with no arguments; autoloading old record\n"
1305 my $primary_key = $self->dbdef_table->primary_key;
1306 if ( $primary_key ) {
1307 $self->by_key( $self->$primary_key() ) #this is what's returned
1308 or croak "can't find ". $self->table. ".$primary_key ".
1309 $self->$primary_key();
1311 croak $self->table. " has no primary key; pass old record as argument";
1318 Depriciated (use replace instead).
1323 cluck "warning: FS::Record::rep deprecated!";
1324 replace @_; #call method in this scope
1329 Checks virtual fields (using check_blocks). Subclasses should still provide
1330 a check method to validate real fields, foreign keys, etc., and call this
1331 method via $self->SUPER::check.
1333 (FIXME: Should this method try to make sure that it I<is> being called from
1334 a subclass's check method, to keep the current semantics as far as possible?)
1339 #confess "FS::Record::check not implemented; supply one in subclass!";
1342 foreach my $field ($self->virtual_fields) {
1343 for ($self->getfield($field)) {
1344 # See notes on check_block in FS::part_virtual_field.
1345 eval $self->pvf($field)->check_block;
1347 #this is bad, probably want to follow the stack backtrace up and see
1349 my $err = "Fatal error checking $field for $self";
1351 return "$err (see log for backtrace): $@";
1354 $self->setfield($field, $_);
1360 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1362 Processes a batch import as a queued JSRPC job
1364 JOB is an FS::queue entry.
1366 OPTIONS_HASHREF can have the following keys:
1372 Table name (required).
1376 Listref of field names for static fields. They will be given values from the
1377 PARAMS hashref and passed as a "params" hashref to batch_import.
1381 Formats hashref. Keys are field names, values are listrefs that define the
1384 Each listref value can be a column name or a code reference. Coderefs are run
1385 with the row object, data and a FS::Conf object as the three parameters.
1386 For example, this coderef does the same thing as using the "columnname" string:
1389 my( $record, $data, $conf ) = @_;
1390 $record->columnname( $data );
1393 Coderefs are run after all "column name" fields are assigned.
1397 Optional format hashref of types. Keys are field names, values are "csv",
1398 "xls" or "fixedlength". Overrides automatic determination of file type
1401 =item format_headers
1403 Optional format hashref of header lines. Keys are field names, values are 0
1404 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1407 =item format_sep_chars
1409 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1410 CSV separation character.
1412 =item format_fixedlenth_formats
1414 Optional format hashref of fixed length format defintiions. Keys are field
1415 names, values Parse::FixedLength listrefs of field definitions.
1419 Set true to default to CSV file type if the filename does not contain a
1420 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1425 PARAMS is a base64-encoded Storable string containing the POSTed data as
1426 a hash ref. It normally contains at least one field, "uploaded files",
1427 generated by /elements/file-upload.html and containing the list of uploaded
1428 files. Currently only supports a single file named "file".
1432 use Storable qw(thaw);
1435 sub process_batch_import {
1436 my($job, $opt) = ( shift, shift );
1438 my $table = $opt->{table};
1439 my @pass_params = @{ $opt->{params} };
1440 my %formats = %{ $opt->{formats} };
1442 my $param = thaw(decode_base64(shift));
1443 warn Dumper($param) if $DEBUG;
1445 my $files = $param->{'uploaded_files'}
1446 or die "No files provided.\n";
1448 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1450 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1451 my $file = $dir. $files{'file'};
1454 FS::Record::batch_import( {
1457 formats => \%formats,
1458 format_types => $opt->{format_types},
1459 format_headers => $opt->{format_headers},
1460 format_sep_chars => $opt->{format_sep_chars},
1461 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1466 format => $param->{format},
1467 params => { map { $_ => $param->{$_} } @pass_params },
1469 default_csv => $opt->{default_csv},
1474 die "$error\n" if $error;
1477 =item batch_import PARAM_HASHREF
1479 Class method for batch imports. Available params:
1489 =item format_headers
1491 =item format_sep_chars
1493 =item format_fixedlength_formats
1499 FS::queue object, will be updated with progress
1505 csv, xls or fixedlength
1518 warn "$me batch_import call with params: \n". Dumper($param)
1521 my $table = $param->{table};
1522 my $formats = $param->{formats};
1524 my $job = $param->{job};
1525 my $file = $param->{file};
1526 my $format = $param->{'format'};
1527 my $params = $param->{params} || {};
1529 die "unknown format $format" unless exists $formats->{ $format };
1531 my $type = $param->{'format_types'}
1532 ? $param->{'format_types'}{ $format }
1533 : $param->{type} || 'csv';
1536 if ( $file =~ /\.(\w+)$/i ) {
1540 warn "can't parse file type from filename $file; defaulting to CSV";
1544 if $param->{'default_csv'} && $type ne 'xls';
1547 my $header = $param->{'format_headers'}
1548 ? $param->{'format_headers'}{ $param->{'format'} }
1551 my $sep_char = $param->{'format_sep_chars'}
1552 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1555 my $fixedlength_format =
1556 $param->{'format_fixedlength_formats'}
1557 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1560 my @fields = @{ $formats->{ $format } };
1566 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1568 if ( $type eq 'csv' ) {
1571 $attr{sep_char} = $sep_char if $sep_char;
1572 $parser = new Text::CSV_XS \%attr;
1574 } elsif ( $type eq 'fixedlength' ) {
1576 eval "use Parse::FixedLength;";
1578 $parser = new Parse::FixedLength $fixedlength_format;
1581 die "Unknown file type $type\n";
1584 @buffer = split(/\r?\n/, slurp($file) );
1585 splice(@buffer, 0, ($header || 0) );
1586 $count = scalar(@buffer);
1588 } elsif ( $type eq 'xls' ) {
1590 eval "use Spreadsheet::ParseExcel;";
1593 eval "use DateTime::Format::Excel;";
1594 #for now, just let the error be thrown if it is used, since only CDR
1595 # formats bill_west and troop use it, not other excel-parsing things
1598 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1600 $parser = $excel->{Worksheet}[0]; #first sheet
1602 $count = $parser->{MaxRow} || $parser->{MinRow};
1605 $row = $header || 0;
1608 die "Unknown file type $type\n";
1613 local $SIG{HUP} = 'IGNORE';
1614 local $SIG{INT} = 'IGNORE';
1615 local $SIG{QUIT} = 'IGNORE';
1616 local $SIG{TERM} = 'IGNORE';
1617 local $SIG{TSTP} = 'IGNORE';
1618 local $SIG{PIPE} = 'IGNORE';
1620 my $oldAutoCommit = $FS::UID::AutoCommit;
1621 local $FS::UID::AutoCommit = 0;
1626 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1630 if ( $type eq 'csv' ) {
1632 last unless scalar(@buffer);
1633 $line = shift(@buffer);
1635 $parser->parse($line) or do {
1636 $dbh->rollback if $oldAutoCommit;
1637 return "can't parse: ". $parser->error_input();
1639 @columns = $parser->fields();
1641 } elsif ( $type eq 'fixedlength' ) {
1643 @columns = $parser->parse($line);
1645 } elsif ( $type eq 'xls' ) {
1647 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1648 || ! $parser->{Cells}[$row];
1650 my @row = @{ $parser->{Cells}[$row] };
1651 @columns = map $_->{Val}, @row;
1654 #warn $z++. ": $_\n" for @columns;
1657 die "Unknown file type $type\n";
1661 my %hash = %$params;
1663 foreach my $field ( @fields ) {
1665 my $value = shift @columns;
1667 if ( ref($field) eq 'CODE' ) {
1668 #&{$field}(\%hash, $value);
1669 push @later, $field, $value;
1671 #??? $hash{$field} = $value if length($value);
1672 $hash{$field} = $value if defined($value) && length($value);
1677 my $class = "FS::$table";
1679 my $record = $class->new( \%hash );
1681 while ( scalar(@later) ) {
1682 my $sub = shift @later;
1683 my $data = shift @later;
1684 &{$sub}($record, $data, $conf); # $record->&{$sub}($data, $conf);
1687 my $error = $record->insert;
1690 $dbh->rollback if $oldAutoCommit;
1691 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1697 if ( $job && time - $min_sec > $last ) { #progress bar
1698 $job->update_statustext( int(100 * $imported / $count) );
1704 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1706 return "Empty file!" unless $imported || $param->{empty_ok};
1713 my( $self, $action, $time ) = @_;
1718 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1719 real_fields($self->table);
1722 # If we're encrypting then don't ever store the payinfo or CVV2 in the history....
1723 # You can see if it changed by the paymask...
1724 if ($conf && $conf->exists('encryption') ) {
1725 @fields = grep $_ ne 'payinfo' && $_ ne 'cvv2', @fields;
1727 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1729 "INSERT INTO h_". $self->table. " ( ".
1730 join(', ', qw(history_date history_user history_action), @fields ).
1732 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1739 B<Warning>: External use is B<deprecated>.
1741 Replaces COLUMN in record with a unique number, using counters in the
1742 filesystem. Used by the B<insert> method on single-field unique columns
1743 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1744 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1746 Returns the new value.
1751 my($self,$field) = @_;
1752 my($table)=$self->table;
1754 croak "Unique called on field $field, but it is ",
1755 $self->getfield($field),
1757 if $self->getfield($field);
1759 #warn "table $table is tainted" if is_tainted($table);
1760 #warn "field $field is tainted" if is_tainted($field);
1762 my($counter) = new File::CounterFile "$table.$field",0;
1764 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1766 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1769 my $index = $counter->inc;
1770 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1772 $index =~ /^(\d*)$/;
1775 $self->setfield($field,$index);
1779 =item ut_float COLUMN
1781 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1782 null. If there is an error, returns the error, otherwise returns false.
1787 my($self,$field)=@_ ;
1788 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1789 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1790 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1791 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1792 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1793 $self->setfield($field,$1);
1796 =item ut_floatn COLUMN
1798 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1799 null. If there is an error, returns the error, otherwise returns false.
1803 #false laziness w/ut_ipn
1805 my( $self, $field ) = @_;
1806 if ( $self->getfield($field) =~ /^()$/ ) {
1807 $self->setfield($field,'');
1810 $self->ut_float($field);
1814 =item ut_sfloat COLUMN
1816 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1817 May not be null. If there is an error, returns the error, otherwise returns
1823 my($self,$field)=@_ ;
1824 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1825 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1826 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1827 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1828 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1829 $self->setfield($field,$1);
1832 =item ut_sfloatn COLUMN
1834 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1835 null. If there is an error, returns the error, otherwise returns false.
1840 my( $self, $field ) = @_;
1841 if ( $self->getfield($field) =~ /^()$/ ) {
1842 $self->setfield($field,'');
1845 $self->ut_sfloat($field);
1849 =item ut_snumber COLUMN
1851 Check/untaint signed numeric data (whole numbers). If there is an error,
1852 returns the error, otherwise returns false.
1857 my($self, $field) = @_;
1858 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1859 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1860 $self->setfield($field, "$1$2");
1864 =item ut_snumbern COLUMN
1866 Check/untaint signed numeric data (whole numbers). If there is an error,
1867 returns the error, otherwise returns false.
1872 my($self, $field) = @_;
1873 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1874 or return "Illegal (numeric) $field: ". $self->getfield($field);
1876 return "Illegal (numeric) $field: ". $self->getfield($field)
1879 $self->setfield($field, "$1$2");
1883 =item ut_number COLUMN
1885 Check/untaint simple numeric data (whole numbers). May not be null. If there
1886 is an error, returns the error, otherwise returns false.
1891 my($self,$field)=@_;
1892 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1893 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1894 $self->setfield($field,$1);
1898 =item ut_numbern COLUMN
1900 Check/untaint simple numeric data (whole numbers). May be null. If there is
1901 an error, returns the error, otherwise returns false.
1906 my($self,$field)=@_;
1907 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1908 or return "Illegal (numeric) $field: ". $self->getfield($field);
1909 $self->setfield($field,$1);
1913 =item ut_money COLUMN
1915 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1916 is an error, returns the error, otherwise returns false.
1921 my($self,$field)=@_;
1922 $self->setfield($field, 0) if $self->getfield($field) eq '';
1923 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1924 or return "Illegal (money) $field: ". $self->getfield($field);
1925 #$self->setfield($field, "$1$2$3" || 0);
1926 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1930 =item ut_text COLUMN
1932 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1933 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ]
1934 May not be null. If there is an error, returns the error, otherwise returns
1940 my($self,$field)=@_;
1941 #warn "msgcat ". \&msgcat. "\n";
1942 #warn "notexist ". \¬exist. "\n";
1943 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1944 $self->getfield($field)
1945 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]+)$/
1946 or return gettext('illegal_or_empty_text'). " $field: ".
1947 $self->getfield($field);
1948 $self->setfield($field,$1);
1952 =item ut_textn COLUMN
1954 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1955 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1956 May be null. If there is an error, returns the error, otherwise returns false.
1961 my($self,$field)=@_;
1962 $self->getfield($field)
1963 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
1964 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1965 $self->setfield($field,$1);
1969 =item ut_alpha COLUMN
1971 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1972 an error, returns the error, otherwise returns false.
1977 my($self,$field)=@_;
1978 $self->getfield($field) =~ /^(\w+)$/
1979 or return "Illegal or empty (alphanumeric) $field: ".
1980 $self->getfield($field);
1981 $self->setfield($field,$1);
1985 =item ut_alpha COLUMN
1987 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1988 error, returns the error, otherwise returns false.
1993 my($self,$field)=@_;
1994 $self->getfield($field) =~ /^(\w*)$/
1995 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1996 $self->setfield($field,$1);
2000 =item ut_alpha_lower COLUMN
2002 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2003 there is an error, returns the error, otherwise returns false.
2007 sub ut_alpha_lower {
2008 my($self,$field)=@_;
2009 $self->getfield($field) =~ /[[:upper:]]/
2010 and return "Uppercase characters are not permitted in $field";
2011 $self->ut_alpha($field);
2014 =item ut_phonen COLUMN [ COUNTRY ]
2016 Check/untaint phone numbers. May be null. If there is an error, returns
2017 the error, otherwise returns false.
2019 Takes an optional two-letter ISO country code; without it or with unsupported
2020 countries, ut_phonen simply calls ut_alphan.
2025 my( $self, $field, $country ) = @_;
2026 return $self->ut_alphan($field) unless defined $country;
2027 my $phonen = $self->getfield($field);
2028 if ( $phonen eq '' ) {
2029 $self->setfield($field,'');
2030 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2032 $phonen = $conf->config('cust_main-default_areacode').$phonen
2033 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2034 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2035 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2036 $phonen = "$1-$2-$3";
2037 $phonen .= " x$4" if $4;
2038 $self->setfield($field,$phonen);
2040 warn "warning: don't know how to check phone numbers for country $country";
2041 return $self->ut_textn($field);
2048 Check/untaint hexadecimal values.
2053 my($self, $field) = @_;
2054 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2055 or return "Illegal (hex) $field: ". $self->getfield($field);
2056 $self->setfield($field, uc($1));
2060 =item ut_hexn COLUMN
2062 Check/untaint hexadecimal values. May be null.
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));
2075 Check/untaint ip addresses. IPv4 only for now.
2080 my( $self, $field ) = @_;
2081 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2082 or return "Illegal (IP address) $field: ". $self->getfield($field);
2083 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2084 $self->setfield($field, "$1.$2.$3.$4");
2090 Check/untaint ip addresses. IPv4 only for now. May be null.
2095 my( $self, $field ) = @_;
2096 if ( $self->getfield($field) =~ /^()$/ ) {
2097 $self->setfield($field,'');
2100 $self->ut_ip($field);
2104 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2106 Check/untaint coordinates.
2107 Accepts the following forms:
2117 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2118 The latter form (that is, the MMM are thousands of minutes) is
2119 assumed if the "MMM" is exactly three digits or two digits > 59.
2121 To be safe, just use the DDD.DDDDD form.
2123 If LOWER or UPPER are specified, then the coordinate is checked
2124 for lower and upper bounds, respectively.
2130 my ($self, $field) = (shift, shift);
2132 my $lower = shift if scalar(@_);
2133 my $upper = shift if scalar(@_);
2134 my $coord = $self->getfield($field);
2135 my $neg = $coord =~ s/^(-)//;
2137 my ($d, $m, $s) = (0, 0, 0);
2140 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2141 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2142 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2144 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2147 return "Invalid (coordinate with minutes > 59) $field: "
2148 . $self->getfield($field);
2151 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2153 if (defined($lower) and ($coord < $lower)) {
2154 return "Invalid (coordinate < $lower) $field: "
2155 . $self->getfield($field);;
2158 if (defined($upper) and ($coord > $upper)) {
2159 return "Invalid (coordinate > $upper) $field: "
2160 . $self->getfield($field);;
2163 $self->setfield($field, $coord);
2167 return "Invalid (coordinate) $field: " . $self->getfield($field);
2171 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2173 Same as ut_coord, except optionally null.
2179 my ($self, $field) = (shift, shift);
2181 if ($self->getfield($field) =~ /^$/) {
2184 return $self->ut_coord($field, @_);
2190 =item ut_domain COLUMN
2192 Check/untaint host and domain names.
2197 my( $self, $field ) = @_;
2198 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2199 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2200 or return "Illegal (domain) $field: ". $self->getfield($field);
2201 $self->setfield($field,$1);
2205 =item ut_name COLUMN
2207 Check/untaint proper names; allows alphanumerics, spaces and the following
2208 punctuation: , . - '
2215 my( $self, $field ) = @_;
2216 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2217 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2218 $self->setfield($field,$1);
2224 Check/untaint zip codes.
2228 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2231 my( $self, $field, $country ) = @_;
2233 if ( $country eq 'US' ) {
2235 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2236 or return gettext('illegal_zip'). " $field for country $country: ".
2237 $self->getfield($field);
2238 $self->setfield($field, $1);
2240 } elsif ( $country eq 'CA' ) {
2242 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2243 or return gettext('illegal_zip'). " $field for country $country: ".
2244 $self->getfield($field);
2245 $self->setfield($field, "$1 $2");
2249 if ( $self->getfield($field) =~ /^\s*$/
2250 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2253 $self->setfield($field,'');
2255 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2256 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2257 $self->setfield($field,$1);
2265 =item ut_country COLUMN
2267 Check/untaint country codes. Country names are changed to codes, if possible -
2268 see L<Locale::Country>.
2273 my( $self, $field ) = @_;
2274 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2275 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2276 && country2code($1) ) {
2277 $self->setfield($field,uc(country2code($1)));
2280 $self->getfield($field) =~ /^(\w\w)$/
2281 or return "Illegal (country) $field: ". $self->getfield($field);
2282 $self->setfield($field,uc($1));
2286 =item ut_anything COLUMN
2288 Untaints arbitrary data. Be careful.
2293 my( $self, $field ) = @_;
2294 $self->getfield($field) =~ /^(.*)$/s
2295 or return "Illegal $field: ". $self->getfield($field);
2296 $self->setfield($field,$1);
2300 =item ut_enum COLUMN CHOICES_ARRAYREF
2302 Check/untaint a column, supplying all possible choices, like the "enum" type.
2307 my( $self, $field, $choices ) = @_;
2308 foreach my $choice ( @$choices ) {
2309 if ( $self->getfield($field) eq $choice ) {
2310 $self->setfield($choice);
2314 return "Illegal (enum) field $field: ". $self->getfield($field);
2317 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2319 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2320 on the column first.
2324 sub ut_foreign_key {
2325 my( $self, $field, $table, $foreign ) = @_;
2326 return '' if $no_check_foreign;
2327 qsearchs($table, { $foreign => $self->getfield($field) })
2328 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2329 " in $table.$foreign";
2333 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2335 Like ut_foreign_key, except the null value is also allowed.
2339 sub ut_foreign_keyn {
2340 my( $self, $field, $table, $foreign ) = @_;
2341 $self->getfield($field)
2342 ? $self->ut_foreign_key($field, $table, $foreign)
2346 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2348 Checks this column as an agentnum, taking into account the current users's
2349 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2350 right or rights allowing no agentnum.
2354 sub ut_agentnum_acl {
2355 my( $self, $field ) = (shift, shift);
2356 my $null_acl = scalar(@_) ? shift : [];
2357 $null_acl = [ $null_acl ] unless ref($null_acl);
2359 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2360 return "Illegal agentnum: $error" if $error;
2362 my $curuser = $FS::CurrentUser::CurrentUser;
2364 if ( $self->$field() ) {
2366 return "Access denied"
2367 unless $curuser->agentnum($self->$field());
2371 return "Access denied"
2372 unless grep $curuser->access_right($_), @$null_acl;
2380 =item virtual_fields [ TABLE ]
2382 Returns a list of virtual fields defined for the table. This should not
2383 be exported, and should only be called as an instance or class method.
2387 sub virtual_fields {
2390 $table = $self->table or confess "virtual_fields called on non-table";
2392 confess "Unknown table $table" unless dbdef->table($table);
2394 return () unless dbdef->table('part_virtual_field');
2396 unless ( $virtual_fields_cache{$table} ) {
2397 my $query = 'SELECT name from part_virtual_field ' .
2398 "WHERE dbtable = '$table'";
2400 my $result = $dbh->selectcol_arrayref($query);
2401 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2403 $virtual_fields_cache{$table} = $result;
2406 @{$virtual_fields_cache{$table}};
2411 =item fields [ TABLE ]
2413 This is a wrapper for real_fields and virtual_fields. Code that called
2414 fields before should probably continue to call fields.
2419 my $something = shift;
2421 if($something->isa('FS::Record')) {
2422 $table = $something->table;
2424 $table = $something;
2425 $something = "FS::$table";
2427 return (real_fields($table), $something->virtual_fields());
2430 =item pvf FIELD_NAME
2432 Returns the FS::part_virtual_field object corresponding to a field in the
2433 record (specified by FIELD_NAME).
2438 my ($self, $name) = (shift, shift);
2440 if(grep /^$name$/, $self->virtual_fields) {
2441 return qsearchs('part_virtual_field', { dbtable => $self->table,
2447 =item vfieldpart_hashref TABLE
2449 Returns a hashref of virtual field names and vfieldparts applicable to the given
2454 sub vfieldpart_hashref {
2456 my $table = $self->table;
2458 return {} unless dbdef->table('part_virtual_field');
2461 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2462 "dbtable = '$table'";
2463 my $sth = $dbh->prepare($statement);
2464 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2465 return { map { $_->{name}, $_->{vfieldpart} }
2466 @{$sth->fetchall_arrayref({})} };
2470 =item encrypt($value)
2472 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2474 Returns the encrypted string.
2476 You should generally not have to worry about calling this, as the system handles this for you.
2481 my ($self, $value) = @_;
2484 if ($conf->exists('encryption')) {
2485 if ($self->is_encrypted($value)) {
2486 # Return the original value if it isn't plaintext.
2487 $encrypted = $value;
2490 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2491 # RSA doesn't like the empty string so let's pack it up
2492 # The database doesn't like the RSA data so uuencode it
2493 my $length = length($value)+1;
2494 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2496 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2503 =item is_encrypted($value)
2505 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2511 my ($self, $value) = @_;
2512 # Possible Bug - Some work may be required here....
2514 if ($value =~ /^M/ && length($value) > 80) {
2521 =item decrypt($value)
2523 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2525 You should generally not have to worry about calling this, as the system handles this for you.
2530 my ($self,$value) = @_;
2531 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2532 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2534 if (ref($rsa_decrypt) =~ /::RSA/) {
2535 my $encrypted = unpack ("u*", $value);
2536 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2537 if ($@) {warn "Decryption Failed"};
2545 #Initialize the Module
2546 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2548 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2549 $rsa_module = $conf->config('encryptionmodule');
2553 eval ("require $rsa_module"); # No need to import the namespace
2556 # Initialize Encryption
2557 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2558 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2559 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2562 # Intitalize Decryption
2563 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2564 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2565 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2569 =item h_search ACTION
2571 Given an ACTION, either "insert", or "delete", returns the appropriate history
2572 record corresponding to this record, if any.
2577 my( $self, $action ) = @_;
2579 my $table = $self->table;
2582 my $primary_key = dbdef->table($table)->primary_key;
2585 'table' => "h_$table",
2586 'hashref' => { $primary_key => $self->$primary_key(),
2587 'history_action' => $action,
2595 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2596 appropriate history record corresponding to this record, if any.
2601 my($self, $action) = @_;
2602 my $h = $self->h_search($action);
2603 $h ? $h->history_date : '';
2612 =item real_fields [ TABLE ]
2614 Returns a list of the real columns in the specified table. Called only by
2615 fields() and other subroutines elsewhere in FS::Record.
2622 my($table_obj) = dbdef->table($table);
2623 confess "Unknown table $table" unless $table_obj;
2624 $table_obj->columns;
2627 =item _quote VALUE, TABLE, COLUMN
2629 This is an internal function used to construct SQL statements. It returns
2630 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2631 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2636 my($value, $table, $column) = @_;
2637 my $column_obj = dbdef->table($table)->column($column);
2638 my $column_type = $column_obj->type;
2639 my $nullable = $column_obj->null;
2641 warn " $table.$column: $value ($column_type".
2642 ( $nullable ? ' NULL' : ' NOT NULL' ).
2643 ")\n" if $DEBUG > 2;
2645 if ( $value eq '' && $nullable ) {
2647 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2648 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2651 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2652 ! $column_type =~ /(char|binary|text)$/i ) {
2661 This is deprecated. Don't use it.
2663 It returns a hash-type list with the fields of this record's table set true.
2668 carp "warning: hfields is deprecated";
2671 foreach (fields($table)) {
2680 "$_: ". $self->getfield($_). "|"
2681 } (fields($self->table)) );
2684 sub DESTROY { return; }
2688 # #use Carp qw(cluck);
2689 # #cluck "DESTROYING $self";
2690 # warn "DESTROYING $self";
2694 # return ! eval { join('',@_), kill 0; 1; };
2697 =item str2time_sql [ DRIVER_NAME ]
2699 Returns a function to convert to unix time based on database type, such as
2700 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2701 the str2time_sql_closing method to return a closing string rather than just
2702 using a closing parenthesis as previously suggested.
2704 You can pass an optional driver name such as "Pg", "mysql" or
2705 $dbh->{Driver}->{Name} to return a function for that database instead of
2706 the current database.
2711 my $driver = shift || driver_name;
2713 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2714 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2716 warn "warning: unknown database type $driver; guessing how to convert ".
2717 "dates to UNIX timestamps";
2718 return 'EXTRACT(EPOCH FROM ';
2722 =item str2time_sql_closing [ DRIVER_NAME ]
2724 Returns the closing suffix of a function to convert to unix time based on
2725 database type, such as ")::integer" for Pg or ")" for mysql.
2727 You can pass an optional driver name such as "Pg", "mysql" or
2728 $dbh->{Driver}->{Name} to return a function for that database instead of
2729 the current database.
2733 sub str2time_sql_closing {
2734 my $driver = shift || driver_name;
2736 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2744 This module should probably be renamed, since much of the functionality is
2745 of general use. It is not completely unlike Adapter::DBI (see below).
2747 Exported qsearch and qsearchs should be deprecated in favor of method calls
2748 (against an FS::Record object like the old search and searchs that qsearch
2749 and qsearchs were on top of.)
2751 The whole fields / hfields mess should be removed.
2753 The various WHERE clauses should be subroutined.
2755 table string should be deprecated in favor of DBIx::DBSchema::Table.
2757 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2758 true maps to the database (and WHERE clauses) would also help.
2760 The ut_ methods should ask the dbdef for a default length.
2762 ut_sqltype (like ut_varchar) should all be defined
2764 A fallback check method should be provided which uses the dbdef.
2766 The ut_money method assumes money has two decimal digits.
2768 The Pg money kludge in the new method only strips `$'.
2770 The ut_phonen method only checks US-style phone numbers.
2772 The _quote function should probably use ut_float instead of a regex.
2774 All the subroutines probably should be methods, here or elsewhere.
2776 Probably should borrow/use some dbdef methods where appropriate (like sub
2779 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2780 or allow it to be set. Working around it is ugly any way around - DBI should
2781 be fixed. (only affects RDBMS which return uppercase column names)
2783 ut_zip should take an optional country like ut_phone.
2787 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2789 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.