4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
6 $conf $conf_encryption $money_char
8 $nowarn_identical $nowarn_classload
9 $no_update_diff $no_check_foreign
13 use Carp qw(carp cluck croak confess);
14 use Scalar::Util qw( blessed );
15 use File::CounterFile;
18 use File::Slurp qw( slurp );
19 use DBI qw(:sql_types);
20 use DBIx::DBSchema 0.38;
21 use FS::UID qw(dbh getotaker datasrc driver_name);
23 use FS::Schema qw(dbdef);
25 use FS::Msgcat qw(gettext);
26 use NetAddr::IP; # for validation
28 #use FS::Conf; #dependency loop bs, in install_callback below instead
30 use FS::part_virtual_field;
36 @encrypt_payby = qw( CARD DCRD CHEK DCHK );
38 #export dbdef for now... everything else expects to find it here
40 dbh fields hfields qsearch qsearchs dbdef jsearch
41 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql concat_sql
47 $nowarn_identical = 0;
48 $nowarn_classload = 0;
50 $no_check_foreign = 0;
58 $conf_encryption = '';
59 FS::UID->install_callback( sub {
62 $conf = FS::Conf->new;
63 $conf_encryption = $conf->exists('encryption');
64 $money_char = $conf->config('money_char') || '$';
65 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
66 if ( driver_name eq 'Pg' ) {
67 eval "use DBD::Pg ':pg_types'";
70 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
76 FS::Record - Database record objects
81 use FS::Record qw(dbh fields qsearch qsearchs);
83 $record = new FS::Record 'table', \%hash;
84 $record = new FS::Record 'table', { 'column' => 'value', ... };
86 $record = qsearchs FS::Record 'table', \%hash;
87 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
88 @records = qsearch FS::Record 'table', \%hash;
89 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
91 $table = $record->table;
92 $dbdef_table = $record->dbdef_table;
94 $value = $record->get('column');
95 $value = $record->getfield('column');
96 $value = $record->column;
98 $record->set( 'column' => 'value' );
99 $record->setfield( 'column' => 'value' );
100 $record->column('value');
102 %hash = $record->hash;
104 $hashref = $record->hashref;
106 $error = $record->insert;
108 $error = $record->delete;
110 $error = $new_record->replace($old_record);
112 # external use deprecated - handled by the database (at least for Pg, mysql)
113 $value = $record->unique('column');
115 $error = $record->ut_float('column');
116 $error = $record->ut_floatn('column');
117 $error = $record->ut_number('column');
118 $error = $record->ut_numbern('column');
119 $error = $record->ut_snumber('column');
120 $error = $record->ut_snumbern('column');
121 $error = $record->ut_money('column');
122 $error = $record->ut_text('column');
123 $error = $record->ut_textn('column');
124 $error = $record->ut_alpha('column');
125 $error = $record->ut_alphan('column');
126 $error = $record->ut_phonen('column');
127 $error = $record->ut_anything('column');
128 $error = $record->ut_name('column');
130 $quoted_value = _quote($value,'table','field');
133 $fields = hfields('table');
134 if ( $fields->{Field} ) { # etc.
136 @fields = fields 'table'; #as a subroutine
137 @fields = $record->fields; #as a method call
142 (Mostly) object-oriented interface to database records. Records are currently
143 implemented on top of DBI. FS::Record is intended as a base class for
144 table-specific classes to inherit from, i.e. FS::cust_main.
150 =item new [ TABLE, ] HASHREF
152 Creates a new record. It doesn't store it in the database, though. See
153 L<"insert"> for that.
155 Note that the object stores this hash reference, not a distinct copy of the
156 hash it points to. You can ask the object for a copy with the I<hash>
159 TABLE can only be omitted when a dervived class overrides the table method.
165 my $class = ref($proto) || $proto;
167 bless ($self, $class);
169 unless ( defined ( $self->table ) ) {
170 $self->{'Table'} = shift;
171 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
172 unless $nowarn_classload;
175 $self->{'Hash'} = shift;
177 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
178 $self->{'Hash'}{$field}='';
181 $self->_rebless if $self->can('_rebless');
183 $self->{'modified'} = 0;
185 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
192 my $class = ref($proto) || $proto;
194 bless ($self, $class);
196 $self->{'Table'} = shift unless defined ( $self->table );
198 my $hashref = $self->{'Hash'} = shift;
200 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
201 my $obj = $cache->cache->{$hashref->{$cache->key}};
202 $obj->_cache($hashref, $cache) if $obj->can('_cache');
205 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
212 my $class = ref($proto) || $proto;
214 bless ($self, $class);
215 if ( defined $self->table ) {
216 cluck "create constructor is deprecated, use new!";
219 croak "FS::Record::create called (not from a subclass)!";
223 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
225 Searches the database for all records matching (at least) the key/value pairs
226 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
227 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
230 The preferred usage is to pass a hash reference of named parameters:
232 @records = qsearch( {
233 'table' => 'table_name',
234 'hashref' => { 'field' => 'value'
235 'field' => { 'op' => '<',
240 #these are optional...
242 'extra_sql' => 'AND field = ? AND intfield = ?',
243 'extra_param' => [ 'value', [ 5, 'int' ] ],
244 'order_by' => 'ORDER BY something',
245 #'cache_obj' => '', #optional
246 'addl_from' => 'LEFT JOIN othtable USING ( field )',
251 Much code still uses old-style positional parameters, this is also probably
252 fine in the common case where there are only two parameters:
254 my @records = qsearch( 'table', { 'field' => 'value' } );
256 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
257 the individual PARAMS_HASHREF queries
259 ###oops, argh, FS::Record::new only lets us create database fields.
260 #Normal behaviour if SELECT is not specified is `*', as in
261 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
262 #feature where you can specify SELECT - remember, the objects returned,
263 #although blessed into the appropriate `FS::TABLE' package, will only have the
264 #fields you specify. This might have unwanted results if you then go calling
265 #regular FS::TABLE methods
270 my %TYPE = (); #for debugging
273 my($type, $value) = @_;
275 my $bind_type = { TYPE => SQL_VARCHAR };
277 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
279 $bind_type = { TYPE => SQL_INTEGER };
281 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
283 if ( driver_name eq 'Pg' ) {
285 $bind_type = { pg_type => PG_BYTEA };
287 # $bind_type = ? #SQL_VARCHAR could be fine?
290 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
291 #fixed by DBD::Pg 2.11.8
292 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
293 #(make a Tron test first)
294 } elsif ( _is_fs_float( $type, $value ) ) {
296 $bind_type = { TYPE => SQL_DECIMAL };
305 my($type, $value) = @_;
306 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
307 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
315 my( @stable, @record, @cache );
316 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
318 my %union_options = ();
319 if ( ref($_[0]) eq 'ARRAY' ) {
322 foreach my $href ( @$optlist ) {
323 push @stable, ( $href->{'table'} or die "table name is required" );
324 push @record, ( $href->{'hashref'} || {} );
325 push @select, ( $href->{'select'} || '*' );
326 push @extra_sql, ( $href->{'extra_sql'} || '' );
327 push @extra_param, ( $href->{'extra_param'} || [] );
328 push @order_by, ( $href->{'order_by'} || '' );
329 push @cache, ( $href->{'cache_obj'} || '' );
330 push @addl_from, ( $href->{'addl_from'} || '' );
331 push @debug, ( $href->{'debug'} || '' );
333 die "at least one hashref is required" unless scalar(@stable);
334 } elsif ( ref($_[0]) eq 'HASH' ) {
336 $stable[0] = $opt->{'table'} or die "table name is required";
337 $record[0] = $opt->{'hashref'} || {};
338 $select[0] = $opt->{'select'} || '*';
339 $extra_sql[0] = $opt->{'extra_sql'} || '';
340 $extra_param[0] = $opt->{'extra_param'} || [];
341 $order_by[0] = $opt->{'order_by'} || '';
342 $cache[0] = $opt->{'cache_obj'} || '';
343 $addl_from[0] = $opt->{'addl_from'} || '';
344 $debug[0] = $opt->{'debug'} || '';
355 my $cache = $cache[0];
361 foreach my $stable ( @stable ) {
362 #stop altering the caller's hashref
363 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
364 my $select = shift @select;
365 my $extra_sql = shift @extra_sql;
366 my $extra_param = shift @extra_param;
367 my $order_by = shift @order_by;
368 my $cache = shift @cache;
369 my $addl_from = shift @addl_from;
370 my $debug = shift @debug;
372 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
374 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
377 my $table = $cache ? $cache->table : $stable;
378 my $dbdef_table = dbdef->table($table)
379 or die "No schema for table $table found - ".
380 "do you need to run freeside-upgrade?";
381 my $pkey = $dbdef_table->primary_key;
383 my @real_fields = grep exists($record->{$_}), real_fields($table);
385 my $statement .= "SELECT $select FROM $stable";
386 $statement .= " $addl_from" if $addl_from;
387 if ( @real_fields ) {
388 $statement .= ' WHERE '. join(' AND ',
389 get_real_fields($table, $record, \@real_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 my $table = $stable[0];
457 $table = '' if grep { $_ ne $table } @stable;
458 $pkey = dbdef->table($table)->primary_key if $table;
461 tie %result, "Tie::IxHash";
462 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
463 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
464 %result = map { $_->{$pkey}, $_ } @stuff;
466 @result{@stuff} = @stuff;
472 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
473 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
474 #derivied class didn't override new method, so this optimization is safe
477 new_or_cached( "FS::$table", { %{$_} }, $cache )
481 new( "FS::$table", { %{$_} } )
485 #okay, its been tested
486 # warn "untested code (class FS::$table uses custom new method)";
488 eval 'FS::'. $table. '->new( { %{$_} } )';
492 # Check for encrypted fields and decrypt them.
493 ## only in the local copy, not the cached object
494 if ( $conf_encryption
495 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
496 foreach my $record (@return) {
497 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
498 next if $field eq 'payinfo'
499 && ($record->isa('FS::payinfo_transaction_Mixin')
500 || $record->isa('FS::payinfo_Mixin') )
502 && !grep { $record->payby eq $_ } @encrypt_payby;
503 # Set it directly... This may cause a problem in the future...
504 $record->setfield($field, $record->decrypt($record->getfield($field)));
509 cluck "warning: FS::$table not loaded; returning FS::Record objects"
510 unless $nowarn_classload;
512 FS::Record->new( $table, { %{$_} } );
518 ## makes this easier to read
520 sub get_real_fields {
523 my $real_fields = shift;
525 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
531 my $type = dbdef->table($table)->column($column)->type;
532 my $value = $record->{$column};
533 $value = $value->{'value'} if ref($value);
534 if ( ref($record->{$_}) ) {
535 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
536 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
537 if ( uc($op) eq 'ILIKE' ) {
539 $record->{$_}{'value'} = lc($record->{$_}{'value'});
540 $column = "LOWER($_)";
542 $record->{$_} = $record->{$_}{'value'}
545 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
547 if ( driver_name eq 'Pg' ) {
548 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
549 qq-( $column IS NULL )-;
551 qq-( $column IS NULL OR $column = '' )-;
554 qq-( $column IS NULL OR $column = "" )-;
556 } elsif ( $op eq '!=' ) {
557 if ( driver_name eq 'Pg' ) {
558 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
559 qq-( $column IS NOT NULL )-;
561 qq-( $column IS NOT NULL AND $column != '' )-;
564 qq-( $column IS NOT NULL AND $column != "" )-;
567 if ( driver_name eq 'Pg' ) {
568 qq-( $column $op '' )-;
570 qq-( $column $op "" )-;
573 #if this needs to be re-enabled, it needs to use a custom op like
574 #"APPROX=" or something (better name?, not '=', to avoid affecting other
576 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
577 # ( "$column <= ?", "$column >= ?" );
581 } @{ $real_fields } );
584 =item by_key PRIMARY_KEY_VALUE
586 This is a class method that returns the record with the given primary key
587 value. This method is only useful in FS::Record subclasses. For example:
589 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
593 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
598 my ($class, $pkey_value) = @_;
600 my $table = $class->table
601 or croak "No table for $class found";
603 my $dbdef_table = dbdef->table($table)
604 or die "No schema for table $table found - ".
605 "do you need to create it or run dbdef-create?";
606 my $pkey = $dbdef_table->primary_key
607 or die "No primary key for table $table";
609 return qsearchs($table, { $pkey => $pkey_value });
612 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
614 Experimental JOINed search method. Using this method, you can execute a
615 single SELECT spanning multiple tables, and cache the results for subsequent
616 method calls. Interface will almost definately change in an incompatible
624 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
625 my $cache = FS::SearchCache->new( $ptable, $pkey );
628 grep { !$saw{$_->getfield($pkey)}++ }
629 qsearch($table, $record, $select, $extra_sql, $cache )
633 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
635 Same as qsearch, except that if more than one record matches, it B<carp>s but
636 returns the first. If this happens, you either made a logic error in asking
637 for a single item, or your data is corrupted.
641 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
643 my(@result) = qsearch(@_);
644 cluck "warning: Multiple records in scalar search ($table)"
645 if scalar(@result) > 1;
646 #should warn more vehemently if the search was on a primary key?
647 scalar(@result) ? ($result[0]) : ();
658 Returns the table name.
663 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
670 Returns the DBIx::DBSchema::Table object for the table.
676 my($table)=$self->table;
677 dbdef->table($table);
682 Returns the primary key for the table.
688 my $pkey = $self->dbdef_table->primary_key;
691 =item get, getfield COLUMN
693 Returns the value of the column/field/key COLUMN.
698 my($self,$field) = @_;
699 # to avoid "Use of unitialized value" errors
700 if ( defined ( $self->{Hash}->{$field} ) ) {
701 $self->{Hash}->{$field};
711 =item set, setfield COLUMN, VALUE
713 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
718 my($self,$field,$value) = @_;
719 $self->{'modified'} = 1;
720 $self->{'Hash'}->{$field} = $value;
729 Returns true if the column/field/key COLUMN exists.
734 my($self,$field) = @_;
735 exists($self->{Hash}->{$field});
738 =item AUTLOADED METHODS
740 $record->column is a synonym for $record->get('column');
742 $record->column('value') is a synonym for $record->set('column','value');
749 my($field)=$AUTOLOAD;
751 if ( defined($value) ) {
752 confess "errant AUTOLOAD $field for $self (arg $value)"
753 unless blessed($self) && $self->can('setfield');
754 $self->setfield($field,$value);
756 confess "errant AUTOLOAD $field for $self (no args)"
757 unless blessed($self) && $self->can('getfield');
758 $self->getfield($field);
764 # my $field = $AUTOLOAD;
766 # if ( defined($_[1]) ) {
767 # $_[0]->setfield($field, $_[1]);
769 # $_[0]->getfield($field);
775 Returns a list of the column/value pairs, usually for assigning to a new hash.
777 To make a distinct duplicate of an FS::Record object, you can do:
779 $new = new FS::Record ( $old->table, { $old->hash } );
785 confess $self. ' -> hash: Hash attribute is undefined'
786 unless defined($self->{'Hash'});
787 %{ $self->{'Hash'} };
792 Returns a reference to the column/value hash. This may be deprecated in the
793 future; if there's a reason you can't just use the autoloaded or get/set
805 Returns true if any of this object's values have been modified with set (or via
806 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
816 =item select_for_update
818 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
823 sub select_for_update {
825 my $primary_key = $self->primary_key;
828 'table' => $self->table,
829 'hashref' => { $primary_key => $self->$primary_key() },
830 'extra_sql' => 'FOR UPDATE',
836 Locks this table with a database-driver specific lock method. This is used
837 as a mutex in order to do a duplicate search.
839 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
841 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
843 Errors are fatal; no useful return value.
845 Note: To use this method for new tables other than svc_acct and svc_phone,
846 edit freeside-upgrade and add those tables to the duplicate_lock list.
852 my $table = $self->table;
854 warn "$me locking $table table\n" if $DEBUG;
856 if ( driver_name =~ /^Pg/i ) {
858 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
861 } elsif ( driver_name =~ /^mysql/i ) {
863 dbh->do("SELECT * FROM duplicate_lock
864 WHERE lockname = '$table'
866 ) or die dbh->errstr;
870 die "unknown database ". driver_name. "; don't know how to lock table";
874 warn "$me acquired $table table lock\n" if $DEBUG;
880 Inserts this record to the database. If there is an error, returns the error,
881 otherwise returns false.
889 warn "$self -> insert" if $DEBUG;
891 my $error = $self->check;
892 return $error if $error;
894 #single-field unique keys are given a value if false
895 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
896 foreach ( $self->dbdef_table->unique_singles) {
897 $self->unique($_) unless $self->getfield($_);
900 #and also the primary key, if the database isn't going to
901 my $primary_key = $self->dbdef_table->primary_key;
903 if ( $primary_key ) {
904 my $col = $self->dbdef_table->column($primary_key);
907 uc($col->type) =~ /^(BIG)?SERIAL\d?/
908 || ( driver_name eq 'Pg'
909 && defined($col->default)
910 && $col->quoted_default =~ /^nextval\(/i
912 || ( driver_name eq 'mysql'
913 && defined($col->local)
914 && $col->local =~ /AUTO_INCREMENT/i
916 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
919 my $table = $self->table;
921 # Encrypt before the database
922 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
923 && scalar( eval '@FS::'. $table . '::encrypted_fields')
924 && $conf->exists('encryption')
926 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
927 next if $field eq 'payinfo'
928 && ($self->isa('FS::payinfo_transaction_Mixin')
929 || $self->isa('FS::payinfo_Mixin') )
931 && !grep { $self->payby eq $_ } @encrypt_payby;
932 $saved->{$field} = $self->getfield($field);
933 $self->setfield($field, $self->encrypt($self->getfield($field)));
937 #false laziness w/delete
939 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
942 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
945 my $statement = "INSERT INTO $table ";
946 if ( @real_fields ) {
949 join( ', ', @real_fields ).
951 join( ', ', @values ).
955 $statement .= 'DEFAULT VALUES';
957 warn "[debug]$me $statement\n" if $DEBUG > 1;
958 my $sth = dbh->prepare($statement) or return dbh->errstr;
960 local $SIG{HUP} = 'IGNORE';
961 local $SIG{INT} = 'IGNORE';
962 local $SIG{QUIT} = 'IGNORE';
963 local $SIG{TERM} = 'IGNORE';
964 local $SIG{TSTP} = 'IGNORE';
965 local $SIG{PIPE} = 'IGNORE';
967 $sth->execute or return $sth->errstr;
969 # get inserted id from the database, if applicable & needed
970 if ( $db_seq && ! $self->getfield($primary_key) ) {
971 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
975 if ( driver_name eq 'Pg' ) {
977 #my $oid = $sth->{'pg_oid_status'};
978 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
980 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
981 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
982 dbh->rollback if $FS::UID::AutoCommit;
983 return "can't parse $table.$primary_key default value".
984 " for sequence name: $default";
988 my $i_sql = "SELECT currval('$sequence')";
989 my $i_sth = dbh->prepare($i_sql) or do {
990 dbh->rollback if $FS::UID::AutoCommit;
993 $i_sth->execute() or do { #$i_sth->execute($oid)
994 dbh->rollback if $FS::UID::AutoCommit;
995 return $i_sth->errstr;
997 $insertid = $i_sth->fetchrow_arrayref->[0];
999 } elsif ( driver_name eq 'mysql' ) {
1001 $insertid = dbh->{'mysql_insertid'};
1002 # work around mysql_insertid being null some of the time, ala RT :/
1003 unless ( $insertid ) {
1004 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1005 "using SELECT LAST_INSERT_ID();";
1006 my $i_sql = "SELECT LAST_INSERT_ID()";
1007 my $i_sth = dbh->prepare($i_sql) or do {
1008 dbh->rollback if $FS::UID::AutoCommit;
1011 $i_sth->execute or do {
1012 dbh->rollback if $FS::UID::AutoCommit;
1013 return $i_sth->errstr;
1015 $insertid = $i_sth->fetchrow_arrayref->[0];
1020 dbh->rollback if $FS::UID::AutoCommit;
1021 return "don't know how to retreive inserted ids from ". driver_name.
1022 ", try using counterfiles (maybe run dbdef-create?)";
1026 $self->setfield($primary_key, $insertid);
1031 if ( defined dbdef->table('h_'. $table) ) {
1032 my $h_statement = $self->_h_statement('insert');
1033 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1034 $h_sth = dbh->prepare($h_statement) or do {
1035 dbh->rollback if $FS::UID::AutoCommit;
1041 $h_sth->execute or return $h_sth->errstr if $h_sth;
1043 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1045 # Now that it has been saved, reset the encrypted fields so that $new
1046 # can still be used.
1047 foreach my $field (keys %{$saved}) {
1048 $self->setfield($field, $saved->{$field});
1056 Depriciated (use insert instead).
1061 cluck "warning: FS::Record::add deprecated!";
1062 insert @_; #call method in this scope
1067 Delete this record from the database. If there is an error, returns the error,
1068 otherwise returns false.
1075 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1077 $self->getfield($_) eq ''
1078 #? "( $_ IS NULL OR $_ = \"\" )"
1079 ? ( driver_name eq 'Pg'
1081 : "( $_ IS NULL OR $_ = \"\" )"
1083 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1084 } ( $self->dbdef_table->primary_key )
1085 ? ( $self->dbdef_table->primary_key)
1086 : real_fields($self->table)
1088 warn "[debug]$me $statement\n" if $DEBUG > 1;
1089 my $sth = dbh->prepare($statement) or return dbh->errstr;
1092 if ( defined dbdef->table('h_'. $self->table) ) {
1093 my $h_statement = $self->_h_statement('delete');
1094 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1095 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1100 my $primary_key = $self->dbdef_table->primary_key;
1102 local $SIG{HUP} = 'IGNORE';
1103 local $SIG{INT} = 'IGNORE';
1104 local $SIG{QUIT} = 'IGNORE';
1105 local $SIG{TERM} = 'IGNORE';
1106 local $SIG{TSTP} = 'IGNORE';
1107 local $SIG{PIPE} = 'IGNORE';
1109 my $rc = $sth->execute or return $sth->errstr;
1110 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1111 $h_sth->execute or return $h_sth->errstr if $h_sth;
1113 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1115 #no need to needlessly destoy the data either (causes problems actually)
1116 #undef $self; #no need to keep object!
1123 Depriciated (use delete instead).
1128 cluck "warning: FS::Record::del deprecated!";
1129 &delete(@_); #call method in this scope
1132 =item replace OLD_RECORD
1134 Replace the OLD_RECORD with this one in the database. If there is an error,
1135 returns the error, otherwise returns false.
1140 my ($new, $old) = (shift, shift);
1142 $old = $new->replace_old unless defined($old);
1144 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1146 if ( $new->can('replace_check') ) {
1147 my $error = $new->replace_check($old);
1148 return $error if $error;
1151 return "Records not in same table!" unless $new->table eq $old->table;
1153 my $primary_key = $old->dbdef_table->primary_key;
1154 return "Can't change primary key $primary_key ".
1155 'from '. $old->getfield($primary_key).
1156 ' to ' . $new->getfield($primary_key)
1158 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1160 my $error = $new->check;
1161 return $error if $error;
1163 # Encrypt for replace
1165 if ( $conf->exists('encryption')
1166 && defined(eval '@FS::'. $new->table . '::encrypted_fields')
1167 && scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1169 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1170 next if $field eq 'payinfo'
1171 && ($new->isa('FS::payinfo_transaction_Mixin')
1172 || $new->isa('FS::payinfo_Mixin') )
1174 && !grep { $new->payby eq $_ } @encrypt_payby;
1175 $saved->{$field} = $new->getfield($field);
1176 $new->setfield($field, $new->encrypt($new->getfield($field)));
1180 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1181 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1182 ? ($_, $new->getfield($_)) : () } $old->fields;
1184 unless (keys(%diff) || $no_update_diff ) {
1185 carp "[warning]$me ". ref($new)."->replace ".
1186 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1187 ": records identical"
1188 unless $nowarn_identical;
1192 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1194 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1195 } real_fields($old->table)
1200 if ( $old->getfield($_) eq '' ) {
1202 #false laziness w/qsearch
1203 if ( driver_name eq 'Pg' ) {
1204 my $type = $old->dbdef_table->column($_)->type;
1205 if ( $type =~ /(int|(big)?serial)/i ) {
1208 qq-( $_ IS NULL OR $_ = '' )-;
1211 qq-( $_ IS NULL OR $_ = "" )-;
1215 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1218 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1221 warn "[debug]$me $statement\n" if $DEBUG > 1;
1222 my $sth = dbh->prepare($statement) or return dbh->errstr;
1225 if ( defined dbdef->table('h_'. $old->table) ) {
1226 my $h_old_statement = $old->_h_statement('replace_old');
1227 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1228 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1234 if ( defined dbdef->table('h_'. $new->table) ) {
1235 my $h_new_statement = $new->_h_statement('replace_new');
1236 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1237 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1242 local $SIG{HUP} = 'IGNORE';
1243 local $SIG{INT} = 'IGNORE';
1244 local $SIG{QUIT} = 'IGNORE';
1245 local $SIG{TERM} = 'IGNORE';
1246 local $SIG{TSTP} = 'IGNORE';
1247 local $SIG{PIPE} = 'IGNORE';
1249 my $rc = $sth->execute or return $sth->errstr;
1250 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1251 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1252 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1254 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1256 # Now that it has been saved, reset the encrypted fields so that $new
1257 # can still be used.
1258 foreach my $field (keys %{$saved}) {
1259 $new->setfield($field, $saved->{$field});
1267 my( $self ) = shift;
1268 warn "[$me] replace called with no arguments; autoloading old record\n"
1271 my $primary_key = $self->dbdef_table->primary_key;
1272 if ( $primary_key ) {
1273 $self->by_key( $self->$primary_key() ) #this is what's returned
1274 or croak "can't find ". $self->table. ".$primary_key ".
1275 $self->$primary_key();
1277 croak $self->table. " has no primary key; pass old record as argument";
1284 Depriciated (use replace instead).
1289 cluck "warning: FS::Record::rep deprecated!";
1290 replace @_; #call method in this scope
1295 Checks custom fields. Subclasses should still provide a check method to validate
1296 non-custom fields, foreign keys, etc., and call this method via $self->SUPER::check.
1302 foreach my $field ($self->virtual_fields) {
1303 my $error = $self->ut_textn($field);
1304 return $error if $error;
1309 =item virtual_fields [ TABLE ]
1311 Returns a list of virtual fields defined for the table. This should not
1312 be exported, and should only be called as an instance or class method.
1316 sub virtual_fields {
1319 $table = $self->table or confess "virtual_fields called on non-table";
1321 confess "Unknown table $table" unless dbdef->table($table);
1323 return () unless dbdef->table('part_virtual_field');
1325 unless ( $virtual_fields_cache{$table} ) {
1326 my $concat = [ "'cf_'", "name" ];
1327 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1328 "WHERE dbtable = '$table'";
1330 my $result = $dbh->selectcol_arrayref($query);
1331 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1333 $virtual_fields_cache{$table} = $result;
1336 @{$virtual_fields_cache{$table}};
1340 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1342 Processes a batch import as a queued JSRPC job
1344 JOB is an FS::queue entry.
1346 OPTIONS_HASHREF can have the following keys:
1352 Table name (required).
1356 Listref of field names for static fields. They will be given values from the
1357 PARAMS hashref and passed as a "params" hashref to batch_import.
1361 Formats hashref. Keys are field names, values are listrefs that define the
1364 Each listref value can be a column name or a code reference. Coderefs are run
1365 with the row object, data and a FS::Conf object as the three parameters.
1366 For example, this coderef does the same thing as using the "columnname" string:
1369 my( $record, $data, $conf ) = @_;
1370 $record->columnname( $data );
1373 Coderefs are run after all "column name" fields are assigned.
1377 Optional format hashref of types. Keys are field names, values are "csv",
1378 "xls" or "fixedlength". Overrides automatic determination of file type
1381 =item format_headers
1383 Optional format hashref of header lines. Keys are field names, values are 0
1384 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1387 =item format_sep_chars
1389 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1390 CSV separation character.
1392 =item format_fixedlenth_formats
1394 Optional format hashref of fixed length format defintiions. Keys are field
1395 names, values Parse::FixedLength listrefs of field definitions.
1399 Set true to default to CSV file type if the filename does not contain a
1400 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1405 PARAMS is a base64-encoded Storable string containing the POSTed data as
1406 a hash ref. It normally contains at least one field, "uploaded files",
1407 generated by /elements/file-upload.html and containing the list of uploaded
1408 files. Currently only supports a single file named "file".
1412 use Storable qw(thaw);
1415 sub process_batch_import {
1416 my($job, $opt) = ( shift, shift );
1418 my $table = $opt->{table};
1419 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1420 my %formats = %{ $opt->{formats} };
1422 my $param = thaw(decode_base64(shift));
1423 warn Dumper($param) if $DEBUG;
1425 my $files = $param->{'uploaded_files'}
1426 or die "No files provided.\n";
1428 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1430 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1431 my $file = $dir. $files{'file'};
1436 formats => \%formats,
1437 format_types => $opt->{format_types},
1438 format_headers => $opt->{format_headers},
1439 format_sep_chars => $opt->{format_sep_chars},
1440 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1441 format_xml_formats => $opt->{format_xml_formats},
1442 format_row_callbacks => $opt->{format_row_callbacks},
1447 format => $param->{format},
1448 params => { map { $_ => $param->{$_} } @pass_params },
1450 default_csv => $opt->{default_csv},
1451 postinsert_callback => $opt->{postinsert_callback},
1454 if ( $opt->{'batch_namecol'} ) {
1455 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1456 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1459 my $error = FS::Record::batch_import( \%iopt );
1463 die "$error\n" if $error;
1466 =item batch_import PARAM_HASHREF
1468 Class method for batch imports. Available params:
1474 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1480 =item format_headers
1482 =item format_sep_chars
1484 =item format_fixedlength_formats
1486 =item format_row_callbacks
1488 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1490 =item preinsert_callback
1492 =item postinsert_callback
1498 FS::queue object, will be updated with progress
1504 csv, xls, fixedlength, xml
1515 warn "$me batch_import call with params: \n". Dumper($param)
1518 my $table = $param->{table};
1520 my $job = $param->{job};
1521 my $file = $param->{file};
1522 my $params = $param->{params} || {};
1524 my( $type, $header, $sep_char, $fixedlength_format,
1525 $xml_format, $row_callback, @fields );
1527 my $postinsert_callback = '';
1528 $postinsert_callback = $param->{'postinsert_callback'}
1529 if $param->{'postinsert_callback'};
1530 my $preinsert_callback = '';
1531 $preinsert_callback = $param->{'preinsert_callback'}
1532 if $param->{'preinsert_callback'};
1534 if ( $param->{'format'} ) {
1536 my $format = $param->{'format'};
1537 my $formats = $param->{formats};
1538 die "unknown format $format" unless exists $formats->{ $format };
1540 $type = $param->{'format_types'}
1541 ? $param->{'format_types'}{ $format }
1542 : $param->{type} || 'csv';
1545 $header = $param->{'format_headers'}
1546 ? $param->{'format_headers'}{ $param->{'format'} }
1549 $sep_char = $param->{'format_sep_chars'}
1550 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1553 $fixedlength_format =
1554 $param->{'format_fixedlength_formats'}
1555 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1559 $param->{'format_xml_formats'}
1560 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1564 $param->{'format_row_callbacks'}
1565 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1568 @fields = @{ $formats->{ $format } };
1570 } elsif ( $param->{'fields'} ) {
1572 $type = ''; #infer from filename
1575 $fixedlength_format = '';
1577 @fields = @{ $param->{'fields'} };
1580 die "neither format nor fields specified";
1583 #my $file = $param->{file};
1586 if ( $file =~ /\.(\w+)$/i ) {
1590 warn "can't parse file type from filename $file; defaulting to CSV";
1594 if $param->{'default_csv'} && $type ne 'xls';
1602 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1604 if ( $type eq 'csv' ) {
1607 $attr{sep_char} = $sep_char if $sep_char;
1608 $parser = new Text::CSV_XS \%attr;
1610 } elsif ( $type eq 'fixedlength' ) {
1612 eval "use Parse::FixedLength;";
1614 $parser = Parse::FixedLength->new($fixedlength_format);
1618 die "Unknown file type $type\n";
1621 @buffer = split(/\r?\n/, slurp($file) );
1622 splice(@buffer, 0, ($header || 0) );
1623 $count = scalar(@buffer);
1625 } elsif ( $type eq 'xls' ) {
1627 eval "use Spreadsheet::ParseExcel;";
1630 eval "use DateTime::Format::Excel;";
1631 #for now, just let the error be thrown if it is used, since only CDR
1632 # formats bill_west and troop use it, not other excel-parsing things
1635 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1637 $parser = $excel->{Worksheet}[0]; #first sheet
1639 $count = $parser->{MaxRow} || $parser->{MinRow};
1642 $row = $header || 0;
1643 } elsif ( $type eq 'xml' ) {
1645 eval "use XML::Simple;";
1647 my $xmlrow = $xml_format->{'xmlrow'};
1648 $parser = $xml_format->{'xmlkeys'};
1649 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
1650 my $data = XML::Simple::XMLin(
1652 'SuppressEmpty' => '', #sets empty values to ''
1656 $rows = $rows->{$_} foreach @$xmlrow;
1657 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
1658 $count = @buffer = @$rows;
1660 die "Unknown file type $type\n";
1665 local $SIG{HUP} = 'IGNORE';
1666 local $SIG{INT} = 'IGNORE';
1667 local $SIG{QUIT} = 'IGNORE';
1668 local $SIG{TERM} = 'IGNORE';
1669 local $SIG{TSTP} = 'IGNORE';
1670 local $SIG{PIPE} = 'IGNORE';
1672 my $oldAutoCommit = $FS::UID::AutoCommit;
1673 local $FS::UID::AutoCommit = 0;
1676 #my $params = $param->{params} || {};
1677 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
1678 my $batch_col = $param->{'batch_keycol'};
1680 my $batch_class = 'FS::'. $param->{'batch_table'};
1681 my $batch = $batch_class->new({
1682 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
1684 my $error = $batch->insert;
1686 $dbh->rollback if $oldAutoCommit;
1687 return "can't insert batch record: $error";
1689 #primary key via dbdef? (so the column names don't have to match)
1690 my $batch_value = $batch->get( $param->{'batch_keycol'} );
1692 $params->{ $batch_col } = $batch_value;
1695 #my $job = $param->{job};
1698 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1702 if ( $type eq 'csv' ) {
1704 last unless scalar(@buffer);
1705 $line = shift(@buffer);
1707 next if $line =~ /^\s*$/; #skip empty lines
1709 $line = &{$row_callback}($line) if $row_callback;
1711 next if $line =~ /^\s*$/; #skip empty lines
1713 $parser->parse($line) or do {
1714 $dbh->rollback if $oldAutoCommit;
1715 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
1717 @columns = $parser->fields();
1719 } elsif ( $type eq 'fixedlength' ) {
1721 last unless scalar(@buffer);
1722 $line = shift(@buffer);
1724 @columns = $parser->parse($line);
1726 } elsif ( $type eq 'xls' ) {
1728 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1729 || ! $parser->{Cells}[$row];
1731 my @row = @{ $parser->{Cells}[$row] };
1732 @columns = map $_->{Val}, @row;
1735 #warn $z++. ": $_\n" for @columns;
1737 } elsif ( $type eq 'xml' ) {
1738 # $parser = [ 'Column0Key', 'Column1Key' ... ]
1739 last unless scalar(@buffer);
1740 my $row = shift @buffer;
1741 @columns = @{ $row }{ @$parser };
1743 die "Unknown file type $type\n";
1747 my %hash = %$params;
1749 foreach my $field ( @fields ) {
1751 my $value = shift @columns;
1753 if ( ref($field) eq 'CODE' ) {
1754 #&{$field}(\%hash, $value);
1755 push @later, $field, $value;
1757 #??? $hash{$field} = $value if length($value);
1758 $hash{$field} = $value if defined($value) && length($value);
1763 #my $table = $param->{table};
1764 my $class = "FS::$table";
1766 my $record = $class->new( \%hash );
1769 while ( scalar(@later) ) {
1770 my $sub = shift @later;
1771 my $data = shift @later;
1773 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
1776 $dbh->rollback if $oldAutoCommit;
1777 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
1779 last if exists( $param->{skiprow} );
1781 next if exists( $param->{skiprow} );
1783 if ( $preinsert_callback ) {
1784 my $error = &{$preinsert_callback}($record, $param);
1786 $dbh->rollback if $oldAutoCommit;
1787 return "preinsert_callback error". ( $line ? " for $line" : '' ).
1790 next if exists $param->{skiprow} && $param->{skiprow};
1793 my $error = $record->insert;
1796 $dbh->rollback if $oldAutoCommit;
1797 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1803 if ( $postinsert_callback ) {
1804 my $error = &{$postinsert_callback}($record, $param);
1806 $dbh->rollback if $oldAutoCommit;
1807 return "postinsert_callback error". ( $line ? " for $line" : '' ).
1812 if ( $job && time - $min_sec > $last ) { #progress bar
1813 $job->update_statustext( int(100 * $imported / $count) );
1819 unless ( $imported || $param->{empty_ok} ) {
1820 $dbh->rollback if $oldAutoCommit;
1821 return "Empty file!";
1824 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1831 my( $self, $action, $time ) = @_;
1835 my %nohistory = map { $_=>1 } $self->nohistory_fields;
1838 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1839 real_fields($self->table);
1842 # If we're encrypting then don't store the payinfo in the history
1843 if ( $conf && $conf->exists('encryption') && $self->table ne 'banned_pay' ) {
1844 @fields = grep { $_ ne 'payinfo' } @fields;
1847 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1849 "INSERT INTO h_". $self->table. " ( ".
1850 join(', ', qw(history_date history_user history_action), @fields ).
1852 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1859 B<Warning>: External use is B<deprecated>.
1861 Replaces COLUMN in record with a unique number, using counters in the
1862 filesystem. Used by the B<insert> method on single-field unique columns
1863 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1864 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1866 Returns the new value.
1871 my($self,$field) = @_;
1872 my($table)=$self->table;
1874 croak "Unique called on field $field, but it is ",
1875 $self->getfield($field),
1877 if $self->getfield($field);
1879 #warn "table $table is tainted" if is_tainted($table);
1880 #warn "field $field is tainted" if is_tainted($field);
1882 my($counter) = new File::CounterFile "$table.$field",0;
1884 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1886 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1889 my $index = $counter->inc;
1890 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1892 $index =~ /^(\d*)$/;
1895 $self->setfield($field,$index);
1899 =item ut_float COLUMN
1901 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1902 null. If there is an error, returns the error, otherwise returns false.
1907 my($self,$field)=@_ ;
1908 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1909 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1910 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1911 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1912 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1913 $self->setfield($field,$1);
1916 =item ut_floatn COLUMN
1918 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1919 null. If there is an error, returns the error, otherwise returns false.
1923 #false laziness w/ut_ipn
1925 my( $self, $field ) = @_;
1926 if ( $self->getfield($field) =~ /^()$/ ) {
1927 $self->setfield($field,'');
1930 $self->ut_float($field);
1934 =item ut_sfloat COLUMN
1936 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1937 May not be null. If there is an error, returns the error, otherwise returns
1943 my($self,$field)=@_ ;
1944 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1945 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1946 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1947 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1948 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1949 $self->setfield($field,$1);
1952 =item ut_sfloatn COLUMN
1954 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1955 null. If there is an error, returns the error, otherwise returns false.
1960 my( $self, $field ) = @_;
1961 if ( $self->getfield($field) =~ /^()$/ ) {
1962 $self->setfield($field,'');
1965 $self->ut_sfloat($field);
1969 =item ut_snumber COLUMN
1971 Check/untaint signed numeric data (whole numbers). If there is an error,
1972 returns the error, otherwise returns false.
1977 my($self, $field) = @_;
1978 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1979 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1980 $self->setfield($field, "$1$2");
1984 =item ut_snumbern COLUMN
1986 Check/untaint signed numeric data (whole numbers). If there is an error,
1987 returns the error, otherwise returns false.
1992 my($self, $field) = @_;
1993 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1994 or return "Illegal (numeric) $field: ". $self->getfield($field);
1996 return "Illegal (numeric) $field: ". $self->getfield($field)
1999 $self->setfield($field, "$1$2");
2003 =item ut_number COLUMN
2005 Check/untaint simple numeric data (whole numbers). May not be null. If there
2006 is an error, returns the error, otherwise returns false.
2011 my($self,$field)=@_;
2012 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2013 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2014 $self->setfield($field,$1);
2018 =item ut_numbern COLUMN
2020 Check/untaint simple numeric data (whole numbers). May be null. If there is
2021 an error, returns the error, otherwise returns false.
2026 my($self,$field)=@_;
2027 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2028 or return "Illegal (numeric) $field: ". $self->getfield($field);
2029 $self->setfield($field,$1);
2033 =item ut_money COLUMN
2035 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2036 is an error, returns the error, otherwise returns false.
2041 my($self,$field)=@_;
2042 $self->setfield($field, 0) if $self->getfield($field) eq '';
2043 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
2044 or return "Illegal (money) $field: ". $self->getfield($field);
2045 #$self->setfield($field, "$1$2$3" || 0);
2046 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2050 =item ut_moneyn COLUMN
2052 Check/untaint monetary numbers. May be negative. If there
2053 is an error, returns the error, otherwise returns false.
2058 my($self,$field)=@_;
2059 if ($self->getfield($field) eq '') {
2060 $self->setfield($field, '');
2063 $self->ut_money($field);
2066 =item ut_text COLUMN
2068 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2069 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2070 May not be null. If there is an error, returns the error, otherwise returns
2076 my($self,$field)=@_;
2077 #warn "msgcat ". \&msgcat. "\n";
2078 #warn "notexist ". \¬exist. "\n";
2079 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2080 $self->getfield($field)
2081 =~ /^([\wô \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2082 or return gettext('illegal_or_empty_text'). " $field: ".
2083 $self->getfield($field);
2084 $self->setfield($field,$1);
2088 =item ut_textn COLUMN
2090 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2091 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2092 May be null. If there is an error, returns the error, otherwise returns false.
2097 my($self,$field)=@_;
2098 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2099 $self->ut_text($field);
2102 =item ut_alpha COLUMN
2104 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2105 an error, returns the error, otherwise returns false.
2110 my($self,$field)=@_;
2111 $self->getfield($field) =~ /^(\w+)$/
2112 or return "Illegal or empty (alphanumeric) $field: ".
2113 $self->getfield($field);
2114 $self->setfield($field,$1);
2118 =item ut_alphan COLUMN
2120 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2121 error, returns the error, otherwise returns false.
2126 my($self,$field)=@_;
2127 $self->getfield($field) =~ /^(\w*)$/
2128 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2129 $self->setfield($field,$1);
2133 =item ut_alphasn COLUMN
2135 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2136 an error, returns the error, otherwise returns false.
2141 my($self,$field)=@_;
2142 $self->getfield($field) =~ /^([\w ]*)$/
2143 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2144 $self->setfield($field,$1);
2149 =item ut_alpha_lower COLUMN
2151 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2152 there is an error, returns the error, otherwise returns false.
2156 sub ut_alpha_lower {
2157 my($self,$field)=@_;
2158 $self->getfield($field) =~ /[[:upper:]]/
2159 and return "Uppercase characters are not permitted in $field";
2160 $self->ut_alpha($field);
2163 =item ut_phonen COLUMN [ COUNTRY ]
2165 Check/untaint phone numbers. May be null. If there is an error, returns
2166 the error, otherwise returns false.
2168 Takes an optional two-letter ISO country code; without it or with unsupported
2169 countries, ut_phonen simply calls ut_alphan.
2174 my( $self, $field, $country ) = @_;
2175 return $self->ut_alphan($field) unless defined $country;
2176 my $phonen = $self->getfield($field);
2177 if ( $phonen eq '' ) {
2178 $self->setfield($field,'');
2179 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2181 $phonen = $conf->config('cust_main-default_areacode').$phonen
2182 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2183 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2184 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2185 $phonen = "$1-$2-$3";
2186 $phonen .= " x$4" if $4;
2187 $self->setfield($field,$phonen);
2189 warn "warning: don't know how to check phone numbers for country $country";
2190 return $self->ut_textn($field);
2197 Check/untaint hexadecimal values.
2202 my($self, $field) = @_;
2203 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2204 or return "Illegal (hex) $field: ". $self->getfield($field);
2205 $self->setfield($field, uc($1));
2209 =item ut_hexn COLUMN
2211 Check/untaint hexadecimal values. May be null.
2216 my($self, $field) = @_;
2217 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2218 or return "Illegal (hex) $field: ". $self->getfield($field);
2219 $self->setfield($field, uc($1));
2223 =item ut_mac_addr COLUMN
2225 Check/untaint mac addresses. May be null.
2230 my($self, $field) = @_;
2232 my $mac = $self->get($field);
2235 $self->set($field, $mac);
2237 my $e = $self->ut_hex($field);
2240 return "Illegal (mac address) $field: ". $self->getfield($field)
2241 unless length($self->getfield($field)) == 12;
2247 =item ut_mac_addrn COLUMN
2249 Check/untaint mac addresses. May be null.
2254 my($self, $field) = @_;
2255 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2260 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2266 my( $self, $field ) = @_;
2267 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2268 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2269 or return "Illegal (IP address) $field: ". $self->getfield($field);
2270 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2271 $self->setfield($field, "$1.$2.$3.$4");
2277 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2278 to 127.0.0.1. May be null.
2283 my( $self, $field ) = @_;
2284 if ( $self->getfield($field) =~ /^()$/ ) {
2285 $self->setfield($field,'');
2288 $self->ut_ip($field);
2292 =item ut_ip46 COLUMN
2294 Check/untaint IPv4 or IPv6 address.
2299 my( $self, $field ) = @_;
2300 my $ip = NetAddr::IP->new($self->getfield($field))
2301 or return "Illegal (IP address) $field: ".$self->getfield($field);
2302 $self->setfield($field, lc($ip->addr));
2308 Check/untaint IPv6 or IPv6 address. May be null.
2313 my( $self, $field ) = @_;
2314 if ( $self->getfield($field) =~ /^$/ ) {
2315 $self->setfield($field, '');
2318 $self->ut_ip46($field);
2321 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2323 Check/untaint coordinates.
2324 Accepts the following forms:
2334 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2335 The latter form (that is, the MMM are thousands of minutes) is
2336 assumed if the "MMM" is exactly three digits or two digits > 59.
2338 To be safe, just use the DDD.DDDDD form.
2340 If LOWER or UPPER are specified, then the coordinate is checked
2341 for lower and upper bounds, respectively.
2347 my ($self, $field) = (shift, shift);
2349 my $lower = shift if scalar(@_);
2350 my $upper = shift if scalar(@_);
2351 my $coord = $self->getfield($field);
2352 my $neg = $coord =~ s/^(-)//;
2354 my ($d, $m, $s) = (0, 0, 0);
2357 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2358 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2359 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2361 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2364 return "Invalid (coordinate with minutes > 59) $field: "
2365 . $self->getfield($field);
2368 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2370 if (defined($lower) and ($coord < $lower)) {
2371 return "Invalid (coordinate < $lower) $field: "
2372 . $self->getfield($field);;
2375 if (defined($upper) and ($coord > $upper)) {
2376 return "Invalid (coordinate > $upper) $field: "
2377 . $self->getfield($field);;
2380 $self->setfield($field, $coord);
2384 return "Invalid (coordinate) $field: " . $self->getfield($field);
2388 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2390 Same as ut_coord, except optionally null.
2396 my ($self, $field) = (shift, shift);
2398 if ($self->getfield($field) =~ /^$/) {
2401 return $self->ut_coord($field, @_);
2407 =item ut_domain COLUMN
2409 Check/untaint host and domain names.
2414 my( $self, $field ) = @_;
2415 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2416 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2417 or return "Illegal (domain) $field: ". $self->getfield($field);
2418 $self->setfield($field,$1);
2422 =item ut_name COLUMN
2424 Check/untaint proper names; allows alphanumerics, spaces and the following
2425 punctuation: , . - '
2432 my( $self, $field ) = @_;
2433 # warn "ut_name allowed alphanumerics: +(sort grep /\w/, map { chr() } 0..255), "\n";
2434 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2435 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2436 $self->setfield($field,$1);
2442 Check/untaint zip codes.
2446 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2449 my( $self, $field, $country ) = @_;
2451 if ( $country eq 'US' ) {
2453 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2454 or return gettext('illegal_zip'). " $field for country $country: ".
2455 $self->getfield($field);
2456 $self->setfield($field, $1);
2458 } elsif ( $country eq 'CA' ) {
2460 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2461 or return gettext('illegal_zip'). " $field for country $country: ".
2462 $self->getfield($field);
2463 $self->setfield($field, "$1 $2");
2467 if ( $self->getfield($field) =~ /^\s*$/
2468 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2471 $self->setfield($field,'');
2473 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
2474 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2475 $self->setfield($field,$1);
2483 =item ut_country COLUMN
2485 Check/untaint country codes. Country names are changed to codes, if possible -
2486 see L<Locale::Country>.
2491 my( $self, $field ) = @_;
2492 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2493 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2494 && country2code($1) ) {
2495 $self->setfield($field,uc(country2code($1)));
2498 $self->getfield($field) =~ /^(\w\w)$/
2499 or return "Illegal (country) $field: ". $self->getfield($field);
2500 $self->setfield($field,uc($1));
2504 =item ut_anything COLUMN
2506 Untaints arbitrary data. Be careful.
2511 my( $self, $field ) = @_;
2512 $self->getfield($field) =~ /^(.*)$/s
2513 or return "Illegal $field: ". $self->getfield($field);
2514 $self->setfield($field,$1);
2518 =item ut_enum COLUMN CHOICES_ARRAYREF
2520 Check/untaint a column, supplying all possible choices, like the "enum" type.
2525 my( $self, $field, $choices ) = @_;
2526 foreach my $choice ( @$choices ) {
2527 if ( $self->getfield($field) eq $choice ) {
2528 $self->setfield($field, $choice);
2532 return "Illegal (enum) field $field: ". $self->getfield($field);
2535 =item ut_enumn COLUMN CHOICES_ARRAYREF
2537 Like ut_enum, except the null value is also allowed.
2542 my( $self, $field, $choices ) = @_;
2543 $self->getfield($field)
2544 ? $self->ut_enum($field, $choices)
2549 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2551 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2552 on the column first.
2556 sub ut_foreign_key {
2557 my( $self, $field, $table, $foreign ) = @_;
2558 return '' if $no_check_foreign;
2559 qsearchs($table, { $foreign => $self->getfield($field) })
2560 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2561 " in $table.$foreign";
2565 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2567 Like ut_foreign_key, except the null value is also allowed.
2571 sub ut_foreign_keyn {
2572 my( $self, $field, $table, $foreign ) = @_;
2573 $self->getfield($field)
2574 ? $self->ut_foreign_key($field, $table, $foreign)
2578 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2580 Checks this column as an agentnum, taking into account the current users's
2581 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2582 right or rights allowing no agentnum.
2586 sub ut_agentnum_acl {
2587 my( $self, $field ) = (shift, shift);
2588 my $null_acl = scalar(@_) ? shift : [];
2589 $null_acl = [ $null_acl ] unless ref($null_acl);
2591 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2592 return "Illegal agentnum: $error" if $error;
2594 my $curuser = $FS::CurrentUser::CurrentUser;
2596 if ( $self->$field() ) {
2598 return "Access denied"
2599 unless $curuser->agentnum($self->$field());
2603 return "Access denied"
2604 unless grep $curuser->access_right($_), @$null_acl;
2612 =item fields [ TABLE ]
2614 This is a wrapper for real_fields. Code that called
2615 fields before should probably continue to call fields.
2620 my $something = shift;
2622 if($something->isa('FS::Record')) {
2623 $table = $something->table;
2625 $table = $something;
2626 $something = "FS::$table";
2628 return (real_fields($table));
2632 =item encrypt($value)
2634 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2636 Returns the encrypted string.
2638 You should generally not have to worry about calling this, as the system handles this for you.
2643 my ($self, $value) = @_;
2646 if ($conf->exists('encryption')) {
2647 if ($self->is_encrypted($value)) {
2648 # Return the original value if it isn't plaintext.
2649 $encrypted = $value;
2652 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2653 # RSA doesn't like the empty string so let's pack it up
2654 # The database doesn't like the RSA data so uuencode it
2655 my $length = length($value)+1;
2656 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2658 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2665 =item is_encrypted($value)
2667 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2673 my ($self, $value) = @_;
2674 # Possible Bug - Some work may be required here....
2676 if ($value =~ /^M/ && length($value) > 80) {
2683 =item decrypt($value)
2685 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2687 You should generally not have to worry about calling this, as the system handles this for you.
2692 my ($self,$value) = @_;
2693 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2694 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2696 if (ref($rsa_decrypt) =~ /::RSA/) {
2697 my $encrypted = unpack ("u*", $value);
2698 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2699 if ($@) {warn "Decryption Failed"};
2707 #Initialize the Module
2708 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2710 if ($conf->exists('encryptionmodule') && $conf->config('encryptionmodule') ne '') {
2711 $rsa_module = $conf->config('encryptionmodule');
2715 eval ("require $rsa_module"); # No need to import the namespace
2718 # Initialize Encryption
2719 if ($conf->exists('encryptionpublickey') && $conf->config('encryptionpublickey') ne '') {
2720 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2721 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2724 # Intitalize Decryption
2725 if ($conf->exists('encryptionprivatekey') && $conf->config('encryptionprivatekey') ne '') {
2726 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2727 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2731 =item h_search ACTION
2733 Given an ACTION, either "insert", or "delete", returns the appropriate history
2734 record corresponding to this record, if any.
2739 my( $self, $action ) = @_;
2741 my $table = $self->table;
2744 my $primary_key = dbdef->table($table)->primary_key;
2747 'table' => "h_$table",
2748 'hashref' => { $primary_key => $self->$primary_key(),
2749 'history_action' => $action,
2757 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2758 appropriate history record corresponding to this record, if any.
2763 my($self, $action) = @_;
2764 my $h = $self->h_search($action);
2765 $h ? $h->history_date : '';
2768 =item scalar_sql SQL [ PLACEHOLDER, ... ]
2770 A class or object method. Executes the sql statement represented by SQL and
2771 returns a scalar representing the result: the first column of the first row.
2773 Dies on bogus SQL. Returns an empty string if no row is returned.
2775 Typically used for statments which return a single value such as "SELECT
2776 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
2781 my($self, $sql) = (shift, shift);
2782 my $sth = dbh->prepare($sql) or die dbh->errstr;
2784 or die "Unexpected error executing statement $sql: ". $sth->errstr;
2785 my $row = $sth->fetchrow_arrayref or return '';
2786 my $scalar = $row->[0];
2787 defined($scalar) ? $scalar : '';
2796 =item real_fields [ TABLE ]
2798 Returns a list of the real columns in the specified table. Called only by
2799 fields() and other subroutines elsewhere in FS::Record.
2806 my($table_obj) = dbdef->table($table);
2807 confess "Unknown table $table" unless $table_obj;
2808 $table_obj->columns;
2811 =item pvf FIELD_NAME
2813 Returns the FS::part_virtual_field object corresponding to a field in the
2814 record (specified by FIELD_NAME).
2819 my ($self, $name) = (shift, shift);
2821 if(grep /^$name$/, $self->virtual_fields) {
2823 my $concat = [ "'cf_'", "name" ];
2824 return qsearchs({ table => 'part_virtual_field',
2825 hashref => { dbtable => $self->table,
2828 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
2834 =item _quote VALUE, TABLE, COLUMN
2836 This is an internal function used to construct SQL statements. It returns
2837 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2838 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2843 my($value, $table, $column) = @_;
2844 my $column_obj = dbdef->table($table)->column($column);
2845 my $column_type = $column_obj->type;
2846 my $nullable = $column_obj->null;
2848 warn " $table.$column: $value ($column_type".
2849 ( $nullable ? ' NULL' : ' NOT NULL' ).
2850 ")\n" if $DEBUG > 2;
2852 if ( $value eq '' && $nullable ) {
2854 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2855 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2858 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2859 ! $column_type =~ /(char|binary|text)$/i ) {
2861 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
2862 && driver_name eq 'Pg'
2866 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
2867 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
2868 # single-quote the whole mess, and put an "E" in front.
2869 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
2877 This is deprecated. Don't use it.
2879 It returns a hash-type list with the fields of this record's table set true.
2884 carp "warning: hfields is deprecated";
2887 foreach (fields($table)) {
2896 "$_: ". $self->getfield($_). "|"
2897 } (fields($self->table)) );
2900 sub DESTROY { return; }
2904 # #use Carp qw(cluck);
2905 # #cluck "DESTROYING $self";
2906 # warn "DESTROYING $self";
2910 # return ! eval { join('',@_), kill 0; 1; };
2913 =item str2time_sql [ DRIVER_NAME ]
2915 Returns a function to convert to unix time based on database type, such as
2916 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2917 the str2time_sql_closing method to return a closing string rather than just
2918 using a closing parenthesis as previously suggested.
2920 You can pass an optional driver name such as "Pg", "mysql" or
2921 $dbh->{Driver}->{Name} to return a function for that database instead of
2922 the current database.
2927 my $driver = shift || driver_name;
2929 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2930 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2932 warn "warning: unknown database type $driver; guessing how to convert ".
2933 "dates to UNIX timestamps";
2934 return 'EXTRACT(EPOCH FROM ';
2938 =item str2time_sql_closing [ DRIVER_NAME ]
2940 Returns the closing suffix of a function to convert to unix time based on
2941 database type, such as ")::integer" for Pg or ")" for mysql.
2943 You can pass an optional driver name such as "Pg", "mysql" or
2944 $dbh->{Driver}->{Name} to return a function for that database instead of
2945 the current database.
2949 sub str2time_sql_closing {
2950 my $driver = shift || driver_name;
2952 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2956 =item regexp_sql [ DRIVER_NAME ]
2958 Returns the operator to do a regular expression comparison based on database
2959 type, such as '~' for Pg or 'REGEXP' for mysql.
2961 You can pass an optional driver name such as "Pg", "mysql" or
2962 $dbh->{Driver}->{Name} to return a function for that database instead of
2963 the current database.
2968 my $driver = shift || driver_name;
2970 return '~' if $driver =~ /^Pg/i;
2971 return 'REGEXP' if $driver =~ /^mysql/i;
2973 die "don't know how to use regular expressions in ". driver_name." databases";
2977 =item not_regexp_sql [ DRIVER_NAME ]
2979 Returns the operator to do a regular expression negation based on database
2980 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
2982 You can pass an optional driver name such as "Pg", "mysql" or
2983 $dbh->{Driver}->{Name} to return a function for that database instead of
2984 the current database.
2988 sub not_regexp_sql {
2989 my $driver = shift || driver_name;
2991 return '!~' if $driver =~ /^Pg/i;
2992 return 'NOT REGEXP' if $driver =~ /^mysql/i;
2994 die "don't know how to use regular expressions in ". driver_name." databases";
2998 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3000 Returns the items concatendated based on database type, using "CONCAT()" for
3001 mysql and " || " for Pg and other databases.
3003 You can pass an optional driver name such as "Pg", "mysql" or
3004 $dbh->{Driver}->{Name} to return a function for that database instead of
3005 the current database.
3010 my $driver = ref($_[0]) ? driver_name : shift;
3013 if ( $driver =~ /^mysql/i ) {
3014 'CONCAT('. join(',', @$items). ')';
3016 join('||', @$items);
3025 This module should probably be renamed, since much of the functionality is
3026 of general use. It is not completely unlike Adapter::DBI (see below).
3028 Exported qsearch and qsearchs should be deprecated in favor of method calls
3029 (against an FS::Record object like the old search and searchs that qsearch
3030 and qsearchs were on top of.)
3032 The whole fields / hfields mess should be removed.
3034 The various WHERE clauses should be subroutined.
3036 table string should be deprecated in favor of DBIx::DBSchema::Table.
3038 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3039 true maps to the database (and WHERE clauses) would also help.
3041 The ut_ methods should ask the dbdef for a default length.
3043 ut_sqltype (like ut_varchar) should all be defined
3045 A fallback check method should be provided which uses the dbdef.
3047 The ut_money method assumes money has two decimal digits.
3049 The Pg money kludge in the new method only strips `$'.
3051 The ut_phonen method only checks US-style phone numbers.
3053 The _quote function should probably use ut_float instead of a regex.
3055 All the subroutines probably should be methods, here or elsewhere.
3057 Probably should borrow/use some dbdef methods where appropriate (like sub
3060 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3061 or allow it to be set. Working around it is ugly any way around - DBI should
3062 be fixed. (only affects RDBMS which return uppercase column names)
3064 ut_zip should take an optional country like ut_phone.
3068 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3070 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.