[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.27, Sun Sep 30 03:46:30 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;
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  =back  =back
433    
434  =cut  =cut
435    
436  sub LoadAttributeKey {  sub LoadAttributesFrom {
437      # Get the parameters.      # Get the parameters.
438      my ($self, $entityName, $fieldName, $fh, $keyCol, $dataCol) = @_;      my ($self, $fileName, %options) = @_;
439      # Create the return variable.      # Declare the return variable.
440      my $retVal;      my $retVal = Stats->new('keys', 'values');
441      # Insure the entity exists.      # Initialize the timers.
442      my $found = grep { $_ eq $entityName } $self->GetEntityTypes();      my ($insertTime, $eraseTime, $archiveTime) = (0, 0, 0);
443      if (! $found) {      # Check for append mode.
444          Confess("Entity \"$entityName\" not found in database.");      my $append = ($options{append} ? 1 : 0);
445      } else {      # Create a hash of key names found.
446          # Get the field structure for the named entity.      my %keyHash = ();
447          my $fieldHash = $self->GetFieldTable($entityName);      # Open the file for input. Note we must anticipate the possibility of an
448          # Verify that the attribute exists.      # open filehandle being passed in.
449          if (! exists $fieldHash->{$fieldName}) {      my $fh;
450              Confess("Attribute key \"$fieldName\" does not exist in entity $entityName.");      if (ref $fileName) {
451          } else {          Trace("Using file opened by caller.") if T(3);
452              # Create a loader for the specified attribute. We need the          $fh = $fileName;
             # relation name first.  
             my $relName = $fieldHash->{$fieldName}->{relation};  
             my $loadAttribute = ERDBLoad->new($self, $relName, $FIG_Config::temp);  
             # Loop through the input file.  
             while (! eof $fh) {  
                 # Get the next line of the file.  
                 my @fields = Tracer::GetLine($fh);  
                 $loadAttribute->Add("lineIn");  
                 # Now we need to validate the line.  
                 if ($#fields < $dataCol) {  
                     $loadAttribute->Add("shortLine");  
                 } elsif (! $self->Exists($entityName, $fields[$keyCol])) {  
                     $loadAttribute->Add("badKey");  
453                  } else {                  } else {
454                      # It's valid,so send it to the loader.          Trace("Attributes will be loaded from $fileName.") if T(3);
455                      $loadAttribute->Put($fields[$keyCol], $fields[$dataCol]);          $fh = Open(undef, "<$fileName");
                     $loadAttribute->Add("lineUsed");  
456                  }                  }
457        # Now check to see if we need to archive.
458        my $ah;
459        if ($options{archive}) {
460            $ah = Open(undef, ">$options{archive}");
461            Trace("Load file will be archived to $options{archive}.") if T(3);
462        }
463        # Finally, open a database transaction.
464        $self->BeginTran();
465        # Insure we recover from errors. If an error occurs, we will delete the archive file and
466        # roll back the updates.
467        eval {
468            # Loop through the file.
469            while (! eof $fh) {
470                # Read the current line.
471                my ($id, $key, @values) = Tracer::GetLine($fh);
472                $retVal->Add(linesIn => 1);
473                # Check to see if we need to fix up the object ID.
474                if ($options{objectType}) {
475                    $id = "$options{objectType}:$id";
476                }
477                # Archive the line (if necessary).
478                if (defined $ah) {
479                    my $startTime = time();
480                    Tracer::PutLine($ah, [$id, $key, @values]);
481                    $archiveTime += time() - $startTime;
482                }
483                # Do some validation.
484                if (! $id) {
485                    # We ignore blank lines.
486                    $retVal->Add(blankLines => 1);
487                } elsif (substr($id, 0, 1) eq '#') {
488                    # A line beginning with a pound sign is a comment.
489                    $retVal->Add(comments => 1);
490                } elsif (! defined($key)) {
491                    # An ID without a key is a serious error.
492                    my $lines = $retVal->Ask('linesIn');
493                    Confess("Line $lines in $fileName has no attribute key.");
494                } elsif (! @values) {
495                    # A line with no values is not allowed.
496                    my $lines = $retVal->Ask('linesIn');
497                    Trace("Line $lines for key $key has no attribute values.") if T(1);
498                    $retVal->Add(skipped => 1);
499                } else {
500                    # The key contains a real part and an optional sub-part. We need the real part.
501                    my ($realKey, $subKey) = $self->SplitKey($key);
502                    # Now we need to check for a new key.
503                    if (! exists $keyHash{$realKey}) {
504                        if (! $self->Exists('AttributeKey', $realKey)) {
505                            my $line = $retVal->Ask('linesIn');
506                            Confess("Attribute \"$realKey\" on line $line of $fileName not found in database.");
507                        } else {
508                            # Make sure we know this is no longer a new key.
509                            $keyHash{$realKey} = 1;
510                            $retVal->Add(keys => 1);
511                            # If this is NOT append mode, erase the key.
512                            if (! $append) {
513                                my $startTime = time();
514                                $self->EraseAttribute($realKey);
515                                $eraseTime += time() - $startTime;
516                                Trace("Attribute $realKey erased.") if T(3);
517                            }
518                        }
519                        Trace("Key $realKey found.") if T(3);
520                    }
521                    # Everything is all set up, so add the value.
522                    my $startTime = time();
523                    $self->AddAttribute($id, $key, @values);
524                    $insertTime += time() - $startTime;
525                    my $progress = $retVal->Add(values => 1);
526                    Trace("$progress values loaded.") if T(3) && ($progress % 1000 == 0);
527                }
528            }
529            $retVal->Add(eraseTime  =>  $eraseTime);
530            $retVal->Add(insertTime =>  $insertTime);
531            $retVal->Add(archiveTime => $archiveTime);
532        };
533        # Check for an error.
534        if ($@) {
535            # Here we have an error. Roll back the transaction and delete the archive file.
536            my $message = $@;
537            Trace("Rolling back attribute updates due to error.") if T(1);
538            $self->RollbackTran();
539            if (defined $ah) {
540                Trace("Deleting archive file $options{archive}.") if T(1);
541                close $ah;
542                unlink $options{archive};
543              }              }
544              # Finish the load.          Confess("Error during attribute load: $message");
545              $retVal = $loadAttribute->FinishAndLoad();      } else {
546            # Here the load worked. Commit the transaction and close the archive file.
547            Trace("Committing attribute upload.") if T(2);
548            $self->CommitTran();
549            if (defined $ah) {
550                Trace("Closing archive file $options{archive}.") if T(2);
551                close $ah;
552          }          }
553      }      }
554      # Return the statistics.      # Return the result.
555      return $retVal;      return $retVal;
556  }  }
557    
558    =head3 BackupKeys
559    
560  =head3 DeleteAttributeKey  C<< my $stats = $attrDB->BackupKeys($fileName, %options); >>
   
 C<< CustomAttributes::DeleteAttributeKey($entityName, $attributeName); >>  
561    
562  Delete an attribute from the custom attributes database.  Backup the attribute key information from the attribute database.
563    
564  =over 4  =over 4
565    
566  =item entityName  =item fileName
567    
568  Name of the entity possessing the attribute.  Name of the output file.
569    
570  =item attributeName  =item options
571    
572  Name of the attribute to delete.  Options for modifying the backup process.
573    
574    =item RETURN
575    
576    Returns a statistics object for the backup.
577    
578    =back
579    
580    Currently there are no options. The backup is straight to a text file in
581    tab-delimited format. Each key is backup up to two lines. The first line
582    is all of the data from the B<AttributeKey> table. The second is a
583    tab-delimited list of all the groups.
584    
585    =cut
586    
587    sub BackupKeys {
588        # Get the parameters.
589        my ($self, $fileName, %options) = @_;
590        # Declare the return variable.
591        my $retVal = Stats->new();
592        # Open the output file.
593        my $fh = Open(undef, ">$fileName");
594        # Set up to read the keys.
595        my $keyQuery = $self->Get(['AttributeKey'], "", []);
596        # Loop through the keys.
597        while (my $keyData = $keyQuery->Fetch()) {
598            $retVal->Add(key => 1);
599            # Get the fields.
600            my ($id, $type, $description) = $keyData->Values(['AttributeKey(id)', 'AttributeKey(data-type)',
601                                                              'AttributeKey(description)']);
602            # Escape any tabs or new-lines in the description.
603            my $escapedDescription = Tracer::Escape($description);
604            # Write the key data to the output.
605            Tracer::PutLine($fh, [$id, $type, $escapedDescription]);
606            # Get the key's groups.
607            my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?", [$id],
608                                        'IsInGroup(to-link)');
609            $retVal->Add(memberships => scalar(@groups));
610            # Write them to the output. Note we put a marker at the beginning to insure the line
611            # is nonempty.
612            Tracer::PutLine($fh, ['#GROUPS', @groups]);
613        }
614        # Log the operation.
615        $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
616        # Return the result.
617        return $retVal;
618    }
619    
620    =head3 RestoreKeys
621    
622    C<< my $stats = $attrDB->RestoreKeys($fileName, %options); >>
623    
624    Restore the attribute keys and groups from a backup file.
625    
626    =over 4
627    
628    =item fileName
629    
630    Name of the file containing the backed-up keys. Each key has a pair of lines,
631    one containing the key data and one listing its groups.
632    
633  =back  =back
634    
635  =cut  =cut
636    
637  sub DeleteAttributeKey {  sub RestoreKeys {
638      # Get the parameters.      # Get the parameters.
639      my ($entityName, $attributeName) = @_;      my ($self, $fileName, %options) = @_;
640      # Read in the XML for the database defintion. We need to verify that      # Declare the return variable.
641      # the named entity exists and it has the named attribute.      my $retVal = Stats->new();
642      my $metadata = ERDB::ReadMetaXML($FIG_Config::attrDBD);      # Set up a hash to hold the group IDs.
643      my $entityHash = $metadata->{Entities};      my %groups = ();
644      if (! exists $entityHash->{$entityName}) {      # Open the file.
645          Confess("Entity \"$entityName\" not found.");      my $fh = Open(undef, "<$fileName");
646      } else {      # Loop until we're done.
647          # Get the field hash.      while (! eof $fh) {
648          my $fieldHash = ERDB::GetEntityFieldHash($metadata, $entityName);          # Get a key record.
649          if (! exists $fieldHash->{$attributeName}) {          my ($id, $dataType, $description) = Tracer::GetLine($fh);
650              Confess("Attribute key \"$attributeName\" not found in entity $entityName.");          if ($id eq '#GROUPS') {
651          } else {              Confess("Group record found when key record expected.");
652              # Get the attribute's relation name.          } elsif (! defined($description)) {
653              my $relName = $fieldHash->{$attributeName}->{relation};              Confess("Invalid format found for key record.");
654              # Check for an index.          } else {
655              my $indexIdx = ERDB::FindIndexForEntity($metadata, $entityName, $attributeName);              $retVal->Add("keyIn" => 1);
656              if (defined($indexIdx)) {              # Add this key to the database.
657                  Trace("Index for $attributeName found at position $indexIdx for $entityName.") if T(3);              $self->InsertObject('AttributeKey', { id => $id, 'data-type' => $dataType,
658                  delete $entityHash->{$entityName}->{Indexes}->[$indexIdx];                                                    description => Tracer::UnEscape($description) });
659              }              Trace("Attribute $id stored.") if T(3);
660              # Delete the attribute from the field hash.              # Get the group line.
661              Trace("Deleting attribute $attributeName from $entityName.") if T(3);              my ($marker, @groups) = Tracer::GetLine($fh);
662              delete $fieldHash->{$attributeName};              if (! defined($marker)) {
663              # Write the XML back out.                  Confess("End of file found where group record expected.");
664              ERDB::WriteMetaXML($metadata, $FIG_Config::attrDBD);              } elsif ($marker ne '#GROUPS') {
665              # Insure the relation does not exist in the database. This requires connecting                  Confess("Group record not found after key record.");
666              # since we may have to do a table drop.              } else {
667              my $attrDB = CustomAttributes->new();                  $retVal->Add(memberships => scalar(@groups));
668              Trace("Dropping table $relName.") if T(3);                  # Connect the groups.
669              $attrDB->DropRelation($relName);                  for my $group (@groups) {
670                        # Find out if this is a new group.
671                        if (! $groups{$group}) {
672                            $retVal->Add(newGroup => 1);
673                            # Add the group.
674                            $self->InsertObject('AttributeGroup', { id => $group });
675                            Trace("Group $group created.") if T(3);
676                            # Make sure we know it's not new.
677                            $groups{$group} = 1;
678                        }
679                        # Connect the group to our key.
680                        $self->InsertObject('IsInGroup', { 'from-link' => $id, 'to-link' => $group });
681                    }
682                    Trace("$id added to " . scalar(@groups) . " groups.") if T(3);
683                }
684          }          }
685      }      }
686        # Log the operation.
687        $self->LogOperation("Backup Keys", $fileName, $retVal->Display());
688        # Return the result.
689        return $retVal;
690  }  }
691    
692  =head3 ControlForm  =head3 ArchiveFileName
693    
694  C<< my $formHtml = $attrDB->ControlForm($cgi, $name); >>  C<< my $fileName = $ca->ArchiveFileName(); >>
695    
696  Return a form that can be used to control the creation and modification of  Compute a file name for archiving attribute input data. The file will be in the attribute log directory
697  attributes.  
698    =cut
699    
700    sub ArchiveFileName {
701        # Get the parameters.
702        my ($self) = @_;
703        # Declare the return variable.
704        my $retVal;
705        # We start by turning the timestamp into something usable as a file name.
706        my $now = Tracer::Now();
707        $now =~ tr/ :\//___/;
708        # Next we get the directory name.
709        my $dir = "$FIG_Config::var/attributes";
710        if (! -e $dir) {
711            Trace("Creating attribute file directory $dir.") if T(1);
712            mkdir $dir;
713        }
714        # Put it together with the field name and the time stamp.
715        $retVal = "$dir/upload.$now";
716        # Modify the file name to insure it's unique.
717        my $seq = 0;
718        while (-e "$retVal.$seq.tbl") { $seq++ }
719        # Use the computed sequence number to get the correct file name.
720        $retVal .= ".$seq.tbl";
721        # Return the result.
722        return $retVal;
723    }
724    
725    =head3 BackupAllAttributes
726    
727    C<< my $stats = $attrDB->BackupAllAttributes($fileName, %options); >>
728    
729    Backup all of the attributes to a file. The attributes will be stored in a
730    tab-delimited file suitable for reloading via L</LoadAttributesFrom>.
731    
732  =over 4  =over 4
733    
734  =item cgi  =item fileName
735    
736  CGI query object used to create HTML.  Name of the file to which the attribute data should be backed up.
737    
738  =item name  =item options
739    
740  Name to give to the form. This should be unique for the web page.  Hash of options for the backup.
741    
742  =item RETURN  =item RETURN
743    
744  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.  
745    
746  =back  =back
747    
748    Currently there are no options defined.
749    
750  =cut  =cut
751    
752  sub ControlForm {  sub BackupAllAttributes {
753      # Get the parameters.      # Get the parameters.
754      my ($self, $cgi, $name) = @_;      my ($self, $fileName, %options) = @_;
755      # Declare the return list.      # Declare the return variable.
756      my @retVal = ();      my $retVal = Stats->new();
757      # Start the form. We use multipart to support the upload control.      # Get a list of the keys.
758      push @retVal, $cgi->start_multipart_form(-name => $name);      my @keys = $self->GetFlat(['AttributeKey'], "", [], 'AttributeKey(id)');
759      # 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);
760      push @retVal, $cgi->start_table({ border => 2, cellpadding => 2 });      # Open the file for output.
761      # The first row is for selecting the field name.      my $fh = Open(undef, ">$fileName");
762      push @retVal, $cgi->Tr($cgi->th("Select a Field"),      # Loop through the keys.
763                             $cgi->td($self->FieldMenu($cgi, 10, 'fieldName', 1,      for my $key (@keys) {
764                                                       "document.$name.notes.value",          Trace("Backing up attribute $key.") if T(3);
765                                                       "document.$name.dataType.value")));          $retVal->Add(keys => 1);
766      # Now we set up a dropdown for the data types. The values will be the          # Loop through this key's values.
767      # data type names, and the labels will be the descriptions.          my $query = $self->Get(['HasValueFor'], "HasValueFor(from-link) = ?", [$key]);
768      my %types = ERDB::GetDataTypes();          my $valuesFound = 0;
769      my %labelMap = map { $_ => $types{$_}->{notes} } keys %types;          while (my $line = $query->Fetch()) {
770      my $typeMenu = $cgi->popup_menu(-name   => 'dataType',              $valuesFound++;
771                                      -values => [sort keys %types],              # Get this row's data.
772                                      -labels => \%labelMap);              my ($id, $key, $subKey, $value) = $line->Values(['HasValueFor(to-link)',
773      push @retVal, $cgi->Tr($cgi->th("Data type"),                                                               'HasValueFor(from-link)',
774                             $cgi->td($typeMenu));                                                               'HasValueFor(subkey)',
775      # The next row is for the notes.                                                               'HasValueFor(value)']);
776      push @retVal, $cgi->Tr($cgi->th("Description"),              # Check for a subkey.
777                             $cgi->td($cgi->textarea(-name => 'notes',              if ($subKey ne '') {
778                                                     -rows => 6,                  $key = "$key$self->{splitter}$subKey";
779                                                     -columns => 80))              }
780                            );              # Write it to the file.
781      # Allow the user to specify a new field name. This is required if the              Tracer::PutLine($fh, [$id, $key, $value]);
782      # user has selected one of the "(new)" markers.          }
783      push @retVal, $cgi->Tr($cgi->th("New Field Name"),          Trace("$valuesFound values backed up for key $key.") if T(3);
784                             $cgi->td($cgi->textfield(-name => 'newName',          $retVal->Add(values => $valuesFound);
785                                                      -size => 30)),      }
786                                      );      # Log the operation.
787      # If the user wants to upload new values for the field, then we have      $self->LogOperation("Backup Data", $fileName, $retVal->Display());
788      # an upload file name and column indicators.      # Return the result.
789      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, "");  
790  }  }
791    
792  =head3 FieldMenu  =head3 FieldMenu
793    
794  C<< my $menuHtml = $attrDB->FieldMenu($cgi, $height, $name, $newFlag, $noteControl, $typeControl); >>  C<< my $menuHtml = $attrDB->FieldMenu($cgi, $height, $name, $keys, %options); >>
795    
796  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
797  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
798  CGI package, but actually looks like a list. The list will contain  CGI package, but actually looks like a list. The list will contain
799  one selectable row per field, grouped by entity.  one selectable row per field.
800    
801  =over 4  =over 4
802    
# Line 556  Line 813 
813  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
814  appear when the form is submitted.  appear when the form is submitted.
815    
816  =item newFlag (optional)  =item keys
817    
818    Reference to a hash mapping each attribute key name to a list reference,
819    the list itself consisting of the attribute data type, its description,
820    and a list of its groups.
821    
822    =item options
823    
824    Hash containing options that modify the generation of the menu.
825    
826    =item RETURN
827    
828    Returns the HTML to create a form field that can be used to select an
829    attribute from the custom attributes system.
830    
831    =back
832    
833    The permissible options are as follows.
834    
835    =over 4
836    
837    =item new
838    
839  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
840  a new attribute. In other words, the user can select an existing  a new attribute. In other words, the user can select an existing
841  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
842  be created in the parent entity.  be created in the parent entity.
843    
844  =item noteControl (optional)  =item notes
845    
846  If specified, the name of a variable for displaying the notes attached  If specified, the name of a variable for displaying the notes attached
847  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 852 
852  it is copied in. Specifying this parameter generates Javascript for  it is copied in. Specifying this parameter generates Javascript for
853  displaying the field description when a field is selected.  displaying the field description when a field is selected.
854    
855  =item typeControl (optional)  =item type
856    
857  If specified, the name of a variable for displaying the field's  If specified, the name of a variable for displaying the field's
858  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 860 
860  raw value is put into the specified variable. Otherwise, the same  raw value is put into the specified variable. Otherwise, the same
861  rules apply to this value that apply to I<$noteControl>.  rules apply to this value that apply to I<$noteControl>.
862    
863  =item RETURN  =item groups
864    
865  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
866  attribute from the custom attributes system.  a popup menu) which shall be used to display the selected groups.
867    
868  =back  =back
869    
# Line 593  Line 871 
871    
872  sub FieldMenu {  sub FieldMenu {
873      # Get the parameters.      # Get the parameters.
874      my ($self, $cgi, $height, $name, $newFlag, $noteControl, $typeControl) = @_;      my ($self, $cgi, $height, $name, $keys, %options) = @_;
875      # These next two hashes make everything happen. "entities"      # Reformat the list of keys.
876      # maps each entity name to the list of values to be put into its      my %keys = %{$keys};
877      # option group. "labels" maps each entity name to a map from values      # Add the (new) key, if needed.
878      # to labels.      if ($options{new}) {
879      my @entityNames = sort ($self->GetEntityTypes());          $keys{NewName()} = ["string", ""];
880      my %entities = map { $_ => [] } @entityNames;      }
881      my %labels = map { $_ => { }} @entityNames;      # Get a sorted list of key.
882      # Loop through the entities, adding the existing attributes.      my @keys = sort keys %keys;
883      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  
884      # 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
885      # for the menu.      # for the menu.
886      my $changeName = "${name}_setNotes";      my $changeName = "${name}_setNotes";
887      my $retVal = $cgi->popup_menu({name => $name,      my $retVal = $cgi->popup_menu({name => $name,
888                                     size => $height,                                     size => $height,
889                                     onChange => "$changeName(this.value)",                                     onChange => "$changeName(this.value)",
890                                     values => [map { $cgi->optgroup(-name => $_,                                     values => \@keys,
891                                                                     -values => $entities{$_},                                    });
                                                                    -labels => $labels{$_})  
                                                   } @entityNames]}  
                                  );  
892      # Create the change function.      # Create the change function.
893      $retVal .= "\n<script language=\"javascript\">\n";      $retVal .= "\n<script language=\"javascript\">\n";
894      $retVal .= "    function $changeName(fieldValue) {\n";      $retVal .= "    function $changeName(fieldValue) {\n";
895      # 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
896      if ($noteControl || $typeControl) {      # attribute.
897        if ($options{notes} || $options{type} || $options{groups}) {
898          # 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.
899            my $noteControl = $options{notes};
900          my $htmlMode = ($noteControl && $noteControl =~ /innerHTML$/);          my $htmlMode = ($noteControl && $noteControl =~ /innerHTML$/);
901          # 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
902          # field description will be stored in the JavaScript variable "myText"          # field description will be stored in the JavaScript variable "myText"
# Line 652  Line 905 
905          $retVal .= "        var myText = \"\";\n";          $retVal .= "        var myText = \"\";\n";
906          $retVal .= "        var myType = \"string\";\n";          $retVal .= "        var myType = \"string\";\n";
907          $retVal .= "        switch (fieldValue) {\n";          $retVal .= "        switch (fieldValue) {\n";
908          # Loop through the entities.          # Loop through the keys.
909          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};  
910                      # Generate this case.                      # Generate this case.
911                      $retVal .= "        case \"$value\" :\n";              $retVal .= "        case \"$key\" :\n";
912                      # Here we either want to update the note display, the                      # Here we either want to update the note display, the
913                      # type display, or both.              # type display, the group list, or a combination of them.
914                my ($type, $notes, @groups) = @{$keys{$key}};
915                      if ($noteControl) {                      if ($noteControl) {
                         # Here we want the notes updated.  
                         my $notes = $element->{Notes}->{content};  
916                          # Insure it's in the proper form.                          # Insure it's in the proper form.
917                          if ($htmlMode) {                          if ($htmlMode) {
918                              $notes = ERDB::HTMLNote($notes);                              $notes = ERDB::HTMLNote($notes);
# Line 679  Line 922 
922                          $notes =~ s/"/\\"/g;                          $notes =~ s/"/\\"/g;
923                          $retVal .= "           myText = \"$notes\";\n";                          $retVal .= "           myText = \"$notes\";\n";
924                      }                      }
925                      if ($typeControl) {              if ($options{type}) {
926                          # Here we want the type updated.                          # Here we want the type updated.
                         my $type = $element->{type};  
927                          $retVal .= "           myType = \"$type\";\n";                          $retVal .= "           myType = \"$type\";\n";
928                      }                      }
929                if ($options{groups}) {
930                    # Here we want the groups shown. Get a list of this attribute's groups.
931                    # We'll search through this list for each group to see if it belongs with
932                    # our attribute.
933                    my $groupLiteral = "=" . join("=", @groups) . "=";
934                    # Now we need some variables containing useful code for the javascript. It's
935                    # worth knowing we go through a bit of pain to insure $groupField[i] isn't
936                    # parsed as an array element.
937                    my $groupField = $options{groups};
938                    my $currentField = $groupField . "[i]";
939                    # Do the javascript.
940                    $retVal .= "           var groupList = \"$groupLiteral\";\n";
941                    $retVal .= "           for (var i = 0; i < $groupField.length; i++) {\n";
942                    $retVal .= "              var srchString = \"=\" + $currentField.value + \"=\";\n";
943                    $retVal .= "              var srchLoc = groupList.indexOf(srchString);\n";
944                    $retVal .= "              $currentField.checked = (srchLoc >= 0);\n";
945                    $retVal .= "           }\n";
946                }
947                      # Close this case.                      # Close this case.
948                      $retVal .= "           break;\n";                      $retVal .= "           break;\n";
949                  }                  }
             }  
         }  
950          # Close the CASE statement and make the appropriate assignments.          # Close the CASE statement and make the appropriate assignments.
951          $retVal .= "        }\n";          $retVal .= "        }\n";
952          if ($noteControl) {          if ($noteControl) {
953              $retVal .= "        $noteControl = myText;\n";              $retVal .= "        $noteControl = myText;\n";
954          }          }
955          if ($typeControl) {          if ($options{type}) {
956              $retVal .= "        $typeControl = myType;\n";              $retVal .= "        $options{type} = myType;\n";
957          }          }
958      }      }
959      # Terminate the change function.      # Terminate the change function.
# Line 705  Line 963 
963      return $retVal;      return $retVal;
964  }  }
965    
966  =head3 MatchSqlPattern  =head3 GetGroups
967    
968  C<< my $matched = CustomAttributes::MatchSqlPattern($value, $pattern); >>  C<< my @groups = $attrDB->GetGroups(); >>
969    
970  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.  
971    
972  =over 4  =cut
973    
974  =item value  sub GetGroups {
975        # Get the parameters.
976        my ($self) = @_;
977        # Get the groups.
978        my @retVal = $self->GetFlat(['AttributeGroup'], "", [], 'AttributeGroup(id)');
979        # Return them.
980        return @retVal;
981    }
982    
983  Value to be matched against the pattern. Note that an undefined or empty  =head3 GetAttributeData
 value will not match anything.  
984    
985  =item pattern  C<< my %keys = $attrDB->GetAttributeData($type, @list); >>
986    
987  SQL pattern against which to match the value. An undefined or empty pattern will  Return attribute data for the selected attributes. The attribute
988  match everything.  data is a hash mapping each attribute key name to a n-tuple containing the
989    data type, the description, and the groups. This is the same format expected in
990    the L</FieldMenu> and L</ControlForm> methods for the list of attributes to display.
991    
992  =item RETURN  =over 4
993    
994  Returns TRUE if the value and pattern match, else FALSE.  =item type
995    
996  =back  Type of attribute criterion: C<name> for attributes whose names begin with the
997    specified string, or C<group> for attributes in the specified group.
998    
999    =item list
1000    
1001    List containing the names of the groups or keys for the desired attributes.
1002    
1003    =item RETURN
1004    
1005    Returns a hash mapping each attribute key name to its data type, description, and
1006    parent groups.
1007    
1008    =back
1009    
1010  =cut  =cut
1011    
1012  sub MatchSqlPattern {  sub GetAttributeData {
1013      # Get the parameters.      # Get the parameters.
1014      my ($value, $pattern) = @_;      my ($self, $type, @list) = @_;
1015      # Declare the return variable.      # Set up a hash to store the attribute data.
1016      my $retVal;      my %retVal = ();
1017      # Insure we have a pattern.      # Loop through the list items.
1018      if (! defined($pattern) || $pattern eq "") {      for my $item (@list) {
1019          $retVal = 1;          # Set up a query for the desired attributes.
1020      } else {          my $query;
1021          # Break the pattern into pieces around the wildcard characters. Because we          if ($type eq 'name') {
1022          # 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
1023          # list elements for the delimiters as well as the rest of the string.              # on a %.
1024          my @pieces = split /([_%]|\\[_%])/, $pattern;              my $parm = $item;
1025          # Check some fast special cases.              $parm =~ s/_/\\_/g;
1026          if ($pattern eq '%') {              $parm =~ s/%/\\%/g;
1027              # A null pattern matches everything.              $parm .= "%";
1028              $retVal = 1;              # Ask for matching attributes. (Note that if the user passed in a null string
1029          } elsif (@pieces == 1) {              # he'll get everything.)
1030              # No wildcards, so we have a literal comparison. Note we're case-insensitive.              $query = $self->Get(['AttributeKey'], "AttributeKey(id) LIKE ?", [$parm]);
1031              $retVal = (lc($value) eq lc($pattern));          } elsif ($type eq 'group') {
1032          } 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);  
1033                  } else {                  } else {
1034                      # Here we have raw text.              Confess("Unknown attribute query type \"$type\".");
                     $realPattern .= quotemeta($piece);  
1035                  }                  }
1036            while (my $row = $query->Fetch()) {
1037                # Get this attribute's data.
1038                my ($key, $type, $notes) = $row->Values(['AttributeKey(id)', 'AttributeKey(data-type)',
1039                                                         'AttributeKey(description)']);
1040                # If it's new, get its groups and add it to the return hash.
1041                if (! exists $retVal{$key}) {
1042                    my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(from-link) = ?",
1043                                                [$key], 'IsInGroup(to-link)');
1044                    $retVal{$key} = [$type, $notes, @groups];
1045              }              }
             # Do the match.  
             $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);  
1046          }          }
1047      }      }
1048      # Return the result.      # Return the result.
1049      return $retVal;      return %retVal;
1050  }  }
1051    
1052  =head3 MigrateAttributes  =head3 LogOperation
1053    
1054  C<< CustomAttributes::MigrateAttributes($fig); >>  C<< $ca->LogOperation($action, $target, $description); >>
1055    
1056  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.  
1057    
1058  =over 4  =over 4
1059    
1060  =item fig  =item action
1061    
1062    Action being logged (e.g. C<Delete Group> or C<Load Key>).
1063    
1064    =item target
1065    
1066    ID of the key or group affected.
1067    
1068    =item description
1069    
1070  A FIG object that can be used to retrieve attributes for migration purposes.  Short description of the action.
1071    
1072  =back  =back
1073    
1074  =cut  =cut
1075    
1076  sub MigrateAttributes {  sub LogOperation {
1077      # Get the parameters.      # Get the parameters.
1078      my ($fig) = @_;      my ($self, $action, $target, $description) = @_;
1079      # Get a list of the objects to migrate. This requires connecting. Note we      # Get the user ID.
1080      # will map each entity type to a file name. The file will contain a list      my $user = $self->{user};
1081      # of the object's IDs so we can get to them when we're not connected to      # Get a timestamp.
1082      # the database.      my $timeString = Tracer::Now();
1083      my $ca = CustomAttributes->new();      # Open the log file for appending.
1084      my %objects = map { $_ => "$FIG_Config::temp/$_.keys.tbl" } $ca->GetEntityTypes();      my $oh = Open(undef, ">>$FIG_Config::var/attributes.log");
1085      # Set up hash of the existing attribute keys for each entity type.      # Write the data to it.
1086      my %oldKeys = ();      Tracer::PutLine($oh, [$timeString, $user, $action, $target, $description]);
1087      # Finally, we have a hash that counts the IDs for each entity type.      # Close the log file.
1088      my %idCounts = map { $_ => 0 } keys %objects;      close $oh;
1089      # Loop through the list, creating key files to read back in.  }
1090      for my $entityType (keys %objects) {  
1091          Trace("Retrieving keys for $entityType.") if T(2);  =head2 Internal Utility Methods
1092          # Create the key file.  
1093          my $idFile = Open(undef, ">$objects{$entityType}");  =head3 _KeywordString
1094          # Loop through the keys.  
1095          my @ids = $ca->GetFlat([$entityType], "", [], "$entityType(id)");  C<< my $keywordString = $ca->_KeywordString($key, $value); >>
1096          for my $id (@ids) {  
1097              print $idFile "$id\n";  Compute the keyword string for a specified key/value pair. This consists of the
1098          }  key name and value converted to lower case with underscores translated to spaces.
1099          close $idFile;  
1100          # 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
1101          # in the database. This avoids a circularity problem that might occur if the $fig  insert a B<HasValueFor> record.
1102          # object is retrieving from the custom attributes database already.  
1103          my %fields = $ca->GetSecondaryFields($entityType);  =over 4
1104          $oldKeys{$entityType} = \%fields;  
1105          # Finally, we have the ID count.  =item key
1106          $idCounts{$entityType} = scalar @ids;  
1107      }  Name of the relevant attribute key.
1108      # Release the custom attributes database so we can add attributes.  
1109      undef $ca;  =item target
1110      # Loop through the objects.  
1111      for my $entityType (keys %objects) {  ID of the target object to which this key/value pair will be associated.
1112          # Get a hash of all the attributes already in this database. These are  
1113          # left untouched.  =item value
1114          my $myOldKeys = $oldKeys{$entityType};  
1115          # Create a hash to control the load file names for each attribute key we find.  The value to store for this key/object combination.
1116          my %keyHash = ();  
1117          # Set up some counters so we can trace our progress.  =item RETURN
1118          my ($totalIDs, $processedIDs, $keyCount, $valueCount) = ($idCounts{$entityType}, 0, 0, 0);  
1119          # Open this object's ID file.  Returns the value that should be stored as the keyword string for the specified
1120          Trace("Migrating data for $entityType. $totalIDs found.") if T(3);  key/value pair.
1121          my $keysIn = Open(undef, "<$objects{$entityType}");  
1122          while (my $id = <$keysIn>) {  =back
1123              # Remove the EOL characters.  
1124              chomp $id;  =cut
1125              # Get this object's attributes.  
1126              my @allData = $fig->get_attributes($id);  sub _KeywordString {
1127              Trace(scalar(@allData) . " attribute values found for $entityType($id).") if T(4);      # Get the parameters.
1128              # Loop through the attribute values one at a time.      my ($self, $key, $value) = @_;
1129              for my $dataTuple (@allData) {      # Get a copy of the key name and convert underscores to spaces.
1130                  # Get the key, value, and URL. We ignore the first element because that's the      my $keywordString = $key;
1131                  # object ID, and we already know the object ID.      $keywordString =~ s/_/ /g;
1132                  my (undef, $key, $value, $url) = @{$dataTuple};      # Add the value convert it all to lower case.
1133                  # Remove the buggy "1" for $url.      my $retVal = lc "$keywordString $value";
1134                  if ($url eq "1") {      # Return the result.
1135                      $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);  
1136  }  }
1137    
1138  =head3 ComputeObjectTypeFromID  =head3 _QueryResults
1139    
1140  C<< my ($entityName, $id) = CustomAttributes::ComputeObjectTypeFromID($objectID); >>  C<< my @attributeList = $attrDB->_QueryResults($query, @values); >>
1141    
1142  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
1143  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
1144  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
1145  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.  
1146    
1147  =over 4  =over 4
1148    
1149  =item objectID  =item query
1150    
1151    A query object that will return the desired B<HasValueFor> records.
1152    
1153  Object ID to examine.  =item values
1154    
1155    List of the desired attribute values, section by section. If C<undef>
1156    or an empty string is specified, all values in that section will match. A
1157    generic match can be requested by placing a percent sign (C<%>) at the end.
1158    In that case, all values that match up to and not including the percent sign
1159    will match. You may also specify a regular expression enclosed
1160    in slashes. All values that match the regular expression will be returned. For
1161    performance reasons, only values have this extra capability.
1162    
1163  =item RETURN  =item RETURN
1164    
1165  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
1166    second is an attribute key, and the remaining elements are the sections of
1167    the attribute value. All of the tuples will match the criteria set forth in
1168    the parameter list.
1169    
1170  =back  =back
1171    
1172  =cut  =cut
1173    
1174  sub ComputeObjectTypeFromID {  sub _QueryResults {
1175      # Get the parameters.      # Get the parameters.
1176      my ($objectID) = @_;      my ($self, $query, @values) = @_;
1177      # Declare the return variables.      # Declare the return value.
1178      my ($entityName, $id);      my @retVal = ();
1179      # 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.
1180      # pair of undefs.      my $sectionCount = scalar(@values);
1181      if ($objectID) {      # Loop through the assignments found.
1182          if (ref $objectID eq 'ARRAY') {      while (my $row = $query->Fetch()) {
1183              # Here we have the new-style list reference. Pull out its pieces.          # Get the current row's data.
1184              ($entityName, $id) = @{$objectID};          my ($id, $realKey, $subKey, $valueString) = $row->Values(['HasValueFor(to-link)',
1185          } else {                                                                    'HasValueFor(from-link)',
1186              # Here the ID is the outgoing ID, and we need to look at its structure                                                                    'HasValueFor(subkey)',
1187              # to determine the entity type.                                                                    'HasValueFor(value)'
1188              $id = $objectID;                                                                  ]);
1189              if ($objectID =~ /^\d+\.\d+/) {          # Form the key from the real key and the sub key.
1190                  # Digits with a single period is a genome.          my $key = $self->JoinKey($realKey, $subKey);
1191                  $entityName = 'Genome';          # Break the value into sections.
1192              } elsif ($objectID =~ /^fig\|/) {          my @sections = split($self->{splitter}, $valueString);
1193                  # The "fig|" prefix indicates a feature.          # Match each section against the incoming values. We'll assume we're
1194                  $entityName = 'Feature';          # okay unless we learn otherwise.
1195            my $matching = 1;
1196            for (my $i = 0; $i < $sectionCount && $matching; $i++) {
1197                # We need to check to see if this section is generic.
1198                my $value = $values[$i];
1199                Trace("Current value pattern is \"$value\".") if T(4);
1200                if (substr($value, -1, 1) eq '%') {
1201                    Trace("Generic match used.") if T(4);
1202                    # Here we have a generic match.
1203                    my $matchLen = length($values[$i]) - 1;
1204                    $matching = substr($sections[$i], 0, $matchLen) eq
1205                                substr($values[$i], 0, $matchLen);
1206                } elsif ($value =~ m#^/(.+)/[a-z]*$#) {
1207                    Trace("Regular expression detected.") if T(4);
1208                    # Here we have a regular expression match.
1209                    my $section = $sections[$i];
1210                    $matching = eval("\$section =~ $value");
1211              } else {              } else {
1212                  # Anything else is illegal!                  # Here we have a strict match.
1213                  Confess("Invalid attribute ID specification \"$objectID\".");                  Trace("Strict match used.") if T(4);
1214                    $matching = ($sections[$i] eq $values[$i]);
1215              }              }
1216          }          }
1217            # If we match, output this row to the return list.
1218            if ($matching) {
1219                push @retVal, [$id, $key, @sections];
1220      }      }
1221      # Return the result.      }
1222      return ($entityName, $id);      # Return the rows found.
1223        return @retVal;
1224  }  }
1225    
1226  =head2 FIG Method Replacements  =head2 FIG Method Replacements
1227    
1228  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.
1229  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
1230  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
1231  capabilities were used in the old system.  capabilities were used in the old system.
1232    
# Line 993  Line 1234 
1234  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
1235  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.
1236    
1237  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,
1238  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
1239  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
1240  value of the splitter parameter on the constructor (L</new>). The default is double  is double colons C<::>.
 colons C<::>.  
1241    
1242  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
1243  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
1244  splitter value would be stored as  splitter value would be stored as
1245    
# Line 1010  Line 1250 
1250    
1251  =head3 GetAttributes  =head3 GetAttributes
1252    
1253  C<< my @attributeList = $attrDB->GetAttributes($objectID, $key, @valuePatterns); >>  C<< my @attributeList = $attrDB->GetAttributes($objectID, $key, @values); >>
1254    
1255  In the database, attribute values are sectioned into pieces using a splitter  In the database, attribute values are sectioned into pieces using a splitter
1256  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
1257  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
1258  these methods. If you are using the static method calls instead of the  these methods. If a value has multiple sections, each section
1259  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.  
1260    
1261  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
1262  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
1263  method therefore correspond structurally to the values expected in each tuple.  method therefore correspond structurally to the values expected in each tuple. In
1264    addition, you can ask for a generic search by suffixing a percent sign (C<%>) to any
1265    of the parameters. So, for example,
1266    
1267      my @attributeList = GetAttributes('fig|100226.1.peg.1004', 'structure%', 1, 2);      my @attributeList = $attrDB->GetAttributes('fig|100226.1.peg.1004', 'structure%', 1, 2);
1268    
1269  would return something like  would return something like
1270    
# Line 1033  Line 1273 
1273      ['fig}100226.1.peg.1004', 'structure2', 1, 2]      ['fig}100226.1.peg.1004', 'structure2', 1, 2]
1274      ['fig}100226.1.peg.1004', 'structureA', 1, 2]      ['fig}100226.1.peg.1004', 'structureA', 1, 2]
1275    
1276  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
1277  the I<$key> and I<@valuePatterns> parameters can contain SQL pattern characters: C<%>, which  a list reference in the ID column. Thus,
1278  matches any sequence of characters, and C<_>, which matches any single character.  
1279  (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');
1280  underscore.)  
1281    would get the PUBMED attribute data for Streptomyces coelicolor A3(2) and all its
1282    features.
1283    
1284  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
1285  values, so even  values, so even
1286    
1287      my @attributeList = GetAttributes($peg, 'virulent');      my @attributeList = $attrDB->GetAttributes($peg, 'virulent');
1288    
1289  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.
1290    
1291  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
1292  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
1293  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
1294  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
1295  be written as  are stored in a single string. As a result, queries in which filter only on value end up
1296    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.  
1297    
1298  =over 4  =over 4
1299    
1300  =item objectID  =item objectID
1301    
1302  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
1303  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
1304  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
1305  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.  
1306    
1307  =item key  =item key
1308    
1309  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
1310  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
1311  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
1312  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.  
1313    
1314  =item valuePatterns  =item values
1315    
1316  List of the desired attribute values, section by section. If C<undef>  List of the desired attribute values, section by section. If C<undef>
1317  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
1318    generic match can be requested by placing a percent sign (C<%>) at the end.
1319    In that case, all values that match up to and not including the percent sign
1320    will match. You may also specify a regular expression enclosed
1321    in slashes. All values that match the regular expression will be returned. For
1322    performance reasons, only values have this extra capability.
1323    
1324  =item RETURN  =item RETURN
1325    
# Line 1107  Line 1334 
1334    
1335  sub GetAttributes {  sub GetAttributes {
1336      # Get the parameters.      # Get the parameters.
1337      my ($self, $objectID, $key, @valuePatterns) = @_;      my ($self, $objectID, $key, @values) = @_;
1338      # Declare the return variable.      # This hash will map "HasValueFor" fields to patterns. We use it to build the
1339      my @retVal = ();      # SQL statement.
1340      # Determine the entity types for our search.      my %data;
1341      my @objects = ();      # Before we do anything else, we must parse the key. The key is treated by the
1342      my ($actualObjectID, $computedType);      # user as a single field, but to us it's actually a real key and a subkey.
1343      if (! $objectID) {      # If the key has no splitter and is exact, the real key is the original key
1344          push @objects, $self->GetEntityTypes();      # and the subkey is an empty string. If the key has a splitter, it is
1345      } else {      # split into two pieces and each piece is processed separately. If the key has
1346          ($computedType, $actualObjectID) = ComputeObjectTypeFromID($objectID);      # no splitter and is generic, the real key is the incoming key and the subkey
1347          push @objects, $computedType;      # is allowed to be wild. Of course, this only matters if an actual key has
1348      }      # been specified.
1349      # Loop through the entity types.      if (defined $key) {
1350      for my $entityType (@objects) {          if ($key =~ /$self->{splitter}/) {
1351          # 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.
1352          # our database object, so this process is fast. Note that our              my ($realKey, $subKey) = $self->SplitKey($key);
1353          # MatchSqlPattern method              $data{'HasValueFor(from-link)'} = $realKey;
1354          my %secondaries = $self->GetSecondaryFields($entityType);              $data{'HasValueFor(subkey)'} = $subKey;
1355          my @fieldList = grep { MatchSqlPattern($_, $key) } keys %secondaries;          } elsif (substr($key, -1, 1) eq '%') {
1356          # Now we figure out whether or not we need to filter by object. We will always              $data{'HasValueFor(from-link)'} = $key;
1357          # filter by key to a limited extent, so if we're filtering by object we need an          } else {
1358          # AND to join the object ID filter with the key filter.              $data{'HasValueFor(from-link)'} = $key;
1359          my $filter = "";              $data{'HasValueFor(subkey)'} = '';
1360          my @params = ();          }
1361          if (defined($actualObjectID)) {      }
1362              # Here the caller wants to filter on object ID. Check for a pattern.      # Add the object ID to the key information.
1363              my $comparator = ($actualObjectID =~ /%/ ? "LIKE" : "=");      $data{'HasValueFor(to-link)'} = $objectID;
1364              # Update the filter and the parameter list.      # The first value represents a problem, because we can search it using SQL, but not
1365              $filter = "$entityType(id) $comparator ? AND ";      # in the normal way. If the user specifies a generic search or exact match for
1366              push @params, $actualObjectID;      # every alternative value (remember, the values may be specified as a list),
1367          }      # then we can create SQL filtering for it. If any of the values are specified
1368          # 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
1369          # each attribute is actually a different field in the database. We know here that      # every value to verify a match.
1370          # all the keys we've collected are for the correct entity because we got them from      if (@values > 0) {
1371          # 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.
1372          for my $key (@fieldList) {          my $valueParm = $values[0];
1373              # Get all of the attribute values for this key.          my @valueList;
1374              my @dataRows = $self->GetAll([$entityType], "$filter$entityType($key) IS NOT NULL",          if (ref $valueParm eq 'ARRAY') {
1375                                           \@params, ["$entityType(id)", "$entityType($key)"]);              @valueList = @{$valueParm};
1376              # Process each value separately. We need to verify the values and reformat the          } else {
1377              # tuples. Note that GetAll will give us one row per matching object ID,              @valueList = ($valueParm);
1378              # with the ID first followed by a list of the data values. This is very          }
1379              # 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
1380              # per value.          # @valueList. We'll copy the values to a new array in which they have been
1381              for my $dataRow (@dataRows) {          # converted to generic requests. If we find a regular-expression match
1382                  # Get the object ID and the list of values.          # anywhere in the list, we toss the whole thing.
1383                  my ($rowObjectID, @dataValues) = @{$dataRow};          my @valuePatterns = ();
1384                  # Loop through the values. There will be one result row per attribute value.          my $okValues = 1;
1385                  for my $dataValue (@dataValues) {          for my $valuePattern (@valueList) {
1386                      # Separate this value into sections.              # Check the pattern type.
1387                      my @sections = split("::", $dataValue);              if (substr($valuePattern, 0, 1) eq '/') {
1388                      # Loop through the value patterns, looking for a mismatch. Note that                  # Regular expressions invalidate the entire process.
1389                      # since we're working through parallel arrays, we are using an index                  $okValues = 0;
1390                      # loop. As soon as a match fails we stop checking. This means that              } elsif (substr($valuePattern, -1, 1) eq '%') {
1391                      # if the value pattern list is longer than the number of sections,                  # A Generic pattern is passed in unmodified.
1392                      # we will fail as soon as we run out of sections.                  push @valuePatterns, $valuePattern;
1393                      my $match = 1;              } else {
1394                      for (my $i = 0; $i <= $#valuePatterns && $match; $i++) {                  # An exact match is converted to generic.
1395                          $match = MatchSqlPattern($sections[$i], $valuePatterns[$i]);                  push @valuePatterns, "$valuePattern%";
1396                      }              }
1397                      # If we match, we save this value in the output list.          }
1398                      if ($match) {          # If everything works, add the value data to the filtering hash.
1399                          push @retVal, [$rowObjectID, $key, @sections];          if ($okValues) {
1400                      }              $data{'HasValueFor(value)'} = \@valuePatterns;
1401                  }          }
1402                  # Here we've processed all the attribute values for the current object ID.      }
1403        # Create some lists to contain the filter fragments and parameter values.
1404        my @filter = ();
1405        my @parms = ();
1406        # This next loop goes through the different fields that can be specified in the
1407        # parameter list and generates filters for each. The %data hash that we built above
1408        # contains all the necessary information to do this.
1409        for my $field (keys %data) {
1410            # Accumulate filter information for this field. We will OR together all the
1411            # elements accumulated to create the final result.
1412            my @fieldFilter = ();
1413            # Get the specified data from the caller.
1414            my $fieldPattern = $data{$field};
1415            # Only proceed if the pattern is one that won't match everything.
1416            if (defined($fieldPattern) && $fieldPattern ne "" && $fieldPattern ne "%") {
1417                # Convert the pattern to an array.
1418                my @patterns = ();
1419                if (ref $fieldPattern eq 'ARRAY') {
1420                    push @patterns, @{$fieldPattern};
1421                } else {
1422                    push @patterns, $fieldPattern;
1423                }
1424                # Only proceed if the array is nonempty. The loop will work fine if the
1425                # array is empty, but when we build the filter string at the end we'll
1426                # get "()" in the filter list, which will result in an SQL syntax error.
1427                if (@patterns) {
1428                    # Loop through the individual patterns.
1429                    for my $pattern (@patterns) {
1430                        # Check for a generic request.
1431                        if (substr($pattern, -1, 1) ne '%') {
1432                            # Here we have a normal request.
1433                            push @fieldFilter, "$field = ?";
1434                            push @parms, $pattern;
1435                        } else {
1436                            # Here we have a generic request, so we will use the LIKE operator to
1437                            # filter the field to this value pattern.
1438                            push @fieldFilter, "$field LIKE ?";
1439                            # We must convert the pattern value to an SQL match pattern. First
1440                            # we get a copy of it.
1441                            my $actualPattern = $pattern;
1442                            # Now we escape the underscores. Underscores are an SQL wild card
1443                            # character, but they are used frequently in key names and object IDs.
1444                            $actualPattern =~ s/_/\\_/g;
1445                            # Add the escaped pattern to the bound parameter list.
1446                            push @parms, $actualPattern;
1447                        }
1448                    }
1449                    # Form the filter for this field.
1450                    my $fieldFilterString = join(" OR ", @fieldFilter);
1451                    push @filter, "($fieldFilterString)";
1452              }              }
             # Here we've processed all the rows returned by GetAll. In general, there will  
             # be one row per object ID.  
1453          }          }
         # Here we've processed all the matching attribute keys.  
1454      }      }
1455      # 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
1456      # results.      # values to bind to them.
1457        my $actualFilter = join(" AND ", @filter);
1458        # Now we're ready to make our query.
1459        my $query = $self->Get(['HasValueFor'], $actualFilter, \@parms);
1460        # Format the results.
1461        my @retVal = $self->_QueryResults($query, @values);
1462        # Return the rows found.
1463      return @retVal;      return @retVal;
1464  }  }
1465    
# Line 1195  Line 1474 
1474    
1475  =item objectID  =item objectID
1476    
1477  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.  
1478    
1479  =item key  =item key
1480    
1481  Attribute key name. This corresponds to the name of a field in the database.  Attribute key name.
1482    
1483  =item values  =item values
1484    
# Line 1225  Line 1501 
1501      } elsif (! @values) {      } elsif (! @values) {
1502          Confess("No values specified in AddAttribute call for key $key.");          Confess("No values specified in AddAttribute call for key $key.");
1503      } else {      } else {
1504          # 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
1505          # computing the object type and ID.          # into a scalar.
         my ($entityName, $id) = ComputeObjectTypeFromID($objectID);  
         # Form the values into a scalar.  
1506          my $valueString = join($self->{splitter}, @values);          my $valueString = join($self->{splitter}, @values);
1507          # Insert the value.          # Split up the key.
1508          $self->InsertValue($id, "$entityName($key)", $valueString);          my ($realKey, $subKey) = $self->SplitKey($key);
1509            # Connect the object to the key.
1510            $self->InsertObject('HasValueFor', { 'from-link' => $realKey,
1511                                                 'to-link'   => $objectID,
1512                                                 'subkey'    => $subKey,
1513                                                 'value'     => $valueString,
1514                                           });
1515      }      }
1516      # Return a one. We do this for backward compatability.      # Return a one, indicating success. We do this for backward compatability.
1517      return 1;      return 1;
1518  }  }
1519    
# Line 1243  Line 1523 
1523    
1524  Delete the specified attribute key/value combination from the database.  Delete the specified attribute key/value combination from the database.
1525    
 The first form will connect to the database and release it. The second form  
 uses the database connection contained in the object.  
   
1526  =over 4  =over 4
1527    
1528  =item objectID  =item objectID
1529    
1530  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.  
1531    
1532  =item key  =item key
1533    
1534  Attribute key name. This corresponds to the name of a field in the database.  Attribute key name.
1535    
1536  =item values  =item values
1537    
1538  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
1539    will be deleted. Otherwise, only a matching value will be deleted.
1540    
1541  =back  =back
1542    
# Line 1275  Line 1550 
1550          Confess("No object ID specified for DeleteAttribute call.");          Confess("No object ID specified for DeleteAttribute call.");
1551      } elsif (! defined($key)) {      } elsif (! defined($key)) {
1552          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.");  
1553      } else {      } else {
1554          # Now compute the object type and ID.          # Split the key into the real key and the subkey.
1555          my ($entityName, $id) = ComputeObjectTypeFromID($objectID);          my ($realKey, $subKey) = $self->SplitKey($key);
1556          # Form the values into a scalar.          if ($subKey eq '' && scalar(@values) == 0) {
1557                # Here we erase the entire key for this object.
1558                $self->DeleteRow('HasValueFor', $key, $objectID);
1559            } else {
1560                # Here we erase the matching values.
1561          my $valueString = join($self->{splitter}, @values);          my $valueString = join($self->{splitter}, @values);
1562          # Delete the value.              $self->DeleteRow('HasValueFor', $realKey, $objectID,
1563          $self->DeleteValue($entityName, $id, $key, $valueString);                               { subkey => $subKey, value => $valueString });
1564            }
1565      }      }
1566      # Return a one. This is for backward compatability.      # Return a one. This is for backward compatability.
1567      return 1;      return 1;
1568  }  }
1569    
1570    =head3 DeleteMatchingAttributes
1571    
1572    C<< my @deleted = $attrDB->DeleteMatchingAttributes($objectID, $key, @values); >>
1573    
1574    Delete all attributes that match the specified criteria. This is equivalent to
1575    calling L</GetAttributes> and then invoking L</DeleteAttribute> for each
1576    row found.
1577    
1578    =over 4
1579    
1580    =item objectID
1581    
1582    ID of object whose attributes are to be deleted. If the attributes for multiple
1583    objects are to be deleted, this parameter can be specified as a list reference. If
1584    attributes are to be deleted for all objects, specify C<undef> or an empty string.
1585    Finally, you can delete attributes for a range of object IDs by putting a percent
1586    sign (C<%>) at the end.
1587    
1588    =item key
1589    
1590    Attribute key name. A value of C<undef> or an empty string will match all
1591    attribute keys. If the values are to be deletedfor multiple keys, this parameter can be
1592    specified as a list reference. Finally, you can delete attributes for a range of
1593    keys by putting a percent sign (C<%>) at the end.
1594    
1595    =item values
1596    
1597    List of the desired attribute values, section by section. If C<undef>
1598    or an empty string is specified, all values in that section will match. A
1599    generic match can be requested by placing a percent sign (C<%>) at the end.
1600    In that case, all values that match up to and not including the percent sign
1601    will match. You may also specify a regular expression enclosed
1602    in slashes. All values that match the regular expression will be deleted. For
1603    performance reasons, only values have this extra capability.
1604    
1605    =item RETURN
1606    
1607    Returns a list of tuples for the attributes that were deleted, in the
1608    same form as L</GetAttributes>.
1609    
1610    =back
1611    
1612    =cut
1613    
1614    sub DeleteMatchingAttributes {
1615        # Get the parameters.
1616        my ($self, $objectID, $key, @values) = @_;
1617        # Get the matching attributes.
1618        my @retVal = $self->GetAttributes($objectID, $key, @values);
1619        # Loop through the attributes, deleting them.
1620        for my $tuple (@retVal) {
1621            $self->DeleteAttribute(@{$tuple});
1622        }
1623        # Log this operation.
1624        my $count = @retVal;
1625        $self->LogOperation("Mass Delete", $key, "$count matching attributes deleted.");
1626        # Return the deleted attributes.
1627        return @retVal;
1628    }
1629    
1630  =head3 ChangeAttribute  =head3 ChangeAttribute
1631    
1632  C<< $attrDB->ChangeAttribute($objectID, $key, \@oldValues, \@newValues); >>  C<< $attrDB->ChangeAttribute($objectID, $key, \@oldValues, \@newValues); >>
# Line 1333  Line 1671 
1671      } elsif (! defined($newValues) || ref $newValues ne 'ARRAY') {      } elsif (! defined($newValues) || ref $newValues ne 'ARRAY') {
1672          Confess("No new values specified in ChangeAttribute call for key $key.");          Confess("No new values specified in ChangeAttribute call for key $key.");
1673      } else {      } else {
1674          # Okay, now we do the change as a delete/add.          # We do the change as a delete/add.
1675          $self->DeleteAttribute($objectID, $key, @{$oldValues});          $self->DeleteAttribute($objectID, $key, @{$oldValues});
1676          $self->AddAttribute($objectID, $key, @{$newValues});          $self->AddAttribute($objectID, $key, @{$newValues});
1677      }      }
# Line 1343  Line 1681 
1681    
1682  =head3 EraseAttribute  =head3 EraseAttribute
1683    
1684  C<< $attrDB->EraseAttribute($entityName, $key); >>  C<< $attrDB->EraseAttribute($key); >>
1685    
1686  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
1687  key from the database; it merely removes all the values.  key from the database; it merely removes all the values.
1688    
1689  =over 4  =over 4
1690    
 =item entityName  
   
 Name of the entity to which the key belongs. If undefined, all entities will be  
 examined for the desired key.  
   
1691  =item key  =item key
1692    
1693  Key to erase.  Key to erase. This must be a real key; that is, it cannot have a subkey
1694    component.
1695    
1696  =back  =back
1697    
# Line 1365  Line 1699 
1699    
1700  sub EraseAttribute {  sub EraseAttribute {
1701      # Get the parameters.      # Get the parameters.
1702      my ($self, $entityName, $key) = @_;      my ($self, $key) = @_;
1703      # Determine the relevant entity types.      # Delete everything connected to the key.
1704      my @objects = ();      $self->Disconnect('HasValueFor', 'AttributeKey', $key);
1705      if (! $entityName) {      # Log the operation.
1706          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);  
         }  
     }  
1707      # Return a 1, for backward compatability.      # Return a 1, for backward compatability.
1708      return 1;      return 1;
1709  }  }
1710    
1711  =head3 GetAttributeKeys  =head3 GetAttributeKeys
1712    
1713  C<< my @keyList = $attrDB->GetAttributeKeys($entityName); >>  C<< my @keyList = $attrDB->GetAttributeKeys($groupName); >>
1714    
1715  Return a list of the attribute keys for a particular entity type.  Return a list of the attribute keys for a particular group.
1716    
1717  =over 4  =over 4
1718    
1719  =item entityName  =item groupName
1720    
1721  Name of the entity whose keys are desired.  Name of the group whose keys are desired.
1722    
1723  =item RETURN  =item RETURN
1724    
1725  Returns a list of the attribute keys for the specified entity.  Returns a list of the attribute keys for the specified group.
1726    
1727  =back  =back
1728    
# Line 1408  Line 1730 
1730    
1731  sub GetAttributeKeys {  sub GetAttributeKeys {
1732      # Get the parameters.      # Get the parameters.
1733      my ($self, $entityName) = @_;      my ($self, $groupName) = @_;
1734      # Get the entity's secondary fields.      # Get the attributes for the specified group.
1735      my %keyList = $self->GetSecondaryFields($entityName);      my @groups = $self->GetFlat(['IsInGroup'], "IsInGroup(to-link) = ?", [$groupName],
1736                                    'IsInGroup(from-link)');
1737      # Return the keys.      # Return the keys.
1738      return sort keys %keyList;      return sort @groups;
1739    }
1740    
1741    =head3 QueryAttributes
1742    
1743    C<< my @attributeData = $ca->QueryAttributes($filter, $filterParms); >>
1744    
1745    Return the attribute data based on an SQL filter clause. In the filter clause,
1746    the name C<$object> should be used for the object ID, C<$key> should be used for
1747    the key name, C<$subkey> for the subkey value, and C<$value> for the value field.
1748    
1749    =over 4
1750    
1751    =item filter
1752    
1753    Filter clause in the standard ERDB format, except that the field names are C<$object> for
1754    the object ID field, C<$key> for the key name field, C<$subkey> for the subkey field,
1755    and C<$value> for the value field. This abstraction enables us to hide the details of
1756    the database construction from the user.
1757    
1758    =item filterParms
1759    
1760    Parameters for the filter clause.
1761    
1762    =item RETURN
1763    
1764    Returns a list of tuples. Each tuple consists of an object ID, a key (with optional subkey), and
1765    one or more attribute values.
1766    
1767    =back
1768    
1769    =cut
1770    
1771    # This hash is used to drive the substitution process.
1772    my %AttributeParms = (object => 'HasValueFor(to-link)',
1773                          key    => 'HasValueFor(from-link)',
1774                          subkey => 'HasValueFor(subkey)',
1775                          value  => 'HasValueFor(value)');
1776    
1777    sub QueryAttributes {
1778        # Get the parameters.
1779        my ($self, $filter, $filterParms) = @_;
1780        # Declare the return variable.
1781        my @retVal = ();
1782        # Make sue we have filter parameters.
1783        my $realParms = (defined($filterParms) ? $filterParms : []);
1784        # Create the query by converting the filter.
1785        my $realFilter = $filter;
1786        for my $name (keys %AttributeParms) {
1787            $realFilter =~ s/\$$name/$AttributeParms{$name}/g;
1788        }
1789        my $query = $self->Get(['HasValueFor'], $realFilter, $realParms);
1790        # Loop through the results, forming the output attribute tuples.
1791        while (my $result = $query->Fetch()) {
1792            # Get the four values from this query result row.
1793            my ($objectID, $key, $subkey, $value) = $result->Values([$AttributeParms{object},
1794                                                                    $AttributeParms{key},
1795                                                                    $AttributeParms{subkey},
1796                                                                    $AttributeParms{value}]);
1797            # Combine the key and the subkey.
1798            my $realKey = ($subkey ? $key . $self->{splitter} . $subkey : $key);
1799            # Split the value.
1800            my @values = split $self->{splitter}, $value;
1801            # Output the result.
1802            push @retVal, [$objectID, $realKey, @values];
1803        }
1804        # Return the result.
1805        return @retVal;
1806    }
1807    
1808    =head2 Key and ID Manipulation Methods
1809    
1810    =head3 ParseID
1811    
1812    C<< my ($type, $id) = CustomAttributes::ParseID($idValue); >>
1813    
1814    Determine the type and object ID corresponding to an ID value from the attribute database.
1815    Most ID values consist of a type name and an ID, separated by a colon (e.g. C<Family:aclame|cluster10>);
1816    however, Genomes, Features, and Subsystems are not stored with a type name, so we need to
1817    deduce the type from the ID value structure.
1818    
1819    The theory here is that you can plug the ID and type directly into a Sprout database method, as
1820    follows
1821    
1822        my ($type, $id) = CustomAttributes::ParseID($attrList[$num]->[0]);
1823        my $target = $sprout->GetEntity($type, $id);
1824    
1825    =over 4
1826    
1827    =item idValue
1828    
1829    ID value taken from the attribute database.
1830    
1831    =item RETURN
1832    
1833    Returns a two-element list. The first element is the type of object indicated by the ID value,
1834    and the second element is the actual object ID.
1835    
1836    =back
1837    
1838    =cut
1839    
1840    sub ParseID {
1841        # Get the parameters.
1842        my ($idValue) = @_;
1843        # Declare the return variables.
1844        my ($type, $id);
1845        # Parse the incoming ID. We first check for the presence of an entity name. Entity names
1846        # can only contain letters, which helps to insure typed object IDs don't collide with
1847        # subsystem names (which are untyped).
1848        if ($idValue =~ /^([A-Za-z]+):(.+)/) {
1849            # Here we have a typed ID.
1850            ($type, $id) = ($1, $2);
1851            # Fix the case sensitivity on PDB IDs.
1852            if ($type eq 'PDB') { $id = lc $id; }
1853        } elsif ($idValue =~ /fig\|/) {
1854            # Here we have a feature ID.
1855            ($type, $id) = (Feature => $idValue);
1856        } elsif ($idValue =~ /\d+\.\d+/) {
1857            # Here we have a genome ID.
1858            ($type, $id) = (Genome => $idValue);
1859        } else {
1860            # The default is a subsystem ID.
1861            ($type, $id) = (Subsystem => $idValue);
1862        }
1863        # Return the results.
1864        return ($type, $id);
1865    }
1866    
1867    =head3 FormID
1868    
1869    C<< my $idValue = CustomAttributes::FormID($type, $id); >>
1870    
1871    Convert an object type and ID pair into an object ID string for the attribute system. Subsystems,
1872    genomes, and features are stored in the database without type information, but all other object IDs
1873    must be prefixed with the object type.
1874    
1875    =over 4
1876    
1877    =item type
1878    
1879    Relevant object type.
1880    
1881    =item id
1882    
1883    ID of the object in question.
1884    
1885    =item RETURN
1886    
1887    Returns a string that will be recognized as an object ID in the attribute database.
1888    
1889    =back
1890    
1891    =cut
1892    
1893    sub FormID {
1894        # Get the parameters.
1895        my ($type, $id) = @_;
1896        # Declare the return variable.
1897        my $retVal;
1898        # Compute the ID string from the type.
1899        if (grep { $type eq $_ } qw(Feature Genome Subsystem)) {
1900            $retVal = $id;
1901        } else {
1902            $retVal = "$type:$id";
1903        }
1904        # Return the result.
1905        return $retVal;
1906    }
1907    
1908    =head3 GetTargetObject
1909    
1910    C<< my $object = CustomAttributes::GetTargetObject($erdb, $idValue); >>
1911    
1912    Return the database object corresponding to the specified attribute object ID. The
1913    object type associated with the ID value must correspond to an entity name in the
1914    specified database.
1915    
1916    =over 4
1917    
1918    =item erdb
1919    
1920    B<ERDB> object for accessing the target database.
1921    
1922    =item idValue
1923    
1924    ID value retrieved from the attribute database.
1925    
1926    =item RETURN
1927    
1928    Returns a B<ERDBObject> for the attribute value's target object.
1929    
1930    =back
1931    
1932    =cut
1933    
1934    sub GetTargetObject {
1935        # Get the parameters.
1936        my ($erdb, $idValue) = @_;
1937        # Declare the return variable.
1938        my $retVal;
1939        # Get the type and ID for the target object.
1940        my ($type, $id) = ParseID($idValue);
1941        # Plug them into the GetEntity method.
1942        $retVal = $erdb->GetEntity($type, $id);
1943        # Return the resulting object.
1944        return $retVal;
1945    }
1946    
1947    =head3 SplitKey
1948    
1949    C<< my ($realKey, $subKey) = $ca->SplitKey($key); >>
1950    
1951    Split an external key (that is, one passed in by a caller) into the real key and the sub key.
1952    The real and sub keys are separated by a splitter value (usually C<::>). If there is no splitter,
1953    then the sub key is presumed to be an empty string.
1954    
1955    =over 4
1956    
1957    =item key
1958    
1959    Incoming key to be split.
1960    
1961    =item RETURN
1962    
1963    Returns a two-element list, the first element of which is the real key and the second element of
1964    which is the sub key.
1965    
1966    =back
1967    
1968    =cut
1969    
1970    sub SplitKey {
1971        # Get the parameters.
1972        my ($self, $key) = @_;
1973        # Do the split.
1974        my ($realKey, $subKey) = split($self->{splitter}, $key, 2);
1975        # Insure the subkey has a value.
1976        if (! defined $subKey) {
1977            $subKey = '';
1978        }
1979        # Return the results.
1980        return ($realKey, $subKey);
1981    }
1982    
1983    =head3 JoinKey
1984    
1985    C<< my $key = $ca->JoinKey($realKey, $subKey); >>
1986    
1987    Join a real key and a subkey together to make an external key. The external key is the attribute key
1988    used by the caller. The real key and the subkey are how the keys are represented in the database. The
1989    real key is the key to the B<AttributeKey> entity. The subkey is an attribute of the B<HasValueFor>
1990    relationship.
1991    
1992    =over 4
1993    
1994    =item realKey
1995    
1996    The real attribute key.
1997    
1998    =item subKey
1999    
2000    The subordinate portion of the attribute key.
2001    
2002    =item RETURN
2003    
2004    Returns a single string representing both keys.
2005    
2006    =back
2007    
2008    =cut
2009    
2010    sub JoinKey {
2011        # Get the parameters.
2012        my ($self, $realKey, $subKey) = @_;
2013        # Declare the return variable.
2014        my $retVal;
2015        # Check for a subkey.
2016        if ($subKey eq '') {
2017            # No subkey, so the real key is the key.
2018            $retVal = $realKey;
2019        } else {
2020            # Subkey found, so the two pieces must be joined by a splitter.
2021            $retVal = "$realKey$self->{splitter}$subKey";
2022  }  }
2023        # Return the result.
2024        return $retVal;
2025    }
2026    
2027    
2028    =head3 AttributeTable
2029    
2030    C<< my $tableHtml = CustomAttributes::AttributeTable($cgi, @attrList); >>
2031    
2032    Format the attribute data into an HTML table.
2033    
2034    =over 4
2035    
2036    =item cgi
2037    
2038    CGI query object used to generate the HTML
2039    
2040    =item attrList
2041    
2042    List of attribute results, in the format returned by the L</GetAttributes> or
2043    L</QueryAttributes> methods.
2044    
2045    =item RETURN
2046    
2047    Returns an HTML table displaying the attribute keys and values.
2048    
2049    =back
2050    
2051    =cut
2052    
2053    sub AttributeTable {
2054        # Get the parameters.
2055        my ($cgi, @attrList) = @_;
2056        # Accumulate the table rows.
2057        my @html = ();
2058        for my $attrData (@attrList) {
2059            # Format the object ID and key.
2060            my @columns = map { CGI::escapeHTML($_) } @{$attrData}[0,1];
2061            # Now we format the values. These remain unchanged unless one of them is a URL.
2062            my $lastValue = scalar(@{$attrData}) - 1;
2063            push @columns, map { $_ =~ /^http:/ ? $cgi->a({ href => $_ }, $_) : $_ } @{$attrData}[2 .. $lastValue];
2064            # Assemble the values into a table row.
2065            push @html, $cgi->Tr($cgi->td(\@columns));
2066        }
2067        # Format the table in the return variable.
2068        my $retVal = $cgi->table({ border => 2 }, $cgi->Tr($cgi->th(['Object', 'Key', 'Values'])), @html);
2069        # Return it.
2070        return $retVal;
2071    }
2072  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3