2 use base qw( Exporter );
6 %virtual_fields_cache %fk_method_cache $fk_table_cache
7 $money_char $lat_lower $lon_upper
9 use Carp qw(carp cluck croak confess);
10 use Scalar::Util qw( blessed );
11 use File::Slurp qw( slurp );
12 use File::CounterFile;
14 use DBI qw(:sql_types);
15 use DBIx::DBSchema 0.43; #0.43 for foreign keys
18 use NetAddr::IP; # for validation
19 use FS::UID qw(dbh 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;
30 our @encrypt_payby = qw( CARD DCRD CHEK DCHK );
32 #export dbdef for now... everything else expects to find it here
34 dbh fields hfields qsearch qsearchs dbdef jsearch
35 str2time_sql str2time_sql_closing regexp_sql not_regexp_sql
36 concat_sql group_concat_sql
37 midnight_sql fk_methods_init
41 our $me = '[FS::Record]';
43 our $nowarn_identical = 0;
44 our $nowarn_classload = 0;
45 our $no_update_diff = 0;
48 our $qsearch_qualify_columns = 1;
50 our $no_check_foreign = 1; #well, not inefficiently in perl by default anymore
58 our $conf_encryption = '';
59 our $conf_encryptionmodule = '';
60 our $conf_encryptionpublickey = '';
61 our $conf_encryptionprivatekey = '';
62 FS::UID->install_callback( sub {
66 $conf = FS::Conf->new;
67 $conf_encryption = $conf->exists('encryption');
68 $conf_encryptionmodule = $conf->config('encryptionmodule');
69 $conf_encryptionpublickey = join("\n",$conf->config('encryptionpublickey'));
70 $conf_encryptionprivatekey = join("\n",$conf->config('encryptionprivatekey'));
71 $money_char = $conf->config('money_char') || '$';
72 my $nw_coords = $conf->exists('geocode-require_nw_coordinates');
73 $lat_lower = $nw_coords ? 1 : -90;
74 $lon_upper = $nw_coords ? -1 : 180;
76 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
78 if ( driver_name eq 'Pg' ) {
79 eval "use DBD::Pg ':pg_types'";
82 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
91 FS::Record - Database record objects
96 use FS::Record qw(dbh fields qsearch qsearchs);
98 $record = new FS::Record 'table', \%hash;
99 $record = new FS::Record 'table', { 'column' => 'value', ... };
101 $record = qsearchs FS::Record 'table', \%hash;
102 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
103 @records = qsearch FS::Record 'table', \%hash;
104 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
106 $table = $record->table;
107 $dbdef_table = $record->dbdef_table;
109 $value = $record->get('column');
110 $value = $record->getfield('column');
111 $value = $record->column;
113 $record->set( 'column' => 'value' );
114 $record->setfield( 'column' => 'value' );
115 $record->column('value');
117 %hash = $record->hash;
119 $hashref = $record->hashref;
121 $error = $record->insert;
123 $error = $record->delete;
125 $error = $new_record->replace($old_record);
127 # external use deprecated - handled by the database (at least for Pg, mysql)
128 $value = $record->unique('column');
130 $error = $record->ut_float('column');
131 $error = $record->ut_floatn('column');
132 $error = $record->ut_number('column');
133 $error = $record->ut_numbern('column');
134 $error = $record->ut_decimal('column');
135 $error = $record->ut_decimaln('column');
136 $error = $record->ut_snumber('column');
137 $error = $record->ut_snumbern('column');
138 $error = $record->ut_money('column');
139 $error = $record->ut_text('column');
140 $error = $record->ut_textn('column');
141 $error = $record->ut_alpha('column');
142 $error = $record->ut_alphan('column');
143 $error = $record->ut_phonen('column');
144 $error = $record->ut_anything('column');
145 $error = $record->ut_name('column');
147 $quoted_value = _quote($value,'table','field');
150 $fields = hfields('table');
151 if ( $fields->{Field} ) { # etc.
153 @fields = fields 'table'; #as a subroutine
154 @fields = $record->fields; #as a method call
159 (Mostly) object-oriented interface to database records. Records are currently
160 implemented on top of DBI. FS::Record is intended as a base class for
161 table-specific classes to inherit from, i.e. FS::cust_main.
167 =item new [ TABLE, ] HASHREF
169 Creates a new record. It doesn't store it in the database, though. See
170 L<"insert"> for that.
172 Note that the object stores this hash reference, not a distinct copy of the
173 hash it points to. You can ask the object for a copy with the I<hash>
176 TABLE can only be omitted when a dervived class overrides the table method.
182 my $class = ref($proto) || $proto;
184 bless ($self, $class);
186 unless ( defined ( $self->table ) ) {
187 $self->{'Table'} = shift;
188 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
189 unless $nowarn_classload;
192 $self->{'Hash'} = shift;
194 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
195 $self->{'Hash'}{$field}='';
198 $self->_rebless if $self->can('_rebless');
200 $self->{'modified'} = 0;
202 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
209 my $class = ref($proto) || $proto;
211 bless ($self, $class);
213 $self->{'Table'} = shift unless defined ( $self->table );
215 my $hashref = $self->{'Hash'} = shift;
217 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
218 my $obj = $cache->cache->{$hashref->{$cache->key}};
219 $obj->_cache($hashref, $cache) if $obj->can('_cache');
222 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
229 my $class = ref($proto) || $proto;
231 bless ($self, $class);
232 if ( defined $self->table ) {
233 cluck "create constructor is deprecated, use new!";
236 croak "FS::Record::create called (not from a subclass)!";
240 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
242 Searches the database for all records matching (at least) the key/value pairs
243 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
244 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
247 The preferred usage is to pass a hash reference of named parameters:
249 @records = qsearch( {
250 'table' => 'table_name',
251 'hashref' => { 'field' => 'value'
252 'field' => { 'op' => '<',
257 #these are optional...
259 'extra_sql' => 'AND field = ? AND intfield = ?',
260 'extra_param' => [ 'value', [ 5, 'int' ] ],
261 'order_by' => 'ORDER BY something',
262 #'cache_obj' => '', #optional
263 'addl_from' => 'LEFT JOIN othtable USING ( field )',
268 Much code still uses old-style positional parameters, this is also probably
269 fine in the common case where there are only two parameters:
271 my @records = qsearch( 'table', { 'field' => 'value' } );
273 Also possible is an experimental LISTREF of PARAMS_HASHREFs for a UNION of
274 the individual PARAMS_HASHREF queries
276 ###oops, argh, FS::Record::new only lets us create database fields.
277 #Normal behaviour if SELECT is not specified is `*', as in
278 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
279 #feature where you can specify SELECT - remember, the objects returned,
280 #although blessed into the appropriate `FS::TABLE' package, will only have the
281 #fields you specify. This might have unwanted results if you then go calling
282 #regular FS::TABLE methods
287 my %TYPE = (); #for debugging
290 my($type, $value) = @_;
292 my $bind_type = { TYPE => SQL_VARCHAR };
294 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^-?\d+(\.\d+)?$/ ) {
296 $bind_type = { TYPE => SQL_INTEGER };
298 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
300 if ( driver_name eq 'Pg' ) {
302 $bind_type = { pg_type => PG_BYTEA };
304 # $bind_type = ? #SQL_VARCHAR could be fine?
307 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
308 #fixed by DBD::Pg 2.11.8
309 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
310 #(make a Tron test first)
311 } elsif ( _is_fs_float( $type, $value ) ) {
313 $bind_type = { TYPE => SQL_DECIMAL };
322 my($type, $value) = @_;
323 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
324 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
332 my( @stable, @record, @cache );
333 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
335 my %union_options = ();
336 if ( ref($_[0]) eq 'ARRAY' ) {
339 foreach my $href ( @$optlist ) {
340 push @stable, ( $href->{'table'} or die "table name is required" );
341 push @record, ( $href->{'hashref'} || {} );
342 push @select, ( $href->{'select'} || '*' );
343 push @extra_sql, ( $href->{'extra_sql'} || '' );
344 push @extra_param, ( $href->{'extra_param'} || [] );
345 push @order_by, ( $href->{'order_by'} || '' );
346 push @cache, ( $href->{'cache_obj'} || '' );
347 push @addl_from, ( $href->{'addl_from'} || '' );
348 push @debug, ( $href->{'debug'} || '' );
350 die "at least one hashref is required" unless scalar(@stable);
351 } elsif ( ref($_[0]) eq 'HASH' ) {
353 $stable[0] = $opt->{'table'} or die "table name is required";
354 $record[0] = $opt->{'hashref'} || {};
355 $select[0] = $opt->{'select'} || '*';
356 $extra_sql[0] = $opt->{'extra_sql'} || '';
357 $extra_param[0] = $opt->{'extra_param'} || [];
358 $order_by[0] = $opt->{'order_by'} || '';
359 $cache[0] = $opt->{'cache_obj'} || '';
360 $addl_from[0] = $opt->{'addl_from'} || '';
361 $debug[0] = $opt->{'debug'} || '';
372 my $cache = $cache[0];
378 foreach my $stable ( @stable ) {
380 carp '->qsearch on cust_main called' if $stable eq 'cust_main' && $DEBUG;
382 #stop altering the caller's hashref
383 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
384 my $select = shift @select;
385 my $extra_sql = shift @extra_sql;
386 my $extra_param = shift @extra_param;
387 my $order_by = shift @order_by;
388 my $cache = shift @cache;
389 my $addl_from = shift @addl_from;
390 my $debug = shift @debug;
392 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
394 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
397 my $table = $cache ? $cache->table : $stable;
398 my $dbdef_table = dbdef->table($table)
399 or die "No schema for table $table found - ".
400 "do you need to run freeside-upgrade?";
401 my $pkey = $dbdef_table->primary_key;
403 my @real_fields = grep exists($record->{$_}), real_fields($table);
405 my $statement .= "SELECT $select FROM $stable";
408 $statement .= " $addl_from";
409 # detect aliasing of the main table
410 if ( $addl_from =~ /^\s*AS\s+(\w+)/i ) {
414 if ( @real_fields ) {
415 $statement .= ' WHERE '. join(' AND ',
416 get_real_fields($table, $record, \@real_fields, $alias_main));
419 $statement .= " $extra_sql" if defined($extra_sql);
420 $statement .= " $order_by" if defined($order_by);
422 push @statement, $statement;
424 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
427 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
430 my $value = $record->{$field};
431 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
432 $value = $value->{'value'} if ref($value);
433 my $type = dbdef->table($table)->column($field)->type;
435 my $bind_type = _bind_type($type, $value);
439 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
441 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
445 push @bind_type, $bind_type;
449 foreach my $param ( @$extra_param ) {
450 my $bind_type = { TYPE => SQL_VARCHAR };
453 $value = $param->[0];
454 my $type = $param->[1];
455 $bind_type = _bind_type($type, $value);
458 push @bind_type, $bind_type;
462 my $statement = join( ' ) UNION ( ', @statement );
463 $statement = "( $statement )" if scalar(@statement) > 1;
464 $statement .= " $union_options{order_by}" if $union_options{order_by};
466 my $sth = $dbh->prepare($statement)
467 or croak "$dbh->errstr doing $statement";
470 foreach my $value ( @value ) {
471 my $bind_type = shift @bind_type;
472 $sth->bind_param($bind++, $value, $bind_type );
475 # $sth->execute( map $record->{$_},
476 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
477 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
479 my $ok = $sth->execute;
481 my $error = "Error executing \"$statement\"";
482 $error .= ' (' . join(', ', map {"'$_'"} @value) . ')' if @value;
483 $error .= ': '. $sth->errstr;
487 my $table = $stable[0];
489 $table = '' if grep { $_ ne $table } @stable;
490 $pkey = dbdef->table($table)->primary_key if $table;
493 tie %result, "Tie::IxHash";
494 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
495 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
496 %result = map { $_->{$pkey}, $_ } @stuff;
498 @result{@stuff} = @stuff;
503 #below was refactored out to _from_hashref, this should use it at some point
506 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
507 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
508 #derivied class didn't override new method, so this optimization is safe
511 new_or_cached( "FS::$table", { %{$_} }, $cache )
515 new( "FS::$table", { %{$_} } )
519 #okay, its been tested
520 # warn "untested code (class FS::$table uses custom new method)";
522 eval 'FS::'. $table. '->new( { %{$_} } )';
526 # Check for encrypted fields and decrypt them.
527 ## only in the local copy, not the cached object
528 no warnings 'deprecated'; # XXX silence the warning for now
529 if ( $conf_encryption
530 && eval '@FS::'. $table . '::encrypted_fields' ) {
531 foreach my $record (@return) {
532 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
533 next if $field eq 'payinfo'
534 && ($record->isa('FS::payinfo_transaction_Mixin')
535 || $record->isa('FS::payinfo_Mixin') )
537 && !grep { $record->payby eq $_ } @encrypt_payby;
538 # Set it directly... This may cause a problem in the future...
539 $record->setfield($field, $record->decrypt($record->getfield($field)));
544 cluck "warning: FS::$table not loaded; returning FS::Record objects"
545 unless $nowarn_classload;
547 FS::Record->new( $table, { %{$_} } );
555 Construct the SQL statement and parameter-binding list for qsearch. Takes
556 the qsearch parameters.
558 Returns a hash containing:
559 'table': The primary table name (if there is one).
560 'statement': The SQL statement itself.
561 'bind_type': An arrayref of bind types.
562 'value': An arrayref of parameter values.
563 'cache': The cache object, if one was passed.
568 my( @stable, @record, @cache );
569 my( @select, @extra_sql, @extra_param, @order_by, @addl_from );
572 my %union_options = ();
573 if ( ref($_[0]) eq 'ARRAY' ) {
576 foreach my $href ( @$optlist ) {
577 push @stable, ( $href->{'table'} or die "table name is required" );
578 push @record, ( $href->{'hashref'} || {} );
579 push @select, ( $href->{'select'} || '*' );
580 push @extra_sql, ( $href->{'extra_sql'} || '' );
581 push @extra_param, ( $href->{'extra_param'} || [] );
582 push @order_by, ( $href->{'order_by'} || '' );
583 push @cache, ( $href->{'cache_obj'} || '' );
584 push @addl_from, ( $href->{'addl_from'} || '' );
585 push @debug, ( $href->{'debug'} || '' );
587 die "at least one hashref is required" unless scalar(@stable);
588 } elsif ( ref($_[0]) eq 'HASH' ) {
590 $stable[0] = $opt->{'table'} or die "table name is required";
591 $record[0] = $opt->{'hashref'} || {};
592 $select[0] = $opt->{'select'} || '*';
593 $extra_sql[0] = $opt->{'extra_sql'} || '';
594 $extra_param[0] = $opt->{'extra_param'} || [];
595 $order_by[0] = $opt->{'order_by'} || '';
596 $cache[0] = $opt->{'cache_obj'} || '';
597 $addl_from[0] = $opt->{'addl_from'} || '';
598 $debug[0] = $opt->{'debug'} || '';
609 my $cache = $cache[0];
615 my $result_table = $stable[0];
616 foreach my $stable ( @stable ) {
617 #stop altering the caller's hashref
618 my $record = { %{ shift(@record) || {} } };#and be liberal in receipt
619 my $select = shift @select;
620 my $extra_sql = shift @extra_sql;
621 my $extra_param = shift @extra_param;
622 my $order_by = shift @order_by;
623 my $cache = shift @cache;
624 my $addl_from = shift @addl_from;
625 my $debug = shift @debug;
627 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
629 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
632 $result_table = '' if $result_table ne $stable;
634 my $table = $cache ? $cache->table : $stable;
635 my $dbdef_table = dbdef->table($table)
636 or die "No schema for table $table found - ".
637 "do you need to run freeside-upgrade?";
638 my $pkey = $dbdef_table->primary_key;
640 my @real_fields = grep exists($record->{$_}), real_fields($table);
642 my $statement .= "SELECT $select FROM $stable";
643 $statement .= " $addl_from" if $addl_from;
644 if ( @real_fields ) {
645 $statement .= ' WHERE '. join(' AND ',
646 get_real_fields($table, $record, \@real_fields));
649 $statement .= " $extra_sql" if defined($extra_sql);
650 $statement .= " $order_by" if defined($order_by);
652 push @statement, $statement;
654 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
658 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
661 my $value = $record->{$field};
662 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
663 $value = $value->{'value'} if ref($value);
664 my $type = dbdef->table($table)->column($field)->type;
666 my $bind_type = _bind_type($type, $value);
670 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
672 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
676 push @bind_type, $bind_type;
680 foreach my $param ( @$extra_param ) {
681 my $bind_type = { TYPE => SQL_VARCHAR };
684 $value = $param->[0];
685 my $type = $param->[1];
686 $bind_type = _bind_type($type, $value);
689 push @bind_type, $bind_type;
693 my $statement = join( ' ) UNION ( ', @statement );
694 $statement = "( $statement )" if scalar(@statement) > 1;
695 $statement .= " $union_options{order_by}" if $union_options{order_by};
698 statement => $statement,
699 bind_type => \@bind_type,
701 table => $result_table,
706 # qsearch should eventually use this
708 my ($table, $cache, @hashrefs) = @_;
710 # XXX get rid of these string evals at some point
711 # (when we have time to test it)
712 # my $class = "FS::$table" if $table;
713 # if ( $class and $class->isa('FS::Record') )
714 # if ( $class->can('new') eq \&new )
716 if ( $table && eval 'scalar(@FS::'. $table. '::ISA);' ) {
717 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
718 #derivied class didn't override new method, so this optimization is safe
721 new_or_cached( "FS::$table", { %{$_} }, $cache )
725 new( "FS::$table", { %{$_} } )
729 #okay, its been tested
730 # warn "untested code (class FS::$table uses custom new method)";
732 eval 'FS::'. $table. '->new( { %{$_} } )';
736 # Check for encrypted fields and decrypt them.
737 ## only in the local copy, not the cached object
738 if ( $conf_encryption
739 && eval '@FS::'. $table . '::encrypted_fields' ) {
740 foreach my $record (@return) {
741 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
742 next if $field eq 'payinfo'
743 && ($record->isa('FS::payinfo_transaction_Mixin')
744 || $record->isa('FS::payinfo_Mixin') )
746 && !grep { $record->payby eq $_ } @encrypt_payby;
747 # Set it directly... This may cause a problem in the future...
748 $record->setfield($field, $record->decrypt($record->getfield($field)));
753 cluck "warning: FS::$table not loaded; returning FS::Record objects"
754 unless $nowarn_classload;
756 FS::Record->new( $table, { %{$_} } );
762 sub get_real_fields {
765 my $real_fields = shift;
766 my $alias_main = shift; # defaults to undef
767 $alias_main ||= $table;
769 ## could be optimized more for readability
775 my $table_column = $qsearch_qualify_columns ? "$alias_main.$column" : $column;
776 my $type = dbdef->table($table)->column($column)->type;
777 my $value = $record->{$column};
778 $value = $value->{'value'} if ref($value);
780 if ( ref($record->{$column}) ) {
781 $op = $record->{$column}{'op'} if $record->{$column}{'op'};
782 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
783 if ( uc($op) eq 'ILIKE' ) {
785 $record->{$column}{'value'} = lc($record->{$column}{'value'});
786 $table_column = "LOWER($table_column)";
788 $record->{$column} = $record->{$column}{'value'}
791 if ( ! defined( $record->{$column} ) || $record->{$column} eq '' ) {
793 if ( driver_name eq 'Pg' ) {
794 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
795 qq-( $table_column IS NULL )-;
797 qq-( $table_column IS NULL OR $table_column = '' )-;
800 qq-( $table_column IS NULL OR $table_column = "" )-;
802 } elsif ( $op eq '!=' ) {
803 if ( driver_name eq 'Pg' ) {
804 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
805 qq-( $table_column IS NOT NULL )-;
807 qq-( $table_column IS NOT NULL AND $table_column != '' )-;
810 qq-( $table_column IS NOT NULL AND $table_column != "" )-;
813 if ( driver_name eq 'Pg' ) {
814 qq-( $table_column $op '' )-;
816 qq-( $table_column $op "" )-;
819 } elsif ( $op eq '!=' ) {
820 qq-( $table_column IS NULL OR $table_column != ? )-;
821 #if this needs to be re-enabled, it needs to use a custom op like
822 #"APPROX=" or something (better name?, not '=', to avoid affecting other
824 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
825 # ( "$table_column <= ?", "$table_column >= ?" );
827 "$table_column $op ?";
834 =item by_key PRIMARY_KEY_VALUE
836 This is a class method that returns the record with the given primary key
837 value. This method is only useful in FS::Record subclasses. For example:
839 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
843 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
848 my ($class, $pkey_value) = @_;
850 my $table = $class->table
851 or croak "No table for $class found";
853 my $dbdef_table = dbdef->table($table)
854 or die "No schema for table $table found - ".
855 "do you need to create it or run dbdef-create?";
856 my $pkey = $dbdef_table->primary_key
857 or die "No primary key for table $table";
859 return qsearchs($table, { $pkey => $pkey_value });
862 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
864 Experimental JOINed search method. Using this method, you can execute a
865 single SELECT spanning multiple tables, and cache the results for subsequent
866 method calls. Interface will almost definately change in an incompatible
874 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
875 my $cache = FS::SearchCache->new( $ptable, $pkey );
878 grep { !$saw{$_->getfield($pkey)}++ }
879 qsearch($table, $record, $select, $extra_sql, $cache )
883 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
885 Same as qsearch, except that if more than one record matches, it B<carp>s but
886 returns the first. If this happens, you either made a logic error in asking
887 for a single item, or your data is corrupted.
891 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
893 my(@result) = qsearch(@_);
894 cluck "warning: Multiple records in scalar search ($table)"
895 #.join(' / ', map "$_=>".$_[1]->{$_}, keys %{ $_[1] } )
896 if scalar(@result) > 1;
897 #should warn more vehemently if the search was on a primary key?
898 scalar(@result) ? ($result[0]) : ();
909 Returns the table name.
914 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
921 Returns the DBIx::DBSchema::Table object for the table.
927 my($table)=$self->table;
928 dbdef->table($table);
933 Returns the primary key for the table.
939 my $pkey = $self->dbdef_table->primary_key;
942 =item get, getfield COLUMN
944 Returns the value of the column/field/key COLUMN.
949 my($self,$field) = @_;
950 # to avoid "Use of unitialized value" errors
951 if ( defined ( $self->{Hash}->{$field} ) ) {
952 $self->{Hash}->{$field};
962 =item set, setfield COLUMN, VALUE
964 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
969 my($self,$field,$value) = @_;
970 $self->{'modified'} = 1;
971 $self->{'Hash'}->{$field} = $value;
980 Returns true if the column/field/key COLUMN exists.
985 my($self,$field) = @_;
986 exists($self->{Hash}->{$field});
989 =item AUTOLOADED METHODS
991 $record->column is a synonym for $record->get('column');
993 $record->column('value') is a synonym for $record->set('column','value');
995 $record->foreign_table_name calls qsearchs and returns a single
996 FS::foreign_table record (for tables referenced by a column of this table) or
997 qsearch and returns an array of FS::foreign_table records (for tables
998 referenced by a column in the foreign table).
1004 my($self,$value)=@_;
1005 my($field)=$AUTOLOAD;
1008 confess "errant AUTOLOAD $field for $self (arg $value)"
1009 unless blessed($self) && $self->can('setfield');
1011 if ( my $fk_info = get_fk_method($self->table, $field) ) {
1013 my $method = $fk_info->{method} || 'qsearchs';
1014 my $table = $fk_info->{table} || $field;
1015 my $column = $fk_info->{column};
1016 my $foreign_column = $fk_info->{references} || $column;
1018 eval "use FS::$table";
1021 carp '->cust_main called' if $table eq 'cust_main' && $DEBUG;
1023 my $pkey_value = $self->$column();
1024 my %search = ( $foreign_column => $pkey_value );
1026 # FS::Record->$method() ? they're actually just subs :/
1027 if ( $method eq 'qsearchs' ) {
1028 return $pkey_value ? qsearchs( $table, \%search ) : '';
1029 } elsif ( $method eq 'qsearch' ) {
1030 return $pkey_value ? qsearch( $table, \%search ) : ();
1032 die "unknown method $method";
1037 if ( defined($value) ) {
1038 $self->setfield($field,$value);
1040 $self->getfield($field);
1044 # efficient (also, old, doesn't support FK stuff)
1046 # my $field = $AUTOLOAD;
1047 # $field =~ s/.*://;
1048 # if ( defined($_[1]) ) {
1049 # $_[0]->setfield($field, $_[1]);
1051 # $_[0]->getfield($field);
1055 # get_fk_method(TABLE, FIELD)
1056 # Internal subroutine for fetching the foreign key descriptor for TABLE.FIELD
1057 # if there is one. If not, returns undef.
1058 # This will initialize fk_method_cache if it hasn't happened yet. It is the
1059 # _only_ allowed way to access the contents of %fk_method_cache.
1061 # if we wanted to be even more efficient we'd create the fk methods in the
1062 # symbol table instead of relying on AUTOLOAD every time
1065 my ($table, $field) = @_;
1067 fk_methods_init() unless exists($fk_method_cache{$table});
1069 if ( exists($fk_method_cache{$table}) and
1070 exists($fk_method_cache{$table}{$field}) ) {
1071 return $fk_method_cache{$table}{$field};
1078 sub fk_methods_init {
1079 warn "[fk_methods_init]\n" if $DEBUG;
1080 foreach my $table ( dbdef->tables ) {
1081 $fk_method_cache{$table} = fk_methods($table);
1090 # foreign keys we reference in other tables
1091 foreach my $fk (dbdef->table($table)->foreign_keys) {
1094 if ( scalar( @{$fk->columns} ) == 1 ) {
1095 if ( ! defined($fk->references)
1096 || ! @{$fk->references}
1097 || $fk->columns->[0] eq $fk->references->[0]
1099 $method = $fk->table;
1101 #some sort of hint in the table.pm or schema for methods not named
1102 # after their foreign table (well, not a whole lot different than
1103 # just providing a small subroutine...)
1107 $hash{$method} = { #fk_info
1108 'method' => 'qsearchs',
1109 'column' => $fk->columns->[0],
1110 #'references' => $fk->references->[0],
1118 # foreign keys referenced in other tables to us
1119 # (alas. why we're cached. still, might this loop better be done once at
1120 # schema load time insetad of every time we AUTOLOAD a method on a new
1122 if (! defined $fk_table_cache) {
1123 foreach my $f_table ( dbdef->tables ) {
1124 foreach my $fk (dbdef->table($f_table)->foreign_keys) {
1125 push @{$fk_table_cache->{$fk->table}},[$f_table,$fk];
1129 foreach my $fks (@{$fk_table_cache->{$table}}) {
1130 my ($f_table,$fk) = @$fks;
1132 if ( scalar( @{$fk->columns} ) == 1 ) {
1133 if ( ! defined($fk->references)
1134 || ! @{$fk->references}
1135 || $fk->columns->[0] eq $fk->references->[0]
1139 #some sort of hint in the table.pm or schema for methods not named
1140 # after their foreign table (well, not a whole lot different than
1141 # just providing a small subroutine...)
1145 $hash{$method} = { #fk_info
1146 'method' => 'qsearch',
1147 'column' => $fk->columns->[0], #references||column
1148 #'references' => $fk->column->[0],
1160 Returns a list of the column/value pairs, usually for assigning to a new hash.
1162 To make a distinct duplicate of an FS::Record object, you can do:
1164 $new = new FS::Record ( $old->table, { $old->hash } );
1170 confess $self. ' -> hash: Hash attribute is undefined'
1171 unless defined($self->{'Hash'});
1172 %{ $self->{'Hash'} };
1177 Returns a reference to the column/value hash. This may be deprecated in the
1178 future; if there's a reason you can't just use the autoloaded or get/set
1192 +{ ( map { $_=>$self->$_ } $self->fields ),
1197 my( $class, %opt ) = @_;
1198 my $table = $class->table;
1199 my $self = $class->new( { map { $_ => $opt{$_} } fields($table) } );
1200 my $error = $self->insert;
1201 return +{ 'error' => $error } if $error;
1202 my $pkey = $self->pkey;
1203 return +{ 'error' => '',
1204 'primary_key' => $pkey,
1205 $pkey => $self->$pkey,
1211 Returns true if any of this object's values have been modified with set (or via
1212 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
1219 $self->{'modified'};
1222 =item select_for_update
1224 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
1229 sub select_for_update {
1231 my $primary_key = $self->primary_key;
1234 'table' => $self->table,
1235 'hashref' => { $primary_key => $self->$primary_key() },
1236 'extra_sql' => 'FOR UPDATE',
1242 Locks this table with a database-driver specific lock method. This is used
1243 as a mutex in order to do a duplicate search.
1245 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
1247 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
1249 Errors are fatal; no useful return value.
1251 Note: To use this method for new tables other than svc_acct and svc_phone,
1252 edit freeside-upgrade and add those tables to the duplicate_lock list.
1258 my $table = $self->table;
1260 warn "$me locking $table table\n" if $DEBUG;
1262 if ( driver_name =~ /^Pg/i ) {
1264 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
1267 } elsif ( driver_name =~ /^mysql/i ) {
1269 dbh->do("SELECT * FROM duplicate_lock
1270 WHERE lockname = '$table'
1272 ) or die dbh->errstr;
1276 die "unknown database ". driver_name. "; don't know how to lock table";
1280 warn "$me acquired $table table lock\n" if $DEBUG;
1286 Inserts this record to the database. If there is an error, returns the error,
1287 otherwise returns false.
1295 warn "$self -> insert" if $DEBUG;
1297 my $error = $self->check;
1298 return $error if $error;
1300 #single-field non-null unique keys are given a value if empty
1301 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
1302 foreach ( $self->dbdef_table->unique_singles) {
1303 next if $self->getfield($_);
1304 next if $self->dbdef_table->column($_)->null eq 'NULL';
1308 #and also the primary key, if the database isn't going to
1309 my $primary_key = $self->dbdef_table->primary_key;
1311 if ( $primary_key ) {
1312 my $col = $self->dbdef_table->column($primary_key);
1315 uc($col->type) =~ /^(BIG)?SERIAL\d?/
1316 || ( driver_name eq 'Pg'
1317 && defined($col->default)
1318 && $col->quoted_default =~ /^nextval\(/i
1320 || ( driver_name eq 'mysql'
1321 && defined($col->local)
1322 && $col->local =~ /AUTO_INCREMENT/i
1324 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
1327 my $table = $self->table;
1329 # Encrypt before the database
1330 if ( scalar( eval '@FS::'. $table . '::encrypted_fields')
1333 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
1334 next if $field eq 'payinfo'
1335 && ($self->isa('FS::payinfo_transaction_Mixin')
1336 || $self->isa('FS::payinfo_Mixin') )
1338 && !grep { $self->payby eq $_ } @encrypt_payby;
1339 $saved->{$field} = $self->getfield($field);
1340 $self->setfield($field, $self->encrypt($self->getfield($field)));
1344 #false laziness w/delete
1346 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
1349 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
1352 my $statement = "INSERT INTO $table ";
1353 if ( @real_fields ) {
1356 join( ', ', @real_fields ).
1358 join( ', ', @values ).
1362 $statement .= 'DEFAULT VALUES';
1364 warn "[debug]$me $statement\n" if $DEBUG > 1;
1365 my $sth = dbh->prepare($statement) or return dbh->errstr;
1367 local $SIG{HUP} = 'IGNORE';
1368 local $SIG{INT} = 'IGNORE';
1369 local $SIG{QUIT} = 'IGNORE';
1370 local $SIG{TERM} = 'IGNORE';
1371 local $SIG{TSTP} = 'IGNORE';
1372 local $SIG{PIPE} = 'IGNORE';
1374 $sth->execute or return $sth->errstr;
1376 # get inserted id from the database, if applicable & needed
1377 if ( $db_seq && ! $self->getfield($primary_key) ) {
1378 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
1382 if ( driver_name eq 'Pg' ) {
1384 #my $oid = $sth->{'pg_oid_status'};
1385 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
1387 my $default = $self->dbdef_table->column($primary_key)->quoted_default;
1388 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
1389 dbh->rollback if $FS::UID::AutoCommit;
1390 return "can't parse $table.$primary_key default value".
1391 " for sequence name: $default";
1395 my $i_sql = "SELECT currval('$sequence')";
1396 my $i_sth = dbh->prepare($i_sql) or do {
1397 dbh->rollback if $FS::UID::AutoCommit;
1400 $i_sth->execute() or do { #$i_sth->execute($oid)
1401 dbh->rollback if $FS::UID::AutoCommit;
1402 return $i_sth->errstr;
1404 $insertid = $i_sth->fetchrow_arrayref->[0];
1406 } elsif ( driver_name eq 'mysql' ) {
1408 $insertid = dbh->{'mysql_insertid'};
1409 # work around mysql_insertid being null some of the time, ala RT :/
1410 unless ( $insertid ) {
1411 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1412 "using SELECT LAST_INSERT_ID();";
1413 my $i_sql = "SELECT LAST_INSERT_ID()";
1414 my $i_sth = dbh->prepare($i_sql) or do {
1415 dbh->rollback if $FS::UID::AutoCommit;
1418 $i_sth->execute or do {
1419 dbh->rollback if $FS::UID::AutoCommit;
1420 return $i_sth->errstr;
1422 $insertid = $i_sth->fetchrow_arrayref->[0];
1427 dbh->rollback if $FS::UID::AutoCommit;
1428 return "don't know how to retreive inserted ids from ". driver_name.
1429 ", try using counterfiles (maybe run dbdef-create?)";
1433 $self->setfield($primary_key, $insertid);
1438 if ( defined( dbdef->table('h_'. $table) ) && ! $no_history ) {
1439 my $h_statement = $self->_h_statement('insert');
1440 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1441 $h_sth = dbh->prepare($h_statement) or do {
1442 dbh->rollback if $FS::UID::AutoCommit;
1448 $h_sth->execute or return $h_sth->errstr if $h_sth;
1450 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1452 # Now that it has been saved, reset the encrypted fields so that $new
1453 # can still be used.
1454 foreach my $field (keys %{$saved}) {
1455 $self->setfield($field, $saved->{$field});
1463 Depriciated (use insert instead).
1468 cluck "warning: FS::Record::add deprecated!";
1469 insert @_; #call method in this scope
1474 Delete this record from the database. If there is an error, returns the error,
1475 otherwise returns false.
1482 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1484 $self->getfield($_) eq ''
1485 #? "( $_ IS NULL OR $_ = \"\" )"
1486 ? ( driver_name eq 'Pg'
1488 : "( $_ IS NULL OR $_ = \"\" )"
1490 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1491 } ( $self->dbdef_table->primary_key )
1492 ? ( $self->dbdef_table->primary_key)
1493 : real_fields($self->table)
1495 warn "[debug]$me $statement\n" if $DEBUG > 1;
1496 my $sth = dbh->prepare($statement) or return dbh->errstr;
1499 if ( defined dbdef->table('h_'. $self->table) ) {
1500 my $h_statement = $self->_h_statement('delete');
1501 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1502 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1507 my $primary_key = $self->dbdef_table->primary_key;
1509 local $SIG{HUP} = 'IGNORE';
1510 local $SIG{INT} = 'IGNORE';
1511 local $SIG{QUIT} = 'IGNORE';
1512 local $SIG{TERM} = 'IGNORE';
1513 local $SIG{TSTP} = 'IGNORE';
1514 local $SIG{PIPE} = 'IGNORE';
1516 my $rc = $sth->execute or return $sth->errstr;
1517 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1518 $h_sth->execute or return $h_sth->errstr if $h_sth;
1520 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1522 #no need to needlessly destoy the data either (causes problems actually)
1523 #undef $self; #no need to keep object!
1530 Depriciated (use delete instead).
1535 cluck "warning: FS::Record::del deprecated!";
1536 &delete(@_); #call method in this scope
1539 =item replace OLD_RECORD
1541 Replace the OLD_RECORD with this one in the database. If there is an error,
1542 returns the error, otherwise returns false.
1547 my ($new, $old) = (shift, shift);
1549 $old = $new->replace_old unless defined($old);
1551 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1553 if ( $new->can('replace_check') ) {
1554 my $error = $new->replace_check($old);
1555 return $error if $error;
1558 return "Records not in same table!" unless $new->table eq $old->table;
1560 my $primary_key = $old->dbdef_table->primary_key;
1561 return "Can't change primary key $primary_key ".
1562 'from '. $old->getfield($primary_key).
1563 ' to ' . $new->getfield($primary_key)
1565 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1567 my $error = $new->check;
1568 return $error if $error;
1570 # Encrypt for replace
1572 if ( scalar( eval '@FS::'. $new->table . '::encrypted_fields')
1575 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1576 next if $field eq 'payinfo'
1577 && ($new->isa('FS::payinfo_transaction_Mixin')
1578 || $new->isa('FS::payinfo_Mixin') )
1580 && !grep { $new->payby eq $_ } @encrypt_payby;
1581 $saved->{$field} = $new->getfield($field);
1582 $new->setfield($field, $new->encrypt($new->getfield($field)));
1586 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1587 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1588 ? ($_, $new->getfield($_)) : () } $old->fields;
1590 unless (keys(%diff) || $no_update_diff ) {
1591 carp "[warning]$me ". ref($new)."->replace ".
1592 ( $primary_key ? "$primary_key ".$new->get($primary_key) : '' ).
1593 ": records identical"
1594 unless $nowarn_identical;
1598 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1600 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1601 } real_fields($old->table)
1606 if ( $old->getfield($_) eq '' ) {
1608 #false laziness w/qsearch
1609 if ( driver_name eq 'Pg' ) {
1610 my $type = $old->dbdef_table->column($_)->type;
1611 if ( $type =~ /(int|(big)?serial)/i ) {
1614 qq-( $_ IS NULL OR $_ = '' )-;
1617 qq-( $_ IS NULL OR $_ = "" )-;
1621 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1624 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1627 warn "[debug]$me $statement\n" if $DEBUG > 1;
1628 my $sth = dbh->prepare($statement) or return dbh->errstr;
1631 if ( defined dbdef->table('h_'. $old->table) ) {
1632 my $h_old_statement = $old->_h_statement('replace_old');
1633 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1634 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1640 if ( defined dbdef->table('h_'. $new->table) ) {
1641 my $h_new_statement = $new->_h_statement('replace_new');
1642 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1643 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1648 local $SIG{HUP} = 'IGNORE';
1649 local $SIG{INT} = 'IGNORE';
1650 local $SIG{QUIT} = 'IGNORE';
1651 local $SIG{TERM} = 'IGNORE';
1652 local $SIG{TSTP} = 'IGNORE';
1653 local $SIG{PIPE} = 'IGNORE';
1655 my $rc = $sth->execute or return $sth->errstr;
1656 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1657 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1658 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1660 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1662 # Now that it has been saved, reset the encrypted fields so that $new
1663 # can still be used.
1664 foreach my $field (keys %{$saved}) {
1665 $new->setfield($field, $saved->{$field});
1673 my( $self ) = shift;
1674 warn "[$me] replace called with no arguments; autoloading old record\n"
1677 my $primary_key = $self->dbdef_table->primary_key;
1678 if ( $primary_key ) {
1679 $self->by_key( $self->$primary_key() ) #this is what's returned
1680 or croak "can't find ". $self->table. ".$primary_key ".
1681 $self->$primary_key();
1683 croak $self->table. " has no primary key; pass old record as argument";
1690 Depriciated (use replace instead).
1695 cluck "warning: FS::Record::rep deprecated!";
1696 replace @_; #call method in this scope
1701 Checks custom fields. Subclasses should still provide a check method to validate
1702 non-custom fields, etc., and call this method via $self->SUPER::check.
1708 foreach my $field ($self->virtual_fields) {
1709 my $error = $self->ut_textn($field);
1710 return $error if $error;
1715 =item virtual_fields [ TABLE ]
1717 Returns a list of virtual fields defined for the table. This should not
1718 be exported, and should only be called as an instance or class method.
1722 sub virtual_fields {
1725 $table = $self->table or confess "virtual_fields called on non-table";
1727 confess "Unknown table $table" unless dbdef->table($table);
1729 return () unless dbdef->table('part_virtual_field');
1731 unless ( $virtual_fields_cache{$table} ) {
1732 my $concat = [ "'cf_'", "name" ];
1733 my $query = "SELECT ".concat_sql($concat).' from part_virtual_field ' .
1734 "WHERE dbtable = '$table'";
1736 my $result = $dbh->selectcol_arrayref($query);
1737 confess "Error executing virtual fields query: $query: ". $dbh->errstr
1739 $virtual_fields_cache{$table} = $result;
1742 @{$virtual_fields_cache{$table}};
1746 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1748 Processes a batch import as a queued JSRPC job
1750 JOB is an FS::queue entry.
1752 OPTIONS_HASHREF can have the following keys:
1758 Table name (required).
1762 Arrayref of field names for static fields. They will be given values from the
1763 PARAMS hashref and passed as a "params" hashref to batch_import.
1767 Formats hashref. Keys are field names, values are listrefs that define the
1770 Each listref value can be a column name or a code reference. Coderefs are run
1771 with the row object, data and a FS::Conf object as the three parameters.
1772 For example, this coderef does the same thing as using the "columnname" string:
1775 my( $record, $data, $conf ) = @_;
1776 $record->columnname( $data );
1779 Coderefs are run after all "column name" fields are assigned.
1783 Optional format hashref of types. Keys are field names, values are "csv",
1784 "xls" or "fixedlength". Overrides automatic determination of file type
1787 =item format_headers
1789 Optional format hashref of header lines. Keys are field names, values are 0
1790 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1793 =item format_sep_chars
1795 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1796 CSV separation character.
1798 =item format_fixedlenth_formats
1800 Optional format hashref of fixed length format defintiions. Keys are field
1801 names, values Parse::FixedLength listrefs of field definitions.
1805 Set true to default to CSV file type if the filename does not contain a
1806 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1811 PARAMS is a hashref (or base64-encoded Storable hashref) containing the
1812 POSTed data. It must contain the field "uploaded files", generated by
1813 /elements/file-upload.html and containing the list of uploaded files.
1814 Currently only supports a single file named "file".
1819 sub process_batch_import {
1820 my($job, $opt, $param) = @_;
1822 my $table = $opt->{table};
1823 my @pass_params = $opt->{params} ? @{ $opt->{params} } : ();
1824 my %formats = %{ $opt->{formats} };
1826 warn Dumper($param) if $DEBUG;
1828 my $files = $param->{'uploaded_files'}
1829 or die "No files provided.\n";
1831 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1833 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1834 my $file = $dir. $files{'file'};
1839 formats => \%formats,
1840 format_types => $opt->{format_types},
1841 format_headers => $opt->{format_headers},
1842 format_sep_chars => $opt->{format_sep_chars},
1843 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1844 format_xml_formats => $opt->{format_xml_formats},
1845 format_asn_formats => $opt->{format_asn_formats},
1846 format_row_callbacks => $opt->{format_row_callbacks},
1847 format_hash_callbacks => $opt->{format_hash_callbacks},
1852 format => $param->{format},
1853 params => { map { $_ => $param->{$_} } @pass_params },
1855 default_csv => $opt->{default_csv},
1856 preinsert_callback => $opt->{preinsert_callback},
1857 postinsert_callback => $opt->{postinsert_callback},
1858 insert_args_callback => $opt->{insert_args_callback},
1861 if ( $opt->{'batch_namecol'} ) {
1862 $iopt{'batch_namevalue'} = $param->{ $opt->{'batch_namecol'} };
1863 $iopt{$_} = $opt->{$_} foreach qw( batch_keycol batch_table batch_namecol );
1866 my $error = FS::Record::batch_import( \%iopt );
1870 die "$error\n" if $error;
1873 =item batch_import PARAM_HASHREF
1875 Class method for batch imports. Available params:
1881 =item format - usual way to specify import, with this format string selecting data from the formats and format_* info hashes
1887 =item format_headers
1889 =item format_sep_chars
1891 =item format_fixedlength_formats
1893 =item format_row_callbacks
1895 =item format_hash_callbacks - After parsing, before object creation
1897 =item fields - Alternate way to specify import, specifying import fields directly as a listref
1899 =item preinsert_callback
1901 =item postinsert_callback
1907 FS::queue object, will be updated with progress
1913 csv, xls, fixedlength, xml
1925 warn "$me batch_import call with params: \n". Dumper($param)
1928 my $table = $param->{table};
1930 my $job = $param->{job};
1931 my $file = $param->{file};
1932 my $params = $param->{params} || {};
1934 my $custnum_prefix = $conf->config('cust_main-custnum-display_prefix');
1935 my $custnum_length = $conf->config('cust_main-custnum-display_length') || 8;
1937 my( $type, $header, $sep_char,
1938 $fixedlength_format, $xml_format, $asn_format,
1939 $parser_opt, $row_callback, $hash_callback, @fields );
1941 my $postinsert_callback = '';
1942 $postinsert_callback = $param->{'postinsert_callback'}
1943 if $param->{'postinsert_callback'};
1944 my $preinsert_callback = '';
1945 $preinsert_callback = $param->{'preinsert_callback'}
1946 if $param->{'preinsert_callback'};
1947 my $insert_args_callback = '';
1948 $insert_args_callback = $param->{'insert_args_callback'}
1949 if $param->{'insert_args_callback'};
1951 if ( $param->{'format'} ) {
1953 my $format = $param->{'format'};
1954 my $formats = $param->{formats};
1955 die "unknown format $format" unless exists $formats->{ $format };
1957 $type = $param->{'format_types'}
1958 ? $param->{'format_types'}{ $format }
1959 : $param->{type} || 'csv';
1962 $header = $param->{'format_headers'}
1963 ? $param->{'format_headers'}{ $param->{'format'} }
1966 $sep_char = $param->{'format_sep_chars'}
1967 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1970 $fixedlength_format =
1971 $param->{'format_fixedlength_formats'}
1972 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1976 $param->{'format_parser_opts'}
1977 ? $param->{'format_parser_opts'}{ $param->{'format'} }
1981 $param->{'format_xml_formats'}
1982 ? $param->{'format_xml_formats'}{ $param->{'format'} }
1986 $param->{'format_asn_formats'}
1987 ? $param->{'format_asn_formats'}{ $param->{'format'} }
1991 $param->{'format_row_callbacks'}
1992 ? $param->{'format_row_callbacks'}{ $param->{'format'} }
1996 $param->{'format_hash_callbacks'}
1997 ? $param->{'format_hash_callbacks'}{ $param->{'format'} }
2000 @fields = @{ $formats->{ $format } };
2002 } elsif ( $param->{'fields'} ) {
2004 $type = ''; #infer from filename
2007 $fixedlength_format = '';
2009 $hash_callback = '';
2010 @fields = @{ $param->{'fields'} };
2013 die "neither format nor fields specified";
2016 #my $file = $param->{file};
2019 if ( $file =~ /\.(\w+)$/i ) {
2023 warn "can't parse file type from filename $file; defaulting to CSV";
2027 if $param->{'default_csv'} && $type ne 'xls';
2035 my $asn_header_buffer;
2036 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
2038 if ( $type eq 'csv' ) {
2040 $parser_opt->{'binary'} = 1;
2041 $parser_opt->{'sep_char'} = $sep_char if $sep_char;
2042 $parser = Text::CSV_XS->new($parser_opt);
2044 } elsif ( $type eq 'fixedlength' ) {
2046 eval "use Parse::FixedLength;";
2048 $parser = Parse::FixedLength->new($fixedlength_format, $parser_opt);
2051 die "Unknown file type $type\n";
2054 @buffer = split(/\r?\n/, slurp($file) );
2055 splice(@buffer, 0, ($header || 0) );
2056 $count = scalar(@buffer);
2058 } elsif ( $type eq 'xls' ) {
2060 eval "use Spreadsheet::ParseExcel;";
2063 eval "use DateTime::Format::Excel;";
2064 #for now, just let the error be thrown if it is used, since only CDR
2065 # formats bill_west and troop use it, not other excel-parsing things
2068 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
2070 $parser = $excel->{Worksheet}[0]; #first sheet
2072 $count = $parser->{MaxRow} || $parser->{MinRow};
2075 $row = $header || 0;
2077 } elsif ( $type eq 'xml' ) {
2080 eval "use XML::Simple;";
2082 my $xmlrow = $xml_format->{'xmlrow'};
2083 $parser = $xml_format->{'xmlkeys'};
2084 die 'no xmlkeys specified' unless ref $parser eq 'ARRAY';
2085 my $data = XML::Simple::XMLin(
2087 'SuppressEmpty' => '', #sets empty values to ''
2091 $rows = $rows->{$_} foreach @$xmlrow;
2092 $rows = [ $rows ] if ref($rows) ne 'ARRAY';
2093 $count = @buffer = @$rows;
2095 } elsif ( $type eq 'asn.1' ) {
2097 eval "use Convert::ASN1";
2100 my $asn = Convert::ASN1->new;
2101 $asn->prepare( $asn_format->{'spec'} ) or die $asn->error;
2103 $parser = $asn->find( $asn_format->{'macro'} ) or die $asn->error;
2105 my $data = slurp($file);
2106 my $asn_output = $parser->decode( $data )
2107 or return "No ". $asn_format->{'macro'}. " found\n";
2109 $asn_header_buffer = &{ $asn_format->{'header_buffer'} }( $asn_output );
2111 my $rows = &{ $asn_format->{'arrayref'} }( $asn_output );
2112 $count = @buffer = @$rows;
2115 die "Unknown file type $type\n";
2120 local $SIG{HUP} = 'IGNORE';
2121 local $SIG{INT} = 'IGNORE';
2122 local $SIG{QUIT} = 'IGNORE';
2123 local $SIG{TERM} = 'IGNORE';
2124 local $SIG{TSTP} = 'IGNORE';
2125 local $SIG{PIPE} = 'IGNORE';
2127 my $oldAutoCommit = $FS::UID::AutoCommit;
2128 local $FS::UID::AutoCommit = 0;
2131 #my $params = $param->{params} || {};
2132 if ( $param->{'batch_namecol'} && $param->{'batch_namevalue'} ) {
2133 my $batch_col = $param->{'batch_keycol'};
2135 my $batch_class = 'FS::'. $param->{'batch_table'};
2136 my $batch = $batch_class->new({
2137 $param->{'batch_namecol'} => $param->{'batch_namevalue'}
2139 my $error = $batch->insert;
2141 $dbh->rollback if $oldAutoCommit;
2142 return "can't insert batch record: $error";
2144 #primary key via dbdef? (so the column names don't have to match)
2145 my $batch_value = $batch->get( $param->{'batch_keycol'} );
2147 $params->{ $batch_col } = $batch_value;
2150 #my $job = $param->{job};
2153 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
2157 my %hash = %$params;
2158 if ( $type eq 'csv' ) {
2160 last unless scalar(@buffer);
2161 $line = shift(@buffer);
2163 next if $line =~ /^\s*$/; #skip empty lines
2165 $line = &{$row_callback}($line) if $row_callback;
2167 next if $line =~ /^\s*$/; #skip empty lines
2169 $parser->parse($line) or do {
2170 $dbh->rollback if $oldAutoCommit;
2171 return "can't parse: ". $parser->error_input() . " " . $parser->error_diag;
2173 @columns = $parser->fields();
2175 } elsif ( $type eq 'fixedlength' ) {
2177 last unless scalar(@buffer);
2178 $line = shift(@buffer);
2180 @columns = $parser->parse($line);
2182 } elsif ( $type eq 'xls' ) {
2184 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
2185 || ! $parser->{Cells}[$row];
2187 my @row = @{ $parser->{Cells}[$row] };
2188 @columns = map $_->{Val}, @row;
2191 #warn $z++. ": $_\n" for @columns;
2193 } elsif ( $type eq 'xml' ) {
2195 # $parser = [ 'Column0Key', 'Column1Key' ... ]
2196 last unless scalar(@buffer);
2197 my $row = shift @buffer;
2198 @columns = @{ $row }{ @$parser };
2200 } elsif ( $type eq 'asn.1' ) {
2202 last unless scalar(@buffer);
2203 my $row = shift @buffer;
2204 &{ $asn_format->{row_callback} }( $row, $asn_header_buffer )
2205 if $asn_format->{row_callback};
2206 foreach my $key ( keys %{ $asn_format->{map} } ) {
2207 $hash{$key} = &{ $asn_format->{map}{$key} }( $row, $asn_header_buffer );
2211 die "Unknown file type $type\n";
2216 foreach my $field ( @fields ) {
2218 my $value = shift @columns;
2220 if ( ref($field) eq 'CODE' ) {
2221 #&{$field}(\%hash, $value);
2222 push @later, $field, $value;
2224 #??? $hash{$field} = $value if length($value);
2225 $hash{$field} = $value if defined($value) && length($value);
2230 if ( $custnum_prefix && $hash{custnum} =~ /^$custnum_prefix(0*([1-9]\d*))$/
2231 && length($1) == $custnum_length ) {
2232 $hash{custnum} = $2;
2235 %hash = &{$hash_callback}(%hash) if $hash_callback;
2237 #my $table = $param->{table};
2238 my $class = "FS::$table";
2240 my $record = $class->new( \%hash );
2243 while ( scalar(@later) ) {
2244 my $sub = shift @later;
2245 my $data = shift @later;
2247 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf)
2250 $dbh->rollback if $oldAutoCommit;
2251 return "can't insert record". ( $line ? " for $line" : '' ). ": $@";
2253 last if exists( $param->{skiprow} );
2255 next if exists( $param->{skiprow} );
2257 if ( $preinsert_callback ) {
2258 my $error = &{$preinsert_callback}($record, $param);
2260 $dbh->rollback if $oldAutoCommit;
2261 return "preinsert_callback error". ( $line ? " for $line" : '' ).
2264 next if exists $param->{skiprow} && $param->{skiprow};
2267 my @insert_args = ();
2268 if ( $insert_args_callback ) {
2269 @insert_args = &{$insert_args_callback}($record, $param);
2272 my $error = $record->insert(@insert_args);
2275 $dbh->rollback if $oldAutoCommit;
2276 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
2282 if ( $postinsert_callback ) {
2283 my $error = &{$postinsert_callback}($record, $param);
2285 $dbh->rollback if $oldAutoCommit;
2286 return "postinsert_callback error". ( $line ? " for $line" : '' ).
2291 if ( $job && time - $min_sec > $last ) { #progress bar
2292 $job->update_statustext( int(100 * $imported / $count) );
2298 unless ( $imported || $param->{empty_ok} ) {
2299 $dbh->rollback if $oldAutoCommit;
2300 return "Empty file!";
2303 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2310 my( $self, $action, $time ) = @_;
2314 my %nohistory = map { $_=>1 } $self->nohistory_fields;
2317 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
2318 real_fields($self->table);
2321 # If we're encrypting then don't store the payinfo in the history
2322 if ( $conf_encryption && $self->table ne 'banned_pay' ) {
2323 @fields = grep { $_ ne 'payinfo' } @fields;
2326 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
2328 "INSERT INTO h_". $self->table. " ( ".
2329 join(', ', qw(history_date history_usernum history_action), @fields ).
2332 $FS::CurrentUser::CurrentUser->usernum,
2333 dbh->quote($action),
2342 B<Warning>: External use is B<deprecated>.
2344 Replaces COLUMN in record with a unique number, using counters in the
2345 filesystem. Used by the B<insert> method on single-field unique columns
2346 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
2347 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
2349 Returns the new value.
2354 my($self,$field) = @_;
2355 my($table)=$self->table;
2357 croak "Unique called on field $field, but it is ",
2358 $self->getfield($field),
2360 if $self->getfield($field);
2362 #warn "table $table is tainted" if is_tainted($table);
2363 #warn "field $field is tainted" if is_tainted($field);
2365 my($counter) = new File::CounterFile "$table.$field",0;
2367 my $index = $counter->inc;
2368 $index = $counter->inc while qsearchs($table, { $field=>$index } );
2370 $index =~ /^(\d*)$/;
2373 $self->setfield($field,$index);
2377 =item ut_float COLUMN
2379 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
2380 null. If there is an error, returns the error, otherwise returns false.
2385 my($self,$field)=@_ ;
2386 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
2387 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
2388 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
2389 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
2390 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2391 $self->setfield($field,$1);
2394 =item ut_floatn COLUMN
2396 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2397 null. If there is an error, returns the error, otherwise returns false.
2401 #false laziness w/ut_ipn
2403 my( $self, $field ) = @_;
2404 if ( $self->getfield($field) =~ /^()$/ ) {
2405 $self->setfield($field,'');
2408 $self->ut_float($field);
2412 =item ut_sfloat COLUMN
2414 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
2415 May not be null. If there is an error, returns the error, otherwise returns
2421 my($self,$field)=@_ ;
2422 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
2423 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
2424 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
2425 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
2426 or return "Illegal or empty (float) $field: ". $self->getfield($field);
2427 $self->setfield($field,$1);
2430 =item ut_sfloatn COLUMN
2432 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
2433 null. If there is an error, returns the error, otherwise returns false.
2438 my( $self, $field ) = @_;
2439 if ( $self->getfield($field) =~ /^()$/ ) {
2440 $self->setfield($field,'');
2443 $self->ut_sfloat($field);
2447 =item ut_snumber COLUMN
2449 Check/untaint signed numeric data (whole numbers). If there is an error,
2450 returns the error, otherwise returns false.
2455 my($self, $field) = @_;
2456 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
2457 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2458 $self->setfield($field, "$1$2");
2462 =item ut_snumbern COLUMN
2464 Check/untaint signed numeric data (whole numbers). If there is an error,
2465 returns the error, otherwise returns false.
2470 my($self, $field) = @_;
2471 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
2472 or return "Illegal (numeric) $field: ". $self->getfield($field);
2474 return "Illegal (numeric) $field: ". $self->getfield($field)
2477 $self->setfield($field, "$1$2");
2481 =item ut_number COLUMN
2483 Check/untaint simple numeric data (whole numbers). May not be null. If there
2484 is an error, returns the error, otherwise returns false.
2489 my($self,$field)=@_;
2490 $self->getfield($field) =~ /^\s*(\d+)\s*$/
2491 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
2492 $self->setfield($field,$1);
2496 =item ut_numbern COLUMN
2498 Check/untaint simple numeric data (whole numbers). May be null. If there is
2499 an error, returns the error, otherwise returns false.
2504 my($self,$field)=@_;
2505 $self->getfield($field) =~ /^\s*(\d*)\s*$/
2506 or return "Illegal (numeric) $field: ". $self->getfield($field);
2507 $self->setfield($field,$1);
2511 =item ut_decimal COLUMN[, DIGITS]
2513 Check/untaint decimal numbers (up to DIGITS decimal places. If there is an
2514 error, returns the error, otherwise returns false.
2516 =item ut_decimaln COLUMN[, DIGITS]
2518 Check/untaint decimal numbers. May be null. If there is an error, returns
2519 the error, otherwise returns false.
2524 my($self, $field, $digits) = @_;
2526 $self->getfield($field) =~ /^\s*(\d+(\.\d{0,$digits})?)\s*$/
2527 or return "Illegal or empty (decimal) $field: ".$self->getfield($field);
2528 $self->setfield($field, $1);
2533 my($self, $field, $digits) = @_;
2534 $self->getfield($field) =~ /^\s*(\d*(\.\d{0,$digits})?)\s*$/
2535 or return "Illegal (decimal) $field: ".$self->getfield($field);
2536 $self->setfield($field, $1);
2540 =item ut_money COLUMN
2542 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
2543 is an error, returns the error, otherwise returns false.
2548 my($self,$field)=@_;
2550 if ( $self->getfield($field) eq '' ) {
2551 $self->setfield($field, 0);
2552 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{1})\s*$/ ) {
2553 #handle one decimal place without barfing out
2554 $self->setfield($field, ( ($1||''). ($2||''). ($3.'0') ) || 0);
2555 } elsif ( $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/ ) {
2556 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
2558 return "Illegal (money) $field: ". $self->getfield($field);
2564 =item ut_moneyn COLUMN
2566 Check/untaint monetary numbers. May be negative. If there
2567 is an error, returns the error, otherwise returns false.
2572 my($self,$field)=@_;
2573 if ($self->getfield($field) eq '') {
2574 $self->setfield($field, '');
2577 $self->ut_money($field);
2580 =item ut_currencyn COLUMN
2582 Check/untaint currency indicators, such as USD or EUR. May be null. If there
2583 is an error, returns the error, otherwise returns false.
2588 my($self, $field) = @_;
2589 if ($self->getfield($field) eq '') { #can be null
2590 $self->setfield($field, '');
2593 $self->ut_currency($field);
2596 =item ut_currency COLUMN
2598 Check/untaint currency indicators, such as USD or EUR. May not be null. If
2599 there is an error, returns the error, otherwise returns false.
2604 my($self, $field) = @_;
2605 my $value = uc( $self->getfield($field) );
2606 if ( code2currency($value) ) {
2607 $self->setfield($value);
2609 return "Unknown currency $value";
2615 =item ut_text COLUMN
2617 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2618 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2619 May not be null. If there is an error, returns the error, otherwise returns
2625 my($self,$field)=@_;
2626 #warn "msgcat ". \&msgcat. "\n";
2627 #warn "notexist ". \¬exist. "\n";
2628 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2629 # \p{Word} = alphanumerics, marks (diacritics), and connectors
2630 # see perldoc perluniprops
2631 $self->getfield($field)
2632 =~ /^([\p{Word} \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>$money_char]+)$/
2633 or return gettext('illegal_or_empty_text'). " $field: ".
2634 $self->getfield($field);
2635 $self->setfield($field,$1);
2639 =item ut_textn COLUMN
2641 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2642 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
2643 May be null. If there is an error, returns the error, otherwise returns false.
2648 my($self,$field)=@_;
2649 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
2650 $self->ut_text($field);
2653 =item ut_alpha COLUMN
2655 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2656 an error, returns the error, otherwise returns false.
2661 my($self,$field)=@_;
2662 $self->getfield($field) =~ /^(\w+)$/
2663 or return "Illegal or empty (alphanumeric) $field: ".
2664 $self->getfield($field);
2665 $self->setfield($field,$1);
2669 =item ut_alphan COLUMN
2671 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2672 error, returns the error, otherwise returns false.
2677 my($self,$field)=@_;
2678 $self->getfield($field) =~ /^(\w*)$/
2679 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2680 $self->setfield($field,$1);
2684 =item ut_alphasn COLUMN
2686 Check/untaint alphanumeric strings, spaces allowed. May be null. If there is
2687 an error, returns the error, otherwise returns false.
2692 my($self,$field)=@_;
2693 $self->getfield($field) =~ /^([\w ]*)$/
2694 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2695 $self->setfield($field,$1);
2700 =item ut_alpha_lower COLUMN
2702 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2703 there is an error, returns the error, otherwise returns false.
2707 sub ut_alpha_lower {
2708 my($self,$field)=@_;
2709 $self->getfield($field) =~ /[[:upper:]]/
2710 and return "Uppercase characters are not permitted in $field";
2711 $self->ut_alpha($field);
2714 =item ut_phonen COLUMN [ COUNTRY ]
2716 Check/untaint phone numbers. May be null. If there is an error, returns
2717 the error, otherwise returns false.
2719 Takes an optional two-letter ISO 3166-1 alpha-2 country code; without
2720 it or with unsupported countries, ut_phonen simply calls ut_alphan.
2725 my( $self, $field, $country ) = @_;
2726 return $self->ut_alphan($field) unless defined $country;
2727 my $phonen = $self->getfield($field);
2728 if ( $phonen eq '' ) {
2729 $self->setfield($field,'');
2730 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2732 $phonen = $conf->config('cust_main-default_areacode').$phonen
2733 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2734 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2735 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2736 $phonen = "$1-$2-$3";
2737 $phonen .= " x$4" if $4;
2738 $self->setfield($field,$phonen);
2740 warn "warning: don't know how to check phone numbers for country $country";
2741 return $self->ut_textn($field);
2748 Check/untaint hexadecimal values.
2753 my($self, $field) = @_;
2754 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2755 or return "Illegal (hex) $field: ". $self->getfield($field);
2756 $self->setfield($field, uc($1));
2760 =item ut_hexn COLUMN
2762 Check/untaint hexadecimal values. May be null.
2767 my($self, $field) = @_;
2768 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2769 or return "Illegal (hex) $field: ". $self->getfield($field);
2770 $self->setfield($field, uc($1));
2774 =item ut_mac_addr COLUMN
2776 Check/untaint mac addresses. May be null.
2781 my($self, $field) = @_;
2783 my $mac = $self->get($field);
2786 $self->set($field, $mac);
2788 my $e = $self->ut_hex($field);
2791 return "Illegal (mac address) $field: ". $self->getfield($field)
2792 unless length($self->getfield($field)) == 12;
2798 =item ut_mac_addrn COLUMN
2800 Check/untaint mac addresses. May be null.
2805 my($self, $field) = @_;
2806 ($self->getfield($field) eq '') ? '' : $self->ut_mac_addr($field);
2811 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2817 my( $self, $field ) = @_;
2818 $self->setfield($field, '127.0.0.1') if $self->getfield($field) eq '::1';
2819 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2820 or return "Illegal (IP address) $field: ". $self->getfield($field);
2821 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2822 $self->setfield($field, "$1.$2.$3.$4");
2828 Check/untaint ip addresses. IPv4 only for now, though ::1 is auto-translated
2829 to 127.0.0.1. May be null.
2834 my( $self, $field ) = @_;
2835 if ( $self->getfield($field) =~ /^()$/ ) {
2836 $self->setfield($field,'');
2839 $self->ut_ip($field);
2843 =item ut_ip46 COLUMN
2845 Check/untaint IPv4 or IPv6 address.
2850 my( $self, $field ) = @_;
2851 my $ip = NetAddr::IP->new($self->getfield($field))
2852 or return "Illegal (IP address) $field: ".$self->getfield($field);
2853 $self->setfield($field, lc($ip->addr));
2859 Check/untaint IPv6 or IPv6 address. May be null.
2864 my( $self, $field ) = @_;
2865 if ( $self->getfield($field) =~ /^$/ ) {
2866 $self->setfield($field, '');
2869 $self->ut_ip46($field);
2872 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2874 Check/untaint coordinates.
2875 Accepts the following forms:
2885 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2886 The latter form (that is, the MMM are thousands of minutes) is
2887 assumed if the "MMM" is exactly three digits or two digits > 59.
2889 To be safe, just use the DDD.DDDDD form.
2891 If LOWER or UPPER are specified, then the coordinate is checked
2892 for lower and upper bounds, respectively.
2897 my ($self, $field) = (shift, shift);
2900 if ( $field =~ /latitude/ ) {
2901 $lower = $lat_lower;
2903 } elsif ( $field =~ /longitude/ ) {
2905 $upper = $lon_upper;
2908 my $coord = $self->getfield($field);
2909 my $neg = $coord =~ s/^(-)//;
2911 my ($d, $m, $s) = (0, 0, 0);
2914 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2915 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2916 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2918 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2921 return "Invalid (coordinate with minutes > 59) $field: "
2922 . $self->getfield($field);
2925 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2927 if (defined($lower) and ($coord < $lower)) {
2928 return "Invalid (coordinate < $lower) $field: "
2929 . $self->getfield($field);;
2932 if (defined($upper) and ($coord > $upper)) {
2933 return "Invalid (coordinate > $upper) $field: "
2934 . $self->getfield($field);;
2937 $self->setfield($field, $coord);
2941 return "Invalid (coordinate) $field: " . $self->getfield($field);
2945 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2947 Same as ut_coord, except optionally null.
2953 my ($self, $field) = (shift, shift);
2955 if ($self->getfield($field) =~ /^\s*$/) {
2958 return $self->ut_coord($field, @_);
2963 =item ut_domain COLUMN
2965 Check/untaint host and domain names. May not be null.
2970 my( $self, $field ) = @_;
2971 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2972 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2973 or return "Illegal (hostname) $field: ". $self->getfield($field);
2974 $self->setfield($field,$1);
2978 =item ut_domainn COLUMN
2980 Check/untaint host and domain names. May be null.
2985 my( $self, $field ) = @_;
2986 if ( $self->getfield($field) =~ /^()$/ ) {
2987 $self->setfield($field,'');
2990 $self->ut_domain($field);
2994 =item ut_name COLUMN
2996 Check/untaint proper names; allows alphanumerics, spaces and the following
2997 punctuation: , . - '
3004 my( $self, $field ) = @_;
3005 $self->getfield($field) =~ /^([\p{Word} \,\.\-\']+)$/
3006 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
3011 $self->setfield($field, $name);
3015 =item ut_namen COLUMN
3017 Check/untaint proper names; allows alphanumerics, spaces and the following
3018 punctuation: , . - '
3025 my( $self, $field ) = @_;
3026 return $self->setfield($field, '') if $self->getfield($field) =~ /^$/;
3027 $self->ut_name($field);
3032 Check/untaint zip codes.
3036 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
3039 my( $self, $field, $country ) = @_;
3041 if ( $country eq 'US' ) {
3043 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
3044 or return gettext('illegal_zip'). " $field for country $country: ".
3045 $self->getfield($field);
3046 $self->setfield($field, $1);
3048 } elsif ( $country eq 'CA' ) {
3050 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
3051 or return gettext('illegal_zip'). " $field for country $country: ".
3052 $self->getfield($field);
3053 $self->setfield($field, "$1 $2");
3057 if ( $self->getfield($field) =~ /^\s*$/
3058 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
3061 $self->setfield($field,'');
3063 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{0,8}\w)\s*$/
3064 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
3065 $self->setfield($field,$1);
3073 =item ut_country COLUMN
3075 Check/untaint country codes. Country names are changed to codes, if possible -
3076 see L<Locale::Country>.
3081 my( $self, $field ) = @_;
3082 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
3083 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
3084 && country2code($1) ) {
3085 $self->setfield($field,uc(country2code($1)));
3088 $self->getfield($field) =~ /^(\w\w)$/
3089 or return "Illegal (country) $field: ". $self->getfield($field);
3090 $self->setfield($field,uc($1));
3094 =item ut_anything COLUMN
3096 Untaints arbitrary data. Be careful.
3101 my( $self, $field ) = @_;
3102 $self->getfield($field) =~ /^(.*)$/s
3103 or return "Illegal $field: ". $self->getfield($field);
3104 $self->setfield($field,$1);
3108 =item ut_enum COLUMN CHOICES_ARRAYREF
3110 Check/untaint a column, supplying all possible choices, like the "enum" type.
3115 my( $self, $field, $choices ) = @_;
3116 foreach my $choice ( @$choices ) {
3117 if ( $self->getfield($field) eq $choice ) {
3118 $self->setfield($field, $choice);
3122 return "Illegal (enum) field $field: ". $self->getfield($field);
3125 =item ut_enumn COLUMN CHOICES_ARRAYREF
3127 Like ut_enum, except the null value is also allowed.
3132 my( $self, $field, $choices ) = @_;
3133 $self->getfield($field)
3134 ? $self->ut_enum($field, $choices)
3138 =item ut_flag COLUMN
3140 Check/untaint a column if it contains either an empty string or 'Y'. This
3141 is the standard form for boolean flags in Freeside.
3146 my( $self, $field ) = @_;
3147 my $value = uc($self->getfield($field));
3148 if ( $value eq '' or $value eq 'Y' ) {
3149 $self->setfield($field, $value);
3152 return "Illegal (flag) field $field: $value";
3155 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
3157 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
3158 on the column first.
3162 sub ut_foreign_key {
3163 my( $self, $field, $table, $foreign ) = @_;
3164 return $self->ut_number($field) if $no_check_foreign;
3165 qsearchs($table, { $foreign => $self->getfield($field) })
3166 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
3167 " in $table.$foreign";
3171 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
3173 Like ut_foreign_key, except the null value is also allowed.
3177 sub ut_foreign_keyn {
3178 my( $self, $field, $table, $foreign ) = @_;
3179 $self->getfield($field)
3180 ? $self->ut_foreign_key($field, $table, $foreign)
3184 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
3186 Checks this column as an agentnum, taking into account the current users's
3187 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
3188 right or rights allowing no agentnum.
3192 sub ut_agentnum_acl {
3193 my( $self, $field ) = (shift, shift);
3194 my $null_acl = scalar(@_) ? shift : [];
3195 $null_acl = [ $null_acl ] unless ref($null_acl);
3197 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
3198 return "Illegal agentnum: $error" if $error;
3200 my $curuser = $FS::CurrentUser::CurrentUser;
3202 if ( $self->$field() ) {
3204 return 'Access denied to agent '. $self->$field()
3205 unless $curuser->agentnum($self->$field());
3209 return 'Access denied to global'
3210 unless grep $curuser->access_right($_), @$null_acl;
3218 =item fields [ TABLE ]
3220 This is a wrapper for real_fields. Code that called
3221 fields before should probably continue to call fields.
3226 my $something = shift;
3228 if($something->isa('FS::Record')) {
3229 $table = $something->table;
3231 $table = $something;
3232 #$something = "FS::$table";
3234 return (real_fields($table));
3238 =item encrypt($value)
3240 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
3242 Returns the encrypted string.
3244 You should generally not have to worry about calling this, as the system handles this for you.
3249 my ($self, $value) = @_;
3250 my $encrypted = $value;
3252 if ($conf_encryption) {
3253 if ($self->is_encrypted($value)) {
3254 # Return the original value if it isn't plaintext.
3255 $encrypted = $value;
3258 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
3259 # RSA doesn't like the empty string so let's pack it up
3260 # The database doesn't like the RSA data so uuencode it
3261 my $length = length($value)+1;
3262 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
3264 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
3271 =item is_encrypted($value)
3273 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
3279 my ($self, $value) = @_;
3280 # could be more precise about it, but this will do for now
3281 $value =~ /^M/ && length($value) > 80;
3284 =item decrypt($value)
3286 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
3288 You should generally not have to worry about calling this, as the system handles this for you.
3293 my ($self,$value) = @_;
3294 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
3295 if ($conf_encryption && $self->is_encrypted($value)) {
3297 if (ref($rsa_decrypt) =~ /::RSA/) {
3298 my $encrypted = unpack ("u*", $value);
3299 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
3300 if ($@) {warn "Decryption Failed"};
3308 #Initialize the Module
3309 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
3311 if ($conf_encryptionmodule && $conf_encryptionmodule ne '') {
3312 $rsa_module = $conf_encryptionmodule;
3316 eval ("require $rsa_module"); # No need to import the namespace
3319 # Initialize Encryption
3320 if ($conf_encryptionpublickey && $conf_encryptionpublickey ne '') {
3321 $rsa_encrypt = $rsa_module->new_public_key($conf_encryptionpublickey);
3324 # Intitalize Decryption
3325 if ($conf_encryptionprivatekey && $conf_encryptionprivatekey ne '') {
3326 $rsa_decrypt = $rsa_module->new_private_key($conf_encryptionprivatekey);
3330 =item h_search ACTION
3332 Given an ACTION, either "insert", or "delete", returns the appropriate history
3333 record corresponding to this record, if any.
3338 my( $self, $action ) = @_;
3340 my $table = $self->table;
3343 my $primary_key = dbdef->table($table)->primary_key;
3346 'table' => "h_$table",
3347 'hashref' => { $primary_key => $self->$primary_key(),
3348 'history_action' => $action,
3356 Given an ACTION, either "insert", or "delete", returns the timestamp of the
3357 appropriate history record corresponding to this record, if any.
3362 my($self, $action) = @_;
3363 my $h = $self->h_search($action);
3364 $h ? $h->history_date : '';
3367 =item scalar_sql SQL [ PLACEHOLDER, ... ]
3369 A class or object method. Executes the sql statement represented by SQL and
3370 returns a scalar representing the result: the first column of the first row.
3372 Dies on bogus SQL. Returns an empty string if no row is returned.
3374 Typically used for statments which return a single value such as "SELECT
3375 COUNT(*) FROM table WHERE something" OR "SELECT column FROM table WHERE key = ?"
3380 my($self, $sql) = (shift, shift);
3381 my $sth = dbh->prepare($sql) or die dbh->errstr;
3383 or die "Unexpected error executing statement $sql: ". $sth->errstr;
3384 my $row = $sth->fetchrow_arrayref or return '';
3385 my $scalar = $row->[0];
3386 defined($scalar) ? $scalar : '';
3389 =item count [ WHERE [, PLACEHOLDER ...] ]
3391 Convenience method for the common case of "SELECT COUNT(*) FROM table",
3392 with optional WHERE. Must be called as method on a class with an
3398 my($self, $where) = (shift, shift);
3399 my $table = $self->table or die 'count called on object of class '.ref($self);
3400 my $sql = "SELECT COUNT(*) FROM $table";
3401 $sql .= " WHERE $where" if $where;
3402 $self->scalar_sql($sql, @_);
3405 =item row_exists [ WHERE [, PLACEHOLDER ...] ]
3407 Convenience method for the common case of "SELECT 1 FROM table ... LIMIT 1"
3408 with optional (but almost always needed) WHERE.
3413 my($self, $where) = (shift, shift);
3414 my $table = $self->table or die 'row_exists called on object of class '.ref($self);
3415 my $sql = "SELECT 1 FROM $table";
3416 $sql .= " WHERE $where" if $where;
3418 $self->scalar_sql($sql, @_);
3427 =item real_fields [ TABLE ]
3429 Returns a list of the real columns in the specified table. Called only by
3430 fields() and other subroutines elsewhere in FS::Record.
3437 my($table_obj) = dbdef->table($table);
3438 confess "Unknown table $table" unless $table_obj;
3439 $table_obj->columns;
3442 =item pvf FIELD_NAME
3444 Returns the FS::part_virtual_field object corresponding to a field in the
3445 record (specified by FIELD_NAME).
3450 my ($self, $name) = (shift, shift);
3452 if(grep /^$name$/, $self->virtual_fields) {
3454 my $concat = [ "'cf_'", "name" ];
3455 return qsearchs({ table => 'part_virtual_field',
3456 hashref => { dbtable => $self->table,
3459 select => 'vfieldpart, dbtable, length, label, '.concat_sql($concat).' as name',
3465 =item _quote VALUE, TABLE, COLUMN
3467 This is an internal function used to construct SQL statements. It returns
3468 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
3469 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
3474 my($value, $table, $column) = @_;
3475 my $column_obj = dbdef->table($table)->column($column);
3476 my $column_type = $column_obj->type;
3477 my $nullable = $column_obj->null;
3479 utf8::upgrade($value);
3481 warn " $table.$column: $value ($column_type".
3482 ( $nullable ? ' NULL' : ' NOT NULL' ).
3483 ")\n" if $DEBUG > 2;
3485 if ( $value eq '' && $nullable ) {
3487 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
3488 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
3491 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
3492 ! $column_type =~ /(char|binary|text)$/i ) {
3494 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
3495 && driver_name eq 'Pg'
3499 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
3500 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
3501 # single-quote the whole mess, and put an "E" in front.
3502 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
3510 This is deprecated. Don't use it.
3512 It returns a hash-type list with the fields of this record's table set true.
3517 carp "warning: hfields is deprecated";
3520 foreach (fields($table)) {
3529 "$_: ". $self->getfield($_). "|"
3530 } (fields($self->table)) );
3533 sub DESTROY { return; }
3537 # #use Carp qw(cluck);
3538 # #cluck "DESTROYING $self";
3539 # warn "DESTROYING $self";
3543 # return ! eval { join('',@_), kill 0; 1; };
3546 =item str2time_sql [ DRIVER_NAME ]
3548 Returns a function to convert to unix time based on database type, such as
3549 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
3550 the str2time_sql_closing method to return a closing string rather than just
3551 using a closing parenthesis as previously suggested.
3553 You can pass an optional driver name such as "Pg", "mysql" or
3554 $dbh->{Driver}->{Name} to return a function for that database instead of
3555 the current database.
3560 my $driver = shift || driver_name;
3562 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
3563 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
3565 warn "warning: unknown database type $driver; guessing how to convert ".
3566 "dates to UNIX timestamps";
3567 return 'EXTRACT(EPOCH FROM ';
3571 =item str2time_sql_closing [ DRIVER_NAME ]
3573 Returns the closing suffix of a function to convert to unix time based on
3574 database type, such as ")::integer" for Pg or ")" for mysql.
3576 You can pass an optional driver name such as "Pg", "mysql" or
3577 $dbh->{Driver}->{Name} to return a function for that database instead of
3578 the current database.
3582 sub str2time_sql_closing {
3583 my $driver = shift || driver_name;
3585 return ' )::INTEGER ' if $driver =~ /^Pg/i;
3589 =item regexp_sql [ DRIVER_NAME ]
3591 Returns the operator to do a regular expression comparison based on database
3592 type, such as '~' for Pg or 'REGEXP' for mysql.
3594 You can pass an optional driver name such as "Pg", "mysql" or
3595 $dbh->{Driver}->{Name} to return a function for that database instead of
3596 the current database.
3601 my $driver = shift || driver_name;
3603 return '~' if $driver =~ /^Pg/i;
3604 return 'REGEXP' if $driver =~ /^mysql/i;
3606 die "don't know how to use regular expressions in ". driver_name." databases";
3610 =item not_regexp_sql [ DRIVER_NAME ]
3612 Returns the operator to do a regular expression negation based on database
3613 type, such as '!~' for Pg or 'NOT REGEXP' for mysql.
3615 You can pass an optional driver name such as "Pg", "mysql" or
3616 $dbh->{Driver}->{Name} to return a function for that database instead of
3617 the current database.
3621 sub not_regexp_sql {
3622 my $driver = shift || driver_name;
3624 return '!~' if $driver =~ /^Pg/i;
3625 return 'NOT REGEXP' if $driver =~ /^mysql/i;
3627 die "don't know how to use regular expressions in ". driver_name." databases";
3631 =item concat_sql [ DRIVER_NAME ] ITEMS_ARRAYREF
3633 Returns the items concatenated based on database type, using "CONCAT()" for
3634 mysql and " || " for Pg and other databases.
3636 You can pass an optional driver name such as "Pg", "mysql" or
3637 $dbh->{Driver}->{Name} to return a function for that database instead of
3638 the current database.
3643 my $driver = ref($_[0]) ? driver_name : shift;
3646 if ( $driver =~ /^mysql/i ) {
3647 'CONCAT('. join(',', @$items). ')';
3649 join('||', @$items);
3654 =item group_concat_sql COLUMN, DELIMITER
3656 Returns an SQL expression to concatenate an aggregate column, using
3657 GROUP_CONCAT() for mysql and array_to_string() and array_agg() for Pg.
3661 sub group_concat_sql {
3662 my ($col, $delim) = @_;
3663 $delim = dbh->quote($delim);
3664 if ( driver_name() =~ /^mysql/i ) {
3665 # DISTINCT(foo) is valid as $col
3666 return "GROUP_CONCAT($col SEPARATOR $delim)";
3668 return "array_to_string(array_agg($col), $delim)";
3672 =item midnight_sql DATE
3674 Returns an SQL expression to convert DATE (a unix timestamp) to midnight
3675 on that day in the system timezone, using the default driver name.
3680 my $driver = driver_name;
3682 if ( $driver =~ /^mysql/i ) {
3683 "UNIX_TIMESTAMP(DATE(FROM_UNIXTIME($expr)))";
3686 "EXTRACT( EPOCH FROM DATE(TO_TIMESTAMP($expr)) )";
3694 This module should probably be renamed, since much of the functionality is
3695 of general use. It is not completely unlike Adapter::DBI (see below).
3697 Exported qsearch and qsearchs should be deprecated in favor of method calls
3698 (against an FS::Record object like the old search and searchs that qsearch
3699 and qsearchs were on top of.)
3701 The whole fields / hfields mess should be removed.
3703 The various WHERE clauses should be subroutined.
3705 table string should be deprecated in favor of DBIx::DBSchema::Table.
3707 No doubt we could benefit from a Tied hash. Documenting how exists / defined
3708 true maps to the database (and WHERE clauses) would also help.
3710 The ut_ methods should ask the dbdef for a default length.
3712 ut_sqltype (like ut_varchar) should all be defined
3714 A fallback check method should be provided which uses the dbdef.
3716 The ut_money method assumes money has two decimal digits.
3718 The Pg money kludge in the new method only strips `$'.
3720 The ut_phonen method only checks US-style phone numbers.
3722 The _quote function should probably use ut_float instead of a regex.
3724 All the subroutines probably should be methods, here or elsewhere.
3726 Probably should borrow/use some dbdef methods where appropriate (like sub
3729 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
3730 or allow it to be set. Working around it is ugly any way around - DBI should
3731 be fixed. (only affects RDBMS which return uppercase column names)
3733 ut_zip should take an optional country like ut_phone.
3737 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
3739 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.