4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
5 $me %dbdef_cache %virtual_fields_cache );
6 use subs qw(reload_dbdef);
8 use Carp qw(carp cluck croak confess);
11 use DBI qw(:sql_types);
12 use DBIx::DBSchema 0.23;
13 use FS::UID qw(dbh getotaker datasrc driver_name);
15 use FS::Msgcat qw(gettext);
17 use FS::part_virtual_field;
22 @EXPORT_OK = qw(dbh fields hfields qsearch qsearchs dbdef jsearch);
27 #ask FS::UID to run this stuff for us later
28 $FS::UID::callback{'FS::Record'} = sub {
29 $File::CounterFile::DEFAULT_DIR = "/usr/local/etc/freeside/counters.". datasrc;
30 $dbdef_file = "/usr/local/etc/freeside/dbdef.". datasrc;
31 &reload_dbdef unless $setup_hack; #$setup_hack needed now?
36 FS::Record - Database record objects
41 use FS::Record qw(dbh fields qsearch qsearchs dbdef);
43 $record = new FS::Record 'table', \%hash;
44 $record = new FS::Record 'table', { 'column' => 'value', ... };
46 $record = qsearchs FS::Record 'table', \%hash;
47 $record = qsearchs FS::Record 'table', { 'column' => 'value', ... };
48 @records = qsearch FS::Record 'table', \%hash;
49 @records = qsearch FS::Record 'table', { 'column' => 'value', ... };
51 $table = $record->table;
52 $dbdef_table = $record->dbdef_table;
54 $value = $record->get('column');
55 $value = $record->getfield('column');
56 $value = $record->column;
58 $record->set( 'column' => 'value' );
59 $record->setfield( 'column' => 'value' );
60 $record->column('value');
62 %hash = $record->hash;
64 $hashref = $record->hashref;
66 $error = $record->insert;
68 $error = $record->delete;
70 $error = $new_record->replace($old_record);
72 # external use deprecated - handled by the database (at least for Pg, mysql)
73 $value = $record->unique('column');
75 $error = $record->ut_float('column');
76 $error = $record->ut_number('column');
77 $error = $record->ut_numbern('column');
78 $error = $record->ut_money('column');
79 $error = $record->ut_text('column');
80 $error = $record->ut_textn('column');
81 $error = $record->ut_alpha('column');
82 $error = $record->ut_alphan('column');
83 $error = $record->ut_phonen('column');
84 $error = $record->ut_anything('column');
85 $error = $record->ut_name('column');
87 $dbdef = reload_dbdef;
88 $dbdef = reload_dbdef "/non/standard/filename";
91 $quoted_value = _quote($value,'table','field');
94 $fields = hfields('table');
95 if ( $fields->{Field} ) { # etc.
97 @fields = fields 'table'; #as a subroutine
98 @fields = $record->fields; #as a method call
103 (Mostly) object-oriented interface to database records. Records are currently
104 implemented on top of DBI. FS::Record is intended as a base class for
105 table-specific classes to inherit from, i.e. FS::cust_main.
111 =item new [ TABLE, ] HASHREF
113 Creates a new record. It doesn't store it in the database, though. See
114 L<"insert"> for that.
116 Note that the object stores this hash reference, not a distinct copy of the
117 hash it points to. You can ask the object for a copy with the I<hash>
120 TABLE can only be omitted when a dervived class overrides the table method.
126 my $class = ref($proto) || $proto;
128 bless ($self, $class);
130 unless ( defined ( $self->table ) ) {
131 $self->{'Table'} = shift;
132 carp "warning: FS::Record::new called with table name ". $self->{'Table'};
135 $self->{'Hash'} = shift;
137 foreach my $field ( grep !defined($self->{'Hash'}{$_}), $self->fields ) {
138 $self->{'Hash'}{$field}='';
141 $self->_rebless if $self->can('_rebless');
143 $self->{'modified'} = 0;
145 $self->_cache($self->{'Hash'}, shift) if $self->can('_cache') && @_;
152 my $class = ref($proto) || $proto;
154 bless ($self, $class);
156 $self->{'Table'} = shift unless defined ( $self->table );
158 my $hashref = $self->{'Hash'} = shift;
160 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
161 my $obj = $cache->cache->{$hashref->{$cache->key}};
162 $obj->_cache($hashref, $cache) if $obj->can('_cache');
165 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
172 my $class = ref($proto) || $proto;
174 bless ($self, $class);
175 if ( defined $self->table ) {
176 cluck "create constructor is deprecated, use new!";
179 croak "FS::Record::create called (not from a subclass)!";
183 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
185 Searches the database for all records matching (at least) the key/value pairs
186 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
187 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
190 ###oops, argh, FS::Record::new only lets us create database fields.
191 #Normal behaviour if SELECT is not specified is `*', as in
192 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
193 #feature where you can specify SELECT - remember, the objects returned,
194 #although blessed into the appropriate `FS::TABLE' package, will only have the
195 #fields you specify. This might have unwanted results if you then go calling
196 #regular FS::TABLE methods
202 my($stable, $record, $select, $extra_sql, $cache ) = @_;
203 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
205 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
210 my $table = $cache ? $cache->table : $stable;
211 my $dbdef_table = $dbdef->table($table)
212 or die "No schema for table $table found - ".
213 "do you need to create it or run dbdef-create?";
214 my $pkey = $dbdef_table->primary_key;
216 my @real_fields = grep exists($record->{$_}), real_fields($table);
218 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
219 @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
221 cluck "warning: FS::$table not loaded; virtual fields not searchable";
222 @virtual_fields = ();
225 my $statement = "SELECT $select FROM $stable";
226 if ( @real_fields or @virtual_fields ) {
227 $statement .= ' WHERE '. join(' AND ',
232 if ( ref($record->{$_}) ) {
233 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
234 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
235 if ( uc($op) eq 'ILIKE' ) {
237 $record->{$_}{'value'} = lc($record->{$_}{'value'});
238 $column = "LOWER($_)";
240 $record->{$_} = $record->{$_}{'value'}
243 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
245 if ( driver_name eq 'Pg' ) {
246 my $type = $dbdef->table($table)->column($column)->type;
247 if ( $type =~ /(int|serial)/i ) {
248 qq-( $column IS NULL )-;
250 qq-( $column IS NULL OR $column = '' )-;
253 qq-( $column IS NULL OR $column = "" )-;
255 } elsif ( $op eq '!=' ) {
256 if ( driver_name eq 'Pg' ) {
257 my $type = $dbdef->table($table)->column($column)->type;
258 if ( $type =~ /(int|serial)/i ) {
259 qq-( $column IS NOT NULL )-;
261 qq-( $column IS NOT NULL AND $column != '' )-;
264 qq-( $column IS NOT NULL AND $column != "" )-;
267 if ( driver_name eq 'Pg' ) {
268 qq-( $column $op '' )-;
270 qq-( $column $op "" )-;
280 if ( ref($record->{$_}) ) {
281 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
282 if ( uc($op) eq 'ILIKE' ) {
284 $record->{$_}{'value'} = lc($record->{$_}{'value'});
285 $column = "LOWER($_)";
287 $record->{$_} = $record->{$_}{'value'};
290 # ... EXISTS ( SELECT name, value FROM part_virtual_field
292 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
293 # WHERE recnum = svc_acct.svcnum
294 # AND (name, value) = ('egad', 'brain') )
296 my $value = $record->{$_};
300 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
301 "( SELECT part_virtual_field.name, virtual_field.value ".
302 "FROM part_virtual_field JOIN virtual_field ".
303 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
304 "WHERE virtual_field.recnum = ${table}.${pkey} ".
305 "AND part_virtual_field.name = '${column}'".
307 " AND virtual_field.value ${op} '${value}'"
311 } @virtual_fields ) );
315 $statement .= " $extra_sql" if defined($extra_sql);
317 warn "[debug]$me $statement\n" if $DEBUG > 1;
318 my $sth = $dbh->prepare($statement)
319 or croak "$dbh->errstr doing $statement";
324 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
326 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
327 && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
329 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_INTEGER } );
331 $sth->bind_param($bind++, $record->{$field}, { TYPE => SQL_VARCHAR } );
335 # $sth->execute( map $record->{$_},
336 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
337 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
339 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
341 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
342 @virtual_fields = "FS::$table"->virtual_fields;
344 cluck "warning: FS::$table not loaded; virtual fields not returned either";
345 @virtual_fields = ();
349 tie %result, "Tie::IxHash";
350 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
352 %result = map { $_->{$pkey}, $_ } @stuff;
354 @result{@stuff} = @stuff;
359 if ( keys(%result) and @virtual_fields ) {
361 "SELECT virtual_field.recnum, part_virtual_field.name, ".
362 "virtual_field.value ".
363 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
364 "WHERE part_virtual_field.dbtable = '$table' AND ".
365 "virtual_field.recnum IN (".
366 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
367 join(q!', '!, @virtual_fields) . "')";
368 warn "[debug]$me $statement\n" if $DEBUG > 1;
369 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
370 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
372 foreach (@{ $sth->fetchall_arrayref({}) }) {
373 my $recnum = $_->{recnum};
374 my $name = $_->{name};
375 my $value = $_->{value};
376 if (exists($result{$recnum})) {
377 $result{$recnum}->{$name} = $value;
382 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
383 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
384 #derivied class didn't override new method, so this optimization is safe
387 new_or_cached( "FS::$table", { %{$_} }, $cache )
391 new( "FS::$table", { %{$_} } )
395 warn "untested code (class FS::$table uses custom new method)";
397 eval 'FS::'. $table. '->new( { %{$_} } )';
401 cluck "warning: FS::$table not loaded; returning FS::Record objects";
403 FS::Record->new( $table, { %{$_} } );
409 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
411 Experimental JOINed search method. Using this method, you can execute a
412 single SELECT spanning multiple tables, and cache the results for subsequent
413 method calls. Interface will almost definately change in an incompatible
421 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
422 my $cache = FS::SearchCache->new( $ptable, $pkey );
425 grep { !$saw{$_->getfield($pkey)}++ }
426 qsearch($table, $record, $select, $extra_sql, $cache )
430 =item qsearchs TABLE, HASHREF
432 Same as qsearch, except that if more than one record matches, it B<carp>s but
433 returns the first. If this happens, you either made a logic error in asking
434 for a single item, or your data is corrupted.
438 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
440 my(@result) = qsearch(@_);
441 carp "warning: Multiple records in scalar search ($table)"
442 if scalar(@result) > 1;
443 #should warn more vehemently if the search was on a primary key?
444 scalar(@result) ? ($result[0]) : ();
455 Returns the table name.
460 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
467 Returns the DBIx::DBSchema::Table object for the table.
473 my($table)=$self->table;
474 $dbdef->table($table);
477 =item get, getfield COLUMN
479 Returns the value of the column/field/key COLUMN.
484 my($self,$field) = @_;
485 # to avoid "Use of unitialized value" errors
486 if ( defined ( $self->{Hash}->{$field} ) ) {
487 $self->{Hash}->{$field};
497 =item set, setfield COLUMN, VALUE
499 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
504 my($self,$field,$value) = @_;
505 $self->{'modified'} = 1;
506 $self->{'Hash'}->{$field} = $value;
513 =item AUTLOADED METHODS
515 $record->column is a synonym for $record->get('column');
517 $record->column('value') is a synonym for $record->set('column','value');
524 my($field)=$AUTOLOAD;
526 if ( defined($value) ) {
527 confess "errant AUTOLOAD $field for $self (arg $value)"
528 unless ref($self) && $self->can('setfield');
529 $self->setfield($field,$value);
531 confess "errant AUTOLOAD $field for $self (no args)"
532 unless ref($self) && $self->can('getfield');
533 $self->getfield($field);
539 # my $field = $AUTOLOAD;
541 # if ( defined($_[1]) ) {
542 # $_[0]->setfield($field, $_[1]);
544 # $_[0]->getfield($field);
550 Returns a list of the column/value pairs, usually for assigning to a new hash.
552 To make a distinct duplicate of an FS::Record object, you can do:
554 $new = new FS::Record ( $old->table, { $old->hash } );
560 confess $self. ' -> hash: Hash attribute is undefined'
561 unless defined($self->{'Hash'});
562 %{ $self->{'Hash'} };
567 Returns a reference to the column/value hash. This may be deprecated in the
568 future; if there's a reason you can't just use the autoloaded or get/set
580 Returns true if any of this object's values have been modified with set (or via
581 an autoloaded method). Doesn't yet recognize when you retreive a hashref and
593 Inserts this record to the database. If there is an error, returns the error,
594 otherwise returns false.
601 my $error = $self->check;
602 return $error if $error;
604 #single-field unique keys are given a value if false
605 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
606 foreach ( $self->dbdef_table->unique->singles ) {
607 $self->unique($_) unless $self->getfield($_);
610 #and also the primary key, if the database isn't going to
611 my $primary_key = $self->dbdef_table->primary_key;
613 if ( $primary_key ) {
614 my $col = $self->dbdef_table->column($primary_key);
617 uc($col->type) eq 'SERIAL'
618 || ( driver_name eq 'Pg'
619 && defined($col->default)
620 && $col->default =~ /^nextval\(/i
622 || ( driver_name eq 'mysql'
623 && defined($col->local)
624 && $col->local =~ /AUTO_INCREMENT/i
626 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
629 my $table = $self->table;
630 #false laziness w/delete
632 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
635 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
638 my $statement = "INSERT INTO $table ( ".
639 join( ', ', @real_fields ).
641 join( ', ', @values ).
644 warn "[debug]$me $statement\n" if $DEBUG > 1;
645 my $sth = dbh->prepare($statement) or return dbh->errstr;
647 local $SIG{HUP} = 'IGNORE';
648 local $SIG{INT} = 'IGNORE';
649 local $SIG{QUIT} = 'IGNORE';
650 local $SIG{TERM} = 'IGNORE';
651 local $SIG{TSTP} = 'IGNORE';
652 local $SIG{PIPE} = 'IGNORE';
654 $sth->execute or return $sth->errstr;
657 if ( $db_seq ) { # get inserted id from the database, if applicable
658 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
659 if ( driver_name eq 'Pg' ) {
661 my $oid = $sth->{'pg_oid_status'};
662 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
663 my $i_sth = dbh->prepare($i_sql) or do {
664 dbh->rollback if $FS::UID::AutoCommit;
667 $i_sth->execute($oid) or do {
668 dbh->rollback if $FS::UID::AutoCommit;
669 return $i_sth->errstr;
671 $insertid = $i_sth->fetchrow_arrayref->[0];
673 } elsif ( driver_name eq 'mysql' ) {
675 $insertid = dbh->{'mysql_insertid'};
676 # work around mysql_insertid being null some of the time, ala RT :/
677 unless ( $insertid ) {
678 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
679 "using SELECT LAST_INSERT_ID();";
680 my $i_sql = "SELECT LAST_INSERT_ID()";
681 my $i_sth = dbh->prepare($i_sql) or do {
682 dbh->rollback if $FS::UID::AutoCommit;
685 $i_sth->execute or do {
686 dbh->rollback if $FS::UID::AutoCommit;
687 return $i_sth->errstr;
689 $insertid = $i_sth->fetchrow_arrayref->[0];
693 dbh->rollback if $FS::UID::AutoCommit;
694 return "don't know how to retreive inserted ids from ". driver_name.
695 ", try using counterfiles (maybe run dbdef-create?)";
697 $self->setfield($primary_key, $insertid);
701 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
702 $self->virtual_fields;
703 if (@virtual_fields) {
704 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
706 my $vfieldpart = $self->vfieldpart_hashref;
708 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
711 my $v_sth = dbh->prepare($v_statement) or do {
712 dbh->rollback if $FS::UID::AutoCommit;
716 foreach (keys(%v_values)) {
717 $v_sth->execute($self->getfield($primary_key),
721 dbh->rollback if $FS::UID::AutoCommit;
722 return $v_sth->errstr;
729 if ( defined $dbdef->table('h_'. $table) ) {
730 my $h_statement = $self->_h_statement('insert');
731 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
732 $h_sth = dbh->prepare($h_statement) or do {
733 dbh->rollback if $FS::UID::AutoCommit;
739 $h_sth->execute or return $h_sth->errstr if $h_sth;
741 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
748 Depriciated (use insert instead).
753 cluck "warning: FS::Record::add deprecated!";
754 insert @_; #call method in this scope
759 Delete this record from the database. If there is an error, returns the error,
760 otherwise returns false.
767 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
769 $self->getfield($_) eq ''
770 #? "( $_ IS NULL OR $_ = \"\" )"
771 ? ( driver_name eq 'Pg'
773 : "( $_ IS NULL OR $_ = \"\" )"
775 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
776 } ( $self->dbdef_table->primary_key )
777 ? ( $self->dbdef_table->primary_key)
778 : real_fields($self->table)
780 warn "[debug]$me $statement\n" if $DEBUG > 1;
781 my $sth = dbh->prepare($statement) or return dbh->errstr;
784 if ( defined $dbdef->table('h_'. $self->table) ) {
785 my $h_statement = $self->_h_statement('delete');
786 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
787 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
792 my $primary_key = $self->dbdef_table->primary_key;
795 my $vfp = $self->vfieldpart_hashref;
796 foreach($self->virtual_fields) {
797 next if $self->getfield($_) eq '';
798 unless(@del_vfields) {
799 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
800 $v_sth = dbh->prepare($st) or return dbh->errstr;
802 push @del_vfields, $_;
805 local $SIG{HUP} = 'IGNORE';
806 local $SIG{INT} = 'IGNORE';
807 local $SIG{QUIT} = 'IGNORE';
808 local $SIG{TERM} = 'IGNORE';
809 local $SIG{TSTP} = 'IGNORE';
810 local $SIG{PIPE} = 'IGNORE';
812 my $rc = $sth->execute or return $sth->errstr;
813 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
814 $h_sth->execute or return $h_sth->errstr if $h_sth;
815 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
816 or return $v_sth->errstr
817 foreach (@del_vfields);
819 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
821 #no need to needlessly destoy the data either (causes problems actually)
822 #undef $self; #no need to keep object!
829 Depriciated (use delete instead).
834 cluck "warning: FS::Record::del deprecated!";
835 &delete(@_); #call method in this scope
838 =item replace OLD_RECORD
840 Replace the OLD_RECORD with this one in the database. If there is an error,
841 returns the error, otherwise returns false.
852 warn "[debug]$me replace called with no arguments; autoloading old record\n"
854 my $primary_key = $new->dbdef_table->primary_key;
855 if ( $primary_key ) {
856 $old = qsearchs($new->table, { $primary_key => $new->$primary_key() } )
857 or croak "can't find ". $new->table. ".$primary_key ".
858 $new->$primary_key();
860 croak $new->table. " has no primary key; pass old record as argument";
864 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
866 return "Records not in same table!" unless $new->table eq $old->table;
868 my $primary_key = $old->dbdef_table->primary_key;
869 return "Can't change $primary_key"
871 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
873 my $error = $new->check;
874 return $error if $error;
876 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
877 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
878 ? ($_, $new->getfield($_)) : () } $old->fields;
880 unless ( keys(%diff) ) {
881 carp "[warning]$me $new -> replace $old: records identical";
885 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
887 "$_ = ". _quote($new->getfield($_),$old->table,$_)
888 } real_fields($old->table)
892 $old->getfield($_) eq ''
893 #? "( $_ IS NULL OR $_ = \"\" )"
894 ? ( driver_name eq 'Pg'
895 ? "( $_ IS NULL OR $_ = '' )"
896 : "( $_ IS NULL OR $_ = \"\" )"
898 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
899 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
902 warn "[debug]$me $statement\n" if $DEBUG > 1;
903 my $sth = dbh->prepare($statement) or return dbh->errstr;
906 if ( defined $dbdef->table('h_'. $old->table) ) {
907 my $h_old_statement = $old->_h_statement('replace_old');
908 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
909 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
915 if ( defined $dbdef->table('h_'. $new->table) ) {
916 my $h_new_statement = $new->_h_statement('replace_new');
917 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
918 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
923 # For virtual fields we have three cases with different SQL
924 # statements: add, replace, delete
928 my (@add_vfields, @rep_vfields, @del_vfields);
929 my $vfp = $old->vfieldpart_hashref;
930 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
931 if($diff{$_} eq '') {
933 unless(@del_vfields) {
934 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
935 "AND vfieldpart = ?";
936 warn "[debug]$me $st\n" if $DEBUG > 2;
937 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
939 push @del_vfields, $_;
940 } elsif($old->getfield($_) eq '') {
942 unless(@add_vfields) {
943 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
945 warn "[debug]$me $st\n" if $DEBUG > 2;
946 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
948 push @add_vfields, $_;
951 unless(@rep_vfields) {
952 my $st = "UPDATE virtual_field SET value = ? ".
953 "WHERE recnum = ? AND vfieldpart = ?";
954 warn "[debug]$me $st\n" if $DEBUG > 2;
955 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
957 push @rep_vfields, $_;
961 local $SIG{HUP} = 'IGNORE';
962 local $SIG{INT} = 'IGNORE';
963 local $SIG{QUIT} = 'IGNORE';
964 local $SIG{TERM} = 'IGNORE';
965 local $SIG{TSTP} = 'IGNORE';
966 local $SIG{PIPE} = 'IGNORE';
968 my $rc = $sth->execute or return $sth->errstr;
969 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
970 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
971 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
973 $v_del_sth->execute($old->getfield($primary_key),
975 or return $v_del_sth->errstr
976 foreach(@del_vfields);
978 $v_add_sth->execute($new->getfield($_),
979 $old->getfield($primary_key),
981 or return $v_add_sth->errstr
982 foreach(@add_vfields);
984 $v_rep_sth->execute($new->getfield($_),
985 $old->getfield($primary_key),
987 or return $v_rep_sth->errstr
988 foreach(@rep_vfields);
990 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
998 Depriciated (use replace instead).
1003 cluck "warning: FS::Record::rep deprecated!";
1004 replace @_; #call method in this scope
1009 Checks virtual fields (using check_blocks). Subclasses should still provide
1010 a check method to validate real fields, foreign keys, etc., and call this
1011 method via $self->SUPER::check.
1013 (FIXME: Should this method try to make sure that it I<is> being called from
1014 a subclass's check method, to keep the current semantics as far as possible?)
1019 #confess "FS::Record::check not implemented; supply one in subclass!";
1022 foreach my $field ($self->virtual_fields) {
1023 for ($self->getfield($field)) {
1024 # See notes on check_block in FS::part_virtual_field.
1025 eval $self->pvf($field)->check_block;
1027 #this is bad, probably want to follow the stack backtrace up and see
1029 my $err = "Fatal error checking $field for $self";
1031 return "$err (see log for backtrace): $@";
1034 $self->setfield($field, $_);
1041 my( $self, $action ) = @_;
1044 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
1045 real_fields($self->table);
1047 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
1049 "INSERT INTO h_". $self->table. " ( ".
1050 join(', ', qw(history_date history_user history_action), @fields ).
1052 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
1059 B<Warning>: External use is B<deprecated>.
1061 Replaces COLUMN in record with a unique number, using counters in the
1062 filesystem. Used by the B<insert> method on single-field unique columns
1063 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1064 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1066 Returns the new value.
1071 my($self,$field) = @_;
1072 my($table)=$self->table;
1074 croak "Unique called on field $field, but it is ",
1075 $self->getfield($field),
1077 if $self->getfield($field);
1079 #warn "table $table is tainted" if is_tainted($table);
1080 #warn "field $field is tainted" if is_tainted($field);
1082 my($counter) = new File::CounterFile "$table.$field",0;
1084 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1086 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1089 my $index = $counter->inc;
1090 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1092 $index =~ /^(\d*)$/;
1095 $self->setfield($field,$index);
1099 =item ut_float COLUMN
1101 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1102 null. If there is an error, returns the error, otherwise returns false.
1107 my($self,$field)=@_ ;
1108 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1109 $self->getfield($field) =~ /^(\d+)$/ ||
1110 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1111 $self->getfield($field) =~ /^(\d+e\d+)$/)
1112 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1113 $self->setfield($field,$1);
1117 =item ut_snumber COLUMN
1119 Check/untaint signed numeric data (whole numbers). May not be null. If there
1120 is an error, returns the error, otherwise returns false.
1125 my($self, $field) = @_;
1126 $self->getfield($field) =~ /^(-?)\s*(\d+)$/
1127 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1128 $self->setfield($field, "$1$2");
1132 =item ut_number COLUMN
1134 Check/untaint simple numeric data (whole numbers). May not be null. If there
1135 is an error, returns the error, otherwise returns false.
1140 my($self,$field)=@_;
1141 $self->getfield($field) =~ /^(\d+)$/
1142 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1143 $self->setfield($field,$1);
1147 =item ut_numbern COLUMN
1149 Check/untaint simple numeric data (whole numbers). May be null. If there is
1150 an error, returns the error, otherwise returns false.
1155 my($self,$field)=@_;
1156 $self->getfield($field) =~ /^(\d*)$/
1157 or return "Illegal (numeric) $field: ". $self->getfield($field);
1158 $self->setfield($field,$1);
1162 =item ut_money COLUMN
1164 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1165 is an error, returns the error, otherwise returns false.
1170 my($self,$field)=@_;
1171 $self->setfield($field, 0) if $self->getfield($field) eq '';
1172 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1173 or return "Illegal (money) $field: ". $self->getfield($field);
1174 #$self->setfield($field, "$1$2$3" || 0);
1175 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1179 =item ut_text COLUMN
1181 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1182 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1183 May not be null. If there is an error, returns the error, otherwise returns
1189 my($self,$field)=@_;
1190 #warn "msgcat ". \&msgcat. "\n";
1191 #warn "notexist ". \¬exist. "\n";
1192 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1193 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1194 or return gettext('illegal_or_empty_text'). " $field: ".
1195 $self->getfield($field);
1196 $self->setfield($field,$1);
1200 =item ut_textn COLUMN
1202 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1203 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1204 May be null. If there is an error, returns the error, otherwise returns false.
1209 my($self,$field)=@_;
1210 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1211 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1212 $self->setfield($field,$1);
1216 =item ut_alpha COLUMN
1218 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1219 an error, returns the error, otherwise returns false.
1224 my($self,$field)=@_;
1225 $self->getfield($field) =~ /^(\w+)$/
1226 or return "Illegal or empty (alphanumeric) $field: ".
1227 $self->getfield($field);
1228 $self->setfield($field,$1);
1232 =item ut_alpha COLUMN
1234 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1235 error, returns the error, otherwise returns false.
1240 my($self,$field)=@_;
1241 $self->getfield($field) =~ /^(\w*)$/
1242 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1243 $self->setfield($field,$1);
1247 =item ut_phonen COLUMN [ COUNTRY ]
1249 Check/untaint phone numbers. May be null. If there is an error, returns
1250 the error, otherwise returns false.
1252 Takes an optional two-letter ISO country code; without it or with unsupported
1253 countries, ut_phonen simply calls ut_alphan.
1258 my( $self, $field, $country ) = @_;
1259 return $self->ut_alphan($field) unless defined $country;
1260 my $phonen = $self->getfield($field);
1261 if ( $phonen eq '' ) {
1262 $self->setfield($field,'');
1263 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1265 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1266 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1267 $phonen = "$1-$2-$3";
1268 $phonen .= " x$4" if $4;
1269 $self->setfield($field,$phonen);
1271 warn "warning: don't know how to check phone numbers for country $country";
1272 return $self->ut_textn($field);
1279 Check/untaint ip addresses. IPv4 only for now.
1284 my( $self, $field ) = @_;
1285 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1286 or return "Illegal (IP address) $field: ". $self->getfield($field);
1287 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1288 $self->setfield($field, "$1.$2.$3.$4");
1294 Check/untaint ip addresses. IPv4 only for now. May be null.
1299 my( $self, $field ) = @_;
1300 if ( $self->getfield($field) =~ /^()$/ ) {
1301 $self->setfield($field,'');
1304 $self->ut_ip($field);
1308 =item ut_domain COLUMN
1310 Check/untaint host and domain names.
1315 my( $self, $field ) = @_;
1316 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1317 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1318 or return "Illegal (domain) $field: ". $self->getfield($field);
1319 $self->setfield($field,$1);
1323 =item ut_name COLUMN
1325 Check/untaint proper names; allows alphanumerics, spaces and the following
1326 punctuation: , . - '
1333 my( $self, $field ) = @_;
1334 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1335 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1336 $self->setfield($field,$1);
1342 Check/untaint zip codes.
1347 my( $self, $field, $country ) = @_;
1348 if ( $country eq 'US' ) {
1349 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1350 or return gettext('illegal_zip'). " $field for country $country: ".
1351 $self->getfield($field);
1352 $self->setfield($field,$1);
1354 if ( $self->getfield($field) =~ /^\s*$/ ) {
1355 $self->setfield($field,'');
1357 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1358 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1359 $self->setfield($field,$1);
1365 =item ut_country COLUMN
1367 Check/untaint country codes. Country names are changed to codes, if possible -
1368 see L<Locale::Country>.
1373 my( $self, $field ) = @_;
1374 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1375 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1376 && country2code($1) ) {
1377 $self->setfield($field,uc(country2code($1)));
1380 $self->getfield($field) =~ /^(\w\w)$/
1381 or return "Illegal (country) $field: ". $self->getfield($field);
1382 $self->setfield($field,uc($1));
1386 =item ut_anything COLUMN
1388 Untaints arbitrary data. Be careful.
1393 my( $self, $field ) = @_;
1394 $self->getfield($field) =~ /^(.*)$/s
1395 or return "Illegal $field: ". $self->getfield($field);
1396 $self->setfield($field,$1);
1400 =item ut_enum COLUMN CHOICES_ARRAYREF
1402 Check/untaint a column, supplying all possible choices, like the "enum" type.
1407 my( $self, $field, $choices ) = @_;
1408 foreach my $choice ( @$choices ) {
1409 if ( $self->getfield($field) eq $choice ) {
1410 $self->setfield($choice);
1414 return "Illegal (enum) field $field: ". $self->getfield($field);
1417 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1419 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1420 on the column first.
1424 sub ut_foreign_key {
1425 my( $self, $field, $table, $foreign ) = @_;
1426 qsearchs($table, { $foreign => $self->getfield($field) })
1427 or return "Can't find ". $self->table. ".$field ". $self->getfield($field).
1428 " in $table.$foreign";
1432 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1434 Like ut_foreign_key, except the null value is also allowed.
1438 sub ut_foreign_keyn {
1439 my( $self, $field, $table, $foreign ) = @_;
1440 $self->getfield($field)
1441 ? $self->ut_foreign_key($field, $table, $foreign)
1446 =item virtual_fields [ TABLE ]
1448 Returns a list of virtual fields defined for the table. This should not
1449 be exported, and should only be called as an instance or class method.
1453 sub virtual_fields {
1456 $table = $self->table or confess "virtual_fields called on non-table";
1458 confess "Unknown table $table" unless $dbdef->table($table);
1460 return () unless $self->dbdef->table('part_virtual_field');
1462 unless ( $virtual_fields_cache{$table} ) {
1463 my $query = 'SELECT name from part_virtual_field ' .
1464 "WHERE dbtable = '$table'";
1466 my $result = $dbh->selectcol_arrayref($query);
1467 confess $dbh->errstr if $dbh->err;
1468 $virtual_fields_cache{$table} = $result;
1471 @{$virtual_fields_cache{$table}};
1476 =item fields [ TABLE ]
1478 This is a wrapper for real_fields and virtual_fields. Code that called
1479 fields before should probably continue to call fields.
1484 my $something = shift;
1486 if($something->isa('FS::Record')) {
1487 $table = $something->table;
1489 $table = $something;
1490 $something = "FS::$table";
1492 return (real_fields($table), $something->virtual_fields());
1497 =item pvf FIELD_NAME
1499 Returns the FS::part_virtual_field object corresponding to a field in the
1500 record (specified by FIELD_NAME).
1505 my ($self, $name) = (shift, shift);
1507 if(grep /^$name$/, $self->virtual_fields) {
1508 return qsearchs('part_virtual_field', { dbtable => $self->table,
1518 =item real_fields [ TABLE ]
1520 Returns a list of the real columns in the specified table. Called only by
1521 fields() and other subroutines elsewhere in FS::Record.
1528 my($table_obj) = $dbdef->table($table);
1529 confess "Unknown table $table" unless $table_obj;
1530 $table_obj->columns;
1533 =item reload_dbdef([FILENAME])
1535 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1536 non-default filename. This command is executed at startup unless
1537 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1542 my $file = shift || $dbdef_file;
1544 unless ( exists $dbdef_cache{$file} ) {
1545 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1546 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1547 or die "can't load database schema from $file";
1549 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1551 $dbdef = $dbdef_cache{$file};
1556 Returns the current database definition. See L<DBIx::DBSchema>.
1560 sub dbdef { $dbdef; }
1562 =item _quote VALUE, TABLE, COLUMN
1564 This is an internal function used to construct SQL statements. It returns
1565 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1566 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1571 my($value, $table, $column) = @_;
1572 my $column_obj = $dbdef->table($table)->column($column);
1573 my $column_type = $column_obj->type;
1575 if ( $value eq '' && $column_type =~ /^int/ ) {
1576 if ( $column_obj->null ) {
1579 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1583 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1584 ! $column_type =~ /(char|binary|text)$/i ) {
1591 =item vfieldpart_hashref TABLE
1593 Returns a hashref of virtual field names and vfieldparts applicable to the given
1598 sub vfieldpart_hashref {
1600 my $table = $self->table;
1602 return {} unless $self->dbdef->table('part_virtual_field');
1605 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1606 "dbtable = '$table'";
1607 my $sth = $dbh->prepare($statement);
1608 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1609 return { map { $_->{name}, $_->{vfieldpart} }
1610 @{$sth->fetchall_arrayref({})} };
1617 This is deprecated. Don't use it.
1619 It returns a hash-type list with the fields of this record's table set true.
1624 carp "warning: hfields is deprecated";
1627 foreach (fields($table)) {
1636 "$_: ". $self->getfield($_). "|"
1637 } (fields($self->table)) );
1640 sub DESTROY { return; }
1644 # #use Carp qw(cluck);
1645 # #cluck "DESTROYING $self";
1646 # warn "DESTROYING $self";
1650 # return ! eval { join('',@_), kill 0; 1; };
1657 This module should probably be renamed, since much of the functionality is
1658 of general use. It is not completely unlike Adapter::DBI (see below).
1660 Exported qsearch and qsearchs should be deprecated in favor of method calls
1661 (against an FS::Record object like the old search and searchs that qsearch
1662 and qsearchs were on top of.)
1664 The whole fields / hfields mess should be removed.
1666 The various WHERE clauses should be subroutined.
1668 table string should be deprecated in favor of DBIx::DBSchema::Table.
1670 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1671 true maps to the database (and WHERE clauses) would also help.
1673 The ut_ methods should ask the dbdef for a default length.
1675 ut_sqltype (like ut_varchar) should all be defined
1677 A fallback check method should be provided which uses the dbdef.
1679 The ut_money method assumes money has two decimal digits.
1681 The Pg money kludge in the new method only strips `$'.
1683 The ut_phonen method only checks US-style phone numbers.
1685 The _quote function should probably use ut_float instead of a regex.
1687 All the subroutines probably should be methods, here or elsewhere.
1689 Probably should borrow/use some dbdef methods where appropriate (like sub
1692 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1693 or allow it to be set. Working around it is ugly any way around - DBI should
1694 be fixed. (only affects RDBMS which return uppercase column names)
1696 ut_zip should take an optional country like ut_phone.
1700 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1702 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.