[Bio] / Sprout / CustomAttributes.pm Repository:
ViewVC logotype

Diff of /Sprout/CustomAttributes.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.9, Thu Nov 16 22:09:33 2006 UTC revision 1.30, Fri Oct 5 01:40:58 2007 UTC
# Line 8  Line 8 
8      use strict;      use strict;
9      use Tracer;      use Tracer;
10      use ERDBLoad;      use ERDBLoad;
11        use Stats;
12        use Time::HiRes qw(time);
13    
14  =head1 Custom SEED Attribute Manager  =head1 Custom SEED Attribute Manager
15    
# Line 15  Line 17 
17    
18  The Custom SEED Attributes Manager allows the user to upload and retrieve  The Custom SEED Attributes Manager allows the user to upload and retrieve
19  custom data for SEED objects. It uses the B<ERDB> database system to  custom data for SEED objects. It uses the B<ERDB> database system to
20  store the attributes, which are implemented as multi-valued fields  store the attributes.
21  of ERDB entities.  
22    Attributes are organized by I<attribute key>. Attribute values are
23    assigned to I<objects>. In the real world, objects have types and IDs;
24    however, to the attribute database only the ID matters. This will create
25    a problem if we have a single ID that applies to two objects of different
26    types, but it is more consistent with the original attribute implementation
27    in the SEED (which this implementation replaces).
28    
29    The actual attribute values are stored as a relationship between the attribute
30    keys and the objects. There can be multiple values for a single key/object pair.
31    
32    =head3 Object IDs
33    
34    The object ID is normally represented as
35    
36        I<type>:I<id>
37    
38    where I<type> is the object type (C<Role>, C<Coupling>, etc.) and I<id> is
39    the actual object ID. Note that the object type must consist of only upper- and
40    lower-case letters! Thus, C<GenomeGroup> is a valid object type, but
41    C<genome_group> is not. Given that restriction, the object ID
42    
43        Family:aclame|cluster10
44    
45    would represent the FIG family C<aclame|cluster10>. For historical reasons,
46    there are three exceptions: subsystems, genomes, and features do not need
47    a type. So, for PEG 3361 of Streptomyces coelicolor A3(2), you simply code
48    
49        fig|100226.1.peg.3361
50    
51    The methods L</ParseID> and L</FormID> can be used to make this all seem
52    more consistent. Given any object ID string, L</ParseID> will convert it to an
53    object type and ID, and given any object type and ID, L</FormID> will
54    convert it to an object ID string. The attribute database is pretty
55    freewheeling about what it will allow for an ID; however, for best
56    results, the type should match an entity type from a Sprout genetics
57    database. If this rule is followed, then the database object
58    corresponding to an ID in the attribute database could be retrieved using
59    L</GetTargetObject> method.
60    
61        my $object = CustomAttributes::GetTargetObject($sprout, $idValue);
62    
63    =head3 Retrieval and Logging
64    
65  The full suite of ERDB retrieval capabilities is provided. In addition,  The full suite of ERDB retrieval capabilities is provided. In addition,
66  custom methods are provided specific to this application. To get all  custom methods are provided specific to this application. To get all
67  the values of the attribute C<essential> in a specified B<Feature>, you  the values of the attribute C<essential> in a specified B<Feature>, you
68  would code  would code
69    
70      my @values = $attrDB->GetAttributes([Feature => $fid], 'essential');      my @values = $attrDB->GetAttributes($fid, 'essential');
71    
72  where I<$fid> contains the ID of the desired feature. Each attribute has  where I<$fid> contains the ID of the desired feature.
 an alternate index to allow searching for attributes by value.  
73    
74  New attributes are introduced by updating the database definition at  Keys can be split into two pieces using the splitter value defined in the
75  run-time. Attribute values are stored by uploading data from files.  constructor (the default is C<::>). The first piece of the key is called
76  A web interface is provided for both these activities.  the I<real key>. This portion of the key must be defined using the
77    web interface (C<Attributes.cgi>). The second portion of the key is called
78    the I<sub key>, and can take any value.
79    
80    Major attribute activity is recorded in a log (C<attributes.log>) in the
81    C<$FIG_Config::var> directory. The log reports the user name, time, and
82    the details of the operation. The user name will almost always be unknown,
83    the exception being when it is specified in this object's constructor
84    (see L</new>).
85    
86  =head2 FIG_Config Parameters  =head2 FIG_Config Parameters
87    
# Line 76  Line 127 
127    
128  =back  =back
129    
 The DBD file is critical, and must have reasonable contents before we can  
 begin using the system. In the old system, attributes were only provided  
 for Genomes and Features, so the initial XML file was the following.  
   
     <Database>  
       <Title>SEED Custom Attribute Database</Title>  
       <Entities>  
         <Entity name="Feature" keyType="id-string">  
           <Notes>A [i]feature[/i] is a part of the genome  
           that is of special interest. Features may be spread  
           across multiple contigs of a genome, but never across  
           more than one genome. Features can be assigned to roles  
           via spreadsheet cells, and are the targets of  
           annotation.</Notes>  
         </Entity>  
         <Entity name="Genome" keyType="name-string">  
           <Notes>A [i]genome[/i] describes a particular individual  
           organism's DNA.</Notes>  
         </Entity>  
       </Entities>  
     </Database>  
   
 It is not necessary to put any tables into the database; however, you should  
 run  
   
     AttrDBRefresh  
   
 periodically to insure it has the correct Genomes and Features in it. When  
 converting from the old system, use  
   
     AttrDBRefresh -migrate  
   
 to initialize the database and migrate the legacy data. You should only need  
 to do that once.  
   
 =head2 Implementation Note  
   
 The L</Refresh> method reloads the entities in the database. If new  
 entity types are added, that method will need to be adjusted accordingly.  
   
130  =head2 Public Methods  =head2 Public Methods
131    
132  =head3 new  =head3 new
133    
134  C<< my $attrDB = CustomAttributes->new($splitter); >>  C<< my $attrDB = CustomAttributes->new(%options); >>
135    
136  Construct a new CustomAttributes object. This object cannot be used to add or  Construct a new CustomAttributes object. The following options are
137  delete keys because that requires modifying the database design. To do that,  supported.
 you need to use the static L</StoreAttributeKey> or L</DeleteAttributeKey>  
 methods.  
138    
139  =over 4  =over 4
140    
141  =item splitter  =item splitter
142    
143  Value to be used to split attribute values into sections in the  Value to be used to split attribute values into sections in the
144  L</Fig Replacement Methods>. The default is a double colon C<::>.  L</Fig Replacement Methods>. The default is a double colon C<::>,
145  If you do not use the replacement methods, you do not need to  and should only be overridden in extreme circumstances.
146  worry about this parameter.  
147    =item user
148    
149    Name of the current user. This will appear in the attribute log.
150    
151  =back  =back
152    
# Line 142  Line 154 
154    
155  sub new {  sub new {
156      # Get the parameters.      # Get the parameters.
157      my ($class, $splitter) = @_;      my ($class, %options) = @_;
158      # Connect to the database.      # Connect to the database.
159      my $dbh = DBKernel->new($FIG_Config::attrDbms, $FIG_Config::attrDbName,      my $dbh = DBKernel->new($FIG_Config::attrDbms, $FIG_Config::attrDbName,
160                              $FIG_Config::attrUser, $FIG_Config::attrPass,                              $FIG_Config::attrUser, $FIG_Config::attrPass,
# Line 152  Line 164 
164      my $xmlFileName = $FIG_Config::attrDBD;      my $xmlFileName = $FIG_Config::attrDBD;
165      my $retVal = ERDB::new($class, $dbh, $xmlFileName);      my $retVal = ERDB::new($class, $dbh, $xmlFileName);
166      # Store the splitter value.      # Store the splitter value.
167      $retVal->{splitter} = (defined($splitter) ? $splitter : '::');      $retVal->{splitter} = $options{splitter} || '::';
168        # Store the user name.
169        $retVal->{user} = $options{user} || '<unknown>';
170        Trace("User $retVal->{user} selected for attribute object.") if T(3);
171      # Return the result.      # Return the result.
172      return $retVal;      return $retVal;
173  }  }
174    
175  =head3 StoreAttributeKey  =head3 StoreAttributeKey
176    
177  C<< my $attrDB = CustomAttributes::StoreAttributeKey($entityName, $attributeName, $type, $notes); >>  C<< $attrDB->StoreAttributeKey($attributeName, $type, $notes, \@groups); >>
178    
179  Create or update an attribute for the database. This method will update the database definition  Create or update an attribute for the database.
 XML, but it will not create the table. It will connect to the database so that the caller  
 can upload the attribute values.  
180    
181  =over 4  =over 4
182    
 =item entityName  
   
 Name of the entity containing the attribute. The entity must exist.  
   
183  =item attributeName  =item attributeName
184    
185  Name of the attribute. It must be a valid ERDB field name, consisting entirely of  Name of the attribute (the real key). If it does not exist already, it will be created.
 letters, digits, and hyphens, with a letter at the beginning. If it does not  
 exist already, it will be created.  
186    
187  =item type  =item type
188    
# Line 185  Line 192 
192    
193  Descriptive notes about the attribute. It is presumed to be raw text, not HTML.  Descriptive notes about the attribute. It is presumed to be raw text, not HTML.
194    
195  =item RETURN  =item groups
196    
197  Returns a Custom Attribute Database object if successful. If unsuccessful, an  Reference to a list of the groups to which the attribute should be associated.
198  error will be thrown.  This will replace any groups to which the attribute is currently attached.
199    
200  =back  =back
201    
# Line 196  Line 203 
203    
204  sub StoreAttributeKey {  sub StoreAttributeKey {
205      # Get the parameters.      # Get the parameters.
206      my ($entityName, $attributeName, $type, $notes) = @_;      my ($self, $attributeName, $type, $notes, $groups) = @_;
207      # Declare the return variable.      # Declare the return variable.
208      my $retVal;      my $retVal;
209      # Get the data type hash.      # Get the data type hash.
210      my %types = ERDB::GetDataTypes();      my %types = ERDB::GetDataTypes();
211      # Validate the initial input values.      # Validate the initial input values.
212      if (! ERDB::ValidateFieldName($attributeName)) {      if ($attributeName =~ /$self->{splitter}/) {
213          Confess("Invalid attribute name \"$attributeName\" specified.");          Confess("Invalid attribute name \"$attributeName\" specified.");
214      } elsif (! $notes || length($notes) < 25) {      } elsif (! $notes || length($notes) < 25) {
215          Confess("Missing or incomplete description for $attributeName.");          Confess("Missing or incomplete description for $attributeName.");
216      } elsif (! exists $types{$type}) {      } elsif (! exists $types{$type}) {
217          Confess("Invalid data type \"$type\" for $attributeName.");          Confess("Invalid data type \"$type\" for $attributeName.");
218        } else {
219            # Create a variable to hold the action to be displayed for the log (Add or Update).
220            my $action;
221            # Okay, we're ready to begin. See if this key exists.
222            my $attribute = $self->GetEntity('AttributeKey', $attributeName);
223            if (defined($attribute)) {
224                # It does, so we do an update.
225                $action = "Update Key";
226                $self->UpdateEntity('AttributeKey', $attributeName,
227                                    { description => $notes, 'data-type' => $type });
228                # Detach the key from its current groups.
229                $self->Disconnect('IsInGroup', 'AttributeKey', $attributeName);
230            } else {
231                # It doesn't, so we do an insert.
232                $action = "Insert Key";
233                $self->InsertObject('AttributeKey', { id => $attributeName,
234                                    description => $notes, 'data-type' => $type });
235            }
236            # Attach the key to the specified groups. (We presume the groups already
237            # exist.)
238            for my $group (@{$groups}) {
239                $self->InsertObject('IsInGroup', { 'from-link' => $attributeName,
240                                                   'to-link'   => $group });
241      }      }
242      # Our next step is to read in the XML for the database defintion. We          # Log the operation.
243      # need to verify that the named entity exists.          $self->LogOperation($action, $attributeName, "Group list is " . join(" ", @{$groups}));
     my $metadata = ERDB::ReadMetaXML($FIG_Config::attrDBD);  
     my $entityHash = $metadata->{Entities};  
     if (! exists $entityHash->{$entityName}) {  
         Confess("Entity $entityName not found.");  
     } else {  
         # Okay, we're ready to begin. Get the entity hash and the field hash.  
         my $entityData = $entityHash->{$entityName};  
         my $fieldHash = ERDB::GetEntityFieldHash($metadata, $entityName);  
         # Compare the old attribute data to the new data.  
         my $bigChange = 1;  
         if (exists $fieldHash->{$attributeName} && $fieldHash->{$attributeName}->{type} eq $type) {  
             $bigChange = 0;  
         }  
         # Compute the attribute's relation name.  
         my $relName = join("", $entityName, map { ucfirst $_ } split(/-|_/, $attributeName));  
         # Store the attribute's field data. Note the use of the "content" hash for  
         # the notes. This is how the XML writer knows Notes is a text tag instead of  
         # an attribute.  
         $fieldHash->{$attributeName} = { type => $type, relation => $relName,  
                                          Notes => { content => $notes } };  
         # Insure we have an index for this attribute.  
         my $index = ERDB::FindIndexForEntity($metadata, $entityName, $attributeName);  
         if (! defined($index)) {  
             push @{$entityData->{Indexes}}, { IndexFields => [ { name => $attributeName, order => 'ascending' } ],  
                                               Notes       => "Alternate index provided for access by $attributeName." };  
         }  
         # Write the XML back out.  
         ERDB::WriteMetaXML($metadata, $FIG_Config::attrDBD);  
         # Open a database with the new XML.  
         $retVal = CustomAttributes->new();  
         # Create the table if there has been a significant change.  
         if ($bigChange) {  
             $retVal->CreateTable($relName);  
         }  
244      }      }
     return $retVal;  
245  }  }
246    
 =head3 Refresh  
247    
248  C<< $attrDB->Refresh($fig); >>  =head3 DeleteAttributeKey
249    
250    C<< my $stats = $attrDB->DeleteAttributeKey($attributeName); >>
251    
252  Refresh the primary entity tables from the FIG data store. This method basically  Delete an attribute from the custom attributes database.
 drops and reloads the main tables of the custom attributes database.  
253    
254  =over 4  =over 4
255    
256  =item fig  =item attributeName
257    
258    Name of the attribute to delete.
259    
260    =item RETURN
261    
262  FIG-like object that can be used to find genomes and features.  Returns a statistics object describing the effects of the deletion.
263    
264  =back  =back
265    
266  =cut  =cut
267    
268  sub Refresh {  sub DeleteAttributeKey {
269      # Get the parameters.      # Get the parameters.
270      my ($self, $fig) = @_;      my ($self, $attributeName) = @_;
271      # Create load objects for the genomes and the features.      # Delete the attribute key.
272      my $loadGenome = ERDBLoad->new($self, 'Genome', $FIG_Config::temp);      my $retVal = $self->Delete('AttributeKey', $attributeName);
273      my $loadFeature = ERDBLoad->new($self, 'Feature', $FIG_Config::temp);      # Log this operation.
274      # Get the genome list.      $self->LogOperation("Delete Key", $attributeName, "Key will no longer be available for use by anyone.");
275      my @genomes = $fig->genomes();      # Return the result.
276      # Loop through the genomes.      return $retVal;
277      for my $genomeID (@genomes) {  
         # Put this genome in the genome table.  
         $loadGenome->Put($genomeID);  
         Trace("Processing Genome $genomeID") if T(3);  
         # Put its features into the feature table. Note we have to use a hash to  
         # remove duplicates.  
         my %featureList = map { $_ => 1 } $fig->all_features($genomeID);  
         for my $fid (keys %featureList) {  
             $loadFeature->Put($fid);  
         }  
278      }      }
279      # Get a variable for holding statistics objects.  
280      my $stats;  =head3 NewName
281      # Finish the genome load.  
282      Trace("Loading Genome relation.") if T(2);  C<< my $text = CustomAttributes::NewName(); >>
283      $stats = $loadGenome->FinishAndLoad();  
284      Trace("Genome table load statistics:\n" . $stats->Show()) if T(3);  Return the string used to indicate the user wants to add a new attribute.
285      # Finish the feature load.  
286      Trace("Loading Feature relation.") if T(2);  =cut
287      $stats = $loadFeature->FinishAndLoad();  
288      Trace("Feature table load statistics:\n" . $stats->Show()) if T(3);  sub NewName {
289        return "(new)";
290  }  }
291    
292  =head3 LoadAttributeKey  =head3 ControlForm
293    
294  C<< my $stats = $attrDB->LoadAttributeKey($entityName, $fieldName, $fh, $keyCol, $dataCol); >>  C<< my $formHtml = $attrDB->ControlForm($cgi, $name, \%keys); >>
295    
296  Load the specified attribute from the specified file. The file should be a  Return a form that can be used to control the creation and modification of
297  tab-delimited file with internal tab and new-line characters escaped. This is  attributes. Only a subset of the attribute keys will be displayed, as
298  the typical TBL-style file used by most FIG applications. One of the columns  determined by the incoming list.
 in the input file must contain the appropriate key value and the other the  
 corresponding attribute value.  
299    
300  =over 4  =over 4
301    
302  =item entityName  =item cgi
303    
304    CGI query object used to create HTML.
305    
306    =item name
307    
308    Name to give to the form. This should be unique for the web page.
309    
310    =item keys
311    
312    Reference to a hash mapping attribute keys to n-tuples. Each tuple will contain the
313    attribute's data type, its description, and a list of the groups in which it participates.
314    
315    =item RETURN
316    
317    Returns the HTML for a form that can be used to  submit instructions to the C<Attributes.cgi> script
318    for loading, creating, displaying, changing, or deleting an attribute. Note that only the form
319    controls are generated. The form tags are left to the caller.
320    
321    =back
322    
323  Name of the entity containing the attribute.  =cut
324    
325  =item fieldName  sub ControlForm {
326        # Get the parameters.
327        my ($self, $cgi, $name, $keys) = @_;
328        # Declare the return list.
329        my @retVal = ();
330        # We'll put the controls in a table. Nothing else ever seems to look nice.
331        push @retVal, $cgi->start_table({ border => 2, cellpadding => 2 });
332        # The first row is for selecting the field name.
333        push @retVal, $cgi->Tr($cgi->th("Select a Field"),
334                               $cgi->td($self->FieldMenu($cgi, 10, 'fieldName', $keys,
335                                                         new => 1,
336                                                         notes => "document.$name.notes.value",
337                                                         type => "document.$name.dataType.value",
338                                                         groups => "document.$name.groups")));
339        # Now we set up a dropdown for the data types. The values will be the
340        # data type names, and the labels will be the descriptions.
341        my %types = ERDB::GetDataTypes();
342        my %labelMap = map { $_ => $types{$_}->{notes} } keys %types;
343        my $typeMenu = $cgi->popup_menu(-name   => 'dataType',
344                                        -values => [sort keys %types],
345                                        -labels => \%labelMap,
346                                        -default => 'string');
347        # Allow the user to specify a new field name. This is required if the
348        # user has selected the "(new)" marker.
349        my $fieldField = "document.$name.fieldName";
350        my $newName = "\"" . NewName() . "\"";
351        push @retVal, $cgi->Tr($cgi->th("New Field Name"),
352                               $cgi->td($cgi->textfield(-name => 'newName',
353                                                        -size => 30,
354                                                        -value => "",
355                                                        -onFocus => "setIfEmpty($fieldField, $newName);")),
356                                        );
357        push @retVal, $cgi->Tr($cgi->th("Data type"),
358                               $cgi->td($typeMenu));
359        # The next row is for the notes.
360        push @retVal, $cgi->Tr($cgi->th("Description"),
361                               $cgi->td($cgi->textarea(-name => 'notes',
362                                                       -rows => 6,
363                                                       -columns => 80))
364                              );
365        # Now we have the groups, which are implemented as a checkbox group.
366        my @groups = $self->GetGroups();
367        push @retVal, $cgi->Tr($cgi->th("Groups"),
368                               $cgi->td($cgi->checkbox_group(-name=>'groups',
369                                        -values=> \@groups))
370                              );
371        # Now the four buttons: STORE, SHOW, ERASE, and DELETE.
372        push @retVal, $cgi->Tr($cgi->th("&nbsp;"),
373                               $cgi->td({align => 'center'}, join(" ",
374                                        $cgi->submit(-name => 'Delete', -value => 'DELETE'),
375                                        $cgi->submit(-name => 'Store',  -value => 'STORE'),
376                                        $cgi->submit(-name => 'Erase',  -value => 'ERASE'),
377                                        $cgi->submit(-name => 'Show',   -value => 'SHOW')
378                                       ))
379                              );
380        # Close the table and the form.
381        push @retVal, $cgi->end_table();
382        # Return the assembled HTML.
383        return join("\n", @retVal, "");
384    }
385    
386  Name of the actual attribute.  =head3 LoadAttributesFrom
387    
388  =item fh  C<< my $stats = $attrDB->LoadAttributesFrom($fileName, %options); >>
389    s
390    Load attributes from the specified tab-delimited file. Each line of the file must
391    contain an object ID in the first column, an attribute key name in the second
392    column, and attribute values in the remaining columns. The attribute values will
393    be assembled into a single value using the splitter code. In addition, the key names may
394    contain a splitter. If this is the case, the portion of the key after the splitter is
395    treated as a subkey.
396    
397  Open file handle for the input file.  =over 4
398    
399  =item keyCol  =item fileName
400    
401  Index (0-based) of the column containing the key field. The key field should  Name of the file from which to load the attributes, or an open handle for the file.
402  contain the ID of an instance of the named entity.  (This last enables the method to be used in conjunction with the CGI form upload
403    control.)
404    
405  =item dataCol  =item options
406    
407  Index (0-based) of the column containing the data value field.  Hash of options for modifying the load process.
408    
409  =item RETURN  =item RETURN
410    
411  Returns a statistics object for the load process.  Returns a statistics object describing the load.
412    
413    =back
414    
415    Permissible option values are as follows.
416    
417    =over 4
418    
419    =item append
420    
421    If TRUE, then the attributes will be appended to existing data; otherwise, the
422    first time a key name is encountered, it will be erased.
423    
424    =item archive
425    
426    If specified, the name of a file into which the incoming data file should be saved.
427    
428    =item objectType
429    
430    If specified, the specified object type will be prefixed to each object ID.
431    
432    =item resume
433    
434    If specified, key-value pairs already in the database will not be reinserted.
435    
436  =back  =back
437    
438  =cut  =cut
439    
440  sub LoadAttributeKey {  sub LoadAttributesFrom {
441      # Get the parameters.      # Get the parameters.
442      my ($self, $entityName, $fieldName, $fh, $keyCol, $dataCol) = @_;      my ($self, $fileName, %options) = @_;
443      # Create the return variable.      # Declare the return variable.
444      my $retVal;      my $retVal = Stats->new('keys', 'values');
445      # Insure the entity exists.      # Initialize the timers.
446      my $found = grep { $_ eq $entityName } $self->GetEntityTypes();      my ($insertTime, $eraseTime, $archiveTime, $checkTime) = (0, 0, 0, 0);
447      if (! $found) {      # Check for append mode.
448          Confess("Entity \"$entityName\" not found in database.");      my $append = ($options{append} ? 1 : 0);
449      } else {      # Check for resume mode.
450          # Get the field structure for the named entity.      my $resume = ($options{resume} ? 1 : 0);
451          my $fieldHash = $self->GetFieldTable($entityName);      # Create a hash of key names found.
452          # Verify that the attribute exists.      my %keyHash = ();
453          if (! exists $fieldHash->{$fieldName}) {      # Open the file for input. Note we must anticipate the possibility of an
454              Confess("Attribute key \"$fieldName\" does not exist in entity $entityName.");      # open filehandle being passed in.
455          } else {      my $fh;
456              # Create a loader for the specified attribute. We need the      if (ref $fileName) {
457              # relation name first.          Trace("Using file opened by caller.") if T(3);
458              my $relName = $fieldHash->{$fieldName}->{relation};          $fh = $fileName;
459              my $loadAttribute = ERDBLoad->new($self, $relName, $FIG_Config::temp);      } else {
460              # Loop through the input file.          Trace("Attributes will be loaded from $fileName.") if T(3);
461            $fh = Open(undef, "<$fileName");
462        }
463        # Now check to see if we need to archive.
464        my $ah;
465        if ($options{archive}) {
466            $ah = Open(undef, ">$options{archive}");
467            Trace("Load file will be archived to $options{archive}.") if T(3);
468        }
469        # Insure we recover from errors.
470        eval {
471            # Loop through the file.
472              while (! eof $fh) {              while (! eof $fh) {
473                  # Get the next line of the file.              # Read the current line.
474                  my @fields = Tracer::GetLine($fh);              my ($id, $key, @values) = Tracer::GetLine($fh);
475                  $loadAttribute->Add("lineIn");              $retVal->Add(linesIn => 1);
476                  # Now we need to validate the line.              # Check to see if we need to fix up the object ID.
477                  if ($#fields < $dataCol) {              if ($options{objectType}) {
478                      $loadAttribute->Add("shortLine");                  $id = "$options{objectType}:$id";
479                  } elsif (! $self->Exists($entityName, $fields[$keyCol])) {              }
480                      $loadAttribute->Add("badKey");              # Archive the line (if necessary).
481                if (defined $ah) {
482                    my $startTime = time();
483                    Tracer::PutLine($ah, [$id, $key, @values]);
484                    $archiveTime += time() - $startTime;
485                }
486                # Do some validation.
487                if (! $id) {
488                    # We ignore blank lines.
489                    $retVal->Add(blankLines => 1);
490                } elsif (substr($id, 0, 1) eq '#') {
491                    # A line beginning with a pound sign is a comment.
492                    $retVal->Add(comments => 1);
493                } elsif (! defined($key)) {
494                    # An ID without a key is a serious error.
495                    my $lines = $retVal->Ask('linesIn');
496                    Confess("Line $lines in $fileName has no attribute key.");
497                } elsif (! @values) {
498                    # A line with no values is not allowed.
499                    my $lines = $retVal->Ask('linesIn');
500                    Trace("Line $lines for key $key has no attribute values.") if T(1);
501                    $retVal->Add(skipped => 1);
502                } else {
503                    # The key contains a real part and an optional sub-part. We need the real part.
504                    my ($realKey, $subKey) = $self->SplitKey($key);
505                    # Now we need to check for a new key.
506                    if (! exists $keyHash{$realKey}) {
507                        if (! $self->Exists('AttributeKey', $realKey)) {
508                            my $line = $retVal->Ask('linesIn');
509                            Confess("Attribute \"$realKey\" on line $line of $fileName not found in database.");
510                  } else {                  } else {
511                      # It's valid,so send it to the loader.                          # Make sure we know this is no longer a new key.
512                      $loadAttribute->Put($fields[$keyCol], $fields[$dataCol]);                          $keyHash{$realKey} = 1;
513                      $loadAttribute->Add("lineUsed");                          $retVal->Add(keys => 1);
514                            # If this is NOT append mode, erase the key.
515                            if (! $append) {
516                                my $startTime = time();
517                                $self->EraseAttribute($realKey);
518                                $eraseTime += time() - $startTime;
519                                Trace("Attribute $realKey erased.") if T(3);
520                            }
521                        }
522                        Trace("Key $realKey found.") if T(3);
523                    }
524                    # If we're in resume mode, check to see if this insert is redundant.
525                    my $ok = 1;
526                    if ($resume) {
527                        my $startTime = time();
528                        my $count = $self->GetAttributes($id, $key, @values);
529                        $ok = ! $count;
530                        $checkTime += time() - $startTime;
531                    }
532                    if ($ok) {
533                        # Everything is all set up, so add the value.
534                        my $startTime = time();
535                        $self->AddAttribute($id, $key, @values);
536                        $insertTime += time() - $startTime;
537                        # Turn off resume mode.
538                        $resume = 0;
539                    } else {
540                        # Here we skipped because of resume mode.
541                        $retVal->Add(resumeSkip => 1);
542                  }                  }
543    
544                    my $progress = $retVal->Add(values => 1);
545                    Trace("$progress values loaded.") if T(3) && ($progress % 1000 == 0);
546              }              }
             # Finish the load.  
             $retVal = $loadAttribute->FinishAndLoad();  
547          }          }
548            $retVal->Add(eraseTime   => $eraseTime);
549            $retVal->Add(insertTime  => $insertTime);
550            $retVal->Add(archiveTime => $archiveTime);
551            $retVal->Add(checkTime   => $checkTime);
552        };
553        # Check for an error.
554        if ($@) {
555            # Here we have an error. Display the error message.
556            my $message = $@;
557            Trace("Error during attribute load: $message") if T(0);
558            $retVal->AddMessage($message);
559        }
560        # Close the archive file, if any.
561        if (defined $ah) {
562            Trace("Closing archive file $options{archive}.") if T(2);
563            close $ah;
564      }      }
565      # Return the statistics.      # Return the result.
566      return $retVal;      return $retVal;
567  }  }
568    
569    =head3 BackupKeys
570    
571  =head3 DeleteAttributeKey  C<< my $stats = $attrDB->BackupKeys($fileName, %options); >>
   
 C<< CustomAttributes::DeleteAttributeKey($entityName, $attributeName); >>  
572    
573  Delete an attribute from the custom attributes database.  Backup the attribute key information from the attribute database.
574    
575  =over 4  =over 4
576    
577  =item entityName  =item fileName
578    
579  Name of the entity possessing the attribute.  Name of the output file.
580    
581  =item attributeName  =item options
582    
583  Name of the attribute to delete.  Options for modifying the backup process.
584    
585    =item RETURN
586    
587    Returns a statistics object for the backup.
588    
589  =back  =back
590    
591    Currently there are no options. The backup is straight to a text file in
592    tab-delimited format. Each key is backup up to two lines. The first line
593    is all of the data from the B<AttributeKey> table. The second is a
594    tab-delimited list of all the groups.
595    
596  =cut  =cut
597    
598  sub DeleteAttributeKey {  sub BackupKeys {
599        # Get the parameters.
600        my ($self, $fileName, %options) = @_;
601        # Declare the return variable.
602        my $retVal = Stats->new();
603        # Open the output file.
604        my $fh = Open(undef, ">$fileName");
605        # Set up to read the keys.
606        my $keyQuery = $self->Get(['AttributeKey'], "", []);
607        # Loop through the keys.
608        while (my $keyData = $keyQuery->Fetch()) {
609            $retVal->Add(key => 1);
610            # Get the fields.
611            my ($id, $type, $description) = $keyData->Values(['AttributeKey(id)', 'AttributeKey(data-type)',
612                                                              'AttributeKey(description)']);
613            # Escape any tabs or new-lines in the description.
614            my $escapedDescription = Tracer::Escape($description);
615            # Write the key data to the output.
616            Tracer::PutLine($fh, [$id, $type, $escapedDescription]);
617            # Get the key's groups.
618            my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?", [$id],
619                                        'IsInGroup(to-link)');
620            $retVal->Add(memberships => scalar(@groups));
621            # Write them to the output. Note we put a marker at the beginning to insure the line
622            # is nonempty.
623            Tracer::PutLine($fh, ['#GROUPS', @groups]);
624        }
625        # Log the operation.
626        $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
627        # Return the result.
628        return $retVal;
629    }
630    
631    =head3 RestoreKeys
632    
633    C<< my $stats = $attrDB->RestoreKeys($fileName, %options); >>
634    
635    Restore the attribute keys and groups from a backup file.
636    
637    =over 4
638    
639    =item fileName
640    
641    Name of the file containing the backed-up keys. Each key has a pair of lines,
642    one containing the key data and one listing its groups.
643    
644    =back
645    
646    =cut
647    
648    sub RestoreKeys {
649      # Get the parameters.      # Get the parameters.
650      my ($entityName, $attributeName) = @_;      my ($self, $fileName, %options) = @_;
651      # Read in the XML for the database defintion. We need to verify that      # Declare the return variable.
652      # the named entity exists and it has the named attribute.      my $retVal = Stats->new();
653      my $metadata = ERDB::ReadMetaXML($FIG_Config::attrDBD);      # Set up a hash to hold the group IDs.
654      my $entityHash = $metadata->{Entities};      my %groups = ();
655      if (! exists $entityHash->{$entityName}) {      # Open the file.
656          Confess("Entity \"$entityName\" not found.");      my $fh = Open(undef, "<$fileName");
657      } else {      # Loop until we're done.
658          # Get the field hash.      while (! eof $fh) {
659          my $fieldHash = ERDB::GetEntityFieldHash($metadata, $entityName);          # Get a key record.
660          if (! exists $fieldHash->{$attributeName}) {          my ($id, $dataType, $description) = Tracer::GetLine($fh);
661              Confess("Attribute key \"$attributeName\" not found in entity $entityName.");          if ($id eq '#GROUPS') {
662          } else {              Confess("Group record found when key record expected.");
663              # Get the attribute's relation name.          } elsif (! defined($description)) {
664              my $relName = $fieldHash->{$attributeName}->{relation};              Confess("Invalid format found for key record.");
665              # Check for an index.          } else {
666              my $indexIdx = ERDB::FindIndexForEntity($metadata, $entityName, $attributeName);              $retVal->Add("keyIn" => 1);
667              if (defined($indexIdx)) {              # Add this key to the database.
668                  Trace("Index for $attributeName found at position $indexIdx for $entityName.") if T(3);              $self->InsertObject('AttributeKey', { id => $id, 'data-type' => $dataType,
669                  delete $entityHash->{$entityName}->{Indexes}->[$indexIdx];                                                    description => Tracer::UnEscape($description) });
670              }              Trace("Attribute $id stored.") if T(3);
671              # Delete the attribute from the field hash.              # Get the group line.
672              Trace("Deleting attribute $attributeName from $entityName.") if T(3);              my ($marker, @groups) = Tracer::GetLine($fh);
673              delete $fieldHash->{$attributeName};              if (! defined($marker)) {
674              # Write the XML back out.                  Confess("End of file found where group record expected.");
675              ERDB::WriteMetaXML($metadata, $FIG_Config::attrDBD);              } elsif ($marker ne '#GROUPS') {
676              # Insure the relation does not exist in the database. This requires connecting                  Confess("Group record not found after key record.");
677              # since we may have to do a table drop.              } else {
678              my $attrDB = CustomAttributes->new();                  $retVal->Add(memberships => scalar(@groups));
679              Trace("Dropping table $relName.") if T(3);                  # Connect the groups.
680              $attrDB->DropRelation($relName);                  for my $group (@groups) {
681                        # Find out if this is a new group.
682                        if (! $groups{$group}) {
683                            $retVal->Add(newGroup => 1);
684                            # Add the group.
685                            $self->InsertObject('AttributeGroup', { id => $group });
686                            Trace("Group $group created.") if T(3);
687                            # Make sure we know it's not new.
688                            $groups{$group} = 1;
689                        }
690                        # Connect the group to our key.
691                        $self->InsertObject('IsInGroup', { 'from-link' => $id, 'to-link' => $group });
692          }          }
693                    Trace("$id added to " . scalar(@groups) . " groups.") if T(3);
694                }
695            }
696        }
697        # Log the operation.
698        $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
699        # Return the result.
700        return $retVal;
701      }      }
702    
703    =head3 ArchiveFileName
704    
705    C<< my $fileName = $ca->ArchiveFileName(); >>
706    
707    Compute a file name for archiving attribute input data. The file will be in the attribute log directory
708    
709    =cut
710    
711    sub ArchiveFileName {
712        # Get the parameters.
713        my ($self) = @_;
714        # Declare the return variable.
715        my $retVal;
716        # We start by turning the timestamp into something usable as a file name.
717        my $now = Tracer::Now();
718        $now =~ tr/ :\//___/;
719        # Next we get the directory name.
720        my $dir = "$FIG_Config::var/attributes";
721        if (! -e $dir) {
722            Trace("Creating attribute file directory $dir.") if T(1);
723            mkdir $dir;
724        }
725        # Put it together with the field name and the time stamp.
726        $retVal = "$dir/upload.$now";
727        # Modify the file name to insure it's unique.
728        my $seq = 0;
729        while (-e "$retVal.$seq.tbl") { $seq++ }
730        # Use the computed sequence number to get the correct file name.
731        $retVal .= ".$seq.tbl";
732        # Return the result.
733        return $retVal;
734  }  }
735    
736  =head3 ControlForm  =head3 BackupAllAttributes
737    
738  C<< my $formHtml = $attrDB->ControlForm($cgi, $name); >>  C<< my $stats = $attrDB->BackupAllAttributes($fileName, %options); >>
739    
740  Return a form that can be used to control the creation and modification of  Backup all of the attributes to a file. The attributes will be stored in a
741  attributes.  tab-delimited file suitable for reloading via L</LoadAttributesFrom>.
742    
743  =over 4  =over 4
744    
745  =item cgi  =item fileName
746    
747  CGI query object used to create HTML.  Name of the file to which the attribute data should be backed up.
748    
749  =item name  =item options
750    
751  Name to give to the form. This should be unique for the web page.  Hash of options for the backup.
752    
753  =item RETURN  =item RETURN
754    
755  Returns the HTML for a form that submits instructions to the C<Attributes.cgi> script  Returns a statistics object describing the backup.
 for loading, creating, or deleting an attribute.  
756    
757  =back  =back
758    
759    Currently there are no options defined.
760    
761  =cut  =cut
762    
763  sub ControlForm {  sub BackupAllAttributes {
764      # Get the parameters.      # Get the parameters.
765      my ($self, $cgi, $name) = @_;      my ($self, $fileName, %options) = @_;
766      # Declare the return list.      # Declare the return variable.
767      my @retVal = ();      my $retVal = Stats->new();
768      # Start the form. We use multipart to support the upload control.      # Get a list of the keys.
769      push @retVal, $cgi->start_multipart_form(-name => $name);      my @keys = $self->GetFlat(['AttributeKey'], "", [], 'AttributeKey(id)');
770      # We'll put the controls in a table. Nothing else ever seems to look nice.      Trace(scalar(@keys) . " keys found during backup.") if T(2);
771      push @retVal, $cgi->start_table({ border => 2, cellpadding => 2 });      # Open the file for output.
772      # The first row is for selecting the field name.      my $fh = Open(undef, ">$fileName");
773      push @retVal, $cgi->Tr($cgi->th("Select a Field"),      # Loop through the keys.
774                             $cgi->td($self->FieldMenu($cgi, 10, 'fieldName', 1,      for my $key (@keys) {
775                                                       "document.$name.notes.value",          Trace("Backing up attribute $key.") if T(3);
776                                                       "document.$name.dataType.value")));          $retVal->Add(keys => 1);
777      # Now we set up a dropdown for the data types. The values will be the          # Loop through this key's values.
778      # data type names, and the labels will be the descriptions.          my $query = $self->Get(['HasValueFor'], "HasValueFor(from-link) = ?", [$key]);
779      my %types = ERDB::GetDataTypes();          my $valuesFound = 0;
780      my %labelMap = map { $_ => $types{$_}->{notes} } keys %types;          while (my $line = $query->Fetch()) {
781      my $typeMenu = $cgi->popup_menu(-name   => 'dataType',              $valuesFound++;
782                                      -values => [sort keys %types],              # Get this row's data.
783                                      -labels => \%labelMap);              my ($id, $key, $subKey, $value) = $line->Values(['HasValueFor(to-link)',
784      push @retVal, $cgi->Tr($cgi->th("Data type"),                                                               'HasValueFor(from-link)',
785                             $cgi->td($typeMenu));                                                               'HasValueFor(subkey)',
786      # The next row is for the notes.                                                               'HasValueFor(value)']);
787      push @retVal, $cgi->Tr($cgi->th("Description"),              # Check for a subkey.
788                             $cgi->td($cgi->textarea(-name => 'notes',              if ($subKey ne '') {
789                                                     -rows => 6,                  $key = "$key$self->{splitter}$subKey";
790                                                     -columns => 80))              }
791                            );              # Write it to the file.
792      # Allow the user to specify a new field name. This is required if the              Tracer::PutLine($fh, [$id, $key, $value]);
793      # user has selected one of the "(new)" markers.          }
794      push @retVal, $cgi->Tr($cgi->th("New Field Name"),          Trace("$valuesFound values backed up for key $key.") if T(3);
795                             $cgi->td($cgi->textfield(-name => 'newName',          $retVal->Add(values => $valuesFound);
796                                                      -size => 30)),      }
797                                      );      # Log the operation.
798      # If the user wants to upload new values for the field, then we have      $self->LogOperation("Backup Data", $fileName, $retVal->Display());
799      # an upload file name and column indicators.      # Return the result.
800      push @retVal, $cgi->Tr($cgi->th("Upload Values"),      return $retVal;
                            $cgi->td($cgi->filefield(-name => 'newValueFile',  
                                                     -size => 20) .  
                                     " Key&nbsp;" .  
                                     $cgi->textfield(-name => 'keyCol',  
                                                     -size => 3,  
                                                     -default => 0) .  
                                     " Value&nbsp;" .  
                                     $cgi->textfield(-name => 'valueCol',  
                                                     -size => 3,  
                                                     -default => 1)  
                                    ),  
                           );  
     # Now the three buttons: UPDATE, SHOW, and DELETE.  
     push @retVal, $cgi->Tr($cgi->th("&nbsp;"),  
                            $cgi->td({align => 'center'},  
                                     $cgi->submit(-name => 'Delete', -value => 'DELETE') . " " .  
                                     $cgi->submit(-name => 'Store',  -value => 'STORE') . " " .  
                                     $cgi->submit(-name => 'Show',   -value => 'SHOW')  
                                    )  
                           );  
     # Close the table and the form.  
     push @retVal, $cgi->end_table();  
     push @retVal, $cgi->end_form();  
     # Return the assembled HTML.  
     return join("\n", @retVal, "");  
801  }  }
802    
803  =head3 FieldMenu  =head3 FieldMenu
804    
805  C<< my $menuHtml = $attrDB->FieldMenu($cgi, $height, $name, $newFlag, $noteControl, $typeControl); >>  C<< my $menuHtml = $attrDB->FieldMenu($cgi, $height, $name, $keys, %options); >>
806    
807  Return the HTML for a menu to select an attribute field. The menu will  Return the HTML for a menu to select an attribute field. The menu will
808  be a standard SELECT/OPTION thing which is called "popup menu" in the  be a standard SELECT/OPTION thing which is called "popup menu" in the
809  CGI package, but actually looks like a list. The list will contain  CGI package, but actually looks like a list. The list will contain
810  one selectable row per field, grouped by entity.  one selectable row per field.
811    
812  =over 4  =over 4
813    
# Line 556  Line 824 
824  Name to give to the menu. This is the name under which the value will  Name to give to the menu. This is the name under which the value will
825  appear when the form is submitted.  appear when the form is submitted.
826    
827  =item newFlag (optional)  =item keys
828    
829    Reference to a hash mapping each attribute key name to a list reference,
830    the list itself consisting of the attribute data type, its description,
831    and a list of its groups.
832    
833    =item options
834    
835    Hash containing options that modify the generation of the menu.
836    
837    =item RETURN
838    
839    Returns the HTML to create a form field that can be used to select an
840    attribute from the custom attributes system.
841    
842    =back
843    
844    The permissible options are as follows.
845    
846    =over 4
847    
848    =item new
849    
850  If TRUE, then extra rows will be provided to allow the user to select  If TRUE, then extra rows will be provided to allow the user to select
851  a new attribute. In other words, the user can select an existing  a new attribute. In other words, the user can select an existing
852  attribute, or can choose a C<(new)> marker to indicate a field to  attribute, or can choose a C<(new)> marker to indicate a field to
853  be created in the parent entity.  be created in the parent entity.
854    
855  =item noteControl (optional)  =item notes
856    
857  If specified, the name of a variable for displaying the notes attached  If specified, the name of a variable for displaying the notes attached
858  to the field. This must be in Javascript form ready for assignment.  to the field. This must be in Javascript form ready for assignment.
# Line 574  Line 863 
863  it is copied in. Specifying this parameter generates Javascript for  it is copied in. Specifying this parameter generates Javascript for
864  displaying the field description when a field is selected.  displaying the field description when a field is selected.
865    
866  =item typeControl (optional)  =item type
867    
868  If specified, the name of a variable for displaying the field's  If specified, the name of a variable for displaying the field's
869  data type. Data types are a much more controlled vocabulary than  data type. Data types are a much more controlled vocabulary than
# Line 582  Line 871 
871  raw value is put into the specified variable. Otherwise, the same  raw value is put into the specified variable. Otherwise, the same
872  rules apply to this value that apply to I<$noteControl>.  rules apply to this value that apply to I<$noteControl>.
873    
874  =item RETURN  =item groups
875    
876  Returns the HTML to create a form field that can be used to select an  If specified, the name of a multiple-selection list control (also called
877  attribute from the custom attributes system.  a popup menu) which shall be used to display the selected groups.
878    
879  =back  =back
880    
# Line 593  Line 882 
882    
883  sub FieldMenu {  sub FieldMenu {
884      # Get the parameters.      # Get the parameters.
885      my ($self, $cgi, $height, $name, $newFlag, $noteControl, $typeControl) = @_;      my ($self, $cgi, $height, $name, $keys, %options) = @_;
886      # These next two hashes make everything happen. "entities"      # Reformat the list of keys.
887      # maps each entity name to the list of values to be put into its      my %keys = %{$keys};
888      # option group. "labels" maps each entity name to a map from values      # Add the (new) key, if needed.
889      # to labels.      if ($options{new}) {
890      my @entityNames = sort ($self->GetEntityTypes());          $keys{NewName()} = ["string", ""];
891      my %entities = map { $_ => [] } @entityNames;      }
892      my %labels = map { $_ => { }} @entityNames;      # Get a sorted list of key.
893      # Loop through the entities, adding the existing attributes.      my @keys = sort keys %keys;
894      for my $entity (@entityNames) {      # We need to create the name for the onChange function. This function
         # Get this entity's field table.  
         my $fieldHash = $self->GetFieldTable($entity);  
         # Get its field list in our local hashes.  
         my $fieldList = $entities{$entity};  
         my $labelList = $labels{$entity};  
         # Add the NEW fields if we want them.  
         if ($newFlag) {  
             push @{$fieldList}, $entity;  
             $labelList->{$entity} = "(new)";  
         }  
         # Loop through the fields in the hash. We only keep the ones with a  
         # secondary relation name. (In other words, the name of the relation  
         # in which the field appears cannot be the same as the entity name.)  
         for my $fieldName (sort keys %{$fieldHash}) {  
             if ($fieldHash->{$fieldName}->{relation} ne $entity) {  
                 my $value = "$entity/$fieldName";  
                 push @{$fieldList}, $value;  
                 $labelList->{$value} = $fieldName;  
             }  
         }  
     }  
     # Now we have a hash and a list for each entity, and they correspond  
     # exactly to what the $cgi->optgroup function expects.  
     # The last step is to create the name for the onChange function. This function  
895      # may not do anything, but we need to know the name to generate the HTML      # may not do anything, but we need to know the name to generate the HTML
896      # for the menu.      # for the menu.
897      my $changeName = "${name}_setNotes";      my $changeName = "${name}_setNotes";
898      my $retVal = $cgi->popup_menu({name => $name,      my $retVal = $cgi->popup_menu({name => $name,
899                                     size => $height,                                     size => $height,
900                                     onChange => "$changeName(this.value)",                                     onChange => "$changeName(this.value)",
901                                     values => [map { $cgi->optgroup(-name => $_,                                     values => \@keys,
902                                                                     -values => $entities{$_},                                    });
                                                                    -labels => $labels{$_})  
                                                   } @entityNames]}  
                                  );  
903      # Create the change function.      # Create the change function.
904      $retVal .= "\n<script language=\"javascript\">\n";      $retVal .= "\n<script language=\"javascript\">\n";
905      $retVal .= "    function $changeName(fieldValue) {\n";      $retVal .= "    function $changeName(fieldValue) {\n";
906      # The function only has a body if we have a notes control to store the description.      # The function only has a body if we have a control to store data about the
907      if ($noteControl || $typeControl) {      # attribute.
908        if ($options{notes} || $options{type} || $options{groups}) {
909          # Check to see if we're storing HTML or text into the note control.          # Check to see if we're storing HTML or text into the note control.
910            my $noteControl = $options{notes};
911          my $htmlMode = ($noteControl && $noteControl =~ /innerHTML$/);          my $htmlMode = ($noteControl && $noteControl =~ /innerHTML$/);
912          # We use a CASE statement based on the newly-selected field value. The          # We use a CASE statement based on the newly-selected field value. The
913          # field description will be stored in the JavaScript variable "myText"          # field description will be stored in the JavaScript variable "myText"
# Line 652  Line 916 
916          $retVal .= "        var myText = \"\";\n";          $retVal .= "        var myText = \"\";\n";
917          $retVal .= "        var myType = \"string\";\n";          $retVal .= "        var myType = \"string\";\n";
918          $retVal .= "        switch (fieldValue) {\n";          $retVal .= "        switch (fieldValue) {\n";
919          # Loop through the entities.          # Loop through the keys.
920          for my $entity (@entityNames) {          for my $key (@keys) {
             # Get the entity's field hash. This has the notes in it.  
             my $fieldHash = $self->GetFieldTable($entity);  
             # Loop through the values we might see for this entity's fields.  
             my $fields = $entities{$entity};  
             for my $value (@{$fields}) {  
                 # Only proceed if we have an existing field.  
                 if ($value =~ m!/(.+)$!) {  
                     # Get the field's hash element.  
                     my $element = $fieldHash->{$1};  
921                      # Generate this case.                      # Generate this case.
922                      $retVal .= "        case \"$value\" :\n";              $retVal .= "        case \"$key\" :\n";
923                      # Here we either want to update the note display, the                      # Here we either want to update the note display, the
924                      # type display, or both.              # type display, the group list, or a combination of them.
925                my ($type, $notes, @groups) = @{$keys{$key}};
926                      if ($noteControl) {                      if ($noteControl) {
                         # Here we want the notes updated.  
                         my $notes = $element->{Notes}->{content};  
927                          # Insure it's in the proper form.                          # Insure it's in the proper form.
928                          if ($htmlMode) {                          if ($htmlMode) {
929                              $notes = ERDB::HTMLNote($notes);                              $notes = ERDB::HTMLNote($notes);
# Line 679  Line 933 
933                          $notes =~ s/"/\\"/g;                          $notes =~ s/"/\\"/g;
934                          $retVal .= "           myText = \"$notes\";\n";                          $retVal .= "           myText = \"$notes\";\n";
935                      }                      }
936                      if ($typeControl) {              if ($options{type}) {
937                          # Here we want the type updated.                          # Here we want the type updated.
                         my $type = $element->{type};  
938                          $retVal .= "           myType = \"$type\";\n";                          $retVal .= "           myType = \"$type\";\n";
939                      }                      }
940                if ($options{groups}) {
941                    # Here we want the groups shown. Get a list of this attribute's groups.
942                    # We'll search through this list for each group to see if it belongs with
943                    # our attribute.
944                    my $groupLiteral = "=" . join("=", @groups) . "=";
945                    # Now we need some variables containing useful code for the javascript. It's
946                    # worth knowing we go through a bit of pain to insure $groupField[i] isn't
947                    # parsed as an array element.
948                    my $groupField = $options{groups};
949                    my $currentField = $groupField . "[i]";
950                    # Do the javascript.
951                    $retVal .= "           var groupList = \"$groupLiteral\";\n";
952                    $retVal .= "           for (var i = 0; i < $groupField.length; i++) {\n";
953                    $retVal .= "              var srchString = \"=\" + $currentField.value + \"=\";\n";
954                    $retVal .= "              var srchLoc = groupList.indexOf(srchString);\n";
955                    $retVal .= "              $currentField.checked = (srchLoc >= 0);\n";
956                    $retVal .= "           }\n";
957                }
958                      # Close this case.                      # Close this case.
959                      $retVal .= "           break;\n";                      $retVal .= "           break;\n";
960                  }                  }
             }  
         }  
961          # Close the CASE statement and make the appropriate assignments.          # Close the CASE statement and make the appropriate assignments.
962          $retVal .= "        }\n";          $retVal .= "        }\n";
963          if ($noteControl) {          if ($noteControl) {
964              $retVal .= "        $noteControl = myText;\n";              $retVal .= "        $noteControl = myText;\n";
965          }          }
966          if ($typeControl) {          if ($options{type}) {
967              $retVal .= "        $typeControl = myType;\n";              $retVal .= "        $options{type} = myType;\n";
968          }          }
969      }      }
970      # Terminate the change function.      # Terminate the change function.
# Line 705  Line 974 
974      return $retVal;      return $retVal;
975  }  }
976    
977  =head3 MatchSqlPattern  =head3 GetGroups
978    
979  C<< my $matched = CustomAttributes::MatchSqlPattern($value, $pattern); >>  C<< my @groups = $attrDB->GetGroups(); >>
980    
981  Determine whether or not a specified value matches an SQL pattern. An SQL  Return a list of the available groups.
 pattern has two wild card characters: C<%> that matches multiple characters,  
 and C<_> that matches a single character. These can be escaped using a  
 backslash (C<\>). We pull this off by converting the SQL pattern to a  
 PERL regular expression. As per SQL rules, the match is case-insensitive.  
982    
983  =over 4  =cut
984    
985  =item value  sub GetGroups {
986        # Get the parameters.
987        my ($self) = @_;
988        # Get the groups.
989        my @retVal = $self->GetFlat(['AttributeGroup'], "", [], 'AttributeGroup(id)');
990        # Return them.
991        return @retVal;
992    }
993    
994  Value to be matched against the pattern. Note that an undefined or empty  =head3 GetAttributeData
 value will not match anything.  
995    
996  =item pattern  C<< my %keys = $attrDB->GetAttributeData($type, @list); >>
997    
998  SQL pattern against which to match the value. An undefined or empty pattern will  Return attribute data for the selected attributes. The attribute
999  match everything.  data is a hash mapping each attribute key name to a n-tuple containing the
1000    data type, the description, and the groups. This is the same format expected in
1001    the L</FieldMenu> and L</ControlForm> methods for the list of attributes to display.
1002    
1003  =item RETURN  =over 4
1004    
1005  Returns TRUE if the value and pattern match, else FALSE.  =item type
1006    
1007    Type of attribute criterion: C<name> for attributes whose names begin with the
1008    specified string, or C<group> for attributes in the specified group.
1009    
1010    =item list
1011    
1012    List containing the names of the groups or keys for the desired attributes.
1013    
1014    =item RETURN
1015    
1016    Returns a hash mapping each attribute key name to its data type, description, and
1017    parent groups.
1018    
1019  =back  =back
1020    
1021  =cut  =cut
1022    
1023  sub MatchSqlPattern {  sub GetAttributeData {
1024      # Get the parameters.      # Get the parameters.
1025      my ($value, $pattern) = @_;      my ($self, $type, @list) = @_;
1026      # Declare the return variable.      # Set up a hash to store the attribute data.
1027      my $retVal;      my %retVal = ();
1028      # Insure we have a pattern.      # Loop through the list items.
1029      if (! defined($pattern) || $pattern eq "") {      for my $item (@list) {
1030          $retVal = 1;          # Set up a query for the desired attributes.
1031      } else {          my $query;
1032          # Break the pattern into pieces around the wildcard characters. Because we          if ($type eq 'name') {
1033          # use parentheses in the split function's delimiter expression, we'll get              # Here we're doing a generic name search. We need to escape it and then tack
1034          # list elements for the delimiters as well as the rest of the string.              # on a %.
1035          my @pieces = split /([_%]|\\[_%])/, $pattern;              my $parm = $item;
1036          # Check some fast special cases.              $parm =~ s/_/\\_/g;
1037          if ($pattern eq '%') {              $parm =~ s/%/\\%/g;
1038              # A null pattern matches everything.              $parm .= "%";
1039              $retVal = 1;              # Ask for matching attributes. (Note that if the user passed in a null string
1040          } elsif (@pieces == 1) {              # he'll get everything.)
1041              # No wildcards, so we have a literal comparison. Note we're case-insensitive.              $query = $self->Get(['AttributeKey'], "AttributeKey(id) LIKE ?", [$parm]);
1042              $retVal = (lc($value) eq lc($pattern));          } elsif ($type eq 'group') {
1043          } elsif (@pieces == 2 && $pieces[1] eq '%') {              $query = $self->Get(['IsInGroup', 'AttributeKey'], "IsInGroup(to-link) = ?", [$item]);
             # A wildcard at the end, so we have a substring match. This is also case-insensitive.  
             $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));  
         } else {  
             # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.  
             my $realPattern = "";  
             for my $piece (@pieces) {  
                 # Determine the type of piece.  
                 if ($piece eq "") {  
                     # Empty pieces are ignored.  
                 } elsif ($piece eq "%") {  
                     # Here we have a multi-character wildcard. Note that it can match  
                     # zero or more characters.  
                     $realPattern .= ".*"  
                 } elsif ($piece eq "_") {  
                     # Here we have a single-character wildcard.  
                     $realPattern .= ".";  
                 } elsif ($piece eq "\\%" || $piece eq "\\_") {  
                     # This is an escape sequence (which is a rare thing, actually).  
                     $realPattern .= substr($piece, 1, 1);  
1044                  } else {                  } else {
1045                      # Here we have raw text.              Confess("Unknown attribute query type \"$type\".");
                     $realPattern .= quotemeta($piece);  
1046                  }                  }
1047            while (my $row = $query->Fetch()) {
1048                # Get this attribute's data.
1049                my ($key, $type, $notes) = $row->Values(['AttributeKey(id)', 'AttributeKey(data-type)',
1050                                                         'AttributeKey(description)']);
1051                # If it's new, get its groups and add it to the return hash.
1052                if (! exists $retVal{$key}) {
1053                    my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?",
1054                                                [$key], 'IsInGroup(to-link)');
1055                    $retVal{$key} = [$type, $notes, @groups];
1056              }              }
             # Do the match.  
             $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);  
1057          }          }
1058      }      }
1059      # Return the result.      # Return the result.
1060      return $retVal;      return %retVal;
1061  }  }
1062    
1063  =head3 MigrateAttributes  =head3 LogOperation
1064    
1065  C<< CustomAttributes::MigrateAttributes($fig); >>  C<< $ca->LogOperation($action, $target, $description); >>
1066    
1067  Migrate all the attributes data from the specified FIG instance. This is a long, slow  Write an operation description to the attribute activity log (C<$FIG_Config::var/attributes.log>).
 method used to convert the old attribute data to the new system. Only attribute  
 keys that are not already in the database will be loaded, and only for entity instances  
 current in the database. To get an accurate capture of the attributes in the given  
 instance, you may want to clear the database and the DBD before starting and  
 run L</Refresh> to populate the entities.  
1068    
1069  =over 4  =over 4
1070    
1071  =item fig  =item action
1072    
1073    Action being logged (e.g. C<Delete Group> or C<Load Key>).
1074    
1075    =item target
1076    
1077    ID of the key or group affected.
1078    
1079    =item description
1080    
1081  A FIG object that can be used to retrieve attributes for migration purposes.  Short description of the action.
1082    
1083  =back  =back
1084    
1085  =cut  =cut
1086    
1087  sub MigrateAttributes {  sub LogOperation {
1088      # Get the parameters.      # Get the parameters.
1089      my ($fig) = @_;      my ($self, $action, $target, $description) = @_;
1090      # Get a list of the objects to migrate. This requires connecting. Note we      # Get the user ID.
1091      # will map each entity type to a file name. The file will contain a list      my $user = $self->{user};
1092      # of the object's IDs so we can get to them when we're not connected to      # Get a timestamp.
1093      # the database.      my $timeString = Tracer::Now();
1094      my $ca = CustomAttributes->new();      # Open the log file for appending.
1095      my %objects = map { $_ => "$FIG_Config::temp/$_.keys.tbl" } $ca->GetEntityTypes();      my $oh = Open(undef, ">>$FIG_Config::var/attributes.log");
1096      # Set up hash of the existing attribute keys for each entity type.      # Write the data to it.
1097      my %oldKeys = ();      Tracer::PutLine($oh, [$timeString, $user, $action, $target, $description]);
1098      # Finally, we have a hash that counts the IDs for each entity type.      # Close the log file.
1099      my %idCounts = map { $_ => 0 } keys %objects;      close $oh;
1100      # Loop through the list, creating key files to read back in.  }
1101      for my $entityType (keys %objects) {  
1102          Trace("Retrieving keys for $entityType.") if T(2);  =head2 Internal Utility Methods
1103          # Create the key file.  
1104          my $idFile = Open(undef, ">$objects{$entityType}");  =head3 _KeywordString
1105          # Loop through the keys.  
1106          my @ids = $ca->GetFlat([$entityType], "", [], "$entityType(id)");  C<< my $keywordString = $ca->_KeywordString($key, $value); >>
1107          for my $id (@ids) {  
1108              print $idFile "$id\n";  Compute the keyword string for a specified key/value pair. This consists of the
1109          }  key name and value converted to lower case with underscores translated to spaces.
1110          close $idFile;  
1111          # In addition to the key file, we must get a list of attributes already  This method is for internal use only. It is called whenever we need to update or
1112          # in the database. This avoids a circularity problem that might occur if the $fig  insert a B<HasValueFor> record.
1113          # object is retrieving from the custom attributes database already.  
1114          my %fields = $ca->GetSecondaryFields($entityType);  =over 4
1115          $oldKeys{$entityType} = \%fields;  
1116          # Finally, we have the ID count.  =item key
1117          $idCounts{$entityType} = scalar @ids;  
1118      }  Name of the relevant attribute key.
1119      # Release the custom attributes database so we can add attributes.  
1120      undef $ca;  =item target
1121      # Loop through the objects.  
1122      for my $entityType (keys %objects) {  ID of the target object to which this key/value pair will be associated.
1123          # Get a hash of all the attributes already in this database. These are  
1124          # left untouched.  =item value
1125          my $myOldKeys = $oldKeys{$entityType};  
1126          # Create a hash to control the load file names for each attribute key we find.  The value to store for this key/object combination.
1127          my %keyHash = ();  
1128          # Set up some counters so we can trace our progress.  =item RETURN
1129          my ($totalIDs, $processedIDs, $keyCount, $valueCount) = ($idCounts{$entityType}, 0, 0, 0);  
1130          # Open this object's ID file.  Returns the value that should be stored as the keyword string for the specified
1131          Trace("Migrating data for $entityType. $totalIDs found.") if T(3);  key/value pair.
1132          my $keysIn = Open(undef, "<$objects{$entityType}");  
1133          while (my $id = <$keysIn>) {  =back
1134              # Remove the EOL characters.  
1135              chomp $id;  =cut
1136              # Get this object's attributes.  
1137              my @allData = $fig->get_attributes($id);  sub _KeywordString {
1138              Trace(scalar(@allData) . " attribute values found for $entityType($id).") if T(4);      # Get the parameters.
1139              # Loop through the attribute values one at a time.      my ($self, $key, $value) = @_;
1140              for my $dataTuple (@allData) {      # Get a copy of the key name and convert underscores to spaces.
1141                  # Get the key, value, and URL. We ignore the first element because that's the      my $keywordString = $key;
1142                  # object ID, and we already know the object ID.      $keywordString =~ s/_/ /g;
1143                  my (undef, $key, $value, $url) = @{$dataTuple};      # Add the value convert it all to lower case.
1144                  # Remove the buggy "1" for $url.      my $retVal = lc "$keywordString $value";
1145                  if ($url eq "1") {      # Return the result.
1146                      $url = undef;      return $retVal;
                 }  
                 # Only proceed if this is not an old key.  
                 if (! $myOldKeys->{$key}) {  
                     # See if we've run into this key before.  
                     if (! exists $keyHash{$key}) {  
                         # Here we need to create the attribute key in the database.  
                         StoreAttributeKey($entityType, $key, 'text',  
                                           "Key migrated automatically from the FIG system. " .  
                                           "Please replace these notes as soon as possible " .  
                                           "with useful text."  
                                          );  
                         # Compute the attribute's load file name and open it for output.  
                         my $fileName = "$FIG_Config::temp/$entityType.$key.load.tbl";  
                         my $fh = Open(undef, ">$fileName");  
                         # Store the file name and handle.  
                         $keyHash{$key} = {h => $fh, name => $fileName};  
                         # Count this key.  
                         $keyCount++;  
                     }  
                     # Smash the value and the URL together.  
                     if (defined($url) && length($url) > 0) {  
                         $value .= "::$url";  
                     }  
                     # Write the attribute value to the load file.  
                     Tracer::PutLine($keyHash{$key}->{h}, [$id, $value]);  
                     $valueCount++;  
                 }  
             }  
             # Now we've finished all the attributes for this object. Count and trace it.  
             $processedIDs++;  
             if ($processedIDs % 500 == 0) {  
                 Trace("$processedIDs of $totalIDs ${entityType}s processed.") if T(3);  
                 Trace("$entityType has $keyCount keys and $valueCount values so far.") if T(3);  
             }  
         }  
         # Now we've finished all the attributes for all objects of this type.  
         Trace("$processedIDs ${entityType}s processed, with $keyCount keys and $valueCount values.") if T(2);  
         # Loop through the files, loading the keys into the database.  
         Trace("Connecting to database.") if T(2);  
         my $objectCA = CustomAttributes->new();  
         Trace("Loading key files.") if T(2);  
         for my $key (sort keys %keyHash) {  
             # Close the key's load file.  
             close $keyHash{$key}->{h};  
             # Reopen it for input.  
             my $fileName = $keyHash{$key}->{name};  
             my $fh = Open(undef, "<$fileName");  
             Trace("Loading $key from $fileName.") if T(3);  
             my $stats = $objectCA->LoadAttributeKey($entityType, $key, $fh, 0, 1);  
             Trace("Statistics for $key of $entityType:\n" . $stats->Show()) if T(3);  
         }  
         # All the keys for this entity type are now loaded.  
         Trace("Key files loaded for $entityType.") if T(2);  
     }  
     # All keys for all entity types are now loaded.  
     Trace("Migration complete.") if T(2);  
1147  }  }
1148    
1149  =head3 ComputeObjectTypeFromID  =head3 _QueryResults
1150    
1151  C<< my ($entityName, $id) = CustomAttributes::ComputeObjectTypeFromID($objectID); >>  C<< my @attributeList = $attrDB->_QueryResults($query, @values); >>
1152    
1153  This method will compute the entity type corresponding to a specified object ID.  Match the results of a B<HasValueFor> query against value criteria and return
1154  If the object ID begins with C<fig|>, it is presumed to be a feature ID. If it  the results. This is an internal method that splits the values coming back
1155  is all digits with a single period, it is presumed to by a genome ID. Otherwise,  and matches the sections against the specified section patterns. It serves
1156  it must be a list reference. In this last case the first list element will be  as the back end to L</GetAttributes> and L</FindAttributes>.
 taken as the entity type and the second will be taken as the actual ID.  
1157    
1158  =over 4  =over 4
1159    
1160  =item objectID  =item query
1161    
1162    A query object that will return the desired B<HasValueFor> records.
1163    
1164  Object ID to examine.  =item values
1165    
1166    List of the desired attribute values, section by section. If C<undef>
1167    or an empty string is specified, all values in that section will match. A
1168    generic match can be requested by placing a percent sign (C<%>) at the end.
1169    In that case, all values that match up to and not including the percent sign
1170    will match. You may also specify a regular expression enclosed
1171    in slashes. All values that match the regular expression will be returned. For
1172    performance reasons, only values have this extra capability.
1173    
1174  =item RETURN  =item RETURN
1175    
1176  Returns a 2-element list consisting of the entity type followed by the specified ID.  Returns a list of tuples. The first element in the tuple is an object ID, the
1177    second is an attribute key, and the remaining elements are the sections of
1178    the attribute value. All of the tuples will match the criteria set forth in
1179    the parameter list.
1180    
1181  =back  =back
1182    
1183  =cut  =cut
1184    
1185  sub ComputeObjectTypeFromID {  sub _QueryResults {
1186      # Get the parameters.      # Get the parameters.
1187      my ($objectID) = @_;      my ($self, $query, @values) = @_;
1188      # Declare the return variables.      # Declare the return value.
1189      my ($entityName, $id);      my @retVal = ();
1190      # Only proceed if the object ID is defined. If it's not, we'll be returning a      # Get the number of value sections we have to match.
1191      # pair of undefs.      my $sectionCount = scalar(@values);
1192      if ($objectID) {      # Loop through the assignments found.
1193          if (ref $objectID eq 'ARRAY') {      while (my $row = $query->Fetch()) {
1194              # Here we have the new-style list reference. Pull out its pieces.          # Get the current row's data.
1195              ($entityName, $id) = @{$objectID};          my ($id, $realKey, $subKey, $valueString) = $row->Values(['HasValueFor(to-link)',
1196          } else {                                                                    'HasValueFor(from-link)',
1197              # Here the ID is the outgoing ID, and we need to look at its structure                                                                    'HasValueFor(subkey)',
1198              # to determine the entity type.                                                                    'HasValueFor(value)'
1199              $id = $objectID;                                                                  ]);
1200              if ($objectID =~ /^\d+\.\d+/) {          # Form the key from the real key and the sub key.
1201                  # Digits with a single period is a genome.          my $key = $self->JoinKey($realKey, $subKey);
1202                  $entityName = 'Genome';          # Break the value into sections.
1203              } elsif ($objectID =~ /^fig\|/) {          my @sections = split($self->{splitter}, $valueString);
1204                  # The "fig|" prefix indicates a feature.          # Match each section against the incoming values. We'll assume we're
1205                  $entityName = 'Feature';          # okay unless we learn otherwise.
1206            my $matching = 1;
1207            for (my $i = 0; $i < $sectionCount && $matching; $i++) {
1208                # We need to check to see if this section is generic.
1209                my $value = $values[$i];
1210                Trace("Current value pattern is \"$value\".") if T(4);
1211                if (substr($value, -1, 1) eq '%') {
1212                    Trace("Generic match used.") if T(4);
1213                    # Here we have a generic match.
1214                    my $matchLen = length($values[$i]) - 1;
1215                    $matching = substr($sections[$i], 0, $matchLen) eq
1216                                substr($values[$i], 0, $matchLen);
1217                } elsif ($value =~ m#^/(.+)/[a-z]*$#) {
1218                    Trace("Regular expression detected.") if T(4);
1219                    # Here we have a regular expression match.
1220                    my $section = $sections[$i];
1221                    $matching = eval("\$section =~ $value");
1222              } else {              } else {
1223                  # Anything else is illegal!                  # Here we have a strict match.
1224                  Confess("Invalid attribute ID specification \"$objectID\".");                  Trace("Strict match used.") if T(4);
1225                    $matching = ($sections[$i] eq $values[$i]);
1226              }              }
1227          }          }
1228            # If we match, output this row to the return list.
1229            if ($matching) {
1230                push @retVal, [$id, $key, @sections];
1231      }      }
1232      # Return the result.      }
1233      return ($entityName, $id);      # Return the rows found.
1234        return @retVal;
1235  }  }
1236    
1237  =head2 FIG Method Replacements  =head2 FIG Method Replacements
1238    
1239  The following methods are used by B<FIG.pm> to replace the previous attribute functionality.  The following methods are used by B<FIG.pm> to replace the previous attribute functionality.
1240  Some of the old functionality is no longer present. Controlled vocabulary is no longer  Some of the old functionality is no longer present: controlled vocabulary is no longer
1241  supported and there is no longer any searching by URL. Fortunately, neither of these  supported and there is no longer any searching by URL. Fortunately, neither of these
1242  capabilities were used in the old system.  capabilities were used in the old system.
1243    
# Line 993  Line 1245 
1245  The idea is that these methods represent attribute manipulation allowed by all users, while  The idea is that these methods represent attribute manipulation allowed by all users, while
1246  the others are only for privileged users with access to the attribute server.  the others are only for privileged users with access to the attribute server.
1247    
1248  In the previous implementation, an attribute had a value and a URL. In the new implementation,  In the previous implementation, an attribute had a value and a URL. In this implementation,
1249  there is only a value. In this implementation, each attribute has only a value. These  each attribute has only a value. These methods will treat the value as a list with the individual
1250  methods will treat the value as a list with the individual elements separated by the  elements separated by the value of the splitter parameter on the constructor (L</new>). The default
1251  value of the splitter parameter on the constructor (L</new>). The default is double  is double colons C<::>.
 colons C<::>.  
1252    
1253  So, for example, an old-style keyword with a /value of C<essential> and a URL of  So, for example, an old-style keyword with a value of C<essential> and a URL of
1254  C<http://www.sciencemag.org/cgi/content/abstract/293/5538/2266> using the default  C<http://www.sciencemag.org/cgi/content/abstract/293/5538/2266> using the default
1255  splitter value would be stored as  splitter value would be stored as
1256    
# Line 1010  Line 1261 
1261    
1262  =head3 GetAttributes  =head3 GetAttributes
1263    
1264  C<< my @attributeList = $attrDB->GetAttributes($objectID, $key, @valuePatterns); >>  C<< my @attributeList = $attrDB->GetAttributes($objectID, $key, @values); >>
1265    
1266  In the database, attribute values are sectioned into pieces using a splitter  In the database, attribute values are sectioned into pieces using a splitter
1267  value specified in the constructor (L</new>). This is not a requirement of  value specified in the constructor (L</new>). This is not a requirement of
1268  the attribute system as a whole, merely a convenience for the purpose of  the attribute system as a whole, merely a convenience for the purpose of
1269  these methods. If you are using the static method calls instead of the  these methods. If a value has multiple sections, each section
1270  object-based calls, the splitter will always be the default value of  is matched against the corresponding criterion in the I<@valuePatterns> list.
 double colons (C<::>). If a value has multiple sections, each section  
 is matched against the correspond criterion in the I<@valuePatterns> list.  
1271    
1272  This method returns a series of tuples that match the specified criteria. Each tuple  This method returns a series of tuples that match the specified criteria. Each tuple
1273  will contain an object ID, a key, and one or more values. The parameters to this  will contain an object ID, a key, and one or more values. The parameters to this
1274  method therefore correspond structurally to the values expected in each tuple.  method therefore correspond structurally to the values expected in each tuple. In
1275    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
1276    of the parameters. So, for example,
1277    
1278      my @attributeList = GetAttributes('fig|100226.1.peg.1004', 'structure%', 1, 2);      my @attributeList = $attrDB->GetAttributes('fig|100226.1.peg.1004', 'structure%', 1, 2);
1279    
1280  would return something like  would return something like
1281    
# Line 1033  Line 1284 
1284      ['fig}100226.1.peg.1004', 'structure2', 1, 2]      ['fig}100226.1.peg.1004', 'structure2', 1, 2]
1285      ['fig}100226.1.peg.1004', 'structureA', 1, 2]      ['fig}100226.1.peg.1004', 'structureA', 1, 2]
1286    
1287  Use of C<undef> in any position acts as a wild card (all values). In addition,  Use of C<undef> in any position acts as a wild card (all values). You can also specify
1288  the I<$key> and I<@valuePatterns> parameters can contain SQL pattern characters: C<%>, which  a list reference in the ID column. Thus,
1289  matches any sequence of characters, and C<_>, which matches any single character.  
1290  (You can use an escape sequence C<\%> or C<\_> to match an actual percent sign or      my @attributeList = $attrDB->GetAttributes(['100226.1', 'fig|100226.1.%'], 'PUBMED');
1291  underscore.)  
1292    would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
1293    features.
1294    
1295  In addition to values in multiple sections, a single attribute key can have multiple  In addition to values in multiple sections, a single attribute key can have multiple
1296  values, so even  values, so even
1297    
1298      my @attributeList = GetAttributes($peg, 'virulent');      my @attributeList = $attrDB->GetAttributes($peg, 'virulent');
1299    
1300  which has no wildcard in the key or the object ID, may return multiple tuples.  which has no wildcard in the key or the object ID, may return multiple tuples.
1301    
1302  For reasons of backward compatability, we examine the structure of the object ID to  Value matching in this system works very poorly, because of the way multiple values are
1303  determine the entity type. In that case the only two types allowed are C<Genome> and  stored. For the object ID, key name, and first value, we create queries that filter for the
1304  C<Feature>. An alternative method is to use a list reference, with the list consisting  desired results. On any filtering by value, we must do a comparison after the attributes are
1305  of an entity type name and the actual ID. Thus, the above example could equivalently  retrieved from the database, since the database has no notion of the multiple values, which
1306  be written as  are stored in a single string. As a result, queries in which filter only on value end up
1307    reading a lot more than they need to.
     my @attributeList = GetAttributes([Feature => $peg], 'virulent');  
   
 The list-reference approach allows us to add attributes to other entity types in  
 the future. Doing so, however, will require modifying the L</Refresh> method and  
 updated the database design XML.  
   
 The list-reference approach also allows for a more fault-tolerant approach to  
 getting all objects with a particular attribute.  
   
     my @attributeList = GetAttributes([Feature => undef], 'virulent');  
   
 will only return feature attributes, while  
   
     my @attributeList = GetAttributes(undef, 'virulent');  
   
 could at some point in the future get you attributes for genomes or even subsystems  
 as well as features.  
1308    
1309  =over 4  =over 4
1310    
1311  =item objectID  =item objectID
1312    
1313  ID of the genome or feature whose attributes are desired. In general, an ID that  ID of object whose attributes are desired. If the attributes are desired for multiple
1314  starts with C<fig|> is treated as a feature ID, and an ID that is all digits with a  objects, this parameter can be specified as a list reference. If the attributes are
1315  single period is treated as a genome ID. For other entity types, use a list reference; in  desired for all objects, specify C<undef> or an empty string. Finally, you can specify
1316  this case the first list element is the entity type and the second is the ID. A value of  attributes for a range of object IDs by putting a percent sign (C<%>) at the end.
 C<undef> or an empty string here will match all objects.  
1317    
1318  =item key  =item key
1319    
1320  Attribute key name. Since attributes are stored as fields in the database with a  Attribute key name. A value of C<undef> or an empty string will match all
1321  field name equal to the key name, it is very fast to find a list of all the  attribute keys. If the values are desired for multiple keys, this parameter can be
1322  matching keys. Each key's values require a separate query, however, which may  specified as a list reference. Finally, you can specify attributes for a range of
1323  be a performance problem if the pattern matches a lot of keys. Wild cards are  keys by putting a percent sign (C<%>) at the end.
 acceptable here, and a value of C<undef> or an empty string will match all  
 attribute keys.  
1324    
1325  =item valuePatterns  =item values
1326    
1327  List of the desired attribute values, section by section. If C<undef>  List of the desired attribute values, section by section. If C<undef>
1328  or an empty string is specified, all values in that section will match.  or an empty string is specified, all values in that section will match. A
1329    generic match can be requested by placing a percent sign (C<%>) at the end.
1330    In that case, all values that match up to and not including the percent sign
1331    will match. You may also specify a regular expression enclosed
1332    in slashes. All values that match the regular expression will be returned. For
1333    performance reasons, only values have this extra capability.
1334    
1335  =item RETURN  =item RETURN
1336    
# Line 1107  Line 1345 
1345    
1346  sub GetAttributes {  sub GetAttributes {
1347      # Get the parameters.      # Get the parameters.
1348      my ($self, $objectID, $key, @valuePatterns) = @_;      my ($self, $objectID, $key, @values) = @_;
1349      # Declare the return variable.      # This hash will map "HasValueFor" fields to patterns. We use it to build the
1350      my @retVal = ();      # SQL statement.
1351      # Determine the entity types for our search.      my %data;
1352      my @objects = ();      # Before we do anything else, we must parse the key. The key is treated by the
1353      my ($actualObjectID, $computedType);      # user as a single field, but to us it's actually a real key and a subkey.
1354      if (! $objectID) {      # If the key has no splitter and is exact, the real key is the original key
1355          push @objects, $self->GetEntityTypes();      # and the subkey is an empty string. If the key has a splitter, it is
1356      } else {      # split into two pieces and each piece is processed separately. If the key has
1357          ($computedType, $actualObjectID) = ComputeObjectTypeFromID($objectID);      # no splitter and is generic, the real key is the incoming key and the subkey
1358          push @objects, $computedType;      # is allowed to be wild. Of course, this only matters if an actual key has
1359      }      # been specified.
1360      # Loop through the entity types.      if (defined $key) {
1361      for my $entityType (@objects) {          if ($key =~ /$self->{splitter}/) {
1362          # Now we need to find all the matching keys. The keys are actually stored in              # Here we have a two-part key, so we split it normally.
1363          # our database object, so this process is fast. Note that our              my ($realKey, $subKey) = $self->SplitKey($key);
1364          # MatchSqlPattern method              $data{'HasValueFor(from-link)'} = $realKey;
1365          my %secondaries = $self->GetSecondaryFields($entityType);              $data{'HasValueFor(subkey)'} = $subKey;
1366          my @fieldList = grep { MatchSqlPattern($_, $key) } keys %secondaries;          } elsif (substr($key, -1, 1) eq '%') {
1367          # Now we figure out whether or not we need to filter by object. We will always              $data{'HasValueFor(from-link)'} = $key;
1368          # filter by key to a limited extent, so if we're filtering by object we need an          } else {
1369          # AND to join the object ID filter with the key filter.              $data{'HasValueFor(from-link)'} = $key;
1370          my $filter = "";              $data{'HasValueFor(subkey)'} = '';
1371          my @params = ();          }
1372          if (defined($actualObjectID)) {      }
1373              # Here the caller wants to filter on object ID. Check for a pattern.      # Add the object ID to the key information.
1374              my $comparator = ($actualObjectID =~ /%/ ? "LIKE" : "=");      $data{'HasValueFor(to-link)'} = $objectID;
1375              # Update the filter and the parameter list.      # The first value represents a problem, because we can search it using SQL, but not
1376              $filter = "$entityType(id) $comparator ? AND ";      # in the normal way. If the user specifies a generic search or exact match for
1377              push @params, $actualObjectID;      # every alternative value (remember, the values may be specified as a list),
1378          }      # then we can create SQL filtering for it. If any of the values are specified
1379          # It's time to begin making queries. We process one attribute key at a time, because      # as a regular expression, however, that's a problem, because we need to read
1380          # each attribute is actually a different field in the database. We know here that      # every value to verify a match.
1381          # all the keys we've collected are for the correct entity because we got them from      if (@values > 0) {
1382          # the DBD. That's a good thing, because an invalid key name will cause an SQL error.          # Get the first value and put its alternatives in an array.
1383          for my $key (@fieldList) {          my $valueParm = $values[0];
1384              # Get all of the attribute values for this key.          my @valueList;
1385              my @dataRows = $self->GetAll([$entityType], "$filter$entityType($key) IS NOT NULL",          if (ref $valueParm eq 'ARRAY') {
1386                                           \@params, ["$entityType(id)", "$entityType($key)"]);              @valueList = @{$valueParm};
1387              # Process each value separately. We need to verify the values and reformat the          } else {
1388              # tuples. Note that GetAll will give us one row per matching object ID,              @valueList = ($valueParm);
1389              # with the ID first followed by a list of the data values. This is very          }
1390              # different from the structure we'll be returning, which has one row          # Okay, now we have all the possible criteria for the first value in the list
1391              # per value.          # @valueList. We'll copy the values to a new array in which they have been
1392              for my $dataRow (@dataRows) {          # converted to generic requests. If we find a regular-expression match
1393                  # Get the object ID and the list of values.          # anywhere in the list, we toss the whole thing.
1394                  my ($rowObjectID, @dataValues) = @{$dataRow};          my @valuePatterns = ();
1395                  # Loop through the values. There will be one result row per attribute value.          my $okValues = 1;
1396                  for my $dataValue (@dataValues) {          for my $valuePattern (@valueList) {
1397                      # Separate this value into sections.              # Check the pattern type.
1398                      my @sections = split("::", $dataValue);              if (substr($valuePattern, 0, 1) eq '/') {
1399                      # Loop through the value patterns, looking for a mismatch. Note that                  # Regular expressions invalidate the entire process.
1400                      # since we're working through parallel arrays, we are using an index                  $okValues = 0;
1401                      # loop. As soon as a match fails we stop checking. This means that              } elsif (substr($valuePattern, -1, 1) eq '%') {
1402                      # if the value pattern list is longer than the number of sections,                  # A Generic pattern is passed in unmodified.
1403                      # we will fail as soon as we run out of sections.                  push @valuePatterns, $valuePattern;
1404                      my $match = 1;              } else {
1405                      for (my $i = 0; $i <= $#valuePatterns && $match; $i++) {                  # An exact match is converted to generic.
1406                          $match = MatchSqlPattern($sections[$i], $valuePatterns[$i]);                  push @valuePatterns, "$valuePattern%";
1407                      }              }
1408                      # If we match, we save this value in the output list.          }
1409                      if ($match) {          # If everything works, add the value data to the filtering hash.
1410                          push @retVal, [$rowObjectID, $key, @sections];          if ($okValues) {
1411                      }              $data{'HasValueFor(value)'} = \@valuePatterns;
1412                  }          }
1413                  # Here we've processed all the attribute values for the current object ID.      }
1414        # Create some lists to contain the filter fragments and parameter values.
1415        my @filter = ();
1416        my @parms = ();
1417        # This next loop goes through the different fields that can be specified in the
1418        # parameter list and generates filters for each. The %data hash that we built above
1419        # contains all the necessary information to do this.
1420        for my $field (keys %data) {
1421            # Accumulate filter information for this field. We will OR together all the
1422            # elements accumulated to create the final result.
1423            my @fieldFilter = ();
1424            # Get the specified data from the caller.
1425            my $fieldPattern = $data{$field};
1426            # Only proceed if the pattern is one that won't match everything.
1427            if (defined($fieldPattern) && $fieldPattern ne "" && $fieldPattern ne "%") {
1428                # Convert the pattern to an array.
1429                my @patterns = ();
1430                if (ref $fieldPattern eq 'ARRAY') {
1431                    push @patterns, @{$fieldPattern};
1432                } else {
1433                    push @patterns, $fieldPattern;
1434                }
1435                # Only proceed if the array is nonempty. The loop will work fine if the
1436                # array is empty, but when we build the filter string at the end we'll
1437                # get "()" in the filter list, which will result in an SQL syntax error.
1438                if (@patterns) {
1439                    # Loop through the individual patterns.
1440                    for my $pattern (@patterns) {
1441                        # Check for a generic request.
1442                        if (substr($pattern, -1, 1) ne '%') {
1443                            # Here we have a normal request.
1444                            push @fieldFilter, "$field = ?";
1445                            push @parms, $pattern;
1446                        } else {
1447                            # Here we have a generic request, so we will use the LIKE operator to
1448                            # filter the field to this value pattern.
1449                            push @fieldFilter, "$field LIKE ?";
1450                            # We must convert the pattern value to an SQL match pattern. First
1451                            # we get a copy of it.
1452                            my $actualPattern = $pattern;
1453                            # Now we escape the underscores. Underscores are an SQL wild card
1454                            # character, but they are used frequently in key names and object IDs.
1455                            $actualPattern =~ s/_/\\_/g;
1456                            # Add the escaped pattern to the bound parameter list.
1457                            push @parms, $actualPattern;
1458                        }
1459                    }
1460                    # Form the filter for this field.
1461                    my $fieldFilterString = join(" OR ", @fieldFilter);
1462                    push @filter, "($fieldFilterString)";
1463              }              }
             # Here we've processed all the rows returned by GetAll. In general, there will  
             # be one row per object ID.  
1464          }          }
         # Here we've processed all the matching attribute keys.  
1465      }      }
1466      # Here we've processed all the entity types. That means @retVal has all the matching      # Now @filter contains one or more filter strings and @parms contains the parameter
1467      # results.      # values to bind to them.
1468        my $actualFilter = join(" AND ", @filter);
1469        # Insure we have at least one filter.
1470        if (! $actualFilter) {
1471            Confess("No filter specified in GetAttributes query.");
1472        }
1473        # Now we're ready to make our query.
1474        my $query = $self->Get(['HasValueFor'], $actualFilter, \@parms);
1475        # Format the results.
1476        my @retVal = $self->_QueryResults($query, @values);
1477        # Return the rows found.
1478      return @retVal;      return @retVal;
1479  }  }
1480    
# Line 1195  Line 1489 
1489    
1490  =item objectID  =item objectID
1491    
1492  ID of the genome or feature to which the attribute is to be added. In general, an ID that  ID of the object to which the attribute is to be added.
 starts with C<fig|> is treated as a feature ID, and an ID that is all digits and periods  
 is treated as a genome ID. For IDs of other types, this parameter should be a reference  
 to a 2-tuple consisting of the entity type name followed by the object ID.  
1493    
1494  =item key  =item key
1495    
1496  Attribute key name. This corresponds to the name of a field in the database.  Attribute key name.
1497    
1498  =item values  =item values
1499    
# Line 1225  Line 1516 
1516      } elsif (! @values) {      } elsif (! @values) {
1517          Confess("No values specified in AddAttribute call for key $key.");          Confess("No values specified in AddAttribute call for key $key.");
1518      } else {      } else {
1519          # Okay, now we have some reason to believe we can do this. Start by          # Okay, now we have some reason to believe we can do this. Form the values
1520          # computing the object type and ID.          # into a scalar.
         my ($entityName, $id) = ComputeObjectTypeFromID($objectID);  
         # Form the values into a scalar.  
1521          my $valueString = join($self->{splitter}, @values);          my $valueString = join($self->{splitter}, @values);
1522          # Insert the value.          # Split up the key.
1523          $self->InsertValue($id, "$entityName($key)", $valueString);          my ($realKey, $subKey) = $self->SplitKey($key);
1524            # Connect the object to the key.
1525            $self->InsertObject('HasValueFor', { 'from-link' => $realKey,
1526                                                 'to-link'   => $objectID,
1527                                                 'subkey'    => $subKey,
1528                                                 'value'     => $valueString,
1529                                           });
1530      }      }
1531      # Return a one. We do this for backward compatability.      # Return a one, indicating success. We do this for backward compatability.
1532      return 1;      return 1;
1533  }  }
1534    
# Line 1243  Line 1538 
1538    
1539  Delete the specified attribute key/value combination from the database.  Delete the specified attribute key/value combination from the database.
1540    
 The first form will connect to the database and release it. The second form  
 uses the database connection contained in the object.  
   
1541  =over 4  =over 4
1542    
1543  =item objectID  =item objectID
1544    
1545  ID of the genome or feature to which the attribute is to be added. In general, an ID that  ID of the object whose attribute is to be deleted.
 starts with C<fig|> is treated as a feature ID, and an ID that is all digits and periods  
 is treated as a genome ID. For IDs of other types, this parameter should be a reference  
 to a 2-tuple consisting of the entity type name followed by the object ID.  
1546    
1547  =item key  =item key
1548    
1549  Attribute key name. This corresponds to the name of a field in the database.  Attribute key name.
1550    
1551  =item values  =item values
1552    
1553  One or more values to be associated with the key.  One or more values associated with the key. If no values are specified, then all values
1554    will be deleted. Otherwise, only a matching value will be deleted.
1555    
1556  =back  =back
1557    
# Line 1275  Line 1565 
1565          Confess("No object ID specified for DeleteAttribute call.");          Confess("No object ID specified for DeleteAttribute call.");
1566      } elsif (! defined($key)) {      } elsif (! defined($key)) {
1567          Confess("No attribute key specified for DeleteAttribute call.");          Confess("No attribute key specified for DeleteAttribute call.");
     } elsif (! @values) {  
         Confess("No values specified in DeleteAttribute call for key $key.");  
1568      } else {      } else {
1569          # Now compute the object type and ID.          # Split the key into the real key and the subkey.
1570          my ($entityName, $id) = ComputeObjectTypeFromID($objectID);          my ($realKey, $subKey) = $self->SplitKey($key);
1571          # Form the values into a scalar.          if ($subKey eq '' && scalar(@values) == 0) {
1572                # Here we erase the entire key for this object.
1573                $self->DeleteRow('HasValueFor', $key, $objectID);
1574            } else {
1575                # Here we erase the matching values.
1576          my $valueString = join($self->{splitter}, @values);          my $valueString = join($self->{splitter}, @values);
1577          # Delete the value.              $self->DeleteRow('HasValueFor', $realKey, $objectID,
1578          $self->DeleteValue($entityName, $id, $key, $valueString);                               { subkey => $subKey, value => $valueString });
1579            }
1580      }      }
1581      # Return a one. This is for backward compatability.      # Return a one. This is for backward compatability.
1582      return 1;      return 1;
1583  }  }
1584    
1585    =head3 DeleteMatchingAttributes
1586    
1587    C<< my @deleted = $attrDB->DeleteMatchingAttributes($objectID, $key, @values); >>
1588    
1589    Delete all attributes that match the specified criteria. This is equivalent to
1590    calling L</GetAttributes> and then invoking L</DeleteAttribute> for each
1591    row found.
1592    
1593    =over 4
1594    
1595    =item objectID
1596    
1597    ID of object whose attributes are to be deleted. If the attributes for multiple
1598    objects are to be deleted, this parameter can be specified as a list reference. If
1599    attributes are to be deleted for all objects, specify C<undef> or an empty string.
1600    Finally, you can delete attributes for a range of object IDs by putting a percent
1601    sign (C<%>) at the end.
1602    
1603    =item key
1604    
1605    Attribute key name. A value of C<undef> or an empty string will match all
1606    attribute keys. If the values are to be deletedfor multiple keys, this parameter can be
1607    specified as a list reference. Finally, you can delete attributes for a range of
1608    keys by putting a percent sign (C<%>) at the end.
1609    
1610    =item values
1611    
1612    List of the desired attribute values, section by section. If C<undef>
1613    or an empty string is specified, all values in that section will match. A
1614    generic match can be requested by placing a percent sign (C<%>) at the end.
1615    In that case, all values that match up to and not including the percent sign
1616    will match. You may also specify a regular expression enclosed
1617    in slashes. All values that match the regular expression will be deleted. For
1618    performance reasons, only values have this extra capability.
1619    
1620    =item RETURN
1621    
1622    Returns a list of tuples for the attributes that were deleted, in the
1623    same form as L</GetAttributes>.
1624    
1625    =back
1626    
1627    =cut
1628    
1629    sub DeleteMatchingAttributes {
1630        # Get the parameters.
1631        my ($self, $objectID, $key, @values) = @_;
1632        # Get the matching attributes.
1633        my @retVal = $self->GetAttributes($objectID, $key, @values);
1634        # Loop through the attributes, deleting them.
1635        for my $tuple (@retVal) {
1636            $self->DeleteAttribute(@{$tuple});
1637        }
1638        # Log this operation.
1639        my $count = @retVal;
1640        $self->LogOperation("Mass Delete", $key, "$count matching attributes deleted.");
1641        # Return the deleted attributes.
1642        return @retVal;
1643    }
1644    
1645  =head3 ChangeAttribute  =head3 ChangeAttribute
1646    
1647  C<< $attrDB->ChangeAttribute($objectID, $key, \@oldValues, \@newValues); >>  C<< $attrDB->ChangeAttribute($objectID, $key, \@oldValues, \@newValues); >>
# Line 1333  Line 1686 
1686      } elsif (! defined($newValues) || ref $newValues ne 'ARRAY') {      } elsif (! defined($newValues) || ref $newValues ne 'ARRAY') {
1687          Confess("No new values specified in ChangeAttribute call for key $key.");          Confess("No new values specified in ChangeAttribute call for key $key.");
1688      } else {      } else {
1689          # Okay, now we do the change as a delete/add.          # We do the change as a delete/add.
1690          $self->DeleteAttribute($objectID, $key, @{$oldValues});          $self->DeleteAttribute($objectID, $key, @{$oldValues});
1691          $self->AddAttribute($objectID, $key, @{$newValues});          $self->AddAttribute($objectID, $key, @{$newValues});
1692      }      }
# Line 1343  Line 1696 
1696    
1697  =head3 EraseAttribute  =head3 EraseAttribute
1698    
1699  C<< $attrDB->EraseAttribute($entityName, $key); >>  C<< $attrDB->EraseAttribute($key); >>
1700    
1701  Erase all values for the specified attribute key. This does not remove the  Erase all values for the specified attribute key. This does not remove the
1702  key from the database; it merely removes all the values.  key from the database; it merely removes all the values.
1703    
1704  =over 4  =over 4
1705    
 =item entityName  
   
 Name of the entity to which the key belongs. If undefined, all entities will be  
 examined for the desired key.  
   
1706  =item key  =item key
1707    
1708  Key to erase.  Key to erase. This must be a real key; that is, it cannot have a subkey
1709    component.
1710    
1711  =back  =back
1712    
# Line 1365  Line 1714 
1714    
1715  sub EraseAttribute {  sub EraseAttribute {
1716      # Get the parameters.      # Get the parameters.
1717      my ($self, $entityName, $key) = @_;      my ($self, $key) = @_;
1718      # Determine the relevant entity types.      # Delete everything connected to the key.
1719      my @objects = ();      $self->Disconnect('HasValueFor', 'AttributeKey', $key);
1720      if (! $entityName) {      # Log the operation.
1721          push @objects, $self->GetEntityTypes();      $self->LogOperation("Erase Data", $key);
     } else {  
         push @objects, $entityName;  
     }  
     # Loop through the entity types.  
     for my $entityType (@objects) {  
         # Now check for this key in this entity.  
         my %secondaries = $self->GetSecondaryFields($entityType);  
         if (exists $secondaries{$key}) {  
             # We found it, so delete all the values of the key.  
             $self->DeleteValue($entityType, undef, $key);  
         }  
     }  
1722      # Return a 1, for backward compatability.      # Return a 1, for backward compatability.
1723      return 1;      return 1;
1724  }  }
1725    
1726  =head3 GetAttributeKeys  =head3 GetAttributeKeys
1727    
1728  C<< my @keyList = $attrDB->GetAttributeKeys($entityName); >>  C<< my @keyList = $attrDB->GetAttributeKeys($groupName); >>
1729    
1730  Return a list of the attribute keys for a particular entity type.  Return a list of the attribute keys for a particular group.
1731    
1732  =over 4  =over 4
1733    
1734  =item entityName  =item groupName
1735    
1736  Name of the entity whose keys are desired.  Name of the group whose keys are desired.
1737    
1738  =item RETURN  =item RETURN
1739    
1740  Returns a list of the attribute keys for the specified entity.  Returns a list of the attribute keys for the specified group.
1741    
1742  =back  =back
1743    
# Line 1408  Line 1745 
1745    
1746  sub GetAttributeKeys {  sub GetAttributeKeys {
1747      # Get the parameters.      # Get the parameters.
1748      my ($self, $entityName) = @_;      my ($self, $groupName) = @_;
1749      # Get the entity's secondary fields.      # Get the attributes for the specified group.
1750      my %keyList = $self->GetSecondaryFields($entityName);      my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(to-link) = ?", [$groupName],
1751                                    'IsInGroup(from-link)');
1752      # Return the keys.      # Return the keys.
1753      return sort keys %keyList;      return sort @groups;
1754    }
1755    
1756    =head3 QueryAttributes
1757    
1758    C<< my @attributeData = $ca->QueryAttributes($filter, $filterParms); >>
1759    
1760    Return the attribute data based on an SQL filter clause. In the filter clause,
1761    the name C<$object> should be used for the object ID, C<$key> should be used for
1762    the key name, C<$subkey> for the subkey value, and C<$value> for the value field.
1763    
1764    =over 4
1765    
1766    =item filter
1767    
1768    Filter clause in the standard ERDB format, except that the field names are C<$object> for
1769    the object ID field, C<$key> for the key name field, C<$subkey> for the subkey field,
1770    and C<$value> for the value field. This abstraction enables us to hide the details of
1771    the database construction from the user.
1772    
1773    =item filterParms
1774    
1775    Parameters for the filter clause.
1776    
1777    =item RETURN
1778    
1779    Returns a list of tuples. Each tuple consists of an object ID, a key (with optional subkey), and
1780    one or more attribute values.
1781    
1782    =back
1783    
1784    =cut
1785    
1786    # This hash is used to drive the substitution process.
1787    my %AttributeParms = (object => 'HasValueFor(to-link)',
1788                          key    => 'HasValueFor(from-link)',
1789                          subkey => 'HasValueFor(subkey)',
1790                          value  => 'HasValueFor(value)');
1791    
1792    sub QueryAttributes {
1793        # Get the parameters.
1794        my ($self, $filter, $filterParms) = @_;
1795        # Declare the return variable.
1796        my @retVal = ();
1797        # Make sue we have filter parameters.
1798        my $realParms = (defined($filterParms) ? $filterParms : []);
1799        # Create the query by converting the filter.
1800        my $realFilter = $filter;
1801        for my $name (keys %AttributeParms) {
1802            $realFilter =~ s/\$$name/$AttributeParms{$name}/g;
1803        }
1804        my $query = $self->Get(['HasValueFor'], $realFilter, $realParms);
1805        # Loop through the results, forming the output attribute tuples.
1806        while (my $result = $query->Fetch()) {
1807            # Get the four values from this query result row.
1808            my ($objectID, $key, $subkey, $value) = $result->Values([$AttributeParms{object},
1809                                                                    $AttributeParms{key},
1810                                                                    $AttributeParms{subkey},
1811                                                                    $AttributeParms{value}]);
1812            # Combine the key and the subkey.
1813            my $realKey = ($subkey ? $key . $self->{splitter} . $subkey : $key);
1814            # Split the value.
1815            my @values = split $self->{splitter}, $value;
1816            # Output the result.
1817            push @retVal, [$objectID, $realKey, @values];
1818        }
1819        # Return the result.
1820        return @retVal;
1821    }
1822    
1823    =head2 Key and ID Manipulation Methods
1824    
1825    =head3 ParseID
1826    
1827    C<< my ($type, $id) = CustomAttributes::ParseID($idValue); >>
1828    
1829    Determine the type and object ID corresponding to an ID value from the attribute database.
1830    Most ID values consist of a type name and an ID, separated by a colon (e.g. C<Family:aclame|cluster10>);
1831    however, Genomes, Features, and Subsystems are not stored with a type name, so we need to
1832    deduce the type from the ID value structure.
1833    
1834    The theory here is that you can plug the ID and type directly into a Sprout database method, as
1835    follows
1836    
1837        my ($type, $id) = CustomAttributes::ParseID($attrList[$num]->[0]);
1838        my $target = $sprout->GetEntity($type, $id);
1839    
1840    =over 4
1841    
1842    =item idValue
1843    
1844    ID value taken from the attribute database.
1845    
1846    =item RETURN
1847    
1848    Returns a two-element list. The first element is the type of object indicated by the ID value,
1849    and the second element is the actual object ID.
1850    
1851    =back
1852    
1853    =cut
1854    
1855    sub ParseID {
1856        # Get the parameters.
1857        my ($idValue) = @_;
1858        # Declare the return variables.
1859        my ($type, $id);
1860        # Parse the incoming ID. We first check for the presence of an entity name. Entity names
1861        # can only contain letters, which helps to insure typed object IDs don't collide with
1862        # subsystem names (which are untyped).
1863        if ($idValue =~ /^([A-Za-z]+):(.+)/) {
1864            # Here we have a typed ID.
1865            ($type, $id) = ($1, $2);
1866            # Fix the case sensitivity on PDB IDs.
1867            if ($type eq 'PDB') { $id = lc $id; }
1868        } elsif ($idValue =~ /fig\|/) {
1869            # Here we have a feature ID.
1870            ($type, $id) = (Feature => $idValue);
1871        } elsif ($idValue =~ /\d+\.\d+/) {
1872            # Here we have a genome ID.
1873            ($type, $id) = (Genome => $idValue);
1874        } else {
1875            # The default is a subsystem ID.
1876            ($type, $id) = (Subsystem => $idValue);
1877        }
1878        # Return the results.
1879        return ($type, $id);
1880    }
1881    
1882    =head3 FormID
1883    
1884    C<< my $idValue = CustomAttributes::FormID($type, $id); >>
1885    
1886    Convert an object type and ID pair into an object ID string for the attribute system. Subsystems,
1887    genomes, and features are stored in the database without type information, but all other object IDs
1888    must be prefixed with the object type.
1889    
1890    =over 4
1891    
1892    =item type
1893    
1894    Relevant object type.
1895    
1896    =item id
1897    
1898    ID of the object in question.
1899    
1900    =item RETURN
1901    
1902    Returns a string that will be recognized as an object ID in the attribute database.
1903    
1904    =back
1905    
1906    =cut
1907    
1908    sub FormID {
1909        # Get the parameters.
1910        my ($type, $id) = @_;
1911        # Declare the return variable.
1912        my $retVal;
1913        # Compute the ID string from the type.
1914        if (grep { $type eq $_ } qw(Feature Genome Subsystem)) {
1915            $retVal = $id;
1916        } else {
1917            $retVal = "$type:$id";
1918        }
1919        # Return the result.
1920        return $retVal;
1921    }
1922    
1923    =head3 GetTargetObject
1924    
1925    C<< my $object = CustomAttributes::GetTargetObject($erdb, $idValue); >>
1926    
1927    Return the database object corresponding to the specified attribute object ID. The
1928    object type associated with the ID value must correspond to an entity name in the
1929    specified database.
1930    
1931    =over 4
1932    
1933    =item erdb
1934    
1935    B<ERDB> object for accessing the target database.
1936    
1937    =item idValue
1938    
1939    ID value retrieved from the attribute database.
1940    
1941    =item RETURN
1942    
1943    Returns a B<ERDBObject> for the attribute value's target object.
1944    
1945    =back
1946    
1947    =cut
1948    
1949    sub GetTargetObject {
1950        # Get the parameters.
1951        my ($erdb, $idValue) = @_;
1952        # Declare the return variable.
1953        my $retVal;
1954        # Get the type and ID for the target object.
1955        my ($type, $id) = ParseID($idValue);
1956        # Plug them into the GetEntity method.
1957        $retVal = $erdb->GetEntity($type, $id);
1958        # Return the resulting object.
1959        return $retVal;
1960    }
1961    
1962    =head3 SplitKey
1963    
1964    C<< my ($realKey, $subKey) = $ca->SplitKey($key); >>
1965    
1966    Split an external key (that is, one passed in by a caller) into the real key and the sub key.
1967    The real and sub keys are separated by a splitter value (usually C<::>). If there is no splitter,
1968    then the sub key is presumed to be an empty string.
1969    
1970    =over 4
1971    
1972    =item key
1973    
1974    Incoming key to be split.
1975    
1976    =item RETURN
1977    
1978    Returns a two-element list, the first element of which is the real key and the second element of
1979    which is the sub key.
1980    
1981    =back
1982    
1983    =cut
1984    
1985    sub SplitKey {
1986        # Get the parameters.
1987        my ($self, $key) = @_;
1988        # Do the split.
1989        my ($realKey, $subKey) = split($self->{splitter}, $key, 2);
1990        # Insure the subkey has a value.
1991        if (! defined $subKey) {
1992            $subKey = '';
1993        }
1994        # Return the results.
1995        return ($realKey, $subKey);
1996    }
1997    
1998    =head3 JoinKey
1999    
2000    C<< my $key = $ca->JoinKey($realKey, $subKey); >>
2001    
2002    Join a real key and a subkey together to make an external key. The external key is the attribute key
2003    used by the caller. The real key and the subkey are how the keys are represented in the database. The
2004    real key is the key to the B<AttributeKey> entity. The subkey is an attribute of the B<HasValueFor>
2005    relationship.
2006    
2007    =over 4
2008    
2009    =item realKey
2010    
2011    The real attribute key.
2012    
2013    =item subKey
2014    
2015    The subordinate portion of the attribute key.
2016    
2017    =item RETURN
2018    
2019    Returns a single string representing both keys.
2020    
2021    =back
2022    
2023    =cut
2024    
2025    sub JoinKey {
2026        # Get the parameters.
2027        my ($self, $realKey, $subKey) = @_;
2028        # Declare the return variable.
2029        my $retVal;
2030        # Check for a subkey.
2031        if ($subKey eq '') {
2032            # No subkey, so the real key is the key.
2033            $retVal = $realKey;
2034        } else {
2035            # Subkey found, so the two pieces must be joined by a splitter.
2036            $retVal = "$realKey$self->{splitter}$subKey";
2037  }  }
2038        # Return the result.
2039        return $retVal;
2040    }
2041    
2042    
2043    =head3 AttributeTable
2044    
2045    C<< my $tableHtml = CustomAttributes::AttributeTable($cgi, @attrList); >>
2046    
2047    Format the attribute data into an HTML table.
2048    
2049    =over 4
2050    
2051    =item cgi
2052    
2053    CGI query object used to generate the HTML
2054    
2055    =item attrList
2056    
2057    List of attribute results, in the format returned by the L</GetAttributes> or
2058    L</QueryAttributes> methods.
2059    
2060    =item RETURN
2061    
2062    Returns an HTML table displaying the attribute keys and values.
2063    
2064    =back
2065    
2066    =cut
2067    
2068    sub AttributeTable {
2069        # Get the parameters.
2070        my ($cgi, @attrList) = @_;
2071        # Accumulate the table rows.
2072        my @html = ();
2073        for my $attrData (@attrList) {
2074            # Format the object ID and key.
2075            my @columns = map { CGI::escapeHTML($_) } @{$attrData}[0,1];
2076            # Now we format the values. These remain unchanged unless one of them is a URL.
2077            my $lastValue = scalar(@{$attrData}) - 1;
2078            push @columns, map { $_ =~ /^http:/ ? $cgi->a({ href => $_ }, $_) : $_ } @{$attrData}[2 .. $lastValue];
2079            # Assemble the values into a table row.
2080            push @html, $cgi->Tr($cgi->td(\@columns));
2081        }
2082        # Format the table in the return variable.
2083        my $retVal = $cgi->table({ border => 2 }, $cgi->Tr($cgi->th(['Object', 'Key', 'Values'])), @html);
2084        # Return it.
2085        return $retVal;
2086    }
2087  1;  1;

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.30

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3