4 use vars qw( $dbdef_file $dbdef $setup_hack $AUTOLOAD @ISA @EXPORT_OK $DEBUG
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.21;
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 my $hashref = $self->{'Hash'} = shift;
137 foreach my $field ( grep !defined($hashref->{$_}), $self->fields ) {
138 $hashref->{$field}='';
141 $self->_cache($hashref, shift) if $self->can('_cache') && @_;
148 my $class = ref($proto) || $proto;
150 bless ($self, $class);
152 $self->{'Table'} = shift unless defined ( $self->table );
154 my $hashref = $self->{'Hash'} = shift;
156 if ( defined( $cache->cache->{$hashref->{$cache->key}} ) ) {
157 my $obj = $cache->cache->{$hashref->{$cache->key}};
158 $obj->_cache($hashref, $cache) if $obj->can('_cache');
161 $cache->cache->{$hashref->{$cache->key}} = $self->new($hashref, $cache);
168 my $class = ref($proto) || $proto;
170 bless ($self, $class);
171 if ( defined $self->table ) {
172 cluck "create constructor is deprecated, use new!";
175 croak "FS::Record::create called (not from a subclass)!";
179 =item qsearch TABLE, HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ
181 Searches the database for all records matching (at least) the key/value pairs
182 in HASHREF. Returns all the records found as `FS::TABLE' objects if that
183 module is loaded (i.e. via `use FS::cust_main;'), otherwise returns FS::Record
186 ###oops, argh, FS::Record::new only lets us create database fields.
187 #Normal behaviour if SELECT is not specified is `*', as in
188 #C<SELECT * FROM table WHERE ...>. However, there is an experimental new
189 #feature where you can specify SELECT - remember, the objects returned,
190 #although blessed into the appropriate `FS::TABLE' package, will only have the
191 #fields you specify. This might have unwanted results if you then go calling
192 #regular FS::TABLE methods
198 my($stable, $record, $select, $extra_sql, $cache ) = @_;
199 #$stable =~ /^([\w\_]+)$/ or die "Illegal table: $table";
201 $stable =~ /^([\w\s\(\)\.\,\=]+)$/ or die "Illegal table: $stable";
206 my $table = $cache ? $cache->table : $stable;
207 my $pkey = $dbdef->table($table)->primary_key;
209 my @real_fields = grep exists($record->{$_}), real_fields($table);
210 my @virtual_fields = grep exists($record->{$_}), "FS::$table"->virtual_fields;
212 my $statement = "SELECT $select FROM $stable";
213 if ( @real_fields or @virtual_fields ) {
214 $statement .= ' WHERE '. join(' AND ',
219 if ( ref($record->{$_}) ) {
220 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
221 #$op = 'LIKE' if $op =~ /^ILIKE$/i && driver_name ne 'Pg';
222 if ( uc($op) eq 'ILIKE' ) {
224 $record->{$_}{'value'} = lc($record->{$_}{'value'});
225 $column = "LOWER($_)";
227 $record->{$_} = $record->{$_}{'value'}
230 if ( ! defined( $record->{$_} ) || $record->{$_} eq '' ) {
232 if ( driver_name eq 'Pg' ) {
233 my $type = $dbdef->table($table)->column($column)->type;
234 if ( $type =~ /(int|serial)/i ) {
235 qq-( $column IS NULL )-;
237 qq-( $column IS NULL OR $column = '' )-;
240 qq-( $column IS NULL OR $column = "" )-;
242 } elsif ( $op eq '!=' ) {
243 if ( driver_name eq 'Pg' ) {
244 my $type = $dbdef->table($table)->column($column)->type;
245 if ( $type =~ /(int|serial)/i ) {
246 qq-( $column IS NOT NULL )-;
248 qq-( $column IS NOT NULL AND $column != '' )-;
251 qq-( $column IS NOT NULL AND $column != "" )-;
254 if ( driver_name eq 'Pg' ) {
255 qq-( $column $op '' )-;
257 qq-( $column $op "" )-;
267 if ( ref($record->{$_}) ) {
268 $op = $record->{$_}{'op'} if $record->{$_}{'op'};
269 if ( uc($op) eq 'ILIKE' ) {
271 $record->{$_}{'value'} = lc($record->{$_}{'value'});
272 $column = "LOWER($_)";
274 $record->{$_} = $record->{$_}{'value'};
277 # ... EXISTS ( SELECT name, value FROM part_virtual_field
279 # ON part_virtual_field.vfieldpart = virtual_field.vfieldpart
280 # WHERE recnum = svc_acct.svcnum
281 # AND (name, value) = ('egad', 'brain') )
283 my $value = $record->{$_};
287 $subq = ($value ? 'EXISTS ' : 'NOT EXISTS ') .
288 "( SELECT part_virtual_field.name, virtual_field.value ".
289 "FROM part_virtual_field JOIN virtual_field ".
290 "ON part_virtual_field.vfieldpart = virtual_field.vfieldpart ".
291 "WHERE virtual_field.recnum = ${table}.${pkey} ".
292 "AND part_virtual_field.name = '${column}'".
294 " AND virtual_field.value ${op} '${value}'"
298 } @virtual_fields ) );
302 $statement .= " $extra_sql" if defined($extra_sql);
304 warn "[debug]$me $statement\n" if $DEBUG > 1;
305 my $sth = $dbh->prepare($statement)
306 or croak "$dbh->errstr doing $statement";
311 grep defined( $record->{$_} ) && $record->{$_} ne '', @real_fields
313 if ( $record->{$field} =~ /^\d+(\.\d+)?$/
314 && $dbdef->table($table)->column($field)->type =~ /(int|serial)/i
316 $sth->bind_param($bind++, $record->{$field}, SQL_INTEGER );
318 $sth->bind_param($bind++, $record->{$field}, SQL_VARCHAR );
322 # $sth->execute( map $record->{$_},
323 # grep defined( $record->{$_} ) && $record->{$_} ne '', @fields
324 # ) or croak "Error executing \"$statement\": ". $sth->errstr;
326 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
329 tie %result, "Tie::IxHash";
330 @virtual_fields = "FS::$table"->virtual_fields;
332 my @stuff = @{ $sth->fetchall_arrayref( {} ) };
334 %result = map { $_->{$pkey}, $_ } @stuff;
336 @result{@stuff} = @stuff;
340 if ( keys(%result) and @virtual_fields ) {
342 "SELECT virtual_field.recnum, part_virtual_field.name, ".
343 "virtual_field.value ".
344 "FROM part_virtual_field JOIN virtual_field USING (vfieldpart) ".
345 "WHERE part_virtual_field.dbtable = '$table' AND ".
346 "virtual_field.recnum IN (".
347 join(',', keys(%result)). ") AND part_virtual_field.name IN ('".
348 join(q!', '!, @virtual_fields) . "')";
349 warn "[debug]$me $statement\n" if $DEBUG > 1;
350 $sth = $dbh->prepare($statement) or croak "$dbh->errstr doing $statement";
351 $sth->execute or croak "Error executing \"$statement\": ". $sth->errstr;
353 foreach (@{ $sth->fetchall_arrayref({}) }) {
354 my $recnum = $_->{recnum};
355 my $name = $_->{name};
356 my $value = $_->{value};
357 if (exists($result{$recnum})) {
358 $result{$recnum}->{$name} = $value;
363 if ( eval 'scalar(@FS::'. $table. '::ISA);' ) {
364 if ( eval 'FS::'. $table. '->can(\'new\')' eq \&new ) {
365 #derivied class didn't override new method, so this optimization is safe
368 new_or_cached( "FS::$table", { %{$_} }, $cache )
372 new( "FS::$table", { %{$_} } )
376 warn "untested code (class FS::$table uses custom new method)";
378 eval 'FS::'. $table. '->new( { %{$_} } )';
382 cluck "warning: FS::$table not loaded; returning FS::Record objects";
384 FS::Record->new( $table, { %{$_} } );
390 =item jsearch TABLE, HASHREF, SELECT, EXTRA_SQL, PRIMARY_TABLE, PRIMARY_KEY
392 Experimental JOINed search method. Using this method, you can execute a
393 single SELECT spanning multiple tables, and cache the results for subsequent
394 method calls. Interface will almost definately change in an incompatible
402 my($table, $record, $select, $extra_sql, $ptable, $pkey ) = @_;
403 my $cache = FS::SearchCache->new( $ptable, $pkey );
406 grep { !$saw{$_->getfield($pkey)}++ }
407 qsearch($table, $record, $select, $extra_sql, $cache )
411 =item qsearchs TABLE, HASHREF
413 Same as qsearch, except that if more than one record matches, it B<carp>s but
414 returns the first. If this happens, you either made a logic error in asking
415 for a single item, or your data is corrupted.
419 sub qsearchs { # $result_record = &FS::Record:qsearchs('table',\%hash);
421 my(@result) = qsearch(@_);
422 carp "warning: Multiple records in scalar search ($table)"
423 if scalar(@result) > 1;
424 #should warn more vehemently if the search was on a primary key?
425 scalar(@result) ? ($result[0]) : ();
436 Returns the table name.
441 # cluck "warning: FS::Record::table deprecated; supply one in subclass!";
448 Returns the DBIx::DBSchema::Table object for the table.
454 my($table)=$self->table;
455 $dbdef->table($table);
458 =item get, getfield COLUMN
460 Returns the value of the column/field/key COLUMN.
465 my($self,$field) = @_;
466 # to avoid "Use of unitialized value" errors
467 if ( defined ( $self->{Hash}->{$field} ) ) {
468 $self->{Hash}->{$field};
478 =item set, setfield COLUMN, VALUE
480 Sets the value of the column/field/key COLUMN to VALUE. Returns VALUE.
485 my($self,$field,$value) = @_;
486 $self->{'Hash'}->{$field} = $value;
493 =item AUTLOADED METHODS
495 $record->column is a synonym for $record->get('column');
497 $record->column('value') is a synonym for $record->set('column','value');
504 my($field)=$AUTOLOAD;
506 if ( defined($value) ) {
507 confess "errant AUTOLOAD $field for $self (arg $value)"
508 unless ref($self) && $self->can('setfield');
509 $self->setfield($field,$value);
511 confess "errant AUTOLOAD $field for $self (no args)"
512 unless ref($self) && $self->can('getfield');
513 $self->getfield($field);
519 # my $field = $AUTOLOAD;
521 # if ( defined($_[1]) ) {
522 # $_[0]->setfield($field, $_[1]);
524 # $_[0]->getfield($field);
530 Returns a list of the column/value pairs, usually for assigning to a new hash.
532 To make a distinct duplicate of an FS::Record object, you can do:
534 $new = new FS::Record ( $old->table, { $old->hash } );
540 %{ $self->{'Hash'} };
545 Returns a reference to the column/value hash.
556 Inserts this record to the database. If there is an error, returns the error,
557 otherwise returns false.
564 my $error = $self->check;
565 return $error if $error;
567 #single-field unique keys are given a value if false
568 #(like MySQL's AUTO_INCREMENT or Pg SERIAL)
569 foreach ( $self->dbdef_table->unique->singles ) {
570 $self->unique($_) unless $self->getfield($_);
573 #and also the primary key, if the database isn't going to
574 my $primary_key = $self->dbdef_table->primary_key;
576 if ( $primary_key ) {
577 my $col = $self->dbdef_table->column($primary_key);
580 uc($col->type) eq 'SERIAL'
581 || ( driver_name eq 'Pg'
582 && defined($col->default)
583 && $col->default =~ /^nextval\(/i
585 || ( driver_name eq 'mysql'
586 && defined($col->local)
587 && $col->local =~ /AUTO_INCREMENT/i
589 $self->unique($primary_key) unless $self->getfield($primary_key) || $db_seq;
592 my $table = $self->table;
593 #false laziness w/delete
595 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
598 my @values = map { _quote( $self->getfield($_), $table, $_) } @real_fields;
601 my $statement = "INSERT INTO $table ( ".
602 join( ', ', @real_fields ).
604 join( ', ', @values ).
607 warn "[debug]$me $statement\n" if $DEBUG > 1;
608 my $sth = dbh->prepare($statement) or return dbh->errstr;
610 local $SIG{HUP} = 'IGNORE';
611 local $SIG{INT} = 'IGNORE';
612 local $SIG{QUIT} = 'IGNORE';
613 local $SIG{TERM} = 'IGNORE';
614 local $SIG{TSTP} = 'IGNORE';
615 local $SIG{PIPE} = 'IGNORE';
617 $sth->execute or return $sth->errstr;
620 if ( $db_seq ) { # get inserted id from the database, if applicable
621 warn "[debug]$me retreiving sequence from database\n" if $DEBUG;
622 if ( driver_name eq 'Pg' ) {
624 my $oid = $sth->{'pg_oid_status'};
625 my $i_sql = "SELECT $primary_key FROM $table WHERE oid = ?";
626 my $i_sth = dbh->prepare($i_sql) or do {
627 dbh->rollback if $FS::UID::AutoCommit;
630 $i_sth->execute($oid) or do {
631 dbh->rollback if $FS::UID::AutoCommit;
632 return $i_sth->errstr;
634 $insertid = $i_sth->fetchrow_arrayref->[0];
636 } elsif ( driver_name eq 'mysql' ) {
638 $insertid = dbh->{'mysql_insertid'};
639 # work around mysql_insertid being null some of the time, ala RT :/
640 unless ( $insertid ) {
641 warn "WARNING: DBD::mysql didn't return mysql_insertid; ".
642 "using SELECT LAST_INSERT_ID();";
643 my $i_sql = "SELECT LAST_INSERT_ID()";
644 my $i_sth = dbh->prepare($i_sql) or do {
645 dbh->rollback if $FS::UID::AutoCommit;
648 $i_sth->execute or do {
649 dbh->rollback if $FS::UID::AutoCommit;
650 return $i_sth->errstr;
652 $insertid = $i_sth->fetchrow_arrayref->[0];
656 dbh->rollback if $FS::UID::AutoCommit;
657 return "don't know how to retreive inserted ids from ". driver_name.
658 ", try using counterfiles (maybe run dbdef-create?)";
660 $self->setfield($primary_key, $insertid);
664 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
665 $self->virtual_fields;
666 if (@virtual_fields) {
667 my %v_values = map { $_, $self->getfield($_) } @virtual_fields;
669 my $vfieldpart = $self->vfieldpart_hashref;
671 my $v_statement = "INSERT INTO virtual_field(recnum, vfieldpart, value) ".
674 my $v_sth = dbh->prepare($v_statement) or do {
675 dbh->rollback if $FS::UID::AutoCommit;
679 foreach (keys(%v_values)) {
680 $v_sth->execute($self->getfield($primary_key),
684 dbh->rollback if $FS::UID::AutoCommit;
685 return $v_sth->errstr;
692 if ( defined $dbdef->table('h_'. $table) ) {
693 my $h_statement = $self->_h_statement('insert');
694 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
695 $h_sth = dbh->prepare($h_statement) or do {
696 dbh->rollback if $FS::UID::AutoCommit;
702 $h_sth->execute or return $h_sth->errstr if $h_sth;
704 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
711 Depriciated (use insert instead).
716 cluck "warning: FS::Record::add deprecated!";
717 insert @_; #call method in this scope
722 Delete this record from the database. If there is an error, returns the error,
723 otherwise returns false.
730 my $statement = "DELETE FROM ". $self->table. " WHERE ". join(' AND ',
732 $self->getfield($_) eq ''
733 #? "( $_ IS NULL OR $_ = \"\" )"
734 ? ( driver_name eq 'Pg'
736 : "( $_ IS NULL OR $_ = \"\" )"
738 : "$_ = ". _quote($self->getfield($_),$self->table,$_)
739 } ( $self->dbdef_table->primary_key )
740 ? ( $self->dbdef_table->primary_key)
741 : real_fields($self->table)
743 warn "[debug]$me $statement\n" if $DEBUG > 1;
744 my $sth = dbh->prepare($statement) or return dbh->errstr;
747 if ( defined $dbdef->table('h_'. $self->table) ) {
748 my $h_statement = $self->_h_statement('delete');
749 warn "[debug]$me $h_statement\n" if $DEBUG > 2;
750 $h_sth = dbh->prepare($h_statement) or return dbh->errstr;
755 my $primary_key = $self->dbdef_table->primary_key;
758 my $vfp = $self->vfieldpart_hashref;
759 foreach($self->virtual_fields) {
760 next if $self->getfield($_) eq '';
761 unless(@del_vfields) {
762 my $st = "DELETE FROM virtual_field WHERE recnum = ? AND vfieldpart = ?";
763 $v_sth = dbh->prepare($st) or return dbh->errstr;
765 push @del_vfields, $_;
768 local $SIG{HUP} = 'IGNORE';
769 local $SIG{INT} = 'IGNORE';
770 local $SIG{QUIT} = 'IGNORE';
771 local $SIG{TERM} = 'IGNORE';
772 local $SIG{TSTP} = 'IGNORE';
773 local $SIG{PIPE} = 'IGNORE';
775 my $rc = $sth->execute or return $sth->errstr;
776 #not portable #return "Record not found, statement:\n$statement" if $rc eq "0E0";
777 $h_sth->execute or return $h_sth->errstr if $h_sth;
778 $v_sth->execute($self->getfield($primary_key), $vfp->{$_})
779 or return $v_sth->errstr
780 foreach (@del_vfields);
782 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
784 #no need to needlessly destoy the data either (causes problems actually)
785 #undef $self; #no need to keep object!
792 Depriciated (use delete instead).
797 cluck "warning: FS::Record::del deprecated!";
798 &delete(@_); #call method in this scope
801 =item replace OLD_RECORD
803 Replace the OLD_RECORD with this one in the database. If there is an error,
804 returns the error, otherwise returns false.
809 my ( $new, $old ) = ( shift, shift );
810 warn "[debug]$me $new ->replace $old\n" if $DEBUG;
812 return "Records not in same table!" unless $new->table eq $old->table;
814 my $primary_key = $old->dbdef_table->primary_key;
815 return "Can't change $primary_key"
817 && ( $old->getfield($primary_key) ne $new->getfield($primary_key) );
819 my $error = $new->check;
820 return $error if $error;
822 #my @diff = grep $new->getfield($_) ne $old->getfield($_), $old->fields;
823 my %diff = map { ($new->getfield($_) ne $old->getfield($_))
824 ? ($_, $new->getfield($_)) : () } $old->fields;
826 unless ( keys(%diff) ) {
827 carp "[warning]$me $new -> replace $old: records identical";
831 my $statement = "UPDATE ". $old->table. " SET ". join(', ',
833 "$_ = ". _quote($new->getfield($_),$old->table,$_)
834 } real_fields($old->table)
838 $old->getfield($_) eq ''
839 #? "( $_ IS NULL OR $_ = \"\" )"
840 ? ( driver_name eq 'Pg'
842 : "( $_ IS NULL OR $_ = \"\" )"
844 : "$_ = ". _quote($old->getfield($_),$old->table,$_)
845 } ( $primary_key ? ( $primary_key ) : real_fields($old->table) )
848 warn "[debug]$me $statement\n" if $DEBUG > 1;
849 my $sth = dbh->prepare($statement) or return dbh->errstr;
852 if ( defined $dbdef->table('h_'. $old->table) ) {
853 my $h_old_statement = $old->_h_statement('replace_old');
854 warn "[debug]$me $h_old_statement\n" if $DEBUG > 2;
855 $h_old_sth = dbh->prepare($h_old_statement) or return dbh->errstr;
861 if ( defined $dbdef->table('h_'. $new->table) ) {
862 my $h_new_statement = $new->_h_statement('replace_new');
863 warn "[debug]$me $h_new_statement\n" if $DEBUG > 2;
864 $h_new_sth = dbh->prepare($h_new_statement) or return dbh->errstr;
869 # For virtual fields we have three cases with different SQL
870 # statements: add, replace, delete
874 my (@add_vfields, @rep_vfields, @del_vfields);
875 my $vfp = $old->vfieldpart_hashref;
876 foreach(grep { exists($diff{$_}) } $new->virtual_fields) {
877 if($diff{$_} eq '') {
879 unless(@del_vfields) {
880 my $st = "DELETE FROM virtual_field WHERE recnum = ? ".
881 "AND vfieldpart = ?";
882 warn "[debug]$me $st\n" if $DEBUG > 2;
883 $v_del_sth = dbh->prepare($st) or return dbh->errstr;
885 push @del_vfields, $_;
886 } elsif($old->getfield($_) eq '') {
888 unless(@add_vfields) {
889 my $st = "INSERT INTO virtual_field (value, recnum, vfieldpart) ".
891 warn "[debug]$me $st\n" if $DEBUG > 2;
892 $v_add_sth = dbh->prepare($st) or return dbh->errstr;
894 push @add_vfields, $_;
897 unless(@rep_vfields) {
898 my $st = "UPDATE virtual_field SET value = ? ".
899 "WHERE recnum = ? AND vfieldpart = ?";
900 warn "[debug]$me $st\n" if $DEBUG > 2;
901 $v_rep_sth = dbh->prepare($st) or return dbh->errstr;
903 push @rep_vfields, $_;
907 local $SIG{HUP} = 'IGNORE';
908 local $SIG{INT} = 'IGNORE';
909 local $SIG{QUIT} = 'IGNORE';
910 local $SIG{TERM} = 'IGNORE';
911 local $SIG{TSTP} = 'IGNORE';
912 local $SIG{PIPE} = 'IGNORE';
914 my $rc = $sth->execute or return $sth->errstr;
915 #not portable #return "Record not found (or records identical)." if $rc eq "0E0";
916 $h_old_sth->execute or return $h_old_sth->errstr if $h_old_sth;
917 $h_new_sth->execute or return $h_new_sth->errstr if $h_new_sth;
919 $v_del_sth->execute($old->getfield($primary_key),
921 or return $v_del_sth->errstr
922 foreach(@del_vfields);
924 $v_add_sth->execute($new->getfield($_),
925 $old->getfield($primary_key),
927 or return $v_add_sth->errstr
928 foreach(@add_vfields);
930 $v_rep_sth->execute($new->getfield($_),
931 $old->getfield($primary_key),
933 or return $v_rep_sth->errstr
934 foreach(@rep_vfields);
936 dbh->commit or croak dbh->errstr if $FS::UID::AutoCommit;
944 Depriciated (use replace instead).
949 cluck "warning: FS::Record::rep deprecated!";
950 replace @_; #call method in this scope
955 Checks virtual fields (using check_blocks). Subclasses should still provide
956 a check method to validate real fields, foreign keys, etc., and call this
957 method via $self->SUPER::check.
959 (FIXME: Should this method try to make sure that it I<is> being called from
960 a subclass's check method, to keep the current semantics as far as possible?)
965 #confess "FS::Record::check not implemented; supply one in subclass!";
968 foreach my $field ($self->virtual_fields) {
969 for ($self->getfield($field)) {
970 # See notes on check_block in FS::part_virtual_field.
971 eval $self->pvf($field)->check_block;
973 $self->setfield($field, $_);
980 my( $self, $action ) = @_;
983 grep defined($self->getfield($_)) && $self->getfield($_) ne "",
984 real_fields($self->table);
986 my @values = map { _quote( $self->getfield($_), $self->table, $_) } @fields;
988 "INSERT INTO h_". $self->table. " ( ".
989 join(', ', qw(history_date history_user history_action), @fields ).
991 join(', ', time, dbh->quote(getotaker()), dbh->quote($action), @values).
998 B<Warning>: External use is B<deprecated>.
1000 Replaces COLUMN in record with a unique number, using counters in the
1001 filesystem. Used by the B<insert> method on single-field unique columns
1002 (see L<DBIx::DBSchema::Table>) and also as a fallback for primary keys
1003 that aren't SERIAL (Pg) or AUTO_INCREMENT (mysql).
1005 Returns the new value.
1010 my($self,$field) = @_;
1011 my($table)=$self->table;
1013 croak "Unique called on field $field, but it is ",
1014 $self->getfield($field),
1016 if $self->getfield($field);
1018 #warn "table $table is tainted" if is_tainted($table);
1019 #warn "field $field is tainted" if is_tainted($field);
1021 my($counter) = new File::CounterFile "$table.$field",0;
1023 # getotaker() =~ /^([\w\-]{1,16})$/ or die "Illegal CGI REMOTE_USER!";
1025 # my($counter) = new File::CounterFile "$user/$table.$field",0;
1028 my $index = $counter->inc;
1029 $index = $counter->inc while qsearchs($table, { $field=>$index } );
1031 $index =~ /^(\d*)$/;
1034 $self->setfield($field,$index);
1038 =item ut_float COLUMN
1040 Check/untaint floating point numeric data: 1.1, 1, 1.1e10, 1e10. May not be
1041 null. If there is an error, returns the error, otherwise returns false.
1046 my($self,$field)=@_ ;
1047 ($self->getfield($field) =~ /^(\d+\.\d+)$/ ||
1048 $self->getfield($field) =~ /^(\d+)$/ ||
1049 $self->getfield($field) =~ /^(\d+\.\d+e\d+)$/ ||
1050 $self->getfield($field) =~ /^(\d+e\d+)$/)
1051 or return "Illegal or empty (float) $field: ". $self->getfield($field);
1052 $self->setfield($field,$1);
1056 =item ut_number COLUMN
1058 Check/untaint simple numeric data (whole numbers). May not be null. If there
1059 is an error, returns the error, otherwise returns false.
1064 my($self,$field)=@_;
1065 $self->getfield($field) =~ /^(\d+)$/
1066 or return "Illegal or empty (numeric) $field: ". $self->getfield($field);
1067 $self->setfield($field,$1);
1071 =item ut_numbern COLUMN
1073 Check/untaint simple numeric data (whole numbers). May be null. If there is
1074 an error, returns the error, otherwise returns false.
1079 my($self,$field)=@_;
1080 $self->getfield($field) =~ /^(\d*)$/
1081 or return "Illegal (numeric) $field: ". $self->getfield($field);
1082 $self->setfield($field,$1);
1086 =item ut_money COLUMN
1088 Check/untaint monetary numbers. May be negative. Set to 0 if null. If there
1089 is an error, returns the error, otherwise returns false.
1094 my($self,$field)=@_;
1095 $self->setfield($field, 0) if $self->getfield($field) eq '';
1096 $self->getfield($field) =~ /^(\-)? ?(\d*)(\.\d{2})?$/
1097 or return "Illegal (money) $field: ". $self->getfield($field);
1098 #$self->setfield($field, "$1$2$3" || 0);
1099 $self->setfield($field, ( ($1||''). ($2||''). ($3||'') ) || 0);
1103 =item ut_text COLUMN
1105 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1106 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? / =
1107 May not be null. If there is an error, returns the error, otherwise returns
1113 my($self,$field)=@_;
1114 #warn "msgcat ". \&msgcat. "\n";
1115 #warn "notexist ". \¬exist. "\n";
1116 #warn "AUTOLOAD ". \&AUTOLOAD. "\n";
1117 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]+)$/
1118 or return gettext('illegal_or_empty_text'). " $field: ".
1119 $self->getfield($field);
1120 $self->setfield($field,$1);
1124 =item ut_textn COLUMN
1126 Check/untaint text. Alphanumerics, spaces, and the following punctuation
1127 symbols are currently permitted: ! @ # $ % & ( ) - + ; : ' " , . ? /
1128 May be null. If there is an error, returns the error, otherwise returns false.
1133 my($self,$field)=@_;
1134 $self->getfield($field) =~ /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
1135 or return gettext('illegal_text'). " $field: ". $self->getfield($field);
1136 $self->setfield($field,$1);
1140 =item ut_alpha COLUMN
1142 Check/untaint alphanumeric strings (no spaces). May not be null. If there is
1143 an error, returns the error, otherwise returns false.
1148 my($self,$field)=@_;
1149 $self->getfield($field) =~ /^(\w+)$/
1150 or return "Illegal or empty (alphanumeric) $field: ".
1151 $self->getfield($field);
1152 $self->setfield($field,$1);
1156 =item ut_alpha COLUMN
1158 Check/untaint alphanumeric strings (no spaces). May be null. If there is an
1159 error, returns the error, otherwise returns false.
1164 my($self,$field)=@_;
1165 $self->getfield($field) =~ /^(\w*)$/
1166 or return "Illegal (alphanumeric) $field: ". $self->getfield($field);
1167 $self->setfield($field,$1);
1171 =item ut_phonen COLUMN [ COUNTRY ]
1173 Check/untaint phone numbers. May be null. If there is an error, returns
1174 the error, otherwise returns false.
1176 Takes an optional two-letter ISO country code; without it or with unsupported
1177 countries, ut_phonen simply calls ut_alphan.
1182 my( $self, $field, $country ) = @_;
1183 return $self->ut_alphan($field) unless defined $country;
1184 my $phonen = $self->getfield($field);
1185 if ( $phonen eq '' ) {
1186 $self->setfield($field,'');
1187 } elsif ( $country eq 'US' || $country eq 'CA' ) {
1189 $phonen =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
1190 or return gettext('illegal_phone'). " $field: ". $self->getfield($field);
1191 $phonen = "$1-$2-$3";
1192 $phonen .= " x$4" if $4;
1193 $self->setfield($field,$phonen);
1195 warn "warning: don't know how to check phone numbers for country $country";
1196 return $self->ut_textn($field);
1203 Check/untaint ip addresses. IPv4 only for now.
1208 my( $self, $field ) = @_;
1209 $self->getfield($field) =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
1210 or return "Illegal (IP address) $field: ". $self->getfield($field);
1211 for ( $1, $2, $3, $4 ) { return "Illegal (IP address) $field" if $_ > 255; }
1212 $self->setfield($field, "$1.$2.$3.$4");
1218 Check/untaint ip addresses. IPv4 only for now. May be null.
1223 my( $self, $field ) = @_;
1224 if ( $self->getfield($field) =~ /^()$/ ) {
1225 $self->setfield($field,'');
1228 $self->ut_ip($field);
1232 =item ut_domain COLUMN
1234 Check/untaint host and domain names.
1239 my( $self, $field ) = @_;
1240 #$self->getfield($field) =~/^(\w+\.)*\w+$/
1241 $self->getfield($field) =~/^(([\w\-]+\.)*\w+)$/
1242 or return "Illegal (domain) $field: ". $self->getfield($field);
1243 $self->setfield($field,$1);
1247 =item ut_name COLUMN
1249 Check/untaint proper names; allows alphanumerics, spaces and the following
1250 punctuation: , . - '
1257 my( $self, $field ) = @_;
1258 $self->getfield($field) =~ /^([\w \,\.\-\']+)$/
1259 or return gettext('illegal_name'). " $field: ". $self->getfield($field);
1260 $self->setfield($field,$1);
1266 Check/untaint zip codes.
1271 my( $self, $field, $country ) = @_;
1272 if ( $country eq 'US' ) {
1273 $self->getfield($field) =~ /\s*(\d{5}(\-\d{4})?)\s*$/
1274 or return gettext('illegal_zip'). " $field for country $country: ".
1275 $self->getfield($field);
1276 $self->setfield($field,$1);
1278 $self->getfield($field) =~ /^\s*(\w[\w\-\s]{2,8}\w)\s*$/
1279 or return gettext('illegal_zip'). " $field: ". $self->getfield($field);
1280 $self->setfield($field,$1);
1285 =item ut_country COLUMN
1287 Check/untaint country codes. Country names are changed to codes, if possible -
1288 see L<Locale::Country>.
1293 my( $self, $field ) = @_;
1294 unless ( $self->getfield($field) =~ /^(\w\w)$/ ) {
1295 if ( $self->getfield($field) =~ /^([\w \,\.\(\)\']+)$/
1296 && country2code($1) ) {
1297 $self->setfield($field,uc(country2code($1)));
1300 $self->getfield($field) =~ /^(\w\w)$/
1301 or return "Illegal (country) $field: ". $self->getfield($field);
1302 $self->setfield($field,uc($1));
1306 =item ut_anything COLUMN
1308 Untaints arbitrary data. Be careful.
1313 my( $self, $field ) = @_;
1314 $self->getfield($field) =~ /^(.*)$/s
1315 or return "Illegal $field: ". $self->getfield($field);
1316 $self->setfield($field,$1);
1320 =item ut_enum COLUMN CHOICES_ARRAYREF
1322 Check/untaint a column, supplying all possible choices, like the "enum" type.
1327 my( $self, $field, $choices ) = @_;
1328 foreach my $choice ( @$choices ) {
1329 if ( $self->getfield($field) eq $choice ) {
1330 $self->setfield($choice);
1334 return "Illegal (enum) field $field: ". $self->getfield($field);
1337 =item ut_foreign_key COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1339 Check/untaint a foreign column key. Call a regular ut_ method (like ut_number)
1340 on the column first.
1344 sub ut_foreign_key {
1345 my( $self, $field, $table, $foreign ) = @_;
1346 qsearchs($table, { $foreign => $self->getfield($field) })
1347 or return "Can't find $field ". $self->getfield($field).
1348 " in $table.$foreign";
1352 =item ut_foreign_keyn COLUMN FOREIGN_TABLE FOREIGN_COLUMN
1354 Like ut_foreign_key, except the null value is also allowed.
1358 sub ut_foreign_keyn {
1359 my( $self, $field, $table, $foreign ) = @_;
1360 $self->getfield($field)
1361 ? $self->ut_foreign_key($field, $table, $foreign)
1366 =item virtual_fields [ TABLE ]
1368 Returns a list of virtual fields defined for the table. This should not
1369 be exported, and should only be called as an instance or class method.
1373 sub virtual_fields {
1376 $table = $self->table or confess "virtual_fields called on non-table";
1378 confess "Unknown table $table" unless $dbdef->table($table);
1380 return () unless $self->dbdef->table('part_virtual_field');
1382 # This should be smart enough to cache results.
1384 my $query = 'SELECT name from part_virtual_field ' .
1385 "WHERE dbtable = '$table'";
1387 my $result = $dbh->selectcol_arrayref($query);
1388 confess $dbh->errstr if $dbh->err;
1393 =item fields [ TABLE ]
1395 This is a wrapper for real_fields and virtual_fields. Code that called
1396 fields before should probably continue to call fields.
1401 my $something = shift;
1403 if($something->isa('FS::Record')) {
1404 $table = $something->table;
1406 $table = $something;
1407 $something = "FS::$table";
1409 return (real_fields($table), $something->virtual_fields());
1414 =item pvf FIELD_NAME
1416 Returns the FS::part_virtual_field object corresponding to a field in the
1417 record (specified by FIELD_NAME).
1422 my ($self, $name) = (shift, shift);
1424 if(grep /^$name$/, $self->virtual_fields) {
1425 return qsearchs('part_virtual_field', { dbtable => $self->table,
1435 =item real_fields [ TABLE ]
1437 Returns a list of the real columns in the specified table. Called only by
1438 fields() and other subroutines elsewhere in FS::Record.
1445 my($table_obj) = $dbdef->table($table);
1446 confess "Unknown table $table" unless $table_obj;
1447 $table_obj->columns;
1450 =item reload_dbdef([FILENAME])
1452 Load a database definition (see L<DBIx::DBSchema>), optionally from a
1453 non-default filename. This command is executed at startup unless
1454 I<$FS::Record::setup_hack> is true. Returns a DBIx::DBSchema object.
1459 my $file = shift || $dbdef_file;
1461 unless ( exists $dbdef_cache{$file} ) {
1462 warn "[debug]$me loading dbdef for $file\n" if $DEBUG;
1463 $dbdef_cache{$file} = DBIx::DBSchema->load( $file )
1464 or die "can't load database schema from $file";
1466 warn "[debug]$me re-using cached dbdef for $file\n" if $DEBUG;
1468 $dbdef = $dbdef_cache{$file};
1473 Returns the current database definition. See L<DBIx::DBSchema>.
1477 sub dbdef { $dbdef; }
1479 =item _quote VALUE, TABLE, COLUMN
1481 This is an internal function used to construct SQL statements. It returns
1482 VALUE DBI-quoted (see L<DBI/"quote">) unless VALUE is a number and the column
1483 type (see L<DBIx::DBSchema::Column>) does not end in `char' or `binary'.
1488 my($value, $table, $column) = @_;
1489 my $column_obj = $dbdef->table($table)->column($column);
1490 my $column_type = $column_obj->type;
1492 if ( $value eq '' && $column_type =~ /^int/ ) {
1493 if ( $column_obj->null ) {
1496 cluck "WARNING: Attempting to set non-null integer $table.$column null; ".
1500 } elsif ( $value =~ /^\d+(\.\d+)?$/ &&
1501 ! $column_type =~ /(char|binary|text)$/i ) {
1508 =item vfieldpart_hashref TABLE
1510 Returns a hashref of virtual field names and vfieldparts applicable to the given
1515 sub vfieldpart_hashref {
1517 my $table = $self->table;
1519 return {} unless $self->dbdef->table('part_virtual_field');
1522 my $statement = "SELECT vfieldpart, name FROM part_virtual_field WHERE ".
1523 "dbtable = '$table'";
1524 my $sth = $dbh->prepare($statement);
1525 $sth->execute or croak "Execution of '$statement' failed: ".$dbh->errstr;
1526 return { map { $_->{name}, $_->{vfieldpart} }
1527 @{$sth->fetchall_arrayref({})} };
1534 This is deprecated. Don't use it.
1536 It returns a hash-type list with the fields of this record's table set true.
1541 carp "warning: hfields is deprecated";
1544 foreach (fields($table)) {
1553 "$_: ". $self->getfield($_). "|"
1554 } (fields($self->table)) );
1557 sub DESTROY { return; }
1561 # #use Carp qw(cluck);
1562 # #cluck "DESTROYING $self";
1563 # warn "DESTROYING $self";
1567 # return ! eval { join('',@_), kill 0; 1; };
1574 This module should probably be renamed, since much of the functionality is
1575 of general use. It is not completely unlike Adapter::DBI (see below).
1577 Exported qsearch and qsearchs should be deprecated in favor of method calls
1578 (against an FS::Record object like the old search and searchs that qsearch
1579 and qsearchs were on top of.)
1581 The whole fields / hfields mess should be removed.
1583 The various WHERE clauses should be subroutined.
1585 table string should be deprecated in favor of DBIx::DBSchema::Table.
1587 No doubt we could benefit from a Tied hash. Documenting how exists / defined
1588 true maps to the database (and WHERE clauses) would also help.
1590 The ut_ methods should ask the dbdef for a default length.
1592 ut_sqltype (like ut_varchar) should all be defined
1594 A fallback check method should be provided which uses the dbdef.
1596 The ut_money method assumes money has two decimal digits.
1598 The Pg money kludge in the new method only strips `$'.
1600 The ut_phonen method only checks US-style phone numbers.
1602 The _quote function should probably use ut_float instead of a regex.
1604 All the subroutines probably should be methods, here or elsewhere.
1606 Probably should borrow/use some dbdef methods where appropriate (like sub
1609 As of 1.14, DBI fetchall_hashref( {} ) doesn't set fetchrow_hashref NAME_lc,
1610 or allow it to be set. Working around it is ugly any way around - DBI should
1611 be fixed. (only affects RDBMS which return uppercase column names)
1613 ut_zip should take an optional country like ut_phone.
1617 L<DBIx::DBSchema>, L<FS::UID>, L<DBI>
1619 Adapter::DBI from Ch. 11 of Advanced Perl Programming by Sriram Srinivasan.