4 use vars qw( $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $conf $conf_encryption $me
7 $nowarn_identical $nowarn_classload
8 $no_update_diff $no_check_foreign
11 use Carp qw(carp cluck croak confess);
12 use Scalar::Util qw( blessed );
13 use File::CounterFile;
16 use File::Slurp qw( slurp );
17 use DBI qw(:sql_types);
18 use DBIx::DBSchema 0.33;
19 use FS::UID qw(dbh getotaker datasrc driver_name);
21 use FS::Schema qw(dbdef);
23 use FS::Msgcat qw(gettext);
24 #use FS::Conf; #dependency loop bs, in install_callback below instead
26 use FS::part_virtual_field;
32 #export dbdef for now... everything else expects to find it here
33 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch
34 str2time_sql str2time_sql_closing );
39 $nowarn_identical = 0;
40 $nowarn_classload = 0;
42 $no_check_foreign = 0;
50 $conf_encryption = '';
51 FS::UID->install_callback( sub {
54 $conf = FS::Conf->new;
55 $conf_encryption = $conf->exists('encryption');
56 $File::CounterFile::DEFAULT_DIR = $conf->base_dir . "/counters.". datasrc;
57 if ( driver_name eq 'Pg' ) {
58 eval "use DBD::Pg ':pg_types'";
61 eval "sub PG_BYTEA { die 'guru meditation #9: calling PG_BYTEA when not running Pg?'; }";
67 FS::Record - Database record objects
72 use FS::Record qw(dbh fields qsearch qsearchs);
74 $record = new FS::Record 'table', \%hash;
75 $record = new FS::Record 'table', { 'column' => 'value', ... };
77 $record = qsearchs FS::Record 'table', \%hash;
78 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
79 @records = qsearch FS::Record 'table', \%hash;
80 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
82 $table = $record->table;
83 $dbdef_table = $record->dbdef_table;
85 $value = $record->get('column');
86 $value = $record->getfield('column');
87 $value = $record->column;
89 $record->set( 'column' => 'value' );
90 $record->setfield( 'column' => 'value' );
91 $record->column('value');
93 %hash = $record->hash;
95 $hashref = $record->hashref;
97 $error = $record->insert;
99 $error = $record->delete;
101 $error = $new_record->replace($old_record);
103 # external use deprecated - handled by the database (at least for Pg, mysql)
104 $value = $record->unique('column');
106 $error = $record->ut_float('column');
107 $error = $record->ut_floatn('column');
108 $error = $record->ut_number('column');
109 $error = $record->ut_numbern('column');
110 $error = $record->ut_snumber('column');
111 $error = $record->ut_snumbern('column');
112 $error = $record->ut_money('column');
113 $error = $record->ut_text('column');
114 $error = $record->ut_textn('column');
115 $error = $record->ut_alpha('column');
116 $error = $record->ut_alphan('column');
117 $error = $record->ut_phonen('column');
118 $error = $record->ut_anything('column');
119 $error = $record->ut_name('column');
121 $quoted_value = _quote($value,'table','field');
124 $fields = hfields('table');
125 if ( $fields->{Field} ) { # etc.
127 @fields = fields 'table'; #as a subroutine
128 @fields = $record->fields; #as a method call
133 (Mostly) object-oriented interface to database records. Records are currently
134 implemented on top of DBI. FS::Record is intended as a base class for
135 table-specific classes to inherit from, i.e. FS::cust_main.
141 =item new [ TABLE, ] HASHREF
143 Creates a new record. It doesn't store it in the database, though. See
144 L<"insert"> for that.
146 Note that the object stores this hash reference, not a distinct copy of the
147 hash it points to. You can ask the object for a copy with the I<hash>
150 TABLE can only be omitted when a dervived class overrides the table method.
156 my $class = ref($proto) || $proto;
158 bless ($self, $class);
160 unless ( defined ( $self->table ) ) {
161 $self->{'Table'} = shift;
162 carp "warning: FS::Record::new called with table name ". $self->{'Table'}
163 unless $nowarn_classload;
166 $self->{'Hash'} = shift;
168 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
169 $self->{'Hash'}{$field}='';
172 $self->_rebless if $self->can('_rebless');
174 $self->{'modified'} = 0;
176 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
183 my $class = ref($proto) || $proto;
185 bless ($self, $class);
187 $self->{'Table'} = shift unless defined ( $self->table );
189 my $hashref = $self->{'Hash'} = shift;
191 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
192 my $obj = $cache->cache->{$hashref->{$cache->key}};
193 $obj->_cache($hashref, $cache) if $obj->can('_cache');
196 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
203 my $class = ref($proto) || $proto;
205 bless ($self, $class);
206 if ( defined $self->table ) {
207 cluck "create constructor is deprecated, use new!";
210 croak "FS::Record::create called (not from a subclass)!";
214 =item qsearch PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
216 Searches the database for all records matching (at least) the key/value pairs
217 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
218 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
221 The preferred usage is to pass a hash reference of named parameters:
223 @records = qsearch( {
224 'table' => 'table_name',
225 'hashref' => { 'field' => 'value'
226 'field' => { 'op' => '<',
231 #these are optional...
233 'extra_sql' => 'AND field = ? AND intfield = ?',
234 'extra_param' => [ 'value', [ 5, 'int' ] ],
235 'order_by' => 'ORDER BY something',
236 #'cache_obj' => '', #optional
237 'addl_from' => 'LEFT JOIN othtable USING ( field )',
242 Much code still uses old-style positional parameters, this is also probably
243 fine in the common case where there are only two parameters:
245 my @records = qsearch( 'table', { 'field' => 'value' } );
247 ###oops, argh, FS::Record::new only lets us create database fields.
248 #Normal behaviour if SELECT is not specified is `*', as in
249 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
250 #feature where you can specify SELECT - remember, the objects returned,
251 #although blessed into the appropriate `FS::TABLE' package, will only have the
252 #fields you specify. This might have unwanted results if you then go calling
253 #regular FS::TABLE methods
258 my %TYPE = (); #for debugging
261 my($type, $value) = @_;
263 my $bind_type = { TYPE => SQL_VARCHAR };
265 if ( $type =~ /(big)?(int|serial)/i && $value =~ /^\d+(\.\d+)?$/ ) {
267 $bind_type = { TYPE => SQL_INTEGER };
269 } elsif ( $type =~ /^bytea$/i || $type =~ /(blob|varbinary)/i ) {
271 if ( driver_name eq 'Pg' ) {
273 $bind_type = { pg_type => PG_BYTEA };
275 # $bind_type = ? #SQL_VARCHAR could be fine?
278 #DBD::Pg 1.49: Cannot bind ... unknown sql_type 6 with SQL_FLOAT
279 #fixed by DBD::Pg 2.11.8
280 #can change back to SQL_FLOAT in early-mid 2010, once everyone's upgraded
281 #(make a Tron test first)
282 } elsif ( _is_fs_float( $type, $value ) ) {
284 $bind_type = { TYPE => SQL_DECIMAL };
293 my($type, $value) = @_;
294 if ( ( $type =~ /(numeric)/i && $value =~ /^[+-]?\d+(\.\d+)?$/ ) ||
295 ( $type =~ /(real|float4)/i && $value =~ /[-+]?\d*\.?\d+([eE][-+]?\d+)?/)
303 my($stable, $record, $cache );
304 my( $select, $extra_sql, $extra_param, $order_by, $addl_from );
306 if ( ref($_[0]) ) { #hashref for now, eventually maybe accept a list too
308 $stable = $opt->{'table'} or die "table name is required";
309 $record = $opt->{'hashref'} || {};
310 $select = $opt->{'select'} || '*';
311 $extra_sql = $opt->{'extra_sql'} || '';
312 $extra_param = $opt->{'extra_param'} || [];
313 $order_by = $opt->{'order_by'} || '';
314 $cache = $opt->{'cache_obj'} || '';
315 $addl_from = $opt->{'addl_from'} || '';
316 $debug = $opt->{'debug'} || '';
318 ($stable, $record, $select, $extra_sql, $cache, $addl_from ) = @_;
322 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
324 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
328 my $table = $cache ? $cache->table : $stable;
329 my $dbdef_table = dbdef->table($table)
330 or die "No schema for table $table found - ".
331 "do you need to run freeside-upgrade?";
332 my $pkey = $dbdef_table->primary_key;
334 my @real_fields = grep exists($record->{$_}), real_fields($table);
336 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
337 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
339 cluck "warning: FS::$table not loaded; virtual fields not searchable"
340 unless $nowarn_classload;
341 @virtual_fields = ();
344 my $statement = "SELECT $select FROM $stable";
345 $statement .= " $addl_from" if $addl_from;
346 if ( @real_fields or @virtual_fields ) {
347 $statement .= ' WHERE '. join(' AND ',
348 get_real_fields($table, $record, \@real_fields) ,
349 get_virtual_fields($table, $pkey, $record, \@virtual_fields),
353 $statement .= " $extra_sql" if defined($extra_sql);
354 $statement .= " $order_by" if defined($order_by);
356 warn "[debug]$me $statement\n" if $DEBUG > 1 || $debug;
357 my $sth = $dbh->prepare($statement)
358 or croak "$dbh->errstr doing $statement";
363 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
366 my $value = $record->{$field};
367 my $op = (ref($value) && $value->{op}) ? $value->{op} : '=';
368 $value = $value->{'value'} if ref($value);
369 my $type = dbdef->table($table)->column($field)->type;
371 my $bind_type = _bind_type($type, $value);
375 # %TYPE = map { &{"DBI::$_"}() => $_ } @{ $DBI::EXPORT_TAGS{sql_types} }
377 # warn " bind_param $bind (for field $field), $value, TYPE $TYPE{$TYPE}\n";
380 #if this needs to be re-enabled, it needs to use a custom op like
381 #"APPROX=" or something (better name?, not '=', to avoid affecting other
383 #if ($TYPE eq SQL_DECIMAL && $op eq 'APPROX=' ) {
384 # # these values are arbitrary; better (faster?) ones welcome
385 # $sth->bind_param($bind++, $value*1.00001, { TYPE => $TYPE } );
386 # $sth->bind_param($bind++, $value*.99999, { TYPE => $TYPE } );
388 $sth->bind_param($bind++, $value, $bind_type );
393 foreach my $param ( @$extra_param ) {
394 my $bind_type = { TYPE => SQL_VARCHAR };
397 $value = $param->[0];
398 my $type = $param->[1];
399 $bind_type = _bind_type($type, $value);
401 $sth->bind_param($bind++, $value, $bind_type );
404 # $sth->execute( map $record->{$_},
405 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
406 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
408 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
410 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
411 @virtual_fields = "FS::$table"->virtual_fields;
413 cluck "warning: FS::$table not loaded; virtual fields not returned either"
414 unless $nowarn_classload;
415 @virtual_fields = ();
419 tie %result, "Tie::IxHash";
420 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
421 if ( $pkey && scalar(@stuff) && $stuff[0]->{$pkey} ) {
422 %result = map { $_->{$pkey}, $_ } @stuff;
424 @result{@stuff} = @stuff;
429 if ( keys(%result) and @virtual_fields ) {
431 "SELECT virtual_field.recnum, part_virtual_field.name, ".
432 "virtual_field.value ".
433 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
434 "WHERE part_virtual_field.dbtable = '$table' AND ".
435 "virtual_field.recnum IN (".
436 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
437 join(q!', '!, @virtual_fields) . "')";
438 warn "[debug]$me $statement\n" if $DEBUG > 1;
439 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
440 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
442 foreach (@{ $sth->fetchall_arrayref({}) }) {
443 my $recnum = $_->{recnum};
444 my $name = $_->{name};
445 my $value = $_->{value};
446 if (exists($result{$recnum})) {
447 $result{$recnum}->{$name} = $value;
452 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
453 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
454 #derivied class didn't override new method, so this optimization is safe
457 new_or_cached( "FS::$table", { %{$_} }, $cache )
461 new( "FS::$table", { %{$_} } )
465 #okay, its been tested
466 # warn "untested code (class FS::$table uses custom new method)";
468 eval 'FS::'. $table. '->new( { %{$_} } )';
472 # Check for encrypted fields and decrypt them.
473 ## only in the local copy, not the cached object
474 if ( $conf_encryption
475 && eval 'defined(@FS::'. $table . '::encrypted_fields)' ) {
476 foreach my $record (@return) {
477 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
478 # Set it directly... This may cause a problem in the future...
479 $record->setfield($field, $record->decrypt($record->getfield($field)));
484 cluck "warning: FS::$table not loaded; returning FS::Record objects"
485 unless $nowarn_classload;
487 FS::Record->new( $table, { %{$_} } );
493 ## makes this easier to read
495 sub get_virtual_fields {
499 my $virtual_fields = shift;
505 if ( ref($record->{$_}) ) {
506 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
507 if ( uc($op) eq 'ILIKE' ) {
509 $record->{$_}{'value'} = lc($record->{$_}{'value'});
510 $column = "LOWER($_)";
512 $record->{$_} = $record->{$_}{'value'};
515 # ... EXISTS ( SELECT name, value FROM part_virtual_field
517 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
518 # WHERE recnum = svc_acct.svcnum
519 # AND (name, value) = ('egad', 'brain') )
521 my $value = $record->{$_};
525 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
526 "( SELECT part_virtual_field.name, virtual_field.value ".
527 "FROM part_virtual_field JOIN virtual_field ".
528 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
529 "WHERE virtual_field.recnum = ${table}.${pkey} ".
530 "AND part_virtual_field.name = '${column}'".
532 " AND virtual_field.value ${op} '${value}'"
536 } @{ $virtual_fields } ) ;
539 sub get_real_fields {
542 my $real_fields = shift;
544 ## this huge map was previously inline, just broke it out to help read the qsearch method, should be optimized for readability
550 my $type = dbdef->table($table)->column($column)->type;
551 my $value = $record->{$column};
552 $value = $value->{'value'} if ref($value);
553 if ( ref($record->{$_}) ) {
554 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
555 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
556 if ( uc($op) eq 'ILIKE' ) {
558 $record->{$_}{'value'} = lc($record->{$_}{'value'});
559 $column = "LOWER($_)";
561 $record->{$_} = $record->{$_}{'value'}
564 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
566 if ( driver_name eq 'Pg' ) {
567 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
568 qq-( $column IS NULL )-;
570 qq-( $column IS NULL OR $column = '' )-;
573 qq-( $column IS NULL OR $column = "" )-;
575 } elsif ( $op eq '!=' ) {
576 if ( driver_name eq 'Pg' ) {
577 if ( $type =~ /(int|numeric|real|float4|(big)?serial)/i ) {
578 qq-( $column IS NOT NULL )-;
580 qq-( $column IS NOT NULL AND $column != '' )-;
583 qq-( $column IS NOT NULL AND $column != "" )-;
586 if ( driver_name eq 'Pg' ) {
587 qq-( $column $op '' )-;
589 qq-( $column $op "" )-;
592 #if this needs to be re-enabled, it needs to use a custom op like
593 #"APPROX=" or something (better name?, not '=', to avoid affecting other
595 #} elsif ( $op eq 'APPROX=' && _is_fs_float( $type, $value ) ) {
596 # ( "$column <= ?", "$column >= ?" );
600 } @{ $real_fields } );
603 =item by_key PRIMARY_KEY_VALUE
605 This is a class method that returns the record with the given primary key
606 value. This method is only useful in FS::Record subclasses. For example:
608 my $cust_main = FS::cust_main->by_key(1); # retrieve customer with custnum 1
612 my $cust_main = qsearchs('cust_main', { 'custnum' => 1 } );
617 my ($class, $pkey_value) = @_;
619 my $table = $class->table
620 or croak "No table for $class found";
622 my $dbdef_table = dbdef->table($table)
623 or die "No schema for table $table found - ".
624 "do you need to create it or run dbdef-create?";
625 my $pkey = $dbdef_table->primary_key
626 or die "No primary key for table $table";
628 return qsearchs($table, { $pkey => $pkey_value });
631 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
633 Experimental JOINed search method. Using this method, you can execute a
634 single SELECT spanning multiple tables, and cache the results for subsequent
635 method calls. Interface will almost definately change in an incompatible
643 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
644 my $cache = FS::SearchCache->new( $ptable, $pkey );
647 grep { !$saw{$_->getfield($pkey)}++ }
648 qsearch($table, $record, $select, $extra_sql, $cache )
652 =item qsearchs PARAMS_HASHREF | TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ, ADDL_FROM
654 Same as qsearch, except that if more than one record matches, it B<carp>s but
655 returns the first. If this happens, you either made a logic error in asking
656 for a single item, or your data is corrupted.
660 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
662 my(@result) = qsearch(@_);
663 cluck "warning: Multiple records in scalar search ($table)"
664 if scalar(@result) > 1;
665 #should warn more vehemently if the search was on a primary key?
666 scalar(@result) ? ($result[0]) : ();
677 Returns the table name.
682 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
689 Returns the DBIx::DBSchema::Table object for the table.
695 my($table)=$self->table;
696 dbdef->table($table);
701 Returns the primary key for the table.
707 my $pkey = $self->dbdef_table->primary_key;
710 =item get, getfield COLUMN
712 Returns the value of the column/field/key COLUMN.
717 my($self,$field) = @_;
718 # to avoid "Use of unitialized value" errors
719 if ( defined ( $self->{Hash}->{$field} ) ) {
720 $self->{Hash}->{$field};
730 =item set, setfield COLUMN, VALUE
732 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
737 my($self,$field,$value) = @_;
738 $self->{'modified'} = 1;
739 $self->{'Hash'}->{$field} = $value;
746 =item AUTLOADED METHODS
748 $record->column is a synonym for $record->get('column');
750 $record->column('value') is a synonym for $record->set('column','value');
757 my($field)=$AUTOLOAD;
759 if ( defined($value) ) {
760 confess "errant AUTOLOAD $field for $self (arg $value)"
761 unless blessed($self) && $self->can('setfield');
762 $self->setfield($field,$value);
764 confess "errant AUTOLOAD $field for $self (no args)"
765 unless blessed($self) && $self->can('getfield');
766 $self->getfield($field);
772 # my $field = $AUTOLOAD;
774 # if ( defined($_[1]) ) {
775 # $_[0]->setfield($field, $_[1]);
777 # $_[0]->getfield($field);
783 Returns a list of the column/value pairs, usually for assigning to a new hash.
785 To make a distinct duplicate of an FS::Record object, you can do:
787 $new = new FS::Record ( $old->table, { $old->hash } );
793 confess $self. ' -> hash: Hash attribute is undefined'
794 unless defined($self->{'Hash'});
795 %{ $self->{'Hash'} };
800 Returns a reference to the column/value hash. This may be deprecated in the
801 future; if there's a reason you can't just use the autoloaded or get/set
813 Returns true if any of this object's values have been modified with set (or via
814 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
824 =item select_for_update
826 Selects this record with the SQL "FOR UPDATE" command. This can be useful as
831 sub select_for_update {
833 my $primary_key = $self->primary_key;
836 'table' => $self->table,
837 'hashref' => { $primary_key => $self->$primary_key() },
838 'extra_sql' => 'FOR UPDATE',
844 Locks this table with a database-driver specific lock method. This is used
845 as a mutex in order to do a duplicate search.
847 For PostgreSQL, does "LOCK TABLE tablename IN SHARE ROW EXCLUSIVE MODE".
849 For MySQL, does a SELECT FOR UPDATE on the duplicate_lock table.
851 Errors are fatal; no useful return value.
853 Note: To use this method for new tables other than svc_acct and svc_phone,
854 edit freeside-upgrade and add those tables to the duplicate_lock list.
860 my $table = $self->table;
862 warn "$me locking $table table\n" if $DEBUG;
864 if ( driver_name =~ /^Pg/i ) {
866 dbh->do("LOCK TABLE $table IN SHARE ROW EXCLUSIVE MODE")
869 } elsif ( driver_name =~ /^mysql/i ) {
871 dbh->do("SELECT * FROM duplicate_lock
872 WHERE lockname = '$table'
874 ) or die dbh->errstr;
878 die "unknown database ". driver_name. "; don't know how to lock table";
882 warn "$me acquired $table table lock\n" if $DEBUG;
888 Inserts this record to the database. If there is an error, returns the error,
889 otherwise returns false.
897 warn "$self -> insert" if $DEBUG;
899 my $error = $self->check;
900 return $error if $error;
902 #single-field unique keys are given a value if false
903 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
904 foreach ( $self->dbdef_table->unique_singles) {
905 $self->unique($_) unless $self->getfield($_);
908 #and also the primary key, if the database isn't going to
909 my $primary_key = $self->dbdef_table->primary_key;
911 if ( $primary_key ) {
912 my $col = $self->dbdef_table->column($primary_key);
915 uc($col->type) =~ /^(BIG)?SERIAL\d?/
916 || ( driver_name eq 'Pg'
917 && defined($col->default)
918 && $col->default =~ /^nextval\(/i
920 || ( driver_name eq 'mysql'
921 && defined($col->local)
922 && $col->local =~ /AUTO_INCREMENT/i
924 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
927 my $table = $self->table;
929 # Encrypt before the database
930 if ( defined(eval '@FS::'. $table . '::encrypted_fields')
931 && scalar( eval '@FS::'. $table . '::encrypted_fields')
932 && $conf->exists('encryption')
934 foreach my $field (eval '@FS::'. $table . '::encrypted_fields') {
935 $self->{'saved'} = $self->getfield($field);
936 $self->setfield($field, $self->encrypt($self->getfield($field)));
940 #false laziness w/delete
942 grep { defined($self->getfield($_)) && $self->getfield($_) ne "" }
945 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
948 my $statement = "INSERT INTO $table ";
949 if ( @real_fields ) {
952 join( ', ', @real_fields ).
954 join( ', ', @values ).
958 $statement .= 'DEFAULT VALUES';
960 warn "[debug]$me $statement\n" if $DEBUG > 1;
961 my $sth = dbh->prepare($statement) or return dbh->errstr;
963 local $SIG{HUP} = 'IGNORE';
964 local $SIG{INT} = 'IGNORE';
965 local $SIG{QUIT} = 'IGNORE';
966 local $SIG{TERM} = 'IGNORE';
967 local $SIG{TSTP} = 'IGNORE';
968 local $SIG{PIPE} = 'IGNORE';
970 $sth->execute or return $sth->errstr;
972 # get inserted id from the database, if applicable & needed
973 if ( $db_seq && ! $self->getfield($primary_key) ) {
974 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
978 if ( driver_name eq 'Pg' ) {
980 #my $oid = $sth->{'pg_oid_status'};
981 #my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
983 my $default = $self->dbdef_table->column($primary_key)->default;
984 unless ( $default =~ /^nextval\(\(?'"?([\w\.]+)"?'/i ) {
985 dbh->rollback if $FS::UID::AutoCommit;
986 return "can't parse $table.$primary_key default value".
987 " for sequence name: $default";
991 my $i_sql = "SELECT currval('$sequence')";
992 my $i_sth = dbh->prepare($i_sql) or do {
993 dbh->rollback if $FS::UID::AutoCommit;
996 $i_sth->execute() or do { #$i_sth->execute($oid)
997 dbh->rollback if $FS::UID::AutoCommit;
998 return $i_sth->errstr;
1000 $insertid = $i_sth->fetchrow_arrayref->[0];
1002 } elsif ( driver_name eq 'mysql' ) {
1004 $insertid = dbh->{'mysql_insertid'};
1005 # work around mysql_insertid being null some of the time, ala RT :/
1006 unless ( $insertid ) {
1007 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
1008 "using SELECT LAST_INSERT_ID();";
1009 my $i_sql = "SELECT LAST_INSERT_ID()";
1010 my $i_sth = dbh->prepare($i_sql) or do {
1011 dbh->rollback if $FS::UID::AutoCommit;
1014 $i_sth->execute or do {
1015 dbh->rollback if $FS::UID::AutoCommit;
1016 return $i_sth->errstr;
1018 $insertid = $i_sth->fetchrow_arrayref->[0];
1023 dbh->rollback if $FS::UID::AutoCommit;
1024 return "don't know how to retreive inserted ids from ". driver_name.
1025 ", try using counterfiles (maybe run dbdef-create?)";
1029 $self->setfield($primary_key, $insertid);
1033 my @virtual_fields =
1034 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1035 $self->virtual_fields;
1036 if (@virtual_fields) {
1037 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
1039 my $vfieldpart = $self->vfieldpart_hashref;
1041 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
1044 my $v_sth = dbh->prepare($v_statement) or do {
1045 dbh->rollback if $FS::UID::AutoCommit;
1049 foreach (keys(%v_values)) {
1050 $v_sth->execute($self->getfield($primary_key),
1054 dbh->rollback if $FS::UID::AutoCommit;
1055 return $v_sth->errstr;
1062 if ( defined dbdef->table('h_'. $table) ) {
1063 my $h_statement = $self->_h_statement('insert');
1064 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1065 $h_sth = dbh->prepare($h_statement) or do {
1066 dbh->rollback if $FS::UID::AutoCommit;
1072 $h_sth->execute or return $h_sth->errstr if $h_sth;
1074 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1076 # Now that it has been saved, reset the encrypted fields so that $new
1077 # can still be used.
1078 foreach my $field (keys %{$saved}) {
1079 $self->setfield($field, $saved->{$field});
1087 Depriciated (use insert instead).
1092 cluck "warning: FS::Record::add deprecated!";
1093 insert @_; #call method in this scope
1098 Delete this record from the database. If there is an error, returns the error,
1099 otherwise returns false.
1106 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
1108 $self->getfield($_) eq ''
1109 #? "( $_ IS NULL OR $_ = \"\" )"
1110 ? ( driver_name eq 'Pg'
1112 : "( $_ IS NULL OR $_ = \"\" )"
1114 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
1115 } ( $self->dbdef_table->primary_key )
1116 ? ( $self->dbdef_table->primary_key)
1117 : real_fields($self->table)
1119 warn "[debug]$me $statement\n" if $DEBUG > 1;
1120 my $sth = dbh->prepare($statement) or return dbh->errstr;
1123 if ( defined dbdef->table('h_'. $self->table) ) {
1124 my $h_statement = $self->_h_statement('delete');
1125 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
1126 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
1131 my $primary_key = $self->dbdef_table->primary_key;
1134 my $vfp = $self->vfieldpart_hashref;
1135 foreach($self->virtual_fields) {
1136 next if $self->getfield($_) eq '';
1137 unless(@del_vfields) {
1138 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
1139 $v_sth = dbh->prepare($st) or return dbh->errstr;
1141 push @del_vfields, $_;
1144 local $SIG{HUP} = 'IGNORE';
1145 local $SIG{INT} = 'IGNORE';
1146 local $SIG{QUIT} = 'IGNORE';
1147 local $SIG{TERM} = 'IGNORE';
1148 local $SIG{TSTP} = 'IGNORE';
1149 local $SIG{PIPE} = 'IGNORE';
1151 my $rc = $sth->execute or return $sth->errstr;
1152 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
1153 $h_sth->execute or return $h_sth->errstr if $h_sth;
1154 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
1155 or return $v_sth->errstr
1156 foreach (@del_vfields);
1158 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1160 #no need to needlessly destoy the data either (causes problems actually)
1161 #undef $self; #no need to keep object!
1168 Depriciated (use delete instead).
1173 cluck "warning: FS::Record::del deprecated!";
1174 &delete(@_); #call method in this scope
1177 =item replace OLD_RECORD
1179 Replace the OLD_RECORD with this one in the database. If there is an error,
1180 returns the error, otherwise returns false.
1185 my ($new, $old) = (shift, shift);
1187 $old = $new->replace_old unless defined($old);
1189 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
1191 if ( $new->can('replace_check') ) {
1192 my $error = $new->replace_check($old);
1193 return $error if $error;
1196 return "Records not in same table!" unless $new->table eq $old->table;
1198 my $primary_key = $old->dbdef_table->primary_key;
1199 return "Can't change primary key $primary_key ".
1200 'from '. $old->getfield($primary_key).
1201 ' to ' . $new->getfield($primary_key)
1203 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
1205 my $error = $new->check;
1206 return $error if $error;
1208 # Encrypt for replace
1210 if ($conf->exists('encryption') && defined(eval '@FS::'. $new->table . '::encrypted_fields')) {
1211 foreach my $field (eval '@FS::'. $new->table . '::encrypted_fields') {
1212 $saved->{$field} = $new->getfield($field);
1213 $new->setfield($field, $new->encrypt($new->getfield($field)));
1217 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
1218 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
1219 ? ($_, $new->getfield($_)) : () } $old->fields;
1221 unless (keys(%diff) || $no_update_diff ) {
1222 carp "[warning]$me $new -> replace $old: records identical"
1223 unless $nowarn_identical;
1227 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
1229 "$_ = ". _quote($new->getfield($_),$old->table,$_)
1230 } real_fields($old->table)
1235 if ( $old->getfield($_) eq '' ) {
1237 #false laziness w/qsearch
1238 if ( driver_name eq 'Pg' ) {
1239 my $type = $old->dbdef_table->column($_)->type;
1240 if ( $type =~ /(int|(big)?serial)/i ) {
1243 qq-( $_ IS NULL OR $_ = '' )-;
1246 qq-( $_ IS NULL OR $_ = "" )-;
1250 "$_ = ". _quote($old->getfield($_),$old->table,$_);
1253 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
1256 warn "[debug]$me $statement\n" if $DEBUG > 1;
1257 my $sth = dbh->prepare($statement) or return dbh->errstr;
1260 if ( defined dbdef->table('h_'. $old->table) ) {
1261 my $h_old_statement = $old->_h_statement('replace_old');
1262 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
1263 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
1269 if ( defined dbdef->table('h_'. $new->table) ) {
1270 my $h_new_statement = $new->_h_statement('replace_new');
1271 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
1272 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
1277 # For virtual fields we have three cases with different SQL
1278 # statements: add, replace, delete
1282 my (@add_vfields, @rep_vfields, @del_vfields);
1283 my $vfp = $old->vfieldpart_hashref;
1284 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
1285 if($diff{$_} eq '') {
1287 unless(@del_vfields) {
1288 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
1289 "AND vfieldpart = ?";
1290 warn "[debug]$me $st\n" if $DEBUG > 2;
1291 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
1293 push @del_vfields, $_;
1294 } elsif($old->getfield($_) eq '') {
1296 unless(@add_vfields) {
1297 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
1299 warn "[debug]$me $st\n" if $DEBUG > 2;
1300 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
1302 push @add_vfields, $_;
1305 unless(@rep_vfields) {
1306 my $st = "UPDATE virtual_field SET value = ? ".
1307 "WHERE recnum = ? AND vfieldpart = ?";
1308 warn "[debug]$me $st\n" if $DEBUG > 2;
1309 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
1311 push @rep_vfields, $_;
1315 local $SIG{HUP} = 'IGNORE';
1316 local $SIG{INT} = 'IGNORE';
1317 local $SIG{QUIT} = 'IGNORE';
1318 local $SIG{TERM} = 'IGNORE';
1319 local $SIG{TSTP} = 'IGNORE';
1320 local $SIG{PIPE} = 'IGNORE';
1322 my $rc = $sth->execute or return $sth->errstr;
1323 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
1324 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
1325 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
1327 $v_del_sth->execute($old->getfield($primary_key),
1329 or return $v_del_sth->errstr
1330 foreach(@del_vfields);
1332 $v_add_sth->execute($new->getfield($_),
1333 $old->getfield($primary_key),
1335 or return $v_add_sth->errstr
1336 foreach(@add_vfields);
1338 $v_rep_sth->execute($new->getfield($_),
1339 $old->getfield($primary_key),
1341 or return $v_rep_sth->errstr
1342 foreach(@rep_vfields);
1344 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
1346 # Now that it has been saved, reset the encrypted fields so that $new
1347 # can still be used.
1348 foreach my $field (keys %{$saved}) {
1349 $new->setfield($field, $saved->{$field});
1357 my( $self ) = shift;
1358 warn "[$me] replace called with no arguments; autoloading old record\n"
1361 my $primary_key = $self->dbdef_table->primary_key;
1362 if ( $primary_key ) {
1363 $self->by_key( $self->$primary_key() ) #this is what's returned
1364 or croak "can't find ". $self->table. ".$primary_key ".
1365 $self->$primary_key();
1367 croak $self->table. " has no primary key; pass old record as argument";
1374 Depriciated (use replace instead).
1379 cluck "warning: FS::Record::rep deprecated!";
1380 replace @_; #call method in this scope
1385 Checks virtual fields (using check_blocks). Subclasses should still provide
1386 a check method to validate real fields, foreign keys, etc., and call this
1387 method via $self->SUPER::check.
1389 (FIXME: Should this method try to make sure that it I<is> being called from
1390 a subclass's check method, to keep the current semantics as far as possible?)
1395 #confess "FS::Record::check not implemented; supply one in subclass!";
1398 foreach my $field ($self->virtual_fields) {
1399 for ($self->getfield($field)) {
1400 # See notes on check_block in FS::part_virtual_field.
1401 eval $self->pvf($field)->check_block;
1403 #this is bad, probably want to follow the stack backtrace up and see
1405 my $err = "Fatal error checking $field for $self";
1407 return "$err (see log for backtrace): $@";
1410 $self->setfield($field, $_);
1416 =item process_batch_import JOB OPTIONS_HASHREF PARAMS
1418 Processes a batch import as a queued JSRPC job
1420 JOB is an FS::queue entry.
1422 OPTIONS_HASHREF can have the following keys:
1428 Table name (required).
1432 Listref of field names for static fields. They will be given values from the
1433 PARAMS hashref and passed as a "params" hashref to batch_import.
1437 Formats hashref. Keys are field names, values are listrefs that define the
1440 Each listref value can be a column name or a code reference. Coderefs are run
1441 with the row object, data and a FS::Conf object as the three parameters.
1442 For example, this coderef does the same thing as using the "columnname" string:
1445 my( $record, $data, $conf ) = @_;
1446 $record->columnname( $data );
1449 Coderefs are run after all "column name" fields are assigned.
1453 Optional format hashref of types. Keys are field names, values are "csv",
1454 "xls" or "fixedlength". Overrides automatic determination of file type
1457 =item format_headers
1459 Optional format hashref of header lines. Keys are field names, values are 0
1460 for no header, 1 to ignore the first line, or to higher numbers to ignore that
1463 =item format_sep_chars
1465 Optional format hashref of CSV sep_chars. Keys are field names, values are the
1466 CSV separation character.
1468 =item format_fixedlenth_formats
1470 Optional format hashref of fixed length format defintiions. Keys are field
1471 names, values Parse::FixedLength listrefs of field definitions.
1475 Set true to default to CSV file type if the filename does not contain a
1476 recognizable ".csv" or ".xls" extension (and type is not pre-specified by
1481 PARAMS is a base64-encoded Storable string containing the POSTed data as
1482 a hash ref. It normally contains at least one field, "uploaded files",
1483 generated by /elements/file-upload.html and containing the list of uploaded
1484 files. Currently only supports a single file named "file".
1488 use Storable qw(thaw);
1491 sub process_batch_import {
1492 my($job, $opt) = ( shift, shift );
1494 my $table = $opt->{table};
1495 my @pass_params = @{ $opt->{params} };
1496 my %formats = %{ $opt->{formats} };
1498 my $param = thaw(decode_base64(shift));
1499 warn Dumper($param) if $DEBUG;
1501 my $files = $param->{'uploaded_files'}
1502 or die "No files provided.\n";
1504 my (%files) = map { /^(\w+):([\.\w]+)$/ ? ($1,$2):() } split /,/, $files;
1506 my $dir = '%%%FREESIDE_CACHE%%%/cache.'. $FS::UID::datasrc. '/';
1507 my $file = $dir. $files{'file'};
1510 FS::Record::batch_import( {
1513 formats => \%formats,
1514 format_types => $opt->{format_types},
1515 format_headers => $opt->{format_headers},
1516 format_sep_chars => $opt->{format_sep_chars},
1517 format_fixedlength_formats => $opt->{format_fixedlength_formats},
1522 format => $param->{format},
1523 params => { map { $_ => $param->{$_} } @pass_params },
1525 default_csv => $opt->{default_csv},
1530 die "$error\n" if $error;
1533 =item batch_import PARAM_HASHREF
1535 Class method for batch imports. Available params:
1545 =item format_headers
1547 =item format_sep_chars
1549 =item format_fixedlength_formats
1555 FS::queue object, will be updated with progress
1561 csv, xls or fixedlength
1574 warn "$me batch_import call with params: \n". Dumper($param)
1577 my $table = $param->{table};
1578 my $formats = $param->{formats};
1580 my $job = $param->{job};
1581 my $file = $param->{file};
1582 my $format = $param->{'format'};
1583 my $params = $param->{params} || {};
1585 die "unknown format $format" unless exists $formats->{ $format };
1587 my $type = $param->{'format_types'}
1588 ? $param->{'format_types'}{ $format }
1589 : $param->{type} || 'csv';
1592 if ( $file =~ /\.(\w+)$/i ) {
1596 warn "can't parse file type from filename $file; defaulting to CSV";
1600 if $param->{'default_csv'} && $type ne 'xls';
1603 my $header = $param->{'format_headers'}
1604 ? $param->{'format_headers'}{ $param->{'format'} }
1607 my $sep_char = $param->{'format_sep_chars'}
1608 ? $param->{'format_sep_chars'}{ $param->{'format'} }
1611 my $fixedlength_format =
1612 $param->{'format_fixedlength_formats'}
1613 ? $param->{'format_fixedlength_formats'}{ $param->{'format'} }
1616 my @fields = @{ $formats->{ $format } };
1622 if ( $type eq 'csv' || $type eq 'fixedlength' ) {
1624 if ( $type eq 'csv' ) {
1627 $attr{sep_char} = $sep_char if $sep_char;
1628 $parser = new Text::CSV_XS \%attr;
1630 } elsif ( $type eq 'fixedlength' ) {
1632 eval "use Parse::FixedLength;";
1634 $parser = new Parse::FixedLength $fixedlength_format;
1637 die "Unknown file type $type\n";
1640 @buffer = split(/\r?\n/, slurp($file) );
1641 splice(@buffer, 0, ($header || 0) );
1642 $count = scalar(@buffer);
1644 } elsif ( $type eq 'xls' ) {
1646 eval "use Spreadsheet::ParseExcel;";
1649 eval "use DateTime::Format::Excel;";
1650 #for now, just let the error be thrown if it is used, since only CDR
1651 # formats bill_west and troop use it, not other excel-parsing things
1654 my $excel = Spreadsheet::ParseExcel::Workbook->new->Parse($file);
1656 $parser = $excel->{Worksheet}[0]; #first sheet
1658 $count = $parser->{MaxRow} || $parser->{MinRow};
1661 $row = $header || 0;
1664 die "Unknown file type $type\n";
1669 local $SIG{HUP} = 'IGNORE';
1670 local $SIG{INT} = 'IGNORE';
1671 local $SIG{QUIT} = 'IGNORE';
1672 local $SIG{TERM} = 'IGNORE';
1673 local $SIG{TSTP} = 'IGNORE';
1674 local $SIG{PIPE} = 'IGNORE';
1676 my $oldAutoCommit = $FS::UID::AutoCommit;
1677 local $FS::UID::AutoCommit = 0;
1682 my( $last, $min_sec ) = ( time, 5 ); #progressbar foo
1686 if ( $type eq 'csv' ) {
1688 last unless scalar(@buffer);
1689 $line = shift(@buffer);
1691 $parser->parse($line) or do {
1692 $dbh->rollback if $oldAutoCommit;
1693 return "can't parse: ". $parser->error_input();
1695 @columns = $parser->fields();
1697 } elsif ( $type eq 'fixedlength' ) {
1699 @columns = $parser->parse($line);
1701 } elsif ( $type eq 'xls' ) {
1703 last if $row > ($parser->{MaxRow} || $parser->{MinRow})
1704 || ! $parser->{Cells}[$row];
1706 my @row = @{ $parser->{Cells}[$row] };
1707 @columns = map $_->{Val}, @row;
1710 #warn $z++. ": $_\n" for @columns;
1713 die "Unknown file type $type\n";
1717 my %hash = %$params;
1719 foreach my $field ( @fields ) {
1721 my $value = shift @columns;
1723 if ( ref($field) eq 'CODE' ) {
1724 #&{$field}(\%hash, $value);
1725 push @later, $field, $value;
1727 #??? $hash{$field} = $value if length($value);
1728 $hash{$field} = $value if defined($value) && length($value);
1733 my $class = "FS::$table";
1735 my $record = $class->new( \%hash );
1738 while ( scalar(@later) ) {
1739 my $sub = shift @later;
1740 my $data = shift @later;
1741 &{$sub}($record, $data, $conf, $param); # $record->&{$sub}($data, $conf);
1742 last if exists( $param->{skiprow} );
1744 next if exists( $param->{skiprow} );
1746 my $error = $record->insert;
1749 $dbh->rollback if $oldAutoCommit;
1750 return "can't insert record". ( $line ? " for $line" : '' ). ": $error";
1756 if ( $job && time - $min_sec > $last ) { #progress bar
1757 $job->update_statustext( int(100 * $imported / $count) );
1763 $dbh->commit or die $dbh->errstr if $oldAutoCommit;;
1765 return "Empty file!" unless $imported || $param->{empty_ok};
1772 my( $self, $action, $time ) = @_;
1776 my %nohistory = map { $_=>1 } $self->nohistory_fields;
1779 grep { defined($self->get($_)) && $self->get($_) ne "" && ! $nohistory{$_} }
1780 real_fields($self->table);
1783 # If we're encrypting then don't store the payinfo in the history
1784 if ( $conf && $conf->exists('encryption') ) {
1785 @fields = grep { $_ ne 'payinfo' } @fields;
1788 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1790 "INSERT INTO h_". $self->table. " ( ".
1791 join(', ', qw(history_date history_user history_action), @fields ).
1793 join(', ', $time, dbh->quote(getotaker()), dbh->quote($action), @values).
1800 B<Warning>: External use is B<deprecated>.
1802 Replaces COLUMN in record with a unique number, using counters in the
1803 filesystem. Used by the B<insert> method on single-field unique columns
1804 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1805 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1807 Returns the new value.
1812 my($self,$field) = @_;
1813 my($table)=$self->table;
1815 croak "Unique called on field $field, but it is ",
1816 $self->getfield($field),
1818 if $self->getfield($field);
1820 #warn "table $table is tainted" if is_tainted($table);
1821 #warn "field $field is tainted" if is_tainted($field);
1823 my($counter) = new File::CounterFile "$table.$field",0;
1825 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1827 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1830 my $index = $counter->inc;
1831 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1833 $index =~ /^(\d*)$/;
1836 $self->setfield($field,$index);
1840 =item ut_float COLUMN
1842 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1843 null. If there is an error, returns the error, otherwise returns false.
1848 my($self,$field)=@_ ;
1849 ($self->getfield($field) =~ /^\s*(\d+\.\d+)\s*$/ ||
1850 $self->getfield($field) =~ /^\s*(\d+)\s*$/ ||
1851 $self->getfield($field) =~ /^\s*(\d+\.\d+e\d+)\s*$/ ||
1852 $self->getfield($field) =~ /^\s*(\d+e\d+)\s*$/)
1853 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1854 $self->setfield($field,$1);
1857 =item ut_floatn COLUMN
1859 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1860 null. If there is an error, returns the error, otherwise returns false.
1864 #false laziness w/ut_ipn
1866 my( $self, $field ) = @_;
1867 if ( $self->getfield($field) =~ /^()$/ ) {
1868 $self->setfield($field,'');
1871 $self->ut_float($field);
1875 =item ut_sfloat COLUMN
1877 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10.
1878 May not be null. If there is an error, returns the error, otherwise returns
1884 my($self,$field)=@_ ;
1885 ($self->getfield($field) =~ /^\s*(-?\d+\.\d+)\s*$/ ||
1886 $self->getfield($field) =~ /^\s*(-?\d+)\s*$/ ||
1887 $self->getfield($field) =~ /^\s*(-?\d+\.\d+[eE]-?\d+)\s*$/ ||
1888 $self->getfield($field) =~ /^\s*(-?\d+[eE]-?\d+)\s*$/)
1889 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1890 $self->setfield($field,$1);
1893 =item ut_sfloatn COLUMN
1895 Check/untaint signed floating point numeric data: 1.1, 1, 1.1e10, 1e10. May be
1896 null. If there is an error, returns the error, otherwise returns false.
1901 my( $self, $field ) = @_;
1902 if ( $self->getfield($field) =~ /^()$/ ) {
1903 $self->setfield($field,'');
1906 $self->ut_sfloat($field);
1910 =item ut_snumber COLUMN
1912 Check/untaint signed numeric data (whole numbers). If there is an error,
1913 returns the error, otherwise returns false.
1918 my($self, $field) = @_;
1919 $self->getfield($field) =~ /^\s*(-?)\s*(\d+)\s*$/
1920 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1921 $self->setfield($field, "$1$2");
1925 =item ut_snumbern COLUMN
1927 Check/untaint signed numeric data (whole numbers). If there is an error,
1928 returns the error, otherwise returns false.
1933 my($self, $field) = @_;
1934 $self->getfield($field) =~ /^\s*(-?)\s*(\d*)\s*$/
1935 or return "Illegal (numeric) $field: ". $self->getfield($field);
1937 return "Illegal (numeric) $field: ". $self->getfield($field)
1940 $self->setfield($field, "$1$2");
1944 =item ut_number COLUMN
1946 Check/untaint simple numeric data (whole numbers). May not be null. If there
1947 is an error, returns the error, otherwise returns false.
1952 my($self,$field)=@_;
1953 $self->getfield($field) =~ /^\s*(\d+)\s*$/
1954 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1955 $self->setfield($field,$1);
1959 =item ut_numbern COLUMN
1961 Check/untaint simple numeric data (whole numbers). May be null. If there is
1962 an error, returns the error, otherwise returns false.
1967 my($self,$field)=@_;
1968 $self->getfield($field) =~ /^\s*(\d*)\s*$/
1969 or return "Illegal (numeric) $field: ". $self->getfield($field);
1970 $self->setfield($field,$1);
1974 =item ut_money COLUMN
1976 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1977 is an error, returns the error, otherwise returns false.
1982 my($self,$field)=@_;
1983 $self->setfield($field, 0) if $self->getfield($field) eq '';
1984 $self->getfield($field) =~ /^\s*(\-)?\s*(\d*)(\.\d{2})?\s*$/
1985 or return "Illegal (money) $field: ". $self->getfield($field);
1986 #$self->setfield($field, "$1$2$3" || 0);
1987 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1991 =item ut_text COLUMN
1993 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1994 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / = [ ] < >
1995 May not be null. If there is an error, returns the error, otherwise returns
2001 my($self,$field)=@_;
2002 #warn "msgcat ". \&msgcat. "\n";
2003 #warn "notexist ". \¬exist. "\n";
2004 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
2005 $self->getfield($field)
2006 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]\<\>]+)$/
2007 or return gettext('illegal_or_empty_text'). " $field: ".
2008 $self->getfield($field);
2009 $self->setfield($field,$1);
2013 =item ut_textn COLUMN
2015 Check/untaint text. Alphanumerics, spaces, and the following punctuation
2016 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
2017 May be null. If there is an error, returns the error, otherwise returns false.
2022 my($self,$field)=@_;
2023 $self->getfield($field)
2024 =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=\[\]]*)$/
2025 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
2026 $self->setfield($field,$1);
2030 =item ut_alpha COLUMN
2032 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
2033 an error, returns the error, otherwise returns false.
2038 my($self,$field)=@_;
2039 $self->getfield($field) =~ /^(\w+)$/
2040 or return "Illegal or empty (alphanumeric) $field: ".
2041 $self->getfield($field);
2042 $self->setfield($field,$1);
2046 =item ut_alpha COLUMN
2048 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
2049 error, returns the error, otherwise returns false.
2054 my($self,$field)=@_;
2055 $self->getfield($field) =~ /^(\w*)$/
2056 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
2057 $self->setfield($field,$1);
2061 =item ut_alpha_lower COLUMN
2063 Check/untaint lowercase alphanumeric strings (no spaces). May not be null. If
2064 there is an error, returns the error, otherwise returns false.
2068 sub ut_alpha_lower {
2069 my($self,$field)=@_;
2070 $self->getfield($field) =~ /[[:upper:]]/
2071 and return "Uppercase characters are not permitted in $field";
2072 $self->ut_alpha($field);
2075 =item ut_phonen COLUMN [ COUNTRY ]
2077 Check/untaint phone numbers. May be null. If there is an error, returns
2078 the error, otherwise returns false.
2080 Takes an optional two-letter ISO country code; without it or with unsupported
2081 countries, ut_phonen simply calls ut_alphan.
2086 my( $self, $field, $country ) = @_;
2087 return $self->ut_alphan($field) unless defined $country;
2088 my $phonen = $self->getfield($field);
2089 if ( $phonen eq '' ) {
2090 $self->setfield($field,'');
2091 } elsif ( $country eq 'US' || $country eq 'CA' ) {
2093 $phonen = $conf->config('cust_main-default_areacode').$phonen
2094 if length($phonen)==7 && $conf->config('cust_main-default_areacode');
2095 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
2096 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
2097 $phonen = "$1-$2-$3";
2098 $phonen .= " x$4" if $4;
2099 $self->setfield($field,$phonen);
2101 warn "warning: don't know how to check phone numbers for country $country";
2102 return $self->ut_textn($field);
2109 Check/untaint hexadecimal values.
2114 my($self, $field) = @_;
2115 $self->getfield($field) =~ /^([\da-fA-F]+)$/
2116 or return "Illegal (hex) $field: ". $self->getfield($field);
2117 $self->setfield($field, uc($1));
2121 =item ut_hexn COLUMN
2123 Check/untaint hexadecimal values. May be null.
2128 my($self, $field) = @_;
2129 $self->getfield($field) =~ /^([\da-fA-F]*)$/
2130 or return "Illegal (hex) $field: ". $self->getfield($field);
2131 $self->setfield($field, uc($1));
2136 Check/untaint ip addresses. IPv4 only for now.
2141 my( $self, $field ) = @_;
2142 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
2143 or return "Illegal (IP address) $field: ". $self->getfield($field);
2144 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
2145 $self->setfield($field, "$1.$2.$3.$4");
2151 Check/untaint ip addresses. IPv4 only for now. May be null.
2156 my( $self, $field ) = @_;
2157 if ( $self->getfield($field) =~ /^()$/ ) {
2158 $self->setfield($field,'');
2161 $self->ut_ip($field);
2165 =item ut_coord COLUMN [ LOWER [ UPPER ] ]
2167 Check/untaint coordinates.
2168 Accepts the following forms:
2178 The "DDD MM SS" and "DDD MM MMM" are potentially ambiguous.
2179 The latter form (that is, the MMM are thousands of minutes) is
2180 assumed if the "MMM" is exactly three digits or two digits > 59.
2182 To be safe, just use the DDD.DDDDD form.
2184 If LOWER or UPPER are specified, then the coordinate is checked
2185 for lower and upper bounds, respectively.
2191 my ($self, $field) = (shift, shift);
2193 my $lower = shift if scalar(@_);
2194 my $upper = shift if scalar(@_);
2195 my $coord = $self->getfield($field);
2196 my $neg = $coord =~ s/^(-)//;
2198 my ($d, $m, $s) = (0, 0, 0);
2201 (($d) = ($coord =~ /^(\s*\d{1,3}(?:\.\d+)?)\s*$/)) ||
2202 (($d, $m) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2}(?:\.\d+))\s*$/)) ||
2203 (($d, $m, $s) = ($coord =~ /^(\s*\d{1,3})\s+(\d{1,2})\s+(\d{1,3})\s*$/))
2205 $s = (((($s =~ /^\d{3}$/) or $s > 59) ? ($s / 1000) : ($s / 60)) / 60);
2208 return "Invalid (coordinate with minutes > 59) $field: "
2209 . $self->getfield($field);
2212 $coord = ($neg ? -1 : 1) * sprintf('%.8f', $d + $m + $s);
2214 if (defined($lower) and ($coord < $lower)) {
2215 return "Invalid (coordinate < $lower) $field: "
2216 . $self->getfield($field);;
2219 if (defined($upper) and ($coord > $upper)) {
2220 return "Invalid (coordinate > $upper) $field: "
2221 . $self->getfield($field);;
2224 $self->setfield($field, $coord);
2228 return "Invalid (coordinate) $field: " . $self->getfield($field);
2232 =item ut_coordn COLUMN [ LOWER [ UPPER ] ]
2234 Same as ut_coord, except optionally null.
2240 my ($self, $field) = (shift, shift);
2242 if ($self->getfield($field) =~ /^$/) {
2245 return $self->ut_coord($field, @_);
2251 =item ut_domain COLUMN
2253 Check/untaint host and domain names.
2258 my( $self, $field ) = @_;
2259 #$self->getfield($field) =~/^(\w+\.)*\w+$/
2260 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
2261 or return "Illegal (domain) $field: ". $self->getfield($field);
2262 $self->setfield($field,$1);
2266 =item ut_name COLUMN
2268 Check/untaint proper names; allows alphanumerics, spaces and the following
2269 punctuation: , . - '
2276 my( $self, $field ) = @_;
2277 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
2278 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
2279 $self->setfield($field,$1);
2285 Check/untaint zip codes.
2289 my @zip_reqd_countries = qw( AU CA US ); #CA, US implicit...
2292 my( $self, $field, $country ) = @_;
2294 if ( $country eq 'US' ) {
2296 $self->getfield($field) =~ /^\s*(\d{5}(\-\d{4})?)\s*$/
2297 or return gettext('illegal_zip'). " $field for country $country: ".
2298 $self->getfield($field);
2299 $self->setfield($field, $1);
2301 } elsif ( $country eq 'CA' ) {
2303 $self->getfield($field) =~ /^\s*([A-Z]\d[A-Z])\s*(\d[A-Z]\d)\s*$/i
2304 or return gettext('illegal_zip'). " $field for country $country: ".
2305 $self->getfield($field);
2306 $self->setfield($field, "$1 $2");
2310 if ( $self->getfield($field) =~ /^\s*$/
2311 && ( !$country || ! grep { $_ eq $country } @zip_reqd_countries )
2314 $self->setfield($field,'');
2316 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
2317 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
2318 $self->setfield($field,$1);
2326 =item ut_country COLUMN
2328 Check/untaint country codes. Country names are changed to codes, if possible -
2329 see L<Locale::Country>.
2334 my( $self, $field ) = @_;
2335 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
2336 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
2337 && country2code($1) ) {
2338 $self->setfield($field,uc(country2code($1)));
2341 $self->getfield($field) =~ /^(\w\w)$/
2342 or return "Illegal (country) $field: ". $self->getfield($field);
2343 $self->setfield($field,uc($1));
2347 =item ut_anything COLUMN
2349 Untaints arbitrary data. Be careful.
2354 my( $self, $field ) = @_;
2355 $self->getfield($field) =~ /^(.*)$/s
2356 or return "Illegal $field: ". $self->getfield($field);
2357 $self->setfield($field,$1);
2361 =item ut_enum COLUMN CHOICES_ARRAYREF
2363 Check/untaint a column, supplying all possible choices, like the "enum" type.
2368 my( $self, $field, $choices ) = @_;
2369 foreach my $choice ( @$choices ) {
2370 if ( $self->getfield($field) eq $choice ) {
2371 $self->setfield($field, $choice);
2375 return "Illegal (enum) field $field: ". $self->getfield($field);
2378 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2380 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
2381 on the column first.
2385 sub ut_foreign_key {
2386 my( $self, $field, $table, $foreign ) = @_;
2387 return '' if $no_check_foreign;
2388 qsearchs($table, { $foreign => $self->getfield($field) })
2389 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
2390 " in $table.$foreign";
2394 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
2396 Like ut_foreign_key, except the null value is also allowed.
2400 sub ut_foreign_keyn {
2401 my( $self, $field, $table, $foreign ) = @_;
2402 $self->getfield($field)
2403 ? $self->ut_foreign_key($field, $table, $foreign)
2407 =item ut_agentnum_acl COLUMN [ NULL_RIGHT | NULL_RIGHT_LISTREF ]
2409 Checks this column as an agentnum, taking into account the current users's
2410 ACLs. NULL_RIGHT or NULL_RIGHT_LISTREF, if specified, indicates the access
2411 right or rights allowing no agentnum.
2415 sub ut_agentnum_acl {
2416 my( $self, $field ) = (shift, shift);
2417 my $null_acl = scalar(@_) ? shift : [];
2418 $null_acl = [ $null_acl ] unless ref($null_acl);
2420 my $error = $self->ut_foreign_keyn($field, 'agent', 'agentnum');
2421 return "Illegal agentnum: $error" if $error;
2423 my $curuser = $FS::CurrentUser::CurrentUser;
2425 if ( $self->$field() ) {
2427 return "Access denied"
2428 unless $curuser->agentnum($self->$field());
2432 return "Access denied"
2433 unless grep $curuser->access_right($_), @$null_acl;
2441 =item virtual_fields [ TABLE ]
2443 Returns a list of virtual fields defined for the table. This should not
2444 be exported, and should only be called as an instance or class method.
2448 sub virtual_fields {
2451 $table = $self->table or confess "virtual_fields called on non-table";
2453 confess "Unknown table $table" unless dbdef->table($table);
2455 return () unless dbdef->table('part_virtual_field');
2457 unless ( $virtual_fields_cache{$table} ) {
2458 my $query = 'SELECT name from part_virtual_field ' .
2459 "WHERE dbtable = '$table'";
2461 my $result = $dbh->selectcol_arrayref($query);
2462 confess "Error executing virtual fields query: $query: ". $dbh->errstr
2464 $virtual_fields_cache{$table} = $result;
2467 @{$virtual_fields_cache{$table}};
2472 =item fields [ TABLE ]
2474 This is a wrapper for real_fields and virtual_fields. Code that called
2475 fields before should probably continue to call fields.
2480 my $something = shift;
2482 if($something->isa('FS::Record')) {
2483 $table = $something->table;
2485 $table = $something;
2486 $something = "FS::$table";
2488 return (real_fields($table), $something->virtual_fields());
2491 =item pvf FIELD_NAME
2493 Returns the FS::part_virtual_field object corresponding to a field in the
2494 record (specified by FIELD_NAME).
2499 my ($self, $name) = (shift, shift);
2501 if(grep /^$name$/, $self->virtual_fields) {
2502 return qsearchs('part_virtual_field', { dbtable => $self->table,
2508 =item vfieldpart_hashref TABLE
2510 Returns a hashref of virtual field names and vfieldparts applicable to the given
2515 sub vfieldpart_hashref {
2517 my $table = $self->table;
2519 return {} unless dbdef->table('part_virtual_field');
2522 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
2523 "dbtable = '$table'";
2524 my $sth = $dbh->prepare($statement);
2525 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
2526 return { map { $_->{name}, $_->{vfieldpart} }
2527 @{$sth->fetchall_arrayref({})} };
2531 =item encrypt($value)
2533 Encrypts the credit card using a combination of PK to encrypt and uuencode to armour.
2535 Returns the encrypted string.
2537 You should generally not have to worry about calling this, as the system handles this for you.
2542 my ($self, $value) = @_;
2545 if ($conf->exists('encryption')) {
2546 if ($self->is_encrypted($value)) {
2547 # Return the original value if it isn't plaintext.
2548 $encrypted = $value;
2551 if (ref($rsa_encrypt) =~ /::RSA/) { # We Can Encrypt
2552 # RSA doesn't like the empty string so let's pack it up
2553 # The database doesn't like the RSA data so uuencode it
2554 my $length = length($value)+1;
2555 $encrypted = pack("u*",$rsa_encrypt->encrypt(pack("Z$length",$value)));
2557 die ("You can't encrypt w/o a valid RSA engine - Check your installation or disable encryption");
2564 =item is_encrypted($value)
2566 Checks to see if the string is encrypted and returns true or false (1/0) to indicate it's status.
2572 my ($self, $value) = @_;
2573 # Possible Bug - Some work may be required here....
2575 if ($value =~ /^M/ && length($value) > 80) {
2582 =item decrypt($value)
2584 Uses the private key to decrypt the string. Returns the decryoted string or undef on failure.
2586 You should generally not have to worry about calling this, as the system handles this for you.
2591 my ($self,$value) = @_;
2592 my $decrypted = $value; # Will return the original value if it isn't encrypted or can't be decrypted.
2593 if ($conf->exists('encryption') && $self->is_encrypted($value)) {
2595 if (ref($rsa_decrypt) =~ /::RSA/) {
2596 my $encrypted = unpack ("u*", $value);
2597 $decrypted = unpack("Z*", eval{$rsa_decrypt->decrypt($encrypted)});
2598 if ($@) {warn "Decryption Failed"};
2606 #Initialize the Module
2607 $rsa_module = 'Crypt::OpenSSL::RSA'; # The Default
2609 if ($conf->exists('encryptionmodule') && $conf->config_binary('encryptionmodule') ne '') {
2610 $rsa_module = $conf->config('encryptionmodule');
2614 eval ("require $rsa_module"); # No need to import the namespace
2617 # Initialize Encryption
2618 if ($conf->exists('encryptionpublickey') && $conf->config_binary('encryptionpublickey') ne '') {
2619 my $public_key = join("\n",$conf->config('encryptionpublickey'));
2620 $rsa_encrypt = $rsa_module->new_public_key($public_key);
2623 # Intitalize Decryption
2624 if ($conf->exists('encryptionprivatekey') && $conf->config_binary('encryptionprivatekey') ne '') {
2625 my $private_key = join("\n",$conf->config('encryptionprivatekey'));
2626 $rsa_decrypt = $rsa_module->new_private_key($private_key);
2630 =item h_search ACTION
2632 Given an ACTION, either "insert", or "delete", returns the appropriate history
2633 record corresponding to this record, if any.
2638 my( $self, $action ) = @_;
2640 my $table = $self->table;
2643 my $primary_key = dbdef->table($table)->primary_key;
2646 'table' => "h_$table",
2647 'hashref' => { $primary_key => $self->$primary_key(),
2648 'history_action' => $action,
2656 Given an ACTION, either "insert", or "delete", returns the timestamp of the
2657 appropriate history record corresponding to this record, if any.
2662 my($self, $action) = @_;
2663 my $h = $self->h_search($action);
2664 $h ? $h->history_date : '';
2673 =item real_fields [ TABLE ]
2675 Returns a list of the real columns in the specified table. Called only by
2676 fields() and other subroutines elsewhere in FS::Record.
2683 my($table_obj) = dbdef->table($table);
2684 confess "Unknown table $table" unless $table_obj;
2685 $table_obj->columns;
2688 =item _quote VALUE, TABLE, COLUMN
2690 This is an internal function used to construct SQL statements. It returns
2691 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
2692 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
2697 my($value, $table, $column) = @_;
2698 my $column_obj = dbdef->table($table)->column($column);
2699 my $column_type = $column_obj->type;
2700 my $nullable = $column_obj->null;
2702 warn " $table.$column: $value ($column_type".
2703 ( $nullable ? ' NULL' : ' NOT NULL' ).
2704 ")\n" if $DEBUG > 2;
2706 if ( $value eq '' && $nullable ) {
2708 } elsif ( $value eq '' && $column_type =~ /^(int|numeric)/ ) {
2709 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
2712 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
2713 ! $column_type =~ /(char|binary|text)$/i ) {
2715 } elsif (( $column_type =~ /^bytea$/i || $column_type =~ /(blob|varbinary)/i )
2716 && driver_name eq 'Pg'
2720 # dbh->quote($value, { pg_type => PG_BYTEA() }); # doesn't work right
2721 # Pg binary string quoting: convert each character to 3-digit octal prefixed with \\,
2722 # single-quote the whole mess, and put an "E" in front.
2723 return ("E'" . join('', map { sprintf('\\\\%03o', ord($_)) } split(//, $value) ) . "'");
2731 This is deprecated. Don't use it.
2733 It returns a hash-type list with the fields of this record's table set true.
2738 carp "warning: hfields is deprecated";
2741 foreach (fields($table)) {
2750 "$_: ". $self->getfield($_). "|"
2751 } (fields($self->table)) );
2754 sub DESTROY { return; }
2758 # #use Carp qw(cluck);
2759 # #cluck "DESTROYING $self";
2760 # warn "DESTROYING $self";
2764 # return ! eval { join('',@_), kill 0; 1; };
2767 =item str2time_sql [ DRIVER_NAME ]
2769 Returns a function to convert to unix time based on database type, such as
2770 "EXTRACT( EPOCH FROM" for Pg or "UNIX_TIMESTAMP(" for mysql. See
2771 the str2time_sql_closing method to return a closing string rather than just
2772 using a closing parenthesis as previously suggested.
2774 You can pass an optional driver name such as "Pg", "mysql" or
2775 $dbh->{Driver}->{Name} to return a function for that database instead of
2776 the current database.
2781 my $driver = shift || driver_name;
2783 return 'UNIX_TIMESTAMP(' if $driver =~ /^mysql/i;
2784 return 'EXTRACT( EPOCH FROM ' if $driver =~ /^Pg/i;
2786 warn "warning: unknown database type $driver; guessing how to convert ".
2787 "dates to UNIX timestamps";
2788 return 'EXTRACT(EPOCH FROM ';
2792 =item str2time_sql_closing [ DRIVER_NAME ]
2794 Returns the closing suffix of a function to convert to unix time based on
2795 database type, such as ")::integer" for Pg or ")" for mysql.
2797 You can pass an optional driver name such as "Pg", "mysql" or
2798 $dbh->{Driver}->{Name} to return a function for that database instead of
2799 the current database.
2803 sub str2time_sql_closing {
2804 my $driver = shift || driver_name;
2806 return ' )::INTEGER ' if $driver =~ /^Pg/i;
2814 This module should probably be renamed, since much of the functionality is
2815 of general use. It is not completely unlike Adapter::DBI (see below).
2817 Exported qsearch and qsearchs should be deprecated in favor of method calls
2818 (against an FS::Record object like the old search and searchs that qsearch
2819 and qsearchs were on top of.)
2821 The whole fields / hfields mess should be removed.
2823 The various WHERE clauses should be subroutined.
2825 table string should be deprecated in favor of DBIx::DBSchema::Table.
2827 No doubt we could benefit from a Tied hash. Documenting how exists / defined
2828 true maps to the database (and WHERE clauses) would also help.
2830 The ut_ methods should ask the dbdef for a default length.
2832 ut_sqltype (like ut_varchar) should all be defined
2834 A fallback check method should be provided which uses the dbdef.
2836 The ut_money method assumes money has two decimal digits.
2838 The Pg money kludge in the new method only strips `$'.
2840 The ut_phonen method only checks US-style phone numbers.
2842 The _quote function should probably use ut_float instead of a regex.
2844 All the subroutines probably should be methods, here or elsewhere.
2846 Probably should borrow/use some dbdef methods where appropriate (like sub
2849 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
2850 or allow it to be set. Working around it is ugly any way around - DBI should
2851 be fixed. (only affects RDBMS which return uppercase column names)
2853 ut_zip should take an optional country like ut_phone.
2857 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
2859 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.