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.38;
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 regexp_sql not_regexp_sql );
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;
57 if ( driver_name eq 'Pg' ) {
58 eval "use DBD::Pg ':pg_types'";
61 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
67 FS::Record - Database record objects
72 use FS::Record qw(dbh fields qsearch qsearchs);
74 $record = new FS::Record 'table', \%hash;
75 $record = new FS::Record 'table', { 'column' => 'value', ... };
77 $record = qsearchs FS::Record 'table', \%hash;
78 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
79 @records = qsearch FS::Record 'table', \%hash;
80 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
82 $table = $record->table;
83 $dbdef_table = $record->dbdef_table;
85 $value = $record->get('column');
86 $value = $record->getfield('column');
87 $value = $record->column;
89 $record->set( 'column' => 'value' );
90 $record->setfield( 'column' => 'value' );
91 $record->column('value');
93 %hash = $record->hash;
95 $hashref = $record->hashref;
97 $error = $record->insert;
99 $error = $record->delete;
101 $error = $new_record->replace($old_record);
103 # external use deprecated - handled by the database (at least for Pg, mysql)
104 $value = $record->unique('column');
106 $error = $record->ut_float('column');
107 $error = $record->ut_floatn('column');
108 $error = $record->ut_number('column');
109 $error = $record->ut_numbern('column');
110 $error = $record->ut_snumber('column');
111 $error = $record->ut_snumbern('column');
112 $error = $record->ut_money('column');
113 $error = $record->ut_text('column');
114 $error = $record->ut_textn('column');
115 $error = $record->ut_alpha('column');
116 $error = $record->ut_alphan('column');
117 $error = $record->ut_phonen('column');
118 $error = $record->ut_anything('column');
119 $error = $record->ut_name('column');
121 $quoted_value = _quote($value,'table','field');
124 $fields = hfields('table');
125 if ( $fields->{Field} ) { # etc.
127 @fields = fields 'table'; #as a subroutine
128 @fields = $record->fields; #as a method call
133 (Mostly) object-oriented interface to database records. Records are currently
134 implemented on top of DBI. FS::Record is intended as a base class for
135 table-specific classes to inherit from, i.e. FS::cust_main.
141 =item new [ TABLE, ] HASHREF
143 Creates a new record. It doesn't store it in the database, though. See
144 L<"insert"> for that.
146 Note that the object stores this hash reference, not a distinct copy of the
147 hash it points to. You can ask the object for a copy with the I<hash>
150 TABLE can only be omitted when a dervived class overrides the table method.
156 my $class = ref($proto) || $proto;
158 bless ($self, $class);
160 unless ( defined ( $self->table ) ) {
161 $self->{'Table'} = shift;
162 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
163 unless $nowarn_classload;
166 $self->{'Hash'} = shift;
168 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
169 $self->{'Hash'}{$field}='';
172 $self->_rebless if $self->can('_rebless');
174 $self->{'modified'} = 0;
176 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
183 my $class = ref($proto) || $proto;
185 bless ($self, $class);
187 $self->{'Table'} = shift unless defined ( $self->table );
189 my $hashref = $self->{'Hash'} = shift;
191 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
192 my $obj = $cache->cache->{$hashref->{$cache->key}};
193 $obj->_cache($hashref, $cache) if $obj->can('_cache');
196 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
203 my $class = ref($proto) || $proto;
205 bless ($self, $class);
206 if ( defined $self->table ) {
207 cluck "create constructor is deprecated, use new!";
210 croak "FS::Record::create called (not from a subclass)!";
214 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
216 Searches the database for all records matching (at least) the key/value pairs
217 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
218 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
221 The preferred usage is to pass a hash reference of named parameters:
223 @records = qsearch( {
224 'table' => 'table_name',
225 'hashref' => { 'field' => 'value'
226 'field' => { 'op' => '<',
231 #these are optional...
233 'extra_sql' => 'AND field = ? AND intfield = ?',
234 'extra_param' => [ 'value', [ 5, 'int' ] ],
235 'order_by' => 'ORDER BY something',
236 #'cache_obj' => '', #optional
237 'addl_from' => 'LEFT JOIN othtable USING ( field )',
242 Much code still uses old-style positional parameters, this is also probably
243 fine in the common case where there are only two parameters:
245 my @records = qsearch( 'table', { 'field' => 'value' } );
247 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
248 the individual PARAMS_HASHREF queries
250 ###oops, argh, FS::Record::new only lets us create database fields.
251 #Normal behaviour if SELECT is not specified is `*', as in
252 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
253 #feature where you can specify SELECT - remember, the objects returned,
254 #although blessed into the appropriate `FS::TABLE' package, will only have the
255 #fields you specify. This might have unwanted results if you then go calling
256 #regular FS::TABLE methods
261 my %TYPE = (); #for debugging
264 my($type, $value) = @_;
266 my $bind_type = { TYPE => SQL_VARCHAR };
268 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
270 $bind_type = { TYPE => SQL_INTEGER };
272 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
274 if ( driver_name eq 'Pg' ) {
276 $bind_type = { pg_type => PG_BYTEA };
278 # $bind_type = ? #SQL_VARCHAR could be fine?
281 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
282 #fixed by DBD::Pg 2.11.8
283 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
284 #(make a Tron test first)
285 } elsif ( _is_fs_float( $type, $value ) ) {
287 $bind_type = { TYPE => SQL_DECIMAL };
296 my($type, $value) = @_;
297 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
298 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
306 my( @stable, @record, @cache );
307 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
309 my %union_options = ();
310 if ( ref($_[0]) eq 'ARRAY' ) {
313 foreach my $href ( @$optlist ) {
314 push @stable, ( $href->{'table'} or die "table name is required" );
315 push @record, ( $href->{'hashref'} || {} );
316 push @select, ( $href->{'select'} || '*' );
317 push @extra_sql, ( $href->{'extra_sql'} || '' );
318 push @extra_param, ( $href->{'extra_param'} || [] );
319 push @order_by, ( $href->{'order_by'} || '' );
320 push @cache, ( $href->{'cache_obj'} || '' );
321 push @addl_from, ( $href->{'addl_from'} || '' );
322 push @debug, ( $href->{'debug'} || '' );
324 die "at least one hashref is required" unless scalar(@stable);
325 } elsif ( ref($_[0]) eq 'HASH' ) {
327 $stable[0] = $opt->{'table'} or die "table name is required";
328 $record[0] = $opt->{'hashref'} || {};
329 $select[0] = $opt->{'select'} || '*';
330 $extra_sql[0] = $opt->{'extra_sql'} || '';
331 $extra_param[0] = $opt->{'extra_param'} || [];
332 $order_by[0] = $opt->{'order_by'} || '';
333 $cache[0] = $opt->{'cache_obj'} || '';
334 $addl_from[0] = $opt->{'addl_from'} || '';
335 $debug[0] = $opt->{'debug'} || '';
346 my $cache = $cache[0];
352 foreach my $stable ( @stable ) {
353 my $record = shift @record;
354 my $select = shift @select;
355 my $extra_sql = shift @extra_sql;
356 my $extra_param = shift @extra_param;
357 my $order_by = shift @order_by;
358 my $cache = shift @cache;
359 my $addl_from = shift @addl_from;
360 my $debug = shift @debug;
362 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
364 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
367 my $table = $cache ? $cache->table : $stable;
368 my $dbdef_table = dbdef->table($table)
369 or die "No schema for table $table found - ".
370 "do you need to run freeside-upgrade?";
371 my $pkey = $dbdef_table->primary_key;
373 my @real_fields = grep exists($record->{$_}), real_fields($table);
375 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
376 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
378 cluck "warning: FS::$table not loaded; virtual fields not searchable"
379 unless $nowarn_classload;
380 @virtual_fields = ();
383 my $statement .= "SELECT $select FROM $stable";
384 $statement .= " $addl_from" if $addl_from;
385 if ( @real_fields or @virtual_fields ) {
386 $statement .= ' WHERE '. join(' AND ',
387 get_real_fields($table, $record, \@real_fields) ,
388 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
392 $statement .= " $extra_sql" if defined($extra_sql);
393 $statement .= " $order_by" if defined($order_by);
395 push @statement, $statement;
397 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
401 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
404 my $value = $record->{$field};
405 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
406 $value = $value->{'value'} if ref($value);
407 my $type = dbdef->table($table)->column($field)->type;
409 my $bind_type = _bind_type($type, $value);
413 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
415 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
419 push @bind_type, $bind_type;
423 foreach my $param ( @$extra_param ) {
424 my $bind_type = { TYPE => SQL_VARCHAR };
427 $value = $param->[0];
428 my $type = $param->[1];
429 $bind_type = _bind_type($type, $value);
432 push @bind_type, $bind_type;
436 my $statement = join( ' ) UNION ( ', @statement );
437 $statement = "( $statement )" if scalar(@statement) > 1;
438 $statement .= " $union_options{order_by}" if $union_options{order_by};
440 my $sth = $dbh->prepare($statement)
441 or croak "$dbh->errstr doing $statement";
444 foreach my $value ( @value ) {
445 my $bind_type = shift @bind_type;
446 $sth->bind_param($bind++, $value, $bind_type );
449 # $sth->execute( map $record->{$_},
450 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
451 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
453 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
455 # virtual fields and blessings are nonsense in a heterogeneous UNION, right?
456 my $table = $stable[0];
458 $table = '' if grep { $_ ne $table } @stable;
459 $pkey = dbdef->table($table)->primary_key if $table;
461 my @virtual_fields = ();
462 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
463 @virtual_fields = "FS::$table"->virtual_fields;
465 cluck "warning: FS::$table not loaded; virtual fields not returned either"
466 unless $nowarn_classload;
467 @virtual_fields = ();
471 tie %result, "Tie::IxHash";
472 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
473 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
474 %result = map { $_->{$pkey}, $_ } @stuff;
476 @result{@stuff} = @stuff;
481 if ( keys(%result) and @virtual_fields ) {
483 "SELECT virtual_field.recnum, part_virtual_field.name, ".
484 "virtual_field.value ".
485 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
486 "WHERE part_virtual_field.dbtable = '$table' AND ".
487 "virtual_field.recnum IN (".
488 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
489 join(q!', '!, @virtual_fields) . "')";
490 warn "[debug]$me $statement\n" if $DEBUG > 1;
491 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
492 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
494 foreach (@{ $sth->fetchall_arrayref({}) }) {
495 my $recnum = $_->{recnum};
496 my $name = $_->{name};
497 my $value = $_->{value};
498 if (exists($result{$recnum})) {
499 $result{$recnum}->{$name} = $value;
504 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
505 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
506 #derivied class didn't override new method, so this optimization is safe
509 new_or_cached( "FS::$table", { %{$_} }, $cache )
513 new( "FS::$table", { %{$_} } )
517 #okay, its been tested
518 # warn "untested code (class FS::$table uses custom new method)";
520 eval 'FS::'. $table. '->new( { %{$_} } )';
524 # Check for encrypted fields and decrypt them.
525 ## only in the local copy, not the cached object
526 if ( $conf_encryption
527 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
528 foreach my $record (@return) {
529 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
530 # Set it directly... This may cause a problem in the future...
531 $record->setfield($field, $record->decrypt($record->getfield($field)));
536 cluck "warning: FS::$table not loaded; returning FS::Record objects"
537 unless $nowarn_classload;
539 FS::Record->new( $table, { %{$_} } );
545 ## makes this easier to read
547 sub get_virtual_fields {
551 my $virtual_fields = shift;
557 if ( ref($record->{$_}) ) {
558 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
559 if ( uc($op) eq 'ILIKE' ) {
561 $record->{$_}{'value'} = lc($record->{$_}{'value'});
562 $column = "LOWER($_)";
564 $record->{$_} = $record->{$_}{'value'};
567 # ... EXISTS ( SELECT name, value FROM part_virtual_field
569 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
570 # WHERE recnum = svc_acct.svcnum
571 # AND (name, value) = ('egad', 'brain') )
573 my $value = $record->{$_};
577 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
578 "( SELECT part_virtual_field.name, virtual_field.value ".
579 "FROM part_virtual_field JOIN virtual_field ".
580 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
581 "WHERE virtual_field.recnum = ${table}.${pkey} ".
582 "AND part_virtual_field.name = '${column}'".
584 " AND virtual_field.value ${op} '${value}'"
588 } @{ $virtual_fields } ) ;
591 sub get_real_fields {
594 my $real_fields = shift;
596 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
602 my $type = dbdef->table($table)->column($column)->type;
603 my $value = $record->{$column};
604 $value = $value->{'value'} if ref($value);
605 if ( ref($record->{$_}) ) {
606 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
607 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
608 if ( uc($op) eq 'ILIKE' ) {
610 $record->{$_}{'value'} = lc($record->{$_}{'value'});
611 $column = "LOWER($_)";
613 $record->{$_} = $record->{$_}{'value'}
616 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
618 if ( driver_name eq 'Pg' ) {
619 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
620 qq-( $column IS NULL )-;
622 qq-( $column IS NULL OR $column = '' )-;
625 qq-( $column IS NULL OR $column = "" )-;
627 } elsif ( $op eq '!=' ) {
628 if ( driver_name eq 'Pg' ) {
629 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
630 qq-( $column IS NOT NULL )-;
632 qq-( $column IS NOT NULL AND $column != '' )-;
635 qq-( $column IS NOT NULL AND $column != "" )-;
638 if ( driver_name eq 'Pg' ) {
639 qq-( $column $op '' )-;
641 qq-( $column $op "" )-;
644 #if this needs to be re-enabled, it needs to use a custom op like
645 #"APPROX=" or something (better name?, not '=', to avoid affecting other
647 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
648 # ( "$column <= ?", "$column >= ?" );
652 } @{ $real_fields } );
655 =item by_key PRIMARY_KEY_VALUE
657 This is a class method that returns the record with the given primary key
658 value. This method is only useful in FS::Record subclasses. For example:
660 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
664 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
669 my ($class, $pkey_value) = @_;
671 my $table = $class->table
672 or croak "No table for $class found";
674 my $dbdef_table = dbdef->table($table)
675 or die "No schema for table $table found - ".
676 "do you need to create it or run dbdef-create?";
677 my $pkey = $dbdef_table->primary_key
678 or die "No primary key for table $table";
680 return qsearchs($table, { $pkey => $pkey_value });
683 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
685 Experimental JOINed search method. Using this method, you can execute a
686 single SELECT spanning multiple tables, and cache the results for subsequent
687 method calls. Interface will almost definately change in an incompatible
695 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
696 my $cache = FS::SearchCache->new( $ptable, $pkey );
699 grep { !$saw{$_->getfield($pkey)}++ }
700 qsearch($table, $record, $select, $extra_sql, $cache )
704 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
706 Same as qsearch, except that if more than one record matches, it B<carp>s but
707 returns the first. If this happens, you either made a logic error in asking
708 for a single item, or your data is corrupted.
712 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
714 my(@result) = qsearch(@_);
715 cluck "warning: Multiple records in scalar search ($table)"
716 if scalar(@result) > 1;
717 #should warn more vehemently if the search was on a primary key?
718 scalar(@result) ? ($result[0]) : ();
729 Returns the table name.
734 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
741 Returns the DBIx::DBSchema::Table object for the table.
747 my($table)=$self->table;
748 dbdef->table($table);
753 Returns the primary key for the table.
759 my $pkey = $self->dbdef_table->primary_key;
762 =item get, getfield COLUMN
764 Returns the value of the column/field/key COLUMN.
769 my($self,$field) = @_;
770 # to avoid "Use of unitialized value" errors
771 if ( defined ( $self->{Hash}->{$field} ) ) {
772 $self->{Hash}->{$field};
782 =item set, setfield COLUMN, VALUE
784 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
789 my($self,$field,$value) = @_;
790 $self->{'modified'} = 1;
791 $self->{'Hash'}->{$field} = $value;
800 Returns true if the column/field/key COLUMN exists.
805 my($self,$field) = @_;
806 exists($self->{Hash}->{$field});
809 =item AUTLOADED METHODS
811 $record->column is a synonym for $record->get('column');
813 $record->column('value') is a synonym for $record->set('column','value');
820 my($field)=$AUTOLOAD;
822 if ( defined($value) ) {
823 confess "errant AUTOLOAD $field for $self (arg $value)"
824 unless blessed($self) && $self->can('setfield');
825 $self->setfield($field,$value);
827 confess "errant AUTOLOAD $field for $self (no args)"
828 unless blessed($self) && $self->can('getfield');
829 $self->getfield($field);
835 # my $field = $AUTOLOAD;
837 # if ( defined($_[1]) ) {
838 # $_[0]->setfield($field, $_[1]);
840 # $_[0]->getfield($field);
846 Returns a list of the column/value pairs, usually for assigning to a new hash.
848 To make a distinct duplicate of an FS::Record object, you can do:
850 $new = new FS::Record ( $old->table, { $old->hash } );
856 confess $self. ' -> hash: Hash attribute is undefined'
857 unless defined($self->{'Hash'});
858 %{ $self->{'Hash'} };
863 Returns a reference to the column/value hash. This may be deprecated in the
864 future; if there's a reason you can't just use the autoloaded or get/set
876 Returns true if any of this object's values have been modified with set (or via
877 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
887 =item select_for_update
889 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
894 sub select_for_update {
896 my $primary_key = $self->primary_key;
899 'table' => $self->table,
900 'hashref' => { $primary_key => $self->$primary_key() },
901 'extra_sql' => 'FOR UPDATE',
907 Locks this table with a database-driver specific lock method. This is used
908 as a mutex in order to do a duplicate search.
910 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
912 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
914 Errors are fatal; no useful return value.
916 Note: To use this method for new tables other than svc_acct and svc_phone,
917 edit freeside-upgrade and add those tables to the duplicate_lock list.
923 my $table = $self->table;
925 warn "$me locking $table table\n" if $DEBUG;
927 if ( driver_name =~ /^Pg/i ) {
929 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
932 } elsif ( driver_name =~ /^mysql/i ) {
934 dbh->do("SELECT * FROM duplicate_lock
935 WHERE lockname = '$table'
937 ) or die dbh->errstr;
941 die "unknown database ". driver_name. "; don't know how to lock table";
945 warn "$me acquired $table table lock\n" if $DEBUG;
951 Inserts this record to the database. If there is an error, returns the error,
952 otherwise returns false.
960 warn "$self -> insert" if $DEBUG;
962 my $error = $self->check;
963 return $error if $error;
965 #single-field unique keys are given a value if false
966 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
967 foreach ( $self->dbdef_table->unique_singles) {
968 $self->unique($_) unless $self->getfield($_);
971 #and also the primary key, if the database isn't going to
972 my $primary_key = $self->dbdef_table->primary_key;
974 if ( $primary_key ) {
975 my $col = $self->dbdef_table->column($primary_key);
978 uc($col->type) =~ /^(BIG)?SERIAL\d?/
979 || ( driver_name eq 'Pg'
980 && defined($col->default)
981 && $col->quoted_default =~ /^nextval\(/i
983 || ( driver_name eq 'mysql'
984 && defined($col->local)
985 && $col->local =~ /AUTO_INCREMENT/i
987 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
990 my $table = $self->table;
992 # Encrypt before the database
993 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
994 && scalar( eval '@FS::'. $table . '::encrypted_fields')
995 && $conf->exists('encryption')
997 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
998 $self->{'saved'} = $self->getfield($field);
999 $self->setfield($field, $self->encrypt($self->getfield($field)));
1003 #false laziness w/delete
1005 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1008 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1011 my $statement = "INSERT INTO $table ";
1012 if ( @real_fields ) {
1015 join( ', ', @real_fields ).
1017 join( ', ', @values ).
1021 $statement .= 'DEFAULT VALUES';
1023 warn "[debug]$me $statement\n" if $DEBUG > 1;
1024 my $sth = dbh->prepare($statement) or return dbh->errstr;
1026 local $SIG{HUP} = 'IGNORE';
1027 local $SIG{INT} = 'IGNORE';
1028 local $SIG{QUIT} = 'IGNORE';
1029 local $SIG{TERM} = 'IGNORE';
1030 local $SIG{TSTP} = 'IGNORE';
1031 local $SIG{PIPE} = 'IGNORE';
1033 $sth->execute or return $sth->errstr;
1035 # get inserted id from the database, if applicable & needed
1036 if ( $db_seq && ! $self->getfield($primary_key) ) {
1037 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1041 if ( driver_name eq 'Pg' ) {
1043 #my $oid = $sth->{'pg_oid_status'};
1044 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1046 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1047 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1048 dbh->rollback if $FS::UID::AutoCommit;
1049 return "can't parse $table.$primary_key default value".
1050 " for sequence name: $default";
1054 my $i_sql = "SELECT currval('$sequence')";
1055 my $i_sth = dbh->prepare($i_sql) or do {
1056 dbh->rollback if $FS::UID::AutoCommit;
1059 $i_sth->execute() or do { #$i_sth->execute($oid)
1060 dbh->rollback if $FS::UID::AutoCommit;
1061 return $i_sth->errstr;
1063 $insertid = $i_sth->fetchrow_arrayref->[0];
1065 } elsif ( driver_name eq 'mysql' ) {
1067 $insertid = dbh->{'mysql_insertid'};
1068 # work around mysql_insertid being null some of the time, ala RT :/
1069 unless ( $insertid ) {
1070 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1071 "using SELECT LAST_INSERT_ID();";
1072 my $i_sql = "SELECT LAST_INSERT_ID()";
1073 my $i_sth = dbh->prepare($i_sql) or do {
1074 dbh->rollback if $FS::UID::AutoCommit;
1077 $i_sth->execute or do {
1078 dbh->rollback if $FS::UID::AutoCommit;
1079 return $i_sth->errstr;
1081 $insertid = $i_sth->fetchrow_arrayref->[0];
1086 dbh->rollback if $FS::UID::AutoCommit;
1087 return "don't know how to retreive inserted ids from ". driver_name.
1088 ", try using counterfiles (maybe run dbdef-create?)";
1092 $self->setfield($primary_key, $insertid);
1096 my @virtual_fields =
1097 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1098 $self->virtual_fields;
1099 if (@virtual_fields) {
1100 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
1102 my $vfieldpart = $self->vfieldpart_hashref;
1104 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1107 my $v_sth = dbh->prepare($v_statement) or do {
1108 dbh->rollback if $FS::UID::AutoCommit;
1112 foreach (keys(%v_values)) {
1113 $v_sth->execute($self->getfield($primary_key),
1117 dbh->rollback if $FS::UID::AutoCommit;
1118 return $v_sth->errstr;
1125 if ( defined dbdef->table('h_'. $table) ) {
1126 my $h_statement = $self->_h_statement('insert');
1127 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1128 $h_sth = dbh->prepare($h_statement) or do {
1129 dbh->rollback if $FS::UID::AutoCommit;
1135 $h_sth->execute or return $h_sth->errstr if $h_sth;
1137 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1139 # Now that it has been saved, reset the encrypted fields so that $new
1140 # can still be used.
1141 foreach my $field (keys %{$saved}) {
1142 $self->setfield($field, $saved->{$field});
1150 Depriciated (use insert instead).
1155 cluck "warning: FS::Record::add deprecated!";
1156 insert @_; #call method in this scope
1161 Delete this record from the database. If there is an error, returns the error,
1162 otherwise returns false.
1169 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1171 $self->getfield($_) eq ''
1172 #? "( $_ IS NULL OR $_ = \"\" )"
1173 ? ( driver_name eq 'Pg'
1175 : "( $_ IS NULL OR $_ = \"\" )"
1177 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1178 } ( $self->dbdef_table->primary_key )
1179 ? ( $self->dbdef_table->primary_key)
1180 : real_fields($self->table)
1182 warn "[debug]$me $statement\n" if $DEBUG > 1;
1183 my $sth = dbh->prepare($statement) or return dbh->errstr;
1186 if ( defined dbdef->table('h_'. $self->table) ) {
1187 my $h_statement = $self->_h_statement('delete');
1188 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1189 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1194 my $primary_key = $self->dbdef_table->primary_key;
1197 my $vfp = $self->vfieldpart_hashref;
1198 foreach($self->virtual_fields) {
1199 next if $self->getfield($_) eq '';
1200 unless(@del_vfields) {
1201 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1202 $v_sth = dbh->prepare($st) or return dbh->errstr;
1204 push @del_vfields, $_;
1207 local $SIG{HUP} = 'IGNORE';
1208 local $SIG{INT} = 'IGNORE';
1209 local $SIG{QUIT} = 'IGNORE';
1210 local $SIG{TERM} = 'IGNORE';
1211 local $SIG{TSTP} = 'IGNORE';
1212 local $SIG{PIPE} = 'IGNORE';
1214 my $rc = $sth->execute or return $sth->errstr;
1215 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1216 $h_sth->execute or return $h_sth->errstr if $h_sth;
1217 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1218 or return $v_sth->errstr
1219 foreach (@del_vfields);
1221 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1223 #no need to needlessly destoy the data either (causes problems actually)
1224 #undef $self; #no need to keep object!
1231 Depriciated (use delete instead).
1236 cluck "warning: FS::Record::del deprecated!";
1237 &delete(@_); #call method in this scope
1240 =item replace OLD_RECORD
1242 Replace the OLD_RECORD with this one in the database. If there is an error,
1243 returns the error, otherwise returns false.
1248 my ($new, $old) = (shift, shift);
1250 $old = $new->replace_old unless defined($old);
1252 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1254 if ( $new->can('replace_check') ) {
1255 my $error = $new->replace_check($old);
1256 return $error if $error;
1259 return "Records not in same table!" unless $new->table eq $old->table;
1261 my $primary_key = $old->dbdef_table->primary_key;
1262 return "Can't change primary key $primary_key ".
1263 'from '. $old->getfield($primary_key).
1264 ' to ' . $new->getfield($primary_key)
1266 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1268 my $error = $new->check;
1269 return $error if $error;
1271 # Encrypt for replace
1273 if ( $conf->exists('encryption')
1274 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1275 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1277 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1278 $saved->{$field} = $new->getfield($field);
1279 $new->setfield($field, $new->encrypt($new->getfield($field)));
1283 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1284 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1285 ? ($_, $new->getfield($_)) : () } $old->fields;
1287 unless (keys(%diff) || $no_update_diff ) {
1288 carp "[warning]$me $new -> replace $old: records identical"
1289 unless $nowarn_identical;
1293 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1295 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1296 } real_fields($old->table)
1301 if ( $old->getfield($_) eq '' ) {
1303 #false laziness w/qsearch
1304 if ( driver_name eq 'Pg' ) {
1305 my $type = $old->dbdef_table->column($_)->type;
1306 if ( $type =~ /(int|(big)?serial)/i ) {
1309 qq-( $_ IS NULL OR $_ = '' )-;
1312 qq-( $_ IS NULL OR $_ = "" )-;
1316 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1319 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1322 warn "[debug]$me $statement\n" if $DEBUG > 1;
1323 my $sth = dbh->prepare($statement) or return dbh->errstr;
1326 if ( defined dbdef->table('h_'. $old->table) ) {
1327 my $h_old_statement = $old->_h_statement('replace_old');
1328 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1329 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1335 if ( defined dbdef->table('h_'. $new->table) ) {
1336 my $h_new_statement = $new->_h_statement('replace_new');
1337 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1338 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1343 # For virtual fields we have three cases with different SQL
1344 # statements: add, replace, delete
1348 my (@add_vfields, @rep_vfields, @del_vfields);
1349 my $vfp = $old->vfieldpart_hashref;
1350 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1351 if($diff{$_} eq '') {
1353 unless(@del_vfields) {
1354 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1355 "AND vfieldpart = ?";
1356 warn "[debug]$me $st\n" if $DEBUG > 2;
1357 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1359 push @del_vfields, $_;
1360 } elsif($old->getfield($_) eq '') {
1362 unless(@add_vfields) {
1363 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1365 warn "[debug]$me $st\n" if $DEBUG > 2;
1366 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1368 push @add_vfields, $_;
1371 unless(@rep_vfields) {
1372 my $st = "UPDATE virtual_field SET value = ? ".
1373 "WHERE recnum = ? AND vfieldpart = ?";
1374 warn "[debug]$me $st\n" if $DEBUG > 2;
1375 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1377 push @rep_vfields, $_;
1381 local $SIG{HUP} = 'IGNORE';
1382 local $SIG{INT} = 'IGNORE';
1383 local $SIG{QUIT} = 'IGNORE';
1384 local $SIG{TERM} = 'IGNORE';
1385 local $SIG{TSTP} = 'IGNORE';
1386 local $SIG{PIPE} = 'IGNORE';
1388 my $rc = $sth->execute or return $sth->errstr;
1389 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1390 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1391 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1393 $v_del_sth->execute($old->getfield($primary_key),
1395 or return $v_del_sth->errstr
1396 foreach(@del_vfields);
1398 $v_add_sth->execute($new->getfield($_),
1399 $old->getfield($primary_key),
1401 or return $v_add_sth->errstr
1402 foreach(@add_vfields);
1404 $v_rep_sth->execute($new->getfield($_),
1405 $old->getfield($primary_key),
1407 or return $v_rep_sth->errstr
1408 foreach(@rep_vfields);
1410 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1412 # Now that it has been saved, reset the encrypted fields so that $new
1413 # can still be used.
1414 foreach my $field (keys %{$saved}) {
1415 $new->setfield($field, $saved->{$field});
1423 my( $self ) = shift;
1424 warn "[$me] replace called with no arguments; autoloading old record\n"
1427 my $primary_key = $self->dbdef_table->primary_key;
1428 if ( $primary_key ) {
1429 $self->by_key( $self->$primary_key() ) #this is what's returned
1430 or croak "can't find ". $self->table. ".$primary_key ".
1431 $self->$primary_key();
1433 croak $self->table. " has no primary key; pass old record as argument";
1440 Depriciated (use replace instead).
1445 cluck "warning: FS::Record::rep deprecated!";
1446 replace @_; #call method in this scope
1451 Checks virtual fields (using check_blocks). Subclasses should still provide
1452 a check method to validate real fields, foreign keys, etc., and call this
1453 method via $self->SUPER::check.
1455 (FIXME: Should this method try to make sure that it I<is> being called from
1456 a subclass's check method, to keep the current semantics as far as possible?)
1461 #confess "FS::Record::check not implemented; supply one in subclass!";
1464 foreach my $field ($self->virtual_fields) {
1465 for ($self->getfield($field)) {
1466 # See notes on check_block in FS::part_virtual_field.
1467 eval $self->pvf($field)->check_block;
1469 #this is bad, probably want to follow the stack backtrace up and see
1471 my $err = "Fatal error checking $field for $self";
1473 return "$err (see log for backtrace): $@";
1476 $self->setfield($field, $_);
1482 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1484 Processes a batch import as a queued JSRPC job
1486 JOB is an FS::queue entry.
1488 OPTIONS_HASHREF can have the following keys:
1494 Table name (required).
1498 Listref of field names for static fields. They will be given values from the
1499 PARAMS hashref and passed as a "params" hashref to batch_import.
1503 Formats hashref. Keys are field names, values are listrefs that define the
1506 Each listref value can be a column name or a code reference. Coderefs are run
1507 with the row object, data and a FS::Conf object as the three parameters.
1508 For example, this coderef does the same thing as using the "columnname" string:
1511 my( $record, $data, $conf ) = @_;
1512 $record->columnname( $data );
1515 Coderefs are run after all "column name" fields are assigned.
1519 Optional format hashref of types. Keys are field names, values are "csv",
1520 "xls" or "fixedlength". Overrides automatic determination of file type
1523 =item format_headers
1525 Optional format hashref of header lines. Keys are field names, values are 0
1526 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1529 =item format_sep_chars
1531 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1532 CSV separation character.
1534 =item format_fixedlenth_formats
1536 Optional format hashref of fixed length format defintiions. Keys are field
1537 names, values Parse::FixedLength listrefs of field definitions.
1541 Set true to default to CSV file type if the filename does not contain a
1542 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1547 PARAMS is a base64-encoded Storable string containing the POSTed data as
1548 a hash ref. It normally contains at least one field, "uploaded files",
1549 generated by /elements/file-upload.html and containing the list of uploaded
1550 files. Currently only supports a single file named "file".
1554 use Storable qw(thaw);
1557 sub process_batch_import {
1558 my($job, $opt) = ( shift, shift );
1560 my $table = $opt->{table};
1561 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1562 my %formats = %{ $opt->{formats} };
1564 my $param = thaw(decode_base64(shift));
1565 warn Dumper($param) if $DEBUG;
1567 my $files = $param->{'uploaded_files'}
1568 or die "No files provided.\n";
1570 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1572 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1573 my $file = $dir. $files{'file'};
1578 formats => \%formats,
1579 format_types => $opt->{format_types},
1580 format_headers => $opt->{format_headers},
1581 format_sep_chars => $opt->{format_sep_chars},
1582 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1583 format_row_callbacks => $opt->{format_row_callbacks},
1588 format => $param->{format},
1589 params => { map { $_ => $param->{$_} } @pass_params },
1591 default_csv => $opt->{default_csv},
1594 if ( $opt->{'batch_namecol'} ) {
1595 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1596 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1599 my $error = FS::Record::batch_import( \%iopt );
1603 die "$error\n" if $error;
1606 =item batch_import PARAM_HASHREF
1608 Class method for batch imports. Available params:
1618 =item format_headers
1620 =item format_sep_chars
1622 =item format_fixedlength_formats
1624 =item format_row_callbacks
1630 FS::queue object, will be updated with progress
1636 csv, xls or fixedlength
1649 warn "$me batch_import call with params: \n". Dumper($param)
1652 my $table = $param->{table};
1653 my $formats = $param->{formats};
1655 my $job = $param->{job};
1656 my $file = $param->{file};
1657 my $format = $param->{'format'};
1658 my $params = $param->{params} || {};
1660 die "unknown format $format" unless exists $formats->{ $format };
1662 my $type = $param->{'format_types'}
1663 ? $param->{'format_types'}{ $format }
1664 : $param->{type} || 'csv';
1667 if ( $file =~ /\.(\w+)$/i ) {
1671 warn "can't parse file type from filename $file; defaulting to CSV";
1675 if $param->{'default_csv'} && $type ne 'xls';
1678 my $header = $param->{'format_headers'}
1679 ? $param->{'format_headers'}{ $param->{'format'} }
1682 my $sep_char = $param->{'format_sep_chars'}
1683 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1686 my $fixedlength_format =
1687 $param->{'format_fixedlength_formats'}
1688 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1692 $param->{'format_row_callbacks'}
1693 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1696 my @fields = @{ $formats->{ $format } };
1702 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1704 if ( $type eq 'csv' ) {
1707 $attr{sep_char} = $sep_char if $sep_char;
1708 $parser = new Text::CSV_XS \%attr;
1710 } elsif ( $type eq 'fixedlength' ) {
1712 eval "use Parse::FixedLength;";
1714 $parser = new Parse::FixedLength $fixedlength_format;
1717 die "Unknown file type $type\n";
1720 @buffer = split(/\r?\n/, slurp($file) );
1721 splice(@buffer, 0, ($header || 0) );
1722 $count = scalar(@buffer);
1724 } elsif ( $type eq 'xls' ) {
1726 eval "use Spreadsheet::ParseExcel;";
1729 eval "use DateTime::Format::Excel;";
1730 #for now, just let the error be thrown if it is used, since only CDR
1731 # formats bill_west and troop use it, not other excel-parsing things
1734 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1736 $parser = $excel->{Worksheet}[0]; #first sheet
1738 $count = $parser->{MaxRow} || $parser->{MinRow};
1741 $row = $header || 0;
1744 die "Unknown file type $type\n";
1749 local $SIG{HUP} = 'IGNORE';
1750 local $SIG{INT} = 'IGNORE';
1751 local $SIG{QUIT} = 'IGNORE';
1752 local $SIG{TERM} = 'IGNORE';
1753 local $SIG{TSTP} = 'IGNORE';
1754 local $SIG{PIPE} = 'IGNORE';
1756 my $oldAutoCommit = $FS::UID::AutoCommit;
1757 local $FS::UID::AutoCommit = 0;
1760 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1761 my $batch_col = $param->{'batch_keycol'};
1763 my $batch_class = 'FS::'. $param->{'batch_table'};
1764 my $batch = $batch_class->new({
1765 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1767 my $error = $batch->insert;
1769 $dbh->rollback if $oldAutoCommit;
1770 return "can't insert batch record: $error";
1772 #primary key via dbdef? (so the column names don't have to match)
1773 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1775 $params->{ $batch_col } = $batch_value;
1780 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1784 if ( $type eq 'csv' ) {
1786 last unless scalar(@buffer);
1787 $line = shift(@buffer);
1789 next if $line =~ /^\s*$/; #skip empty lines
1791 $line = &{$row_callback}($line) if $row_callback;
1793 $parser->parse($line) or do {
1794 $dbh->rollback if $oldAutoCommit;
1795 return "can't parse: ". $parser->error_input();
1797 @columns = $parser->fields();
1799 } elsif ( $type eq 'fixedlength' ) {
1801 @columns = $parser->parse($line);
1803 } elsif ( $type eq 'xls' ) {
1805 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1806 || ! $parser->{Cells}[$row];
1808 my @row = @{ $parser->{Cells}[$row] };
1809 @columns = map $_->{Val}, @row;
1812 #warn $z++. ": $_\n" for @columns;
1815 die "Unknown file type $type\n";
1819 my %hash = %$params;
1821 foreach my $field ( @fields ) {
1823 my $value = shift @columns;
1825 if ( ref($field) eq 'CODE' ) {
1826 #&{$field}(\%hash, $value);
1827 push @later, $field, $value;
1829 #??? $hash{$field} = $value if length($value);
1830 $hash{$field} = $value if defined($value) && length($value);
1835 my $class = "FS::$table";
1837 my $record = $class->new( \%hash );
1840 while ( scalar(@later) ) {
1841 my $sub = shift @later;
1842 my $data = shift @later;
1843 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf);
1844 last if exists( $param->{skiprow} );
1846 next if exists( $param->{skiprow} );
1848 my $error = $record->insert;
1851 $dbh->rollback if $oldAutoCommit;
1852 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1858 if ( $job && time - $min_sec > $last ) { #progress bar
1859 $job->update_statustext( int(100 * $imported / $count) );
1865 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1867 return "Empty file!" unless $imported || $param->{empty_ok};
1874 my( $self, $action, $time ) = @_;
1878 my %nohistory = map { $_=>1 } $self->nohistory_fields;
1881 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1882 real_fields($self->table);
1885 # If we're encrypting then don't store the payinfo in the history
1886 if ( $conf && $conf->exists('encryption') ) {
1887 @fields = grep { $_ ne 'payinfo' } @fields;
1890 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1892 "INSERT INTO h_". $self->table. " ( ".
1893 join(', ', qw(history_date history_user history_action), @fields ).
1895 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1902 B<Warning>: External use is B<deprecated>.
1904 Replaces COLUMN in record with a unique number, using counters in the
1905 filesystem. Used by the B<insert> method on single-field unique columns
1906 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1907 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1909 Returns the new value.
1914 my($self,$field) = @_;
1915 my($table)=$self->table;
1917 croak "Unique called on field $field, but it is ",
1918 $self->getfield($field),
1920 if $self->getfield($field);
1922 #warn "table $table is tainted" if is_tainted($table);
1923 #warn "field $field is tainted" if is_tainted($field);
1925 my($counter) = new File::CounterFile "$table.$field",0;
1927 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1929 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1932 my $index = $counter->inc;
1933 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1935 $index =~ /^(\d*)$/;
1938 $self->setfield($field,$index);
1942 =item ut_float COLUMN
1944 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1945 null. If there is an error, returns the error, otherwise returns false.
1950 my($self,$field)=@_ ;
1951 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1952 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1953 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1954 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1955 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1956 $self->setfield($field,$1);
1959 =item ut_floatn COLUMN
1961 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1962 null. If there is an error, returns the error, otherwise returns false.
1966 #false laziness w/ut_ipn
1968 my( $self, $field ) = @_;
1969 if ( $self->getfield($field) =~ /^()$/ ) {
1970 $self->setfield($field,'');
1973 $self->ut_float($field);
1977 =item ut_sfloat COLUMN
1979 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1980 May not be null. If there is an error, returns the error, otherwise returns
1986 my($self,$field)=@_ ;
1987 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1988 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1989 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1990 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1991 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1992 $self->setfield($field,$1);
1995 =item ut_sfloatn COLUMN
1997 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1998 null. If there is an error, returns the error, otherwise returns false.
2003 my( $self, $field ) = @_;
2004 if ( $self->getfield($field) =~ /^()$/ ) {
2005 $self->setfield($field,'');
2008 $self->ut_sfloat($field);
2012 =item ut_snumber COLUMN
2014 Check/untaint signed numeric data (whole numbers). If there is an error,
2015 returns the error, otherwise returns false.
2020 my($self, $field) = @_;
2021 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2022 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2023 $self->setfield($field, "$1$2");
2027 =item ut_snumbern COLUMN
2029 Check/untaint signed numeric data (whole numbers). If there is an error,
2030 returns the error, otherwise returns false.
2035 my($self, $field) = @_;
2036 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2037 or return "Illegal (numeric) $field: ". $self->getfield($field);
2039 return "Illegal (numeric) $field: ". $self->getfield($field)
2042 $self->setfield($field, "$1$2");
2046 =item ut_number COLUMN
2048 Check/untaint simple numeric data (whole numbers). May not be null. If there
2049 is an error, returns the error, otherwise returns false.
2054 my($self,$field)=@_;
2055 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2056 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2057 $self->setfield($field,$1);
2061 =item ut_numbern COLUMN
2063 Check/untaint simple numeric data (whole numbers). May be null. If there is
2064 an error, returns the error, otherwise returns false.
2069 my($self,$field)=@_;
2070 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2071 or return "Illegal (numeric) $field: ". $self->getfield($field);
2072 $self->setfield($field,$1);
2076 =item ut_money COLUMN
2078 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2079 is an error, returns the error, otherwise returns false.
2084 my($self,$field)=@_;
2085 $self->setfield($field, 0) if $self->getfield($field) eq '';
2086 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
2087 or return "Illegal (money) $field: ". $self->getfield($field);
2088 #$self->setfield($field, "$1$2$3" || 0);
2089 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2093 =item ut_moneyn COLUMN
2095 Check/untaint monetary numbers. May be negative. If there
2096 is an error, returns the error, otherwise returns false.
2101 my($self,$field)=@_;
2102 if ($self->getfield($field) eq '') {
2103 $self->setfield($field, '');
2106 $self->ut_money($field);
2109 =item ut_text COLUMN
2111 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2112 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2113 May not be null. If there is an error, returns the error, otherwise returns
2119 my($self,$field)=@_;
2120 #warn "msgcat ". \&msgcat. "\n";
2121 #warn "notexist ". \¬exist. "\n";
2122 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2123 $self->getfield($field)
2124 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
2125 or return gettext('illegal_or_empty_text'). " $field: ".
2126 $self->getfield($field);
2127 $self->setfield($field,$1);
2131 =item ut_textn COLUMN
2133 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2134 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
2135 May be null. If there is an error, returns the error, otherwise returns false.
2140 my($self,$field)=@_;
2141 $self->getfield($field)
2142 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
2143 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
2144 $self->setfield($field,$1);
2148 =item ut_alpha COLUMN
2150 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2151 an error, returns the error, otherwise returns false.
2156 my($self,$field)=@_;
2157 $self->getfield($field) =~ /^(\w+)$/
2158 or return "Illegal or empty (alphanumeric) $field: ".
2159 $self->getfield($field);
2160 $self->setfield($field,$1);
2164 =item ut_alphan COLUMN
2166 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2167 error, returns the error, otherwise returns false.
2172 my($self,$field)=@_;
2173 $self->getfield($field) =~ /^(\w*)$/
2174 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2175 $self->setfield($field,$1);
2179 =item ut_alphasn COLUMN
2181 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2182 an error, returns the error, otherwise returns false.
2187 my($self,$field)=@_;
2188 $self->getfield($field) =~ /^([\w ]*)$/
2189 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2190 $self->setfield($field,$1);
2195 =item ut_alpha_lower COLUMN
2197 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2198 there is an error, returns the error, otherwise returns false.
2202 sub ut_alpha_lower {
2203 my($self,$field)=@_;
2204 $self->getfield($field) =~ /[[:upper:]]/
2205 and return "Uppercase characters are not permitted in $field";
2206 $self->ut_alpha($field);
2209 =item ut_phonen COLUMN [ COUNTRY ]
2211 Check/untaint phone numbers. May be null. If there is an error, returns
2212 the error, otherwise returns false.
2214 Takes an optional two-letter ISO country code; without it or with unsupported
2215 countries, ut_phonen simply calls ut_alphan.
2220 my( $self, $field, $country ) = @_;
2221 return $self->ut_alphan($field) unless defined $country;
2222 my $phonen = $self->getfield($field);
2223 if ( $phonen eq '' ) {
2224 $self->setfield($field,'');
2225 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2227 $phonen = $conf->config('cust_main-default_areacode').$phonen
2228 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2229 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2230 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2231 $phonen = "$1-$2-$3";
2232 $phonen .= " x$4" if $4;
2233 $self->setfield($field,$phonen);
2235 warn "warning: don't know how to check phone numbers for country $country";
2236 return $self->ut_textn($field);
2243 Check/untaint hexadecimal values.
2248 my($self, $field) = @_;
2249 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2250 or return "Illegal (hex) $field: ". $self->getfield($field);
2251 $self->setfield($field, uc($1));
2255 =item ut_hexn COLUMN
2257 Check/untaint hexadecimal values. May be null.
2262 my($self, $field) = @_;
2263 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2264 or return "Illegal (hex) $field: ". $self->getfield($field);
2265 $self->setfield($field, uc($1));
2270 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2276 my( $self, $field ) = @_;
2277 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2278 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2279 or return "Illegal (IP address) $field: ". $self->getfield($field);
2280 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2281 $self->setfield($field, "$1.$2.$3.$4");
2287 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2288 to 127.0.0.1. May be null.
2293 my( $self, $field ) = @_;
2294 if ( $self->getfield($field) =~ /^()$/ ) {
2295 $self->setfield($field,'');
2298 $self->ut_ip($field);
2302 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2304 Check/untaint coordinates.
2305 Accepts the following forms:
2315 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2316 The latter form (that is, the MMM are thousands of minutes) is
2317 assumed if the "MMM" is exactly three digits or two digits > 59.
2319 To be safe, just use the DDD.DDDDD form.
2321 If LOWER or UPPER are specified, then the coordinate is checked
2322 for lower and upper bounds, respectively.
2328 my ($self, $field) = (shift, shift);
2330 my $lower = shift if scalar(@_);
2331 my $upper = shift if scalar(@_);
2332 my $coord = $self->getfield($field);
2333 my $neg = $coord =~ s/^(-)//;
2335 my ($d, $m, $s) = (0, 0, 0);
2338 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2339 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2340 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2342 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2345 return "Invalid (coordinate with minutes > 59) $field: "
2346 . $self->getfield($field);
2349 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2351 if (defined($lower) and ($coord < $lower)) {
2352 return "Invalid (coordinate < $lower) $field: "
2353 . $self->getfield($field);;
2356 if (defined($upper) and ($coord > $upper)) {
2357 return "Invalid (coordinate > $upper) $field: "
2358 . $self->getfield($field);;
2361 $self->setfield($field, $coord);
2365 return "Invalid (coordinate) $field: " . $self->getfield($field);
2369 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2371 Same as ut_coord, except optionally null.
2377 my ($self, $field) = (shift, shift);
2379 if ($self->getfield($field) =~ /^$/) {
2382 return $self->ut_coord($field, @_);
2388 =item ut_domain COLUMN
2390 Check/untaint host and domain names.
2395 my( $self, $field ) = @_;
2396 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2397 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2398 or return "Illegal (domain) $field: ". $self->getfield($field);
2399 $self->setfield($field,$1);
2403 =item ut_name COLUMN
2405 Check/untaint proper names; allows alphanumerics, spaces and the following
2406 punctuation: , . - '
2413 my( $self, $field ) = @_;
2414 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2415 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2416 $self->setfield($field,$1);
2422 Check/untaint zip codes.
2426 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2429 my( $self, $field, $country ) = @_;
2431 if ( $country eq 'US' ) {
2433 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2434 or return gettext('illegal_zip'). " $field for country $country: ".
2435 $self->getfield($field);
2436 $self->setfield($field, $1);
2438 } elsif ( $country eq 'CA' ) {
2440 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2441 or return gettext('illegal_zip'). " $field for country $country: ".
2442 $self->getfield($field);
2443 $self->setfield($field, "$1 $2");
2447 if ( $self->getfield($field) =~ /^\s*$/
2448 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2451 $self->setfield($field,'');
2453 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2454 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2455 $self->setfield($field,$1);
2463 =item ut_country COLUMN
2465 Check/untaint country codes. Country names are changed to codes, if possible -
2466 see L<Locale::Country>.
2471 my( $self, $field ) = @_;
2472 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2473 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2474 && country2code($1) ) {
2475 $self->setfield($field,uc(country2code($1)));
2478 $self->getfield($field) =~ /^(\w\w)$/
2479 or return "Illegal (country) $field: ". $self->getfield($field);
2480 $self->setfield($field,uc($1));
2484 =item ut_anything COLUMN
2486 Untaints arbitrary data. Be careful.
2491 my( $self, $field ) = @_;
2492 $self->getfield($field) =~ /^(.*)$/s
2493 or return "Illegal $field: ". $self->getfield($field);
2494 $self->setfield($field,$1);
2498 =item ut_enum COLUMN CHOICES_ARRAYREF
2500 Check/untaint a column, supplying all possible choices, like the "enum" type.
2505 my( $self, $field, $choices ) = @_;
2506 foreach my $choice ( @$choices ) {
2507 if ( $self->getfield($field) eq $choice ) {
2508 $self->setfield($field, $choice);
2512 return "Illegal (enum) field $field: ". $self->getfield($field);
2515 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2517 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2518 on the column first.
2522 sub ut_foreign_key {
2523 my( $self, $field, $table, $foreign ) = @_;
2524 return '' if $no_check_foreign;
2525 qsearchs($table, { $foreign => $self->getfield($field) })
2526 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2527 " in $table.$foreign";
2531 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2533 Like ut_foreign_key, except the null value is also allowed.
2537 sub ut_foreign_keyn {
2538 my( $self, $field, $table, $foreign ) = @_;
2539 $self->getfield($field)
2540 ? $self->ut_foreign_key($field, $table, $foreign)
2544 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2546 Checks this column as an agentnum, taking into account the current users's
2547 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2548 right or rights allowing no agentnum.
2552 sub ut_agentnum_acl {
2553 my( $self, $field ) = (shift, shift);
2554 my $null_acl = scalar(@_) ? shift : [];
2555 $null_acl = [ $null_acl ] unless ref($null_acl);
2557 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2558 return "Illegal agentnum: $error" if $error;
2560 my $curuser = $FS::CurrentUser::CurrentUser;
2562 if ( $self->$field() ) {
2564 return "Access denied"
2565 unless $curuser->agentnum($self->$field());
2569 return "Access denied"
2570 unless grep $curuser->access_right($_), @$null_acl;
2578 =item virtual_fields [ TABLE ]
2580 Returns a list of virtual fields defined for the table. This should not
2581 be exported, and should only be called as an instance or class method.
2585 sub virtual_fields {
2588 $table = $self->table or confess "virtual_fields called on non-table";
2590 confess "Unknown table $table" unless dbdef->table($table);
2592 return () unless dbdef->table('part_virtual_field');
2594 unless ( $virtual_fields_cache{$table} ) {
2595 my $query = 'SELECT name from part_virtual_field ' .
2596 "WHERE dbtable = '$table'";
2598 my $result = $dbh->selectcol_arrayref($query);
2599 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2601 $virtual_fields_cache{$table} = $result;
2604 @{$virtual_fields_cache{$table}};
2609 =item fields [ TABLE ]
2611 This is a wrapper for real_fields and virtual_fields. Code that called
2612 fields before should probably continue to call fields.
2617 my $something = shift;
2619 if($something->isa('FS::Record')) {
2620 $table = $something->table;
2622 $table = $something;
2623 $something = "FS::$table";
2625 return (real_fields($table), $something->virtual_fields());
2628 =item pvf FIELD_NAME
2630 Returns the FS::part_virtual_field object corresponding to a field in the
2631 record (specified by FIELD_NAME).
2636 my ($self, $name) = (shift, shift);
2638 if(grep /^$name$/, $self->virtual_fields) {
2639 return qsearchs('part_virtual_field', { dbtable => $self->table,
2645 =item vfieldpart_hashref TABLE
2647 Returns a hashref of virtual field names and vfieldparts applicable to the given
2652 sub vfieldpart_hashref {
2654 my $table = $self->table;
2656 return {} unless dbdef->table('part_virtual_field');
2659 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2660 "dbtable = '$table'";
2661 my $sth = $dbh->prepare($statement);
2662 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2663 return { map { $_->{name}, $_->{vfieldpart} }
2664 @{$sth->fetchall_arrayref({})} };
2668 =item encrypt($value)
2670 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2672 Returns the encrypted string.
2674 You should generally not have to worry about calling this, as the system handles this for you.
2679 my ($self, $value) = @_;
2682 if ($conf->exists('encryption')) {
2683 if ($self->is_encrypted($value)) {
2684 # Return the original value if it isn't plaintext.
2685 $encrypted = $value;
2688 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2689 # RSA doesn't like the empty string so let's pack it up
2690 # The database doesn't like the RSA data so uuencode it
2691 my $length = length($value)+1;
2692 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2694 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2701 =item is_encrypted($value)
2703 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2709 my ($self, $value) = @_;
2710 # Possible Bug - Some work may be required here....
2712 if ($value =~ /^M/ && length($value) > 80) {
2719 =item decrypt($value)
2721 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2723 You should generally not have to worry about calling this, as the system handles this for you.
2728 my ($self,$value) = @_;
2729 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2730 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2732 if (ref($rsa_decrypt) =~ /::RSA/) {
2733 my $encrypted = unpack ("u*", $value);
2734 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2735 if ($@) {warn "Decryption Failed"};
2743 #Initialize the Module
2744 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2746 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2747 $rsa_module = $conf->config('encryptionmodule');
2751 eval ("require $rsa_module"); # No need to import the namespace
2754 # Initialize Encryption
2755 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2756 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2757 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2760 # Intitalize Decryption
2761 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2762 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2763 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2767 =item h_search ACTION
2769 Given an ACTION, either "insert", or "delete", returns the appropriate history
2770 record corresponding to this record, if any.
2775 my( $self, $action ) = @_;
2777 my $table = $self->table;
2780 my $primary_key = dbdef->table($table)->primary_key;
2783 'table' => "h_$table",
2784 'hashref' => { $primary_key => $self->$primary_key(),
2785 'history_action' => $action,
2793 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2794 appropriate history record corresponding to this record, if any.
2799 my($self, $action) = @_;
2800 my $h = $self->h_search($action);
2801 $h ? $h->history_date : '';
2804 =item scalar_sql SQL [ PLACEHOLDER, ... ]
2806 A class or object method. Executes the sql statement represented by SQL and
2807 returns a scalar representing the result: the first column of the first row.
2809 Dies on bogus SQL. Returns an empty string if no row is returned.
2811 Typically used for statments which return a single value such as "SELECT
2812 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
2817 my($self, $sql) = (shift, shift);
2818 my $sth = dbh->prepare($sql) or die dbh->errstr;
2820 or die "Unexpected error executing statement $sql: ". $sth->errstr;
2821 my $scalar = $sth->fetchrow_arrayref->[0];
2822 defined($scalar) ? $scalar : '';
2831 =item real_fields [ TABLE ]
2833 Returns a list of the real columns in the specified table. Called only by
2834 fields() and other subroutines elsewhere in FS::Record.
2841 my($table_obj) = dbdef->table($table);
2842 confess "Unknown table $table" unless $table_obj;
2843 $table_obj->columns;
2846 =item _quote VALUE, TABLE, COLUMN
2848 This is an internal function used to construct SQL statements. It returns
2849 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2850 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2855 my($value, $table, $column) = @_;
2856 my $column_obj = dbdef->table($table)->column($column);
2857 my $column_type = $column_obj->type;
2858 my $nullable = $column_obj->null;
2860 warn " $table.$column: $value ($column_type".
2861 ( $nullable ? ' NULL' : ' NOT NULL' ).
2862 ")\n" if $DEBUG > 2;
2864 if ( $value eq '' && $nullable ) {
2866 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2867 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2870 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2871 ! $column_type =~ /(char|binary|text)$/i ) {
2873 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
2874 && driver_name eq 'Pg'
2878 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
2879 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
2880 # single-quote the whole mess, and put an "E" in front.
2881 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
2889 This is deprecated. Don't use it.
2891 It returns a hash-type list with the fields of this record's table set true.
2896 carp "warning: hfields is deprecated";
2899 foreach (fields($table)) {
2908 "$_: ". $self->getfield($_). "|"
2909 } (fields($self->table)) );
2912 sub DESTROY { return; }
2916 # #use Carp qw(cluck);
2917 # #cluck "DESTROYING $self";
2918 # warn "DESTROYING $self";
2922 # return ! eval { join('',@_), kill 0; 1; };
2925 =item str2time_sql [ DRIVER_NAME ]
2927 Returns a function to convert to unix time based on database type, such as
2928 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2929 the str2time_sql_closing method to return a closing string rather than just
2930 using a closing parenthesis as previously suggested.
2932 You can pass an optional driver name such as "Pg", "mysql" or
2933 $dbh->{Driver}->{Name} to return a function for that database instead of
2934 the current database.
2939 my $driver = shift || driver_name;
2941 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2942 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2944 warn "warning: unknown database type $driver; guessing how to convert ".
2945 "dates to UNIX timestamps";
2946 return 'EXTRACT(EPOCH FROM ';
2950 =item str2time_sql_closing [ DRIVER_NAME ]
2952 Returns the closing suffix of a function to convert to unix time based on
2953 database type, such as ")::integer" for Pg or ")" for mysql.
2955 You can pass an optional driver name such as "Pg", "mysql" or
2956 $dbh->{Driver}->{Name} to return a function for that database instead of
2957 the current database.
2961 sub str2time_sql_closing {
2962 my $driver = shift || driver_name;
2964 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2968 =item regexp_sql [ DRIVER_NAME ]
2970 Returns the operator to do a regular expression comparison based on database
2971 type, such as '~' for Pg or 'REGEXP' for mysql.
2973 You can pass an optional driver name such as "Pg", "mysql" or
2974 $dbh->{Driver}->{Name} to return a function for that database instead of
2975 the current database.
2980 my $driver = shift || driver_name;
2982 return '~' if $driver =~ /^Pg/i;
2983 return 'REGEXP' if $driver =~ /^mysql/i;
2985 die "don't know how to use regular expressions in ". driver_name." databases";
2989 =item not_regexp_sql [ DRIVER_NAME ]
2991 Returns the operator to do a regular expression negation based on database
2992 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
2994 You can pass an optional driver name such as "Pg", "mysql" or
2995 $dbh->{Driver}->{Name} to return a function for that database instead of
2996 the current database.
3000 sub not_regexp_sql {
3001 my $driver = shift || driver_name;
3003 return '!~' if $driver =~ /^Pg/i;
3004 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3006 die "don't know how to use regular expressions in ". driver_name." databases";
3014 This module should probably be renamed, since much of the functionality is
3015 of general use. It is not completely unlike Adapter::DBI (see below).
3017 Exported qsearch and qsearchs should be deprecated in favor of method calls
3018 (against an FS::Record object like the old search and searchs that qsearch
3019 and qsearchs were on top of.)
3021 The whole fields / hfields mess should be removed.
3023 The various WHERE clauses should be subroutined.
3025 table string should be deprecated in favor of DBIx::DBSchema::Table.
3027 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3028 true maps to the database (and WHERE clauses) would also help.
3030 The ut_ methods should ask the dbdef for a default length.
3032 ut_sqltype (like ut_varchar) should all be defined
3034 A fallback check method should be provided which uses the dbdef.
3036 The ut_money method assumes money has two decimal digits.
3038 The Pg money kludge in the new method only strips `$'.
3040 The ut_phonen method only checks US-style phone numbers.
3042 The _quote function should probably use ut_float instead of a regex.
3044 All the subroutines probably should be methods, here or elsewhere.
3046 Probably should borrow/use some dbdef methods where appropriate (like sub
3049 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3050 or allow it to be set. Working around it is ugly any way around - DBI should
3051 be fixed. (only affects RDBMS which return uppercase column names)
3053 ut_zip should take an optional country like ut_phone.
3057 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3059 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.